From 1452e500bad302af32e0b8046b2702d28dcf27ef Mon Sep 17 00:00:00 2001 From: voidptr_t Date: Fri, 12 Jul 2024 04:50:38 +0300 Subject: [PATCH 1/5] made a less "machine" translation --- ru/README.md | 46 +++++++++++++++++++++++++++------------------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/ru/README.md b/ru/README.md index 365c4917103..36be41f3c44 100644 --- a/ru/README.md +++ b/ru/README.md @@ -2,52 +2,60 @@ home: true heroImage: null heroText: Nushell -tagline: Новый тип оболочки -actionText: Начать → +tagline: A new type of shell +actionText: Приступим → actionLink: /book/ features: - - title: Конвейеры для управления любой ОС - details: Nu работает на Linux, macOS, BSD и Windows. Выучите его один раз, а затем используйте везде. - - title: Все есть данные - details: Конвейеры Nu используют структурированные данные, поэтому вы можете спокойно выбирать, фильтровать и сортировать их каждый раз одним и тем же способом. Перестаньте парсить строки и начните решать проблемы. - - title: Мощные плагины - details: Nu легко расширяется с помощью мощной системы плагинов. + - title: Пайплайны для управления любой ОС + details: Nu работает на Linux, macOS, BSD, и Windows. Выучите его один раз, используйте его везде. + - title: Всё есть данные + details: Пайплайны в Nu используют структурированные данные, поэтому вы можете безопасно отбирать, фильтровать и сортировать их каждый раз одним и тем же способом. Давайте перестанем разбирать строки и начнём решать реальные проблемы. + - title: Мощная система плагинов + details: Дополнять Nu можно с помощью мощной системы плагинов. --- -Снимок экрана, показывающий использование команды ls +Screenshot showing using the ls command ### Nu работает с существующими данными -Nu говорит на языках [JSON, YAML, SQLite, Excel, и других](/book/loading_data.html) из коробки. В конвейер Nu легко внести данные, будь они в файле, базе данных или веб-API: +Nu "говорит" на [JSON, YAML, SQLite, Excel, и др.](/book/loading_data.html) из коробки. Обработать ваши данные в пейплайне очень просто, будь они в файле, базе данных, либо же в API: -Снимок экрана, показывающий выборку с помощью веб-API +Screenshot showing fetch with a web API -### Nu имеет отличные сообщения об ошибках +### Nu имеет прекрасные сообщения об ошибках -Nu оперирует типизированными данными, поэтому отлавливает ошибки, которые другие оболочки не могут. А когда что-то ломается, Nu точно сообщает, где и почему: +Nu работает с типизированными данными, поэтому отлавливает ошибки, которых не замечают другие оболочки. А когда что-то ломается, Nu точно скажет вам, где и почему: -Снимок экрана, показывающий, как Nu ловит ошибку типа +Screenshot showing Nu catching a type error -## Получить Nu +## Я хочу это! -Nushell доступен в виде [загружаемых двоичных файлов](https://github.com/nushell/nushell/releases), [через ваш любимый менеджер пакетов](https://repology.org/project/nushell/versions), в [Действие GitHub](https://github.com/marketplace/actions/setup-nu), а также в виде [исходного кода](https://github.com/nushell/nushell). Прочитайте [подробные инструкции по установке](/book/installation.html) или сразу приступайте к работе: +Nushell можно получить [в виде бинарного файла](https://github.com/nushell/nushell/releases), [с помощью вашего любимого пакетного менеджера](https://repology.org/project/nushell/versions), в [в GitHub Action](https://github.com/marketplace/actions/setup-nu), или в виде [исходного кода](https://github.com/nushell/nushell). См. [подробную инструкцию по установке](/book/installation.html) или начните уже сейчас: #### macOS / Linux: +##### Homebrew + ```shell $ brew install nushell ``` +##### Nix profile + +```shell +$ nix profile install nixpkgs#nushell +``` + #### Windows: ```shell $ winget install nushell ``` -После установки запустите Nu, набрав `nu`. +После установки, запустите Nu с помощью `nu`. ## Сообщество -Присоединяйтесь к нам [в Discord](https://discord.gg/NtAbbGn), если у вас есть вопросы о Nu! +Присоединяйтесь к нам [в Discord](https://discord.gg/NtAbbGn) если у вас есть любые вопросы о Nu! -Вы можете помочь улучшить этот сайт, [оставив отзыв](https://github.com/nushell/nushell.github.io/issues) или [отправив PR](https://github.com/nushell/nushell.github.io/pulls). +Вы можете улучшить этот сайт [предоставив нам обратную связь](https://github.com/nushell/nushell.github.io/issues) или [отправив PR](https://github.com/nushell/nushell.github.io/pulls). From b601f485764c5a95c0133995952772a46a21f548 Mon Sep 17 00:00:00 2001 From: voidptr_t Date: Fri, 12 Jul 2024 05:01:09 +0300 Subject: [PATCH 2/5] wrong context --- ru/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru/README.md b/ru/README.md index 36be41f3c44..510e720c00e 100644 --- a/ru/README.md +++ b/ru/README.md @@ -24,7 +24,7 @@ Nu "говорит" на [JSON, YAML, SQLite, Excel, и др.](/book/loading_dat ### Nu имеет прекрасные сообщения об ошибках -Nu работает с типизированными данными, поэтому отлавливает ошибки, которых не замечают другие оболочки. А когда что-то ломается, Nu точно скажет вам, где и почему: +Nu работает с типизированными данными, поэтому отлавливает ошибки, которые не замечают другие оболочки. А когда что-то ломается, Nu точно скажет вам, где и почему: Screenshot showing Nu catching a type error From 6fd35719b166ca11dba7d3f6e43fe0b46902513c Mon Sep 17 00:00:00 2001 From: voidptr_t Date: Fri, 12 Jul 2024 08:02:46 +0300 Subject: [PATCH 3/5] installation default_shell quick start --- .vuepress/configs/sidebar/ru.ts | 188 ++-- ru/book/3rdpartyprompts.md | 99 ++ ru/book/README.md | 2 +- ru/book/advanced.md | 20 + ru/book/aliases.md | 113 +++ ru/book/background_task.md | 34 + ru/book/cheat_sheet.md | 522 +++++++++++ ru/book/coloring_and_theming.md | 562 ++++++++++++ ru/book/coming_from_bash.md | 71 ++ ru/book/coming_from_cmd.md | 60 ++ ru/book/coming_to_nu.md | 9 + ru/book/command_signature.md | 22 + ru/book/configuration.md | 234 +++++ ru/book/control_flow.md | 361 ++++++++ ru/book/creating_errors.md | 49 + ru/book/custom_commands.md | 498 ++++++++++ ru/book/custom_completions.md | 168 ++++ ru/book/dataframes.md | 1270 ++++++++++++++++++++++++++ ru/book/default_shell.md | 32 + ru/book/design_notes.md | 7 + ru/book/environment.md | 262 ++++++ ru/book/escaping.md | 19 + ru/book/explore.md | 65 ++ ru/book/externs.md | 66 ++ ru/book/getting_started.md | 9 + ru/book/hooks.md | 298 ++++++ ru/book/how_nushell_code_gets_run.md | 325 +++++++ ru/book/installation.md | 99 ++ ru/book/line_editor.md | 852 +++++++++++++++++ ru/book/loading_data.md | 244 +++++ ru/book/metadata.md | 39 + ru/book/modules.md | 521 +++++++++++ ru/book/moving_around.md | 72 ++ ru/book/nu_as_a_shell.md | 28 + ru/book/nu_fundamentals.md | 20 + ru/book/nushell_map.md | 76 ++ ru/book/nushell_map_functional.md | 47 + ru/book/nushell_map_imperative.md | 75 ++ ru/book/nushell_operator_map.md | 25 + ru/book/operators.md | 294 ++++++ ru/book/overlays.md | 259 ++++++ ru/book/parallelism.md | 43 + ru/book/pipelines.md | 388 ++++++++ ru/book/plugins.md | 187 ++++ ru/book/programming_in_nu.md | 31 + ru/book/quick_tour.md | 53 ++ ru/book/regular_expressions.md | 3 + ru/book/scripts.md | 155 ++++ ru/book/shells_in_shells.md | 52 ++ ru/book/standard_library.md | 3 + ru/book/stdout_stderr_exit_codes.md | 140 +++ ru/book/style_guide.md | 194 ++++ ru/book/table_of_contents.md | 41 + ru/book/testing.md | 178 ++++ ru/book/thinking_in_nu.md | 95 ++ ru/book/types_of_data.md | 518 +++++++++++ ru/book/variables.md | 216 +++++ ru/book/working_with_lists.md | 218 +++++ ru/book/working_with_strings.md | 399 ++++++++ ru/book/working_with_tables.md | 388 ++++++++ 60 files changed, 11219 insertions(+), 99 deletions(-) create mode 100644 ru/book/3rdpartyprompts.md create mode 100644 ru/book/advanced.md create mode 100644 ru/book/aliases.md create mode 100644 ru/book/background_task.md create mode 100644 ru/book/cheat_sheet.md create mode 100644 ru/book/coloring_and_theming.md create mode 100644 ru/book/coming_from_bash.md create mode 100644 ru/book/coming_from_cmd.md create mode 100644 ru/book/coming_to_nu.md create mode 100644 ru/book/command_signature.md create mode 100644 ru/book/configuration.md create mode 100644 ru/book/control_flow.md create mode 100644 ru/book/creating_errors.md create mode 100644 ru/book/custom_commands.md create mode 100644 ru/book/custom_completions.md create mode 100644 ru/book/dataframes.md create mode 100644 ru/book/default_shell.md create mode 100644 ru/book/design_notes.md create mode 100644 ru/book/environment.md create mode 100644 ru/book/escaping.md create mode 100644 ru/book/explore.md create mode 100644 ru/book/externs.md create mode 100644 ru/book/getting_started.md create mode 100644 ru/book/hooks.md create mode 100644 ru/book/how_nushell_code_gets_run.md create mode 100644 ru/book/installation.md create mode 100644 ru/book/line_editor.md create mode 100644 ru/book/loading_data.md create mode 100644 ru/book/metadata.md create mode 100644 ru/book/modules.md create mode 100644 ru/book/moving_around.md create mode 100644 ru/book/nu_as_a_shell.md create mode 100644 ru/book/nu_fundamentals.md create mode 100644 ru/book/nushell_map.md create mode 100644 ru/book/nushell_map_functional.md create mode 100644 ru/book/nushell_map_imperative.md create mode 100644 ru/book/nushell_operator_map.md create mode 100644 ru/book/operators.md create mode 100644 ru/book/overlays.md create mode 100644 ru/book/parallelism.md create mode 100644 ru/book/pipelines.md create mode 100644 ru/book/plugins.md create mode 100644 ru/book/programming_in_nu.md create mode 100644 ru/book/quick_tour.md create mode 100644 ru/book/regular_expressions.md create mode 100644 ru/book/scripts.md create mode 100644 ru/book/shells_in_shells.md create mode 100644 ru/book/standard_library.md create mode 100644 ru/book/stdout_stderr_exit_codes.md create mode 100644 ru/book/style_guide.md create mode 100644 ru/book/table_of_contents.md create mode 100644 ru/book/testing.md create mode 100644 ru/book/thinking_in_nu.md create mode 100644 ru/book/types_of_data.md create mode 100644 ru/book/variables.md create mode 100644 ru/book/working_with_lists.md create mode 100644 ru/book/working_with_strings.md create mode 100644 ru/book/working_with_tables.md diff --git a/.vuepress/configs/sidebar/ru.ts b/.vuepress/configs/sidebar/ru.ts index 7720a5a3bae..62510c06a03 100644 --- a/.vuepress/configs/sidebar/ru.ts +++ b/.vuepress/configs/sidebar/ru.ts @@ -8,103 +8,95 @@ export const sidebarRU: SidebarConfig = { link: '/ru/book/README.md', collapsible: false, }, - // { - // text: 'Начало работы', - // link: '/ru/book/getting_started.md', - // collapsible: false, - // children: [ - // '/ru/book/installation.md', - // '/ru/book/default_shell.md', - // '/ru/book/quick_tour.md', - // '/ru/book/moving_around.md', - // '/ru/book/thinking_in_nu.md', - // '/ru/book/cheat_sheet.md', - // ], - // }, - // { - // text: 'Основы Nu', - // link: '/nu_fundamentals.md', - // collapsible: false, - // children: [ - // '/ru/book/types_of_data.md', - // '/ru/book/loading_data.md', - // '/ru/book/pipelines.md', - // '/ru/book/working_with_strings.md', - // '/ru/book/working_with_lists.md', - // '/ru/book/working_with_tables.md', - // ], - // }, - // { - // text: 'Программирование в Nu', - // link: '/programming_in_nu.md', - // collapsible: false, - // children: [ - // '/ru/book/custom_commands.md', - // '/ru/book/aliases.md', - // '/ru/book/operators.md', - // '/ru/book/variables_and_subexpressions.md', - // '/ru/book/control_flow.md', - // '/ru/book/scripts.md', - // '/ru/book/modules.md', - // '/ru/book/overlays.md', - // '/ru/book/command_signature.md', - // '/ru/book/testing.md', - // '/ru/book/style_guide.md', - // ], - // }, - // { - // text: 'Nu как оболочка', - // link: '/nu_as_a_shell.md', - // collapsible: false, - // children: [ - // '/ru/book/configuration.md', - // '/ru/book/environment.md', - // '/ru/book/stdout_stderr_exit_codes.md', - // '/ru/book/escaping.md', - // '/ru/book/3rdpartyprompts.md', - // '/ru/book/shells_in_shells.md', - // '/ru/book/line_editor.md', - // '/ru/book/externs.md', - // '/ru/book/custom_completions.md', - // '/ru/book/coloring_and_theming.md', - // '/ru/book/hooks.md', - // '/ru/book/background_task.md', - // ], - // }, - // { - // text: 'Переход в Nu', - // link: '/coming_to_nu.md', - // collapsible: false, - // children: [ - // '/ru/book/coming_from_bash.md', - // '/ru/book/coming_from_cmd.md', - // '/ru/book/nushell_map.md', - // '/ru/book/nushell_map_imperative.md', - // '/ru/book/nushell_map_functional.md', - // '/ru/book/nushell_operator_map.md', - // ], - // }, - // { - // text: 'Примечания к дизайну', - // link: '/design_notes.md', - // collapsible: false, - // children: [ - // '/ru/book/how_nushell_code_gets_run.md' - // ], - // }, - // { - // text: '(Не очень) Продвинутый', - // link: '/advanced.md', - // collapsible: false, - // children: [ - // '/ru/book/standard_library.md', - // '/ru/book/dataframes.md', - // '/ru/book/metadata.md', - // '/ru/book/creating_errors.md', - // '/ru/book/parallelism.md', - // '/ru/book/plugins.md', - // '/ru/book/explore.md', - // ], - // }, + { + text: 'Начало работы', + link: '/ru/book/getting_started.md', + collapsible: false, + children: [ + '/ru/book/installation.md', + '/ru/book/default_shell.md', + '/ru/book/quick_tour.md', + '/ru/book/moving_around.md', + '/ru/book/thinking_in_nu.md', + '/ru/book/cheat_sheet.md', + ], + }, + { + text: 'Основы Nu', + link: '/nu_fundamentals.md', + collapsible: false, + children: [ + '/ru/book/types_of_data.md', + '/ru/book/loading_data.md', + '/ru/book/pipelines.md', + '/ru/book/working_with_strings.md', + '/ru/book/working_with_lists.md', + '/ru/book/working_with_tables.md', + ], + }, + { + text: 'Программирование в Nu', + link: '/programming_in_nu.md', + collapsible: false, + children: [ + '/ru/book/custom_commands.md', + '/ru/book/aliases.md', + '/ru/book/operators.md', + '/ru/book/variables_and_subexpressions.md', + '/ru/book/control_flow.md', + '/ru/book/scripts.md', + '/ru/book/modules.md', + '/ru/book/overlays.md', + '/ru/book/command_signature.md', + '/ru/book/testing.md', + '/ru/book/style_guide.md', + ], + }, + { + text: 'Nu как оболочка', + link: '/nu_as_a_shell.md', + collapsible: false, + children: [ + '/ru/book/configuration.md', + '/ru/book/environment.md', + '/ru/book/stdout_stderr_exit_codes.md', + '/ru/book/escaping.md', + '/ru/book/3rdpartyprompts.md', + '/ru/book/shells_in_shells.md', + '/ru/book/line_editor.md', + '/ru/book/externs.md', + '/ru/book/custom_completions.md', + '/ru/book/coloring_and_theming.md', + '/ru/book/hooks.md', + '/ru/book/background_task.md', + ], + }, + { + text: 'Переход на Ин', + link: '/book/coming_to_nu.md', + collapsible: false, + children: [ + '/ru/book/coming_from_bash.md', + '/ru/book/coming_from_cmd.md', + '/ru/book/nushell_map.md', + '/ru/book/nushell_map_imperative.md', + '/ru/book/nushell_map_functional.md', + '/ru/book/nushell_operator_map.md', + ], + }, + { + text: '(Не очень) Продвинутый', + link: '/advanced.md', + collapsible: false, + children: [ + '/ru/book/standard_library.md', + '/ru/book/dataframes.md', + '/ru/book/metadata.md', + '/ru/book/creating_errors.md', + '/ru/book/parallelism.md', + '/ru/book/plugins.md', + '/ru/book/explore.md', + ], + }, ], }; diff --git a/ru/book/3rdpartyprompts.md b/ru/book/3rdpartyprompts.md new file mode 100644 index 00000000000..cadc623c660 --- /dev/null +++ b/ru/book/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/ru/book/README.md b/ru/book/README.md index 371530ecd78..bc6e2c32be5 100644 --- a/ru/book/README.md +++ b/ru/book/README.md @@ -15,7 +15,7 @@ Nu берет пример со многих знакомых мест: трад Книга разделена на главы, которые далее разбиты на разделы. Вы можете нажать на заголовки глав, чтобы получить более подробную информацию о них. -- [Начало работы (EN)](/book/getting_started.md) научит вас, как установить Nushell, и покажет вам, что к чему. В ней также объясняются некоторые принципы проектирования, по которым Nushell отличается от типичных оболочек, таких как bash. +- [Начало работы (RU)](getting_started.md) научит вас, как установить Nushell, и покажет вам, что к чему. В ней также объясняются некоторые принципы проектирования, по которым Nushell отличается от типичных оболочек, таких как bash. - [Основы Nu (EN)](/book/nu_fundamentals.md) объясняет основные понятия языка Nushell. - [Программирование в Nu (EN)](/book/programming_in_nu.md) более глубоко погружает в особенности языка и показывает несколько способов организации и структурирования вашего кода. - [Nu как оболочка (EN)](/book/nu_as_a_shell.md) В центре внимания - возможности оболочки, в первую очередь конфигурация и окружение. diff --git a/ru/book/advanced.md b/ru/book/advanced.md new file mode 100644 index 00000000000..566ec9c963a --- /dev/null +++ b/ru/book/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/ru/book/aliases.md b/ru/book/aliases.md new file mode 100644 index 00000000000..c3ba60b526a --- /dev/null +++ b/ru/book/aliases.md @@ -0,0 +1,113 @@ +# 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/ru/book/background_task.md b/ru/book/background_task.md new file mode 100644 index 00000000000..3ad34edd682 --- /dev/null +++ b/ru/book/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) that makes working with pueue easier. + +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/ru/book/cheat_sheet.md b/ru/book/cheat_sheet.md new file mode 100644 index 00000000000..2af6e412add --- /dev/null +++ b/ru/book/cheat_sheet.md @@ -0,0 +1,522 @@ +# Nushell cheat sheet + +## Data types + +convert string to integer: + +```nu +"12" | into int +``` + +convert present date to provided time zone: + +```nu +date now | date to-timezone "Europe/London" +``` + +update a record's language and if none is specified insert provided value: + +```nu +{'name': 'nu', 'stars': 5, 'language': 'Python'} | upsert language 'Rust' +``` + +convert list of strings to yaml: + +```nu +[one two three] | to yaml +``` + +print table data: + +```nu +[[framework, language]; [Django, Python] [Laravel, PHP]] +``` + +select two named columns from the table and print their values: + +```nu +[{name: 'Robert' age: 34 position: 'Designer'} + {name: 'Margaret' age: 30 position: 'Software Developer'} + {name: 'Natalie' age: 50 position: 'Accountant'} +] | select name position +``` + +## Strings + +interpolate text: + +```nu +> let name = "Alice" +> $"greetings, ($name)!" +greetings, Alice! +``` + +split text on comma delimiter and save the list to `string_list` variable: + +```nu +> let string_list = "one,two,three" | split row "," +> $string_list +╭───┬───────╮ +│ 0 │ one │ +│ 1 │ two │ +│ 2 │ three │ +╰───┴───────╯ +``` + +check if a string contains a substring: + +```nu +> "Hello, world!" | str contains "o, w" +true +``` + +join multiple strings with delimiter: + +```nu +> let str_list = [zero one two] +> $str_list | str join ',' +zero,one,two +``` + +slice text by indices: + +```nu +> 'Hello World!' | str substring 4..8 +o Wor +``` + +parse string into named columns: + +```nu +> 'Nushell 0.80' | parse '{shell} {version}' +╭───┬─────────┬─────────╮ +│ # │ shell │ version │ +├───┼─────────┼─────────┤ +│ 0 │ Nushell │ 0.80 │ +╰───┴─────────┴─────────╯ +``` + +parse comma separated values (csv): + +```nu +> "acronym,long\nAPL,A Programming Language" | from csv +╭───┬─────────┬────────────────────────╮ +│ # │ acronym │ long │ +├───┼─────────┼────────────────────────┤ +│ 0 │ APL │ A Programming Language │ +╰───┴─────────┴────────────────────────╯ +``` + +color text in command-line terminal: + +```nu +> $'(ansi purple_bold)This text is a bold purple!(ansi reset)' +This text is a bold purple! +``` + +## Lists + +insert list value at index: + +```nu +> [foo bar baz] | insert 1 'beeze' +╭───┬───────╮ +│ 0 │ foo │ +│ 1 │ beeze │ +│ 2 │ bar │ +│ 3 │ baz │ +╰───┴───────╯ +``` + +update list value by index: + +```nu +> [1, 2, 3, 4] | update 1 10 +╭───┬────╮ +│ 0 │ 1 │ +│ 1 │ 10 │ +│ 2 │ 3 │ +│ 3 │ 4 │ +╰───┴────╯ +``` + +prepend list value: + +```nu +> let numbers = [1, 2, 3] +> $numbers | prepend 0 +╭───┬───╮ +│ 0 │ 0 │ +│ 1 │ 1 │ +│ 2 │ 2 │ +│ 3 │ 3 │ +╰───┴───╯ +``` + +append list value: + +```nu +> let numbers = [1, 2, 3] +> $numbers | append 4 +╭───┬───╮ +│ 0 │ 1 │ +│ 1 │ 2 │ +│ 2 │ 3 │ +│ 3 │ 4 │ +╰───┴───╯ +``` + +slice first list values: + +```nu +> [cammomile marigold rose forget-me-not] | first 2 +╭───┬───────────╮ +│ 0 │ cammomile │ +│ 1 │ marigold │ +╰───┴───────────╯ +``` + +iterate over a list; `it` is current list value: + +```nu +> let planets = [Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune] +> $planets | each { |it| $"($it) is a planet of the solar system" } +╭───┬─────────────────────────────────────────╮ +│ 0 │ Mercury is a planet of the solar system │ +│ 1 │ Venus is a planet of the solar system │ +│ 2 │ Earth is a planet of the solar system │ +│ 3 │ Mars is a planet of the solar system │ +│ 4 │ Jupiter is a planet of the solar system │ +│ 5 │ Saturn is a planet of the solar system │ +│ 6 │ Uranus is a planet of the solar system │ +│ 7 │ Neptune is a planet of the solar system │ +╰───┴─────────────────────────────────────────╯ +``` + +iterate over a list with an index and value: + +```nu +> $planets | enumerate | each { |it| $"($it.index + 1) - ($it.item)" } +╭───┬─────────────╮ +│ 0 │ 1 - Mercury │ +│ 1 │ 2 - Venus │ +│ 2 │ 3 - Earth │ +│ 3 │ 4 - Mars │ +│ 4 │ 5 - Jupiter │ +│ 5 │ 6 - Saturn │ +│ 6 │ 7 - Uranus │ +│ 7 │ 8 - Neptune │ +╰───┴─────────────╯ +``` + +reduce the list to a single value; `reduce` gives access to accumulator that is applied to each element in the list: + +```nu +> let scores = [3 8 4] +> $"total = ($scores | reduce { |it, acc| $acc + $it })" +total = 15 +``` + +reduce with an initial value (`--fold`): + +```nu +> let scores = [3 8 4] +> $"total = ($scores | reduce --fold 1 { |it, acc| $acc * $it })" +total = 96 +``` + +give access to the 3rd item in the list: + +```nu +> let planets = [Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune] +> $planets.2 +Earth +``` + +check if any string in the list starts with `E`: + +```nu +> let planets = [Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune] +> $planets | any {|it| $it | str starts-with "E" } +true +``` + +slice items that satisfy provided condition: + +```nu +> let cond = {|x| $x < 0 }; [-1 -2 9 1] | take while $cond +╭───┬────╮ +│ 0 │ -1 │ +│ 1 │ -2 │ +╰───┴────╯ +``` + +## Tables + +sort table: + +```nu +ls | sort-by size +``` + +sort table, get first rows: + +```nu +ls | sort-by size | first 5 +``` + +concatenate two tables with same columns: + +```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 │ +╰───┴──────────────┴───────────────┴──────────────╯ +``` + +remove the last column of a table: + +```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 │ +╰───┴───────────────────────┴───────╯ +``` + +## Files & Filesystem + +open a text file with the default text editor: + +```nu +start file.txt +``` + +save a string to text file: + +```nu +'lorem ipsum ' | save file.txt +``` + +append a string to the end of a text file: + +```nu +'dolor sit amet' | save --append file.txt +``` + +save a record to file.json: + +```nu +{ a: 1, b: 2 } | save file.json +``` + +recursively search for files by file name: + +```nu +glob **/*.{rs,toml} --depth 2 +``` + +watch a file, run command whenever it changes: + +```nu +watch . --glob=**/*.rs {|| cargo test } +``` + +## Custom Commands + +custom command with parameter type set to string: + +```nu +> def greet [name: string] { + $"hello ($name)" +} +``` + +custom command with default parameter set to nushell: + +```nu +> def greet [name = "nushell"] { + $"hello ($name)" +} +``` + +passing named parameter by defining flag for custom commands: + +```nu +> def greet [ + name: string + --age: int +] { + [$name $age] +} + +> greet world --age 10 +``` + +using flag as a switch with a shorthand flag (-a) for the age: + +```nu +> def greet [ + name: string + --age (-a): int + --twice +] { + if $twice { + [$name $age $name $age] + } else { + [$name $age] + } +} +> greet -a 10 --twice hello +``` + +custom command which takes any number of positional arguments using rest params: + +```nu +> def greet [...name: string] { + print "hello all:" + for $n in $name { + print $n + } +} +> greet earth mars jupiter venus +hello all: +earth +mars +jupiter +venus +``` + +## Variables + +an immutable variable cannot change its value after declaration: + +```nu +> let val = 42 +> print $val +42 +``` + +shadowing variable (declaring variable with the same name in a different scope): + +```nu +> let val = 42 +> do { let val = 101; $val } +101 +> $val +42 +``` + +declaring a mutable variable with mut key word: + +```nu +> mut val = 42 +> $val += 27 +> $val +69 +``` + +closures and nested defs cannot capture mutable variables from their environment (errors): + +```nu +> mut x = 0 +> [1 2 3] | each { $x += 1 } +Error: nu::parser::expected_keyword + + × Capture of mutable variable. + ╭─[entry #83:1:18] + 1 │ [1 2 3] | each { $x += 1 } + · ─┬ + · ╰── capture of mutable variable + ╰──── +``` + +a constant variable is immutable and is fully evaluated at parse-time: + +```nu +> const file = 'path/to/file.nu' +> source $file +``` + +use question mark operator `?` to return null instead of error if provided path is incorrect: + +```nu +> let files = (ls) +> $files.name?.0? +``` + +assign the result of a pipeline to a variable: + +```nu +> let big_files = (ls | where size > 10kb) +> $big_files +``` + +## Modules + +use an inline module: + +```nu +> module greetings { + export def hello [name: string] { + $"hello ($name)!" + } + + export def hi [where: string] { + $"hi ($where)!" + } +} +> use greetings hello +> hello "world" +``` + +import module from file and use its environment in current scope: + +```nu +# greetings.nu +export-env { + $env.MYNAME = "Arthur, King of the Britons" +} +export def hello [] { + $"hello ($env.MYNAME)" +} + +> use greetings.nu +> $env.MYNAME +Arthur, King of the Britons +> greetings hello +hello Arthur, King of the Britons! +``` + +use main command in module: + +```nu +# greetings.nu +export def hello [name: string] { + $"hello ($name)!" +} + +export def hi [where: string] { + $"hi ($where)!" +} + +export def main [] { + "greetings and salutations!" +} + +> use greetings.nu +> greetings +greetings and salutations! +> greetings hello world +hello world! +``` diff --git a/ru/book/coloring_and_theming.md b/ru/book/coloring_and_theming.md new file mode 100644 index 00000000000..fc7d417a5ec --- /dev/null +++ b/ru/book/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/ru/book/coming_from_bash.md b/ru/book/coming_from_bash.md new file mode 100644 index 00000000000..af1ef2d4234 --- /dev/null +++ b/ru/book/coming_from_bash.md @@ -0,0 +1,71 @@ +# 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.91.0 or later. + +| Bash | Nu | Task | +| ------------------------------------ | ------------------------------------------------------------- | ----------------------------------------------------------------- | +| `ls` | `ls` | Lists the files in the current directory | +| `ls ` | `ls ` | Lists the files in the given directory | +| `ls pattern*` | `ls pattern*` | Lists files that match a given pattern | +| `ls -la` | `ls --long --all` or `ls -la` | List files with all available information, including hidden files | +| `ls -d */` | `ls \| where type == dir` | List directories | +| `find . -name *.rs` | `ls **/*.rs` | Find recursively all files that match a given pattern | +| `find . -name Makefile \| xargs vim` | `ls **/Makefile \| get name \| vim ...$in` | Pass values as command parameters | +| `cd ` | `cd ` | Change to the given directory | +| `cd` | `cd` | Change to the home directory | +| `cd -` | `cd -` | Change to the previous directory | +| `mkdir ` | `mkdir ` | Creates the given path | +| `mkdir -p ` | `mkdir ` | Creates the given path, creating parents as necessary | +| `touch test.txt` | `touch test.txt` | Create a file | +| `> ` | `out> ` or `o> ` | Save command output to a file | +| | `\| save ` | Save command output to a file as structured data | +| `>> ` | `out>> ` or `o>> ` | Append command output to a file | +| | `\| save --append ` | Append command output to a file as structured data | +| `> /dev/null` | `\| ignore` | Discard command output | +| `> /dev/null 2>&1` | `out+err>\| ignore` or `o+e>\| ignore` | Discard command output, including stderr | +| `command 2>&1 \| less` | `command out+err>\| less` or `command o+e>\| less` | Pipe stdout and stderr of a command into less | +| `cmd1 \| tee log.txt \| cmd2` | `cmd1 \| tee { save log.txt } \| cmd2` | Tee command output to a log file | +| `cat ` | `open --raw ` | Display the contents of the given file | +| | `open ` | Read a file as structured data | +| `mv ` | `mv ` | Move file to new location | +| `cp ` | `cp ` | Copy file to new location | +| `cp -r ` | `cp -r ` | Copy directory to a new location, recursively | +| `rm ` | `rm ` | Remove the given file | +| | `rm -t ` | Move the given file to the system trash | +| `rm -rf ` | `rm -r ` | Recursively removes the given path | +| `date -d ` | `"" \| into datetime -f ` | Parse a date ([format documentation](https://docs.rs/chrono/0.4.15/chrono/format/strftime/index.html)) | +| `sed` | `str replace` | Find and replace a pattern in a string | +| `grep ` | `where $it =~ ` or `find ` | Filter strings that contain the substring | +| `man ` | `help ` | Get the help for a given command | +| | `help commands` | List all available commands | +| | `help --find ` | Search for match in all available commands | +| `command1 && command2` | `command1; command2` | Run a command, and if it's successful run a second | +| `stat $(which git)` | `stat (which git).path` | Use command output as argument for other command | +| `echo /tmp/$RANDOM` | `$"/tmp/(random integer)"` | Use command output in a string | +| `cargo b --jobs=$(nproc)` | `cargo b $"--jobs=(sys cpu \| length)"` | Use command output in an option | +| `echo $PATH` | `$env.PATH` (Non-Windows) or `$env.Path` (Windows) | See the current path | +| `` | `vim $nu.config-path` | Update PATH permanently | +| `export PATH = $PATH:/usr/other/bin` | `$env.PATH = ($env.PATH \| append /usr/other/bin)` | Update PATH temporarily | +| `export` | `$env` | List the current environment variables | +| `` | `vim $nu.config-path` | Update environment variables permanently | +| `FOO=BAR ./bin` | `FOO=BAR ./bin` | Update environment temporarily | +| `export FOO=BAR` | `$env.FOO = BAR` | Set environment variable for current session | +| `echo $FOO` | `$env.FOO` | Use environment variables | +| `echo ${FOO:-fallback}` | `$env.FOO? \| default "ABC"` | Use a fallback in place of an unset variable | +| `unset FOO` | `hide-env FOO` | Unset environment variable for current session | +| `alias s="git status -sb"` | `alias s = git status -sb` | Define an alias temporarily | +| `type FOO` | `which FOO` | Display information about a command (builtin, alias, or executable) | +| `` | `vim $nu.config-path` | Add and edit alias permanently (for new shells) | +| `bash -c ` | `nu -c ` | Run a pipeline of commands | +| `bash