nushell/crates/nu-command/src/default_context.rs
Artemiy 2bb0c1c618
Command to get individual keys (#9453)
# Description
Add a `keybindings get` command to listen and get individual "keyboard"
events. This includes different keyboard keys (see example of use) on
seemingly all terminals and mouse, resize, focus and paste events on
some special once. The record returned by this command is similar to
crossterm event structure and is documented in help message. For ease of
use, option `--types` can get a list of event types to filter only
desired events automatically. Additionally `--raw` options displays raw
code of char keys and numeric format of modifier flags.

Example of use, moving a character around a grid with arrow keys:
```nu
def test [] {
  mut x = 0
  mut y = 0
  loop {
    clear
    $x = ([([$x 4] | math min) 0] | math max)
    $y = ([([$y 4] | math min) 0] | math max)

    for i in 0..4 {
      for j in 0..4 {
        if $j == $x and $i == $y {
          print -n "*"
        } else {
          print -n "."
        }
      }
      print ""
    }
    
    let inp = (input listen-t [ key ])
    match $inp.key {
      {type: other key: enter} => (break)
      {type: other key: up} => ($y = $y - 1)
      {type: other key: down} => ($y = $y + 1)
      {type: other key: left} => ($x = $x - 1)
      {type: other key: right} => ($x = $x + 1)
      _ => ()
    }
  }
}

```

# User-Facing Changes
- New `keybindngs get` command
- `keybindings listen` is left as is
- New `input display` command in std, mirroring functionality of
`keybindings listen`

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect -A clippy::result_large_err` to check that
you're using the standard code style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` to run the tests for the
standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2023-07-03 10:23:44 -05:00

442 lines
9.2 KiB
Rust

use nu_protocol::engine::{EngineState, StateWorkingSet};
use crate::{
help::{HelpAliases, HelpCommands, HelpExterns, HelpModules, HelpOperators},
*,
};
pub fn add_shell_command_context(mut engine_state: EngineState) -> EngineState {
let delta = {
let mut working_set = StateWorkingSet::new(&engine_state);
macro_rules! bind_command {
( $( $command:expr ),* $(,)? ) => {
$( working_set.add_decl(Box::new($command)); )*
};
}
// If there are commands that have the same name as default declarations,
// they have to be registered before the main declarations. This helps to make
// them only accessible if the correct input value category is used with the
// declaration
// Database-related
// Adds all related commands to query databases
#[cfg(feature = "sqlite")]
add_database_decls(&mut working_set);
// Charts
bind_command! {
Histogram
}
// Filters
bind_command! {
All,
Any,
Append,
Columns,
Compact,
Default,
Drop,
DropColumn,
DropNth,
Each,
EachWhile,
Empty,
Enumerate,
Every,
Filter,
Find,
First,
Flatten,
Get,
Group,
GroupBy,
Headers,
Insert,
Items,
Join,
SplitBy,
Take,
Merge,
Move,
TakeWhile,
TakeUntil,
Last,
Length,
Lines,
ParEach,
Prepend,
Range,
Reduce,
Reject,
Rename,
Reverse,
Roll,
RollDown,
RollUp,
RollLeft,
RollRight,
Rotate,
Select,
Shuffle,
Skip,
SkipUntil,
SkipWhile,
Sort,
SortBy,
SplitList,
Transpose,
Uniq,
UniqBy,
Upsert,
Update,
UpdateCells,
Values,
Where,
Window,
Wrap,
Zip,
};
// Misc
bind_command! {
Source,
Tutor,
};
// Path
bind_command! {
Path,
PathBasename,
PathDirname,
PathExists,
PathExpand,
PathJoin,
PathParse,
PathRelativeTo,
PathSplit,
PathType,
};
// System
bind_command! {
Complete,
External,
NuCheck,
Sys,
};
// Help
bind_command! {
Help,
HelpAliases,
HelpExterns,
HelpCommands,
HelpModules,
HelpOperators,
};
// Debug
bind_command! {
Ast,
Debug,
Explain,
Inspect,
Metadata,
Profile,
TimeIt,
View,
ViewFiles,
ViewSource,
ViewSpan,
};
#[cfg(unix)]
bind_command! { Exec }
#[cfg(windows)]
bind_command! { RegistryQuery }
#[cfg(any(
target_os = "android",
target_os = "linux",
target_os = "macos",
target_os = "windows"
))]
bind_command! { Ps };
#[cfg(feature = "which-support")]
bind_command! { Which };
// Strings
bind_command! {
Char,
Decode,
Encode,
DecodeBase64,
EncodeBase64,
DecodeHex,
EncodeHex,
DetectColumns,
Format,
FileSize,
Parse,
Size,
Split,
SplitChars,
SplitColumn,
SplitRow,
SplitWords,
Str,
StrCamelCase,
StrCapitalize,
StrContains,
StrDistance,
StrDowncase,
StrEndswith,
StrExpand,
StrJoin,
StrReplace,
StrIndexOf,
StrKebabCase,
StrLength,
StrPascalCase,
StrReverse,
StrScreamingSnakeCase,
StrSnakeCase,
StrStartsWith,
StrSubstring,
StrTrim,
StrTitleCase,
StrUpcase
};
// FileSystem
bind_command! {
Cd,
Cp,
Ls,
Mkdir,
Mv,
Open,
Start,
Rm,
Save,
Touch,
Glob,
Watch,
};
// Platform
bind_command! {
Ansi,
AnsiGradient,
AnsiStrip,
AnsiLink,
Clear,
Du,
Input,
InputList,
InputListen,
Kill,
Sleep,
TermSize,
};
// Date
bind_command! {
Date,
DateFormat,
DateHumanize,
DateListTimezones,
DateNow,
DateToRecord,
DateToTable,
DateToTimezone,
};
// Shells
bind_command! {
Exit,
};
// Formats
bind_command! {
From,
FromCsv,
FromJson,
FromNuon,
FromOds,
FromSsv,
FromToml,
FromTsv,
FromUrl,
FromXlsx,
FromXml,
FromYaml,
FromYml,
To,
ToCsv,
ToHtml,
ToJson,
ToMd,
ToNuon,
ToText,
ToToml,
ToTsv,
Touch,
Upsert,
Where,
ToXml,
ToYaml,
};
// Viewers
bind_command! {
Griddle,
Table,
};
// Conversions
bind_command! {
Fill,
Fmt,
Into,
IntoBool,
IntoBinary,
IntoDatetime,
IntoDecimal,
IntoDuration,
IntoFilesize,
IntoInt,
IntoRecord,
IntoString,
};
// Env
bind_command! {
LetEnvDeprecated,
ExportEnv,
LoadEnv,
SourceEnv,
WithEnv,
ConfigNu,
ConfigEnv,
ConfigMeta,
ConfigReset,
};
// Math
bind_command! {
Math,
MathAbs,
MathAvg,
MathCeil,
MathFloor,
MathMax,
MathMedian,
MathMin,
MathMode,
MathProduct,
MathRound,
MathSqrt,
MathStddev,
MathSum,
MathVariance,
MathSin,
MathCos,
MathTan,
MathSinH,
MathCosH,
MathTanH,
MathArcSin,
MathArcCos,
MathArcTan,
MathArcSinH,
MathArcCosH,
MathArcTanH,
MathPi,
MathTau,
MathEuler,
MathExp,
MathLn,
MathLog,
};
// Network
bind_command! {
Http,
HttpDelete,
HttpGet,
HttpHead,
HttpPatch,
HttpPost,
HttpPut,
HttpOptions,
Url,
UrlBuildQuery,
UrlEncode,
UrlJoin,
UrlParse,
Port,
}
// Random
bind_command! {
Random,
RandomBool,
RandomChars,
RandomDecimal,
RandomDice,
RandomInteger,
RandomUuid,
};
// Generators
bind_command! {
Cal,
Seq,
SeqDate,
SeqChar,
};
// Hash
bind_command! {
Hash,
HashMd5::default(),
HashSha256::default(),
};
// Experimental
bind_command! {
IsAdmin,
};
// Deprecated
bind_command! {
HashBase64,
LPadDeprecated,
MathEvalDeprecated,
RPadDeprecated,
StrCollectDeprecated,
StrDatetimeDeprecated,
StrDecimalDeprecated,
StrFindReplaceDeprecated,
StrIntDeprecated,
};
working_set.render()
};
if let Err(err) = engine_state.merge_delta(delta) {
eprintln!("Error creating default context: {err:?}");
}
// Cache the table decl id so we don't have to look it up later
let table_decl_id = engine_state.find_decl("table".as_bytes(), &[]);
engine_state.table_decl_id = table_decl_id;
engine_state
}