github.com/elves/elvish@v0.15.0/website/ref/language.md (about) 1 <!-- toc number-sections --> 2 3 # Introduction 4 5 This document describes the Elvish programming language. It is both a 6 specification and an advanced tutorial. The parts of this document marked with 7 either **notes** or called out as **examples** are non-normative, and only serve 8 to help you understand the more formal descriptions. 9 10 Examples in this document might use constructs that have not yet been 11 introduced, so some familiarity with the language is assumed. If you are new to 12 Elvish, start with the [learning materials](../learn/). 13 14 # Source code encoding 15 16 Elvish source code must be Unicode text encoded in UTF-8. 17 18 In this document, **character** is a synonym of 19 [Unicode codepoint](https://en.wikipedia.org/wiki/Code_point) or its UTF-8 20 encoding. 21 22 # Lexical elements 23 24 ## Whitespace 25 26 In this document, an **inline whitespace** is any of the following: 27 28 - A space (U+0020); 29 30 - A tab (U+0009); 31 32 - A comment: starting with `#` and ending before (but not including) the next 33 carriage return, newline or end of file; 34 35 - A line continuation: a `^` followed by a newline (`"\n"`), or a carriage 36 return and newline (`"\r\n"`). 37 38 A **whitespace** is any of the following: 39 40 - An inline whitespace; 41 42 - A carriage return (U+000D); 43 44 - A newline (U+000A). 45 46 ## Metacharacters 47 48 The following **metacharacters** serve to introduce or delimit syntax 49 constructs: 50 51 | Metacharacter | Use | 52 | ------------- | ----------------------------------------------------------- | 53 | `$` | Referencing variables | 54 | `*` and `?` | Forming wildcard | 55 | `\|` | Separating forms in a pipeline | 56 | `&` | Marking background pipelines; introducing key-value pairs | 57 | `;` | Separating pipelines | 58 | `<` and `>` | Introducing IO redirections | 59 | `(` and `)` | Enclosing output captures | 60 | `[` and `]` | Enclosing list literals, map literals or function signature | 61 | `{` and `}` | Enclosing lambda literals or brace expressions | 62 63 The following characters are parsed as metacharacters under certain conditions: 64 65 - `~` is a metacharacter if it appears at the beginning of a compound 66 expression, in which case it is subject to 67 [tilde expansion](#tilde-expansion); 68 69 - `=` is a metacharacter when used for terminating [map keys](#map) or option 70 keys, or denoting [legacy assignment form](#legacy-assignment-form) or 71 [temporary assignments](#temporary-assignment). 72 73 ## Single-quoted string 74 75 A single-quoted string consists of zero or more characters enclosed in single 76 quotes (`'`). All enclosed characters represent themselves, except the single 77 quote. 78 79 Two consecutive single quotes are handled as a special case: they represent one 80 single quote, instead of terminating a single-quoted string and starting 81 another. 82 83 **Examples**: `'*\'` evaluates to `*\`, and `'it''s'` evaluates to `it's`. 84 85 ## Double-quoted string 86 87 A double-quoted string consists of zero or more characters enclosed in double 88 quotes (`"`). All enclosed characters represent themselves, except backslashes 89 (`\`), which introduces **escape sequences**. Double quotes are not allowed 90 inside double-quoted strings, except after backslashes. 91 92 The following escape sequences are supported: 93 94 - `\cX`, where _X_ is a character with codepoint between 0x40 and 0x5F, 95 represents the codepoint that is 0x40 lower than _X_. For example, `\cI` is 96 the tab character: 0x49 (`I`) - 0x40 = 0x09 (tab). There is one special 97 case: A question-mark is converted to del; i.e., `\c?` or `\^?` is 98 equivalent to `\x7F`. 99 100 - `\^X` is the same as `\cX`. 101 102 - `\[0..7][0..7][0..7]` is a byte written as an octal value. There must be 103 three octal digits following the backslash. For example, `\000` is the nul 104 character, and `\101` is the same as `A`, but `\0` is an invalid escape 105 sequence (too few digits). 106 107 - `\x..` is a Unicode code point represented by two hexadecimal digits. 108 109 - `\u....` is a Unicode code point represented by four hexadecimal digits. 110 111 - `\U......` is a Unicode code point represented by eight hexadecimal digits. 112 113 - The following single character escape sequences: 114 115 - `\a` is the "bell" character, equivalent to `\007` or `\x07`. 116 117 - `\b` is the "backspace" character, equivalent to `\010` or `\x08`. 118 119 - `\f` is the "form feed" character, equivalent to `\014` or `\x0c`. 120 121 - `\n` is the "new line" character, equivalent to `\012` or `\x0a`. 122 123 - `\r` is the "carriage return" character, equivalent to `\015` or `\x0d`. 124 125 - `\t` is the "tab" character, equivalent to `\011` or `\x09`. 126 127 - `\v` is the "vertical tab" character, equivalent to `\013` or `\x0b`. 128 129 - `\\` is the "backslash" character, equivalent to `\134` or `\x5c`. 130 131 - `\"` is the "double-quote" character, equivalent to `\042` or `\x22`. 132 133 An unsupported escape sequence results in a parse error. 134 135 **Note**: Unlike most other shells, double-quoted strings in Elvish do not 136 support interpolation. For instance, `"$name"` simply evaluates to a string 137 containing `$name`. To get a similar effect, simply concatenate strings: instead 138 of `"my name is $name"`, write `"my name is "$name`. Under the hood this is a 139 [compounding](#compounding) operation. 140 141 ## Bareword 142 143 A string can be written without quoting -- a **bareword**, if it only includes 144 the characters from the following set: 145 146 - ASCII letters (a-z and A-Z) and numbers (0-9); 147 148 - The symbols `!%+,-./:@\_`; 149 150 - Non-ASCII codepoints that are printable, as defined by 151 [unicode.IsPrint](https://godoc.org/unicode#IsPrint) in Go's standard 152 library. 153 154 **Examples**: `a.txt`, `long-bareword`, `elf@elv.sh`, `/usr/local/bin`, 155 `你好世界`. 156 157 Moreover, `~` and `=` are allowed to appear without quoting when they are not 158 parsed as [metacharacters](#metacharacters). 159 160 **Note**: since the backslash (`\`) is a valid bareword character in Elvish, it 161 cannot be used to escape metacharacter. Use quotes instead: for example, to echo 162 a star, write `echo "*"` or `echo '*'`, not `echo \*`. The last command just 163 writes out `\*`. 164 165 # Value types 166 167 ## String 168 169 A string is a (possibly empty) sequence of bytes. 170 171 [Single-quoted string literals](#single-quoted-string), 172 [double-quoted string literals](#double-quoted-string)and [barewords](#bareword) 173 all evaluate to string values. Unless otherwise noted, different syntaxes of 174 string literals are equivalent in the code. For instance, `xyz`, `'xyz'` and 175 `"xyz"` are different syntaxes for the same string with content `xyz`. 176 177 Strings that contain UTF-8 encoded text can be [indexed](#indexing) with a 178 **byte index** where a codepoint starts, which results in the codepoint that 179 starts there. The index can be given as either a typed [number](#number), or a 180 string that parses to a number. Examples: 181 182 - In the string `elv`, every codepoint is encoded with only one byte, so 0, 1, 183 2 are all valid indices: 184 185 ```elvish-transcript 186 ~> put elv[0] 187 ▶ e 188 ~> put elv[1] 189 ▶ l 190 ~> put elv[2] 191 ▶ v 192 ``` 193 194 - In the string `世界`, each codepoint is encoded with three bytes. The first 195 codepoint occupies byte 0 through 2, and the second occupies byte 3 through 196 5\. Hence valid indices are 0 and 3: 197 198 ```elvish-transcript 199 ~> put 世界[0] 200 ▶ 世 201 ~> put 世界[3] 202 ▶ 界 203 ``` 204 205 Such strings may also be indexed with a slice (see documentation of 206 [list](#list) for slice syntax). The range determined by the slice is also 207 interpreted as byte indices, and the range must begin and end at codepoint 208 boundaries. 209 210 The behavior of indexing a string that does not contain valid UTF-8-encoded 211 Unicode text is unspecified. 212 213 **Note**: String indexing will likely change. 214 215 ## Number 216 217 Elvish has a double-precision floating point number type. 218 219 There is no literal syntax for the number type; it can be constructed with the 220 `float64` builtin. The builtin takes a single argument, which should be either 221 another `float64` value, or a string in the following formats (examples below 222 all express the same value): 223 224 - Decimal notation, e.g. `10`. 225 226 - Hexadecimal notation, e.g. `0xA`. 227 228 - Octal notation, e.g. `0o12`. 229 230 - Binary notation, e.g. `0b1010`. 231 232 - Floating point notation, e.g. `10.0`. 233 234 - Scientific notation, e.g. `1.0e1`. 235 236 The following special floating point values are also supported: `+Inf`, `-Inf` 237 and `NaN`. 238 239 The `float64` builtin is case-insensitive. 240 241 Numbers can contain underscores between digits to improve readability. For 242 example, `1000000` and `1_000_000` are equivalent. As is `1.234_56e3` and 243 `1.23456e3`. You can not use an underscore as a prefix or suffix in a number. 244 245 A `float64` data type can be converted to a string using `(to-string $number)`. 246 The resulting string is guaranteed to result in the same value when converted 247 back to a `float64`. Most of the time you won't need to perform this explicit 248 conversion. Elvish will implicitly make the conversion when running external 249 commands and many of the builtins (where the distinction is not important). 250 251 You usually do not need to use `float64` values explicitly; see the discussion 252 of 253 [Commands That Operate On Numbers](./builtin.html#commands-that-operate-on-numbers). 254 255 ## List 256 257 A list is a value containing a sequence of values. Values in a list are called 258 its **elements**. Each element has an index, starting from zero. 259 260 List literals are surrounded by square brackets `[ ]`, with elements separated 261 by whitespace. Examples: 262 263 ```elvish-transcript 264 ~> put [lorem ipsum] 265 ▶ [lorem ipsum] 266 ~> put [lorem 267 ipsum 268 foo 269 bar] 270 ▶ [lorem ipsum foo bar] 271 ``` 272 273 **Note**: In Elvish, commas have no special meanings and are valid bareword 274 characters, so don't use them to separate elements: 275 276 ```elvish-transcript 277 ~> li = [a, b] 278 ~> put $li 279 ▶ [a, b] 280 ~> put $li[0] 281 ▶ a, 282 ``` 283 284 A list can be [indexed](#indexing) with the index of an element to obtain the 285 element, which can take one of two forms: 286 287 - A non-negative integer, an offset counting from the beginning of the list. 288 For example, `$li[0]` is the first element of `$li`. 289 290 - A negative integer, an offset counting from the back of the list. For 291 instance, `$li[-1]` is the last element `$li`. 292 293 In both cases, the index can be given either as a [typed number](#number) or a 294 number-like string. 295 296 A list can also be indexed with a **slice** to obtain a sublist, which can take 297 one of two forms: 298 299 - A slice `$a..$b`, where both `$a` and `$b` are integers. The result is 300 sublist of `$li[$a]` up to, but not including, `$li[$b]`. For instance, 301 `$li[4..7]` equals `[$li[4] $li[5] $li[6]]`, while `$li[1..-1]` contains all 302 elements from `$li` except the first and last one. 303 304 Both integers may be omitted; `$a` defaults to 0 while `$b` defaults to the 305 length of the list. For instance, `$li[..2]` is equivalent to `$li[0..2]`, 306 `$li[2..]` is equivalent to `$li[2..(count $li)]`, and `$li[..]` makes a 307 copy of `$li`. The last form is rarely useful, as lists are immutable. 308 309 Note that the slice needs to be a **single** string, so there cannot be any 310 spaces within the slice. For instance, `$li[2..10]` cannot be written as 311 `$li[2.. 10]`; the latter contains two indices and is equivalent to 312 `$li[2..] $li[10]` (see [Indexing](#indexing)). 313 314 - A slice `$a..=$b`, which is similar to `$a..$b`, but includes `$li[$b]`. 315 316 Examples: 317 318 ```elvish-transcript 319 ~> li = [lorem ipsum foo bar] 320 ~> put $li[0] 321 ▶ lorem 322 ~> put $li[-1] 323 ▶ bar 324 ~> put $li[0..2] 325 ▶ [lorem ipsum] 326 ``` 327 328 ## Map 329 330 A map is a value containing unordered key-value pairs. 331 332 Map literals are surrounded by square brackets; a key/value pair is written 333 `&key=value` (reminiscent to HTTP query parameters), and pairs are separated by 334 whitespaces. Whitespaces are allowed after `=`, but not before `=`. Examples: 335 336 ```elvish-transcript 337 ~> put [&foo=bar &lorem=ipsum] 338 ▶ [&foo=bar &lorem=ipsum] 339 ~> put [&a= 10 340 &b= 23 341 &sum= (+ 10 23)] 342 ▶ [&a=10 &b=23 &sum=33] 343 ``` 344 345 The literal of an empty map is `[&]`. 346 347 Specifying a key without `=` or a value following it is equivalent to specifying 348 `$true` as the value. Specifying a key with `=` but no value following it is 349 equivalent to specifying the empty string as the value. Example: 350 351 ```elvish-transcript 352 ~> echo [&a &b=] 353 [&a=$true &b=''] 354 ``` 355 356 A map can be indexed by any of its keys. Unlike strings and lists, there is no 357 support for slices, and `..` and `..=` have no special meanings. Examples: 358 359 ```elvish-transcript 360 ~> map = [&a=lorem &b=ipsum &a..b=haha] 361 ~> echo $map[a] 362 lorem 363 ~> echo $map[a..b] 364 haha 365 ``` 366 367 ## Pseudo-map 368 369 The concept of **pseudo-map** is not a concrete data type, but refer to certain 370 data types that behave like maps in some aspects. 371 372 A pseudo-map typically has a fixed set of keys, called **fields**. The values of 373 a field can be accessed by [indexing](#indexing). However, unlike maps, it is 374 usually not possible to add new keys, remove existing keys, or even assigning a 375 new value to an existing key. 376 377 The pseudo-map mechanism is often used for introspection. For example, 378 [exceptions](#exception) and [user-defined functions](#function) are both 379 structmaps. 380 381 ## Exception 382 383 An exception carries information about errors during the execution of code. 384 385 There is no literal syntax for exceptions. See the discussion of 386 [exception and flow commands](#exception-and-flow-commands) for more information 387 about this data type. 388 389 An exception is a [pseudo-map](#pseudo-map) with a `reason` field, which is in 390 turn a pseudo-map. The reason pseudo-map has has a `type` field identifying how 391 the exception was raised, and further fields depending on the type: 392 393 - If the `type` field is `fail`, the exception was raised by the 394 [fail](builtins.html#fail) command. 395 396 In this case, the `content` field contains the argument to `fail`. 397 398 - If the `type` field is `flow`, the exception was raised by one of the flow 399 commands. 400 401 In this case, the `name` field contains the name of the flow command. 402 403 - If the `type` field is `pipeline`, the exception was a result of multiple 404 commands in the same pipeline raising exceptions. 405 406 In this case, the `exceptions` field contains the exceptions from the 407 individual commands. 408 409 - If the `type` field starts with `external-cmd/`, the exception was caused by 410 one of several conditions of an external command. In this case, the 411 following fields are available: 412 413 - The `cmd-name` field contains the name of the command. 414 415 - The `pid` field contains the PID of the command. 416 417 - If the `type` field is `external-cmd/exited`, the external command exited 418 with a non-zero status code. In this case, the `exit-status` field contains 419 the exit status. 420 421 - If the `type` field is `external-cmd/signaled`, the external command was 422 killed by a signal. In this case, the following extra fields are available: 423 424 - The `signal-name` field contains the name of the signal. 425 426 - The `signal-number` field contains the numerical value of the signal, as 427 a string. 428 429 - The `core-dumped` field is a boolean reflecting whether a core dump was 430 generated. 431 432 - If the `type` field is `external-cmd/stopped`, the external command was 433 stopped. In this case, the following extra fields are available: 434 435 - The `signal-name` field contains the name of the signal. 436 437 - The `signal-number` field contains the numerical value of the signal, as 438 a string. 439 440 - The `trap-cause` field contains the number indicating the trap cause. 441 442 Examples: 443 444 ```elvish-transcript 445 ~> put ?(fail foo)[reason] 446 ▶ [&content=foo &type=fail] 447 ~> put ?(return)[reason] 448 ▶ [&name=return &type=flow] 449 ~> put ?(false)[reason] 450 ▶ [&cmd-name=false &exit-status=1 &pid=953421 &type=external-cmd/exited] 451 ``` 452 453 ## Function 454 455 A function encapsulates a piece of code that can be executed in an 456 [ordinary command](#ordinary-command), and takes its arguments and options. 457 Functions are first-class values; they can be kept in variables, used as 458 arguments, output on the value channel and embedded in other data structures. 459 Elvish comes with a set of **builtin functions**, and Elvish code can also 460 create **user-defined functions**. 461 462 **Note**: Unlike most programming languages, functions in Elvish do not have 463 return values. Instead, they can output values, which can be 464 [captured](#output-capture) later. 465 466 A **function literal**, or alternatively a **lambda**, evaluates to a 467 user-defined function. The literal syntax consists of an optional **signature 468 list**, followed by a [code chunk](#code-chunk) that defines the body of the 469 function. 470 471 Here is an example without a signature: 472 473 ```elvish-transcript 474 ~> f = { echo "Inside a lambda" } 475 ~> put $f 476 ▶ <closure 0x18a1a340> 477 ``` 478 479 One or more whitespace characters after `{` is required: Elvish relies on the 480 presence of whitespace to disambiguate function literals and 481 [braced lists](#braced-list). 482 483 **Note**: It is good style to put some whitespace before the closing `}` for 484 symmetry, but this is not required by the syntax. 485 486 Functions defined without a signature list do not accept any arguments or 487 options. To do so, write a signature list. Here is an example: 488 489 ```elvish-transcript 490 ~> f = [a b]{ put $b $a } 491 ~> $f lorem ipsum 492 ▶ ipsum 493 ▶ lorem 494 ``` 495 496 There must be no space between `]` and `{`; otherwise Elvish will parse the 497 signature as a list, followed by a lambda without signature: 498 499 ```elvish-transcript 500 ~> put [a]{ nop } 501 ▶ <closure 0xc420153d80> 502 ~> put [a] { nop } 503 ▶ [a] 504 ▶ <closure 0xc42004a480> 505 ``` 506 507 Like in the left hand of assignments, if you prefix one of the arguments with 508 `@`, it becomes a **rest argument**, and its value is a list containing all the 509 remaining arguments: 510 511 ```elvish-transcript 512 ~> f = [a @rest]{ put $a $rest } 513 ~> $f lorem 514 ▶ lorem 515 ▶ [] 516 ~> $f lorem ipsum dolar sit 517 ▶ lorem 518 ▶ [ipsum dolar sit] 519 ~> f = [a @rest b]{ put $a $rest $b } 520 ~> $f lorem ipsum dolar sit 521 ▶ lorem 522 ▶ [ipsum dolar] 523 ▶ sit 524 ``` 525 526 You can also declare options in the signature. The syntax is `&name=default` 527 (like a map pair), where `default` is the default value for the option; the 528 value of the option will be kept in a variable called `name`: 529 530 ```elvish-transcript 531 ~> f = [&opt=default]{ echo "Value of $opt is "$opt } 532 ~> $f 533 Value of $opt is default 534 ~> $f &opt=foobar 535 Value of $opt is foobar 536 ``` 537 538 Options must have default values: Options should be **option**al. 539 540 If you call a function with too few arguments, too many arguments or unknown 541 options, an exception is thrown: 542 543 ```elvish-transcript 544 ~> [a]{ echo $a } foo bar 545 Exception: need 1 arguments, got 2 546 [tty], line 1: [a]{ echo $a } foo bar 547 ~> [a b]{ echo $a $b } foo 548 Exception: need 2 arguments, got 1 549 [tty], line 1: [a b]{ echo $a $b } foo 550 ~> [a b @rest]{ echo $a $b $rest } foo 551 Exception: need 2 or more arguments, got 1 552 [tty], line 1: [a b @rest]{ echo $a $b $rest } foo 553 ~> [&k=v]{ echo $k } &k2=v2 554 Exception: unknown option k2 555 [tty], line 1: [&k=v]{ echo $k } &k2=v2 556 ``` 557 558 A user-defined function is a [pseudo-map](#pseudo-map). If `$f` is a 559 user-defined function, it has the following fields: 560 561 - `$f[arg-names]` is a list containing the names of the arguments. 562 563 - `$f[rest-arg]` is the index of the rest argument. If there is no rest 564 argument, it is `-1`. 565 566 - `$f[opt-names]` is a list containing the names of the options. 567 568 - `$f[opt-defaults]` is a list containing the default values of the options, 569 in the same order as `$f[opt-names]`. 570 571 - `$f[def]` is a string containing the definition of the function, including 572 the signature and the body. 573 574 - `$f[body]` is a string containing the body of the function, without the 575 enclosing brackets. 576 577 - `$f[src]` is a map-like data structure containing information about the 578 source code that the function is defined in. It contains the same value that 579 the [src](builtin.html#src) function would output if called from the 580 function. 581 582 # Variable 583 584 A variable is a named storage location for holding a value. The following 585 characters can be used in variable names (a subset of bareword characters) 586 without quoting: 587 588 A variable exist after it is declared (either explicitly using [`var`](#var) or 589 implicitly using the [legacy assignment form](#legacy-assignment-form)), and its 590 value may be mutated by further assignments. It can be [used](#variable-use) as 591 an expression or part of an expression. 592 593 **Note**: In most other shells, variables can map directly to environmental 594 variables: `$PATH` is the same as the `PATH` environment variable. This is not 595 the case in Elvish. Instead, environment variables are put in a dedicated `E:` 596 namespace; the environment variable `PATH` is known as `$E:PATH`. The `$PATH` 597 variable, on the other hand, does not exist initially, and if you have defined 598 it, only lives in a certain lexical scope within the Elvish interpreter. 599 600 You will notice that variables sometimes have a leading dollar `$`, and 601 sometimes not. The tradition is that they do when they are used for their 602 values, and do not otherwise (e.g. in assignment). This is consistent with most 603 other shells. 604 605 ## Variable suffix 606 607 There are two characters that have special meanings and extra type constraints 608 when used as the suffix of a variable name: 609 610 - If a variable name ends with `~`, it can only take callable values, which 611 are functions and external commands. Such variables are consulted when 612 resolving [ordinary commands](#ordinary-command). 613 614 - If a variable name ends with `:`, it can only take namespaces as values. 615 They are used for accessing namespaced variables. 616 617 ## Scoping rule 618 619 Elvish has lexical scoping. A file or an interactive prompt starts with a 620 top-level scope, and a [function literal](#function) introduce new lexical 621 scopes. 622 623 When you use a variable, Elvish looks for it in the current lexical scope, then 624 its parent lexical scope and so forth, until the outermost scope: 625 626 ```elvish-transcript 627 ~> x = 12 628 ~> { echo $x } # $x is in the global scope 629 12 630 ~> { y = bar; { echo $y } } # $y is in the outer scope 631 bar 632 ``` 633 634 If a variable is not in any of the lexical scopes, Elvish tries to resolve it in 635 the `builtin:` namespace, and if that also fails, fails with an error: 636 637 ```elvish-transcript 638 ~> echo $pid # builtin 639 36613 640 ~> echo $nonexistent 641 Compilation error: variable $nonexistent not found 642 [interactive], line 1: 643 echo $nonexistent 644 ``` 645 646 Note that Elvish resolves all variables in a code chunk before starting to 647 execute any of it; that is why the error message above says _compilation error_. 648 This can be more clearly observed in the following example: 649 650 ```elvish-transcript 651 ~> echo pre-error; echo $nonexistent 652 Compilation error: variable $nonexistent not found 653 [tty], line 1: echo pre-error; echo $nonexistent 654 ``` 655 656 When you assign a variable, Elvish does a similar searching. If the variable 657 cannot be found, instead of causing an error, it will be created in the current 658 scope: 659 660 ```elvish-transcript 661 ~> x = 12 662 ~> { x = 13 } # assigns to x in the global scope 663 ~> echo $x 664 13 665 ~> { z = foo } # creates z in the inner scope 666 ~> echo $z 667 Compilation error: variable $z not found 668 [tty], line 1: echo $z 669 ``` 670 671 One implication of this behavior is that Elvish will not shadow your variable in 672 outer scopes. 673 674 There is a `local:` namespace that always refers to the current scope, and by 675 using it it is possible to force Elvish to shadow variables: 676 677 ```elvish-transcript 678 ~> x = 12 679 ~> { local:x = 13; echo $x } # force shadowing 680 13 681 ~> echo $x 682 12 683 ``` 684 685 After force shadowing, you can still access the variable in the outer scope 686 using the `up:` namespace, which always **skips** the innermost scope: 687 688 ```elvish-transcript 689 ~> x = 12 690 ~> { local:x = 14; echo $x $up:x } 691 14 12 692 ``` 693 694 The `local:` and `up:` namespaces can also be used on unshadowed variables, 695 although they are not useful in those cases: 696 697 ```elvish-transcript 698 ~> foo = a 699 ~> { echo $up:foo } # $up:foo is the same as $foo 700 a 701 ~> { bar = b; echo $local:bar } # $local:bar is the same as $bar 702 b 703 ``` 704 705 It is not possible to refer to a specific outer scope. 706 707 You cannot create new variables in the `builtin:` namespace, although existing 708 variables in it can be assigned new values. 709 710 ## Closure semantics 711 712 When a function literal refers to a variable in an outer scope, the function 713 will keep that variable alive, even if that variable is the local variable of an 714 outer function that that function has returned. This is called 715 [closure semantics](<https://en.wikipedia.org/wiki/Closure_(computer_programming)>), 716 because the function literal "closes" over the environment it is defined in. 717 718 In the following example, the `make-adder` function outputs two functions, both 719 referring to a local variable `$n`. Closure semantics means that: 720 721 1. Both functions can continue to refer to the `$n` variable after `make-adder` 722 has returned. 723 724 2. Multiple calls to the `make-adder` function generates distinct instances of 725 the `$n` variables. 726 727 ```elvish-transcript 728 ~> fn make-adder { 729 n = 0 730 put { put $n } { n = (+ $n 1) } 731 } 732 ~> getter adder = (make-adder) 733 ~> $getter # $getter outputs $n 734 ▶ 0 735 ~> $adder # $adder increments $n 736 ~> $getter # $getter and $setter refer to the same $n 737 ▶ 1 738 ~> getter2 adder2 = (make-adder) 739 ~> $getter2 # $getter2 and $getter refer to different $n 740 ▶ 0 741 ~> $getter 742 ▶ 1 743 ``` 744 745 Variables that get "captured" in closures are called **upvalues**; this is why 746 the pseudo-namespace for variables in outer scopes is called `up:`. When 747 capturing upvalues, Elvish only captures the variables that are used. In the 748 following example, `$m` is not an upvalue of `$g` because it is not used: 749 750 ```elvish-transcript 751 ~> fn f { m = 2; n = 3; put { put $n } } 752 ~> g = (f) 753 ``` 754 755 This effect is not currently observable, but will become so when namespaces 756 [become introspectable](https://github.com/elves/elvish/issues/492). 757 758 # Expressions 759 760 Elvish has a few types of expressions. Some of those are new compared to most 761 other languages, but some are very similar. 762 763 Unlike most other languages, expressions in Elvish may evaluate to any number of 764 values. The concept of multiple values is distinct from a list of multiple 765 elements. 766 767 ## Literal 768 769 Literals of [strings](#string), [lists](#list), [maps](#map) and 770 [functions](#function) all evaluate to one value of their corresponding types. 771 They are described in their respective sections. 772 773 ## Variable use 774 775 A **variable use** expression is formed by a `$` followed by the name of the 776 variable. Examples: 777 778 ```elvish-transcript 779 ~> foo = bar 780 ~> x y = 3 4 781 ~> put $foo 782 ▶ bar 783 ~> put $x 784 ▶ 3 785 ``` 786 787 If the variable name only contains the following characters (a subset of 788 bareword characters), the name can appear unquoted after `$` and the variable 789 use expression extends to the longest sequence of such characters: 790 791 - ASCII letters (a-z and A-Z) and numbers (0-9); 792 793 - The symbols `-_:~`. The colon `:` is special; it is normally used for 794 separating namespaces or denoting namespace variables; 795 796 - Non-ASCII codepoints that are printable, as defined by 797 [unicode.IsPrint](https://godoc.org/unicode#IsPrint) in Go's standard 798 library. 799 800 Alternatively, `$` may be followed immediately by a 801 [single-quoted string](https://elv.sh/ref/language.html#single-quoted-string) or 802 a [double-quoted string](https://elv.sh/ref/language.html#double-quoted-string), 803 in which cases the value of the string specifies the name of the variable. 804 Examples: 805 806 ```elvish-transcript 807 ~> "\n" = foo 808 ~> put $"\n" 809 ▶ foo 810 ~> '!!!' = bar 811 ~> put $'!!!' 812 ▶ bar 813 ``` 814 815 Unlike other shells and other dynamic languages, local namespaces in Elvish are 816 statically checked. This means that referencing a nonexistent variable results 817 in a compilation error, which is triggered before any code is actually 818 evaluated: 819 820 ```elvish-transcript 821 ~> echo $x 822 Compilation error: variable $x not found 823 [tty], line 1: echo $x 824 ~> f = { echo $x } 825 compilation error: variable $x not found 826 [tty 1], line 1: f = { echo $x } 827 ``` 828 829 If a variable contains a list value, you can add `@` before the variable name; 830 this evaluates to all the elements within the list. This is called **exploding** 831 the variable: 832 833 ```elvish-transcript 834 ~> li = [lorem ipsum foo bar] 835 ~> put $li 836 ▶ [lorem ipsum foo bar] 837 ~> put $@li 838 ▶ lorem 839 ▶ ipsum 840 ▶ foo 841 ▶ bar 842 ``` 843 844 **Note**: Since variable uses have higher precedence than [indexing](#indexing), 845 this does not work for exploding a list that is an element of another list. For 846 doing that, and exploding the result of other expressions (such as an output 847 capture), use the builtin [all](builtin.html#all) command.) 848 849 ## Output capture 850 851 An **output capture** expression is formed by putting parentheses `()` around a 852 [code chunk](#code-chunk). It redirects the output of the chunk into an internal 853 pipe, and evaluates to all the values that have been output. 854 855 ```elvish-transcript 856 ~> + 1 10 100 857 ▶ 111 858 ~> x = (+ 1 10 100) 859 ~> put $x 860 ▶ 111 861 ~> put lorem ipsum 862 ▶ lorem 863 ▶ ipsum 864 ~> x y = (put lorem ipsum) 865 ~> put $x 866 ▶ lorem 867 ~> put $y 868 ▶ ipsum 869 ``` 870 871 If the chunk outputs bytes, Elvish strips the last newline (if any), and split 872 them by newlines, and consider each line to be one string value: 873 874 ```elvish-transcript 875 ~> put (echo "a\nb") 876 ▶ a 877 ▶ b 878 ``` 879 880 Trailing carriage returns are also stripped from each line, which effectively 881 makes `\r\n` also valid line separators: 882 883 ```elvish-transcript 884 ~> put (echo "a\r\nb") 885 ▶ a 886 ▶ b 887 ``` 888 889 **Note 1**. Only the last newline is ever removed, so empty lines are preserved; 890 `(echo "a\n")` evaluates to two values, `"a"` and `""`. 891 892 **Note 2**. One consequence of this mechanism is that you can not distinguish 893 outputs that lack a trailing newline from outputs that have one; `(echo what)` 894 evaluates to the same value as `(print what)`. If such a distinction is needed, 895 use [`slurp`](builtin.html#slurp) to preserve the original bytes output. 896 897 If the chunk outputs both values and bytes, the values of output capture will 898 contain both value outputs and lines. However, the ordering between value output 899 and byte output might not agree with the order in which they happened: 900 901 ```elvish-transcript 902 ~> put (put a; echo b) # value order need not be the same as output order 903 ▶ b 904 ▶ a 905 ``` 906 907 ## Exception capture 908 909 An **exception capture** expression is formed by putting `?()` around a code 910 chunk. It runs the chunk and evaluates to the exception it throws. 911 912 ```elvish-transcript 913 ~> fail bad 914 Exception: bad 915 Traceback: 916 [interactive], line 1: 917 fail bad 918 ~> put ?(fail bad) 919 ▶ ?(fail bad) 920 ``` 921 922 If there was no error, it evaluates to the special value `$ok`: 923 924 ```elvish-transcript 925 ~> nop 926 ~> put ?(nop) 927 ▶ $ok 928 ``` 929 930 Exceptions are booleanly false and `$ok` is booleanly true. This is useful in 931 `if` (introduced later): 932 933 ```elvish-transcript 934 if ?(test -d ./a) { 935 # ./a is a directory 936 } 937 ``` 938 939 **Note**: Exception captures do not affect the output of the code chunk. You can 940 combine output capture and exception capture: 941 942 ```elvish 943 output = (error = ?(commands-that-may-fail)) 944 ``` 945 946 ## Braced list 947 948 A **braced list** consists of multiple expressions separated by whitespaces and 949 surrounded by braces (`{}`). There must be no space after the opening brace. A 950 braced list evaluates to whatever the expressions inside it evaluate to. Its 951 most typical use is grouping multiple values in a 952 [compound expression](#compounding). Example: 953 954 ```elvish-transcript 955 ~> put {a b}-{1 2} 956 ▶ a-1 957 ▶ a-2 958 ▶ b-1 959 ▶ b-2 960 ``` 961 962 It can also be used to affect the [order of evaluation](#order-of-evaluation). 963 Examples: 964 965 ```elvish-transcript 966 ~> put * 967 ▶ foo 968 ▶ bar 969 ~> put *o 970 ▶ foo 971 ~> put {*}o 972 ▶ fooo 973 ▶ baro 974 ``` 975 976 **Note**: When used to affect the order of evaluation, braced lists are very 977 similar to parentheses in C-like languages. 978 979 **Note**: A braced list is an expression. It is a syntactical construct and not 980 a separate data structure. 981 982 Elvish currently also supports using commas to separate items in a braced list. 983 This will likely be removed in future, but it also means that literal commas 984 must be quoted right now. 985 986 ## Indexing 987 988 An **indexing expression** is formed by appending one or more indices inside a 989 pair of brackets (`[]`) after another expression (the indexee). Examples: 990 991 ```elvish-transcript 992 ~> li = [foo bar] 993 ~> put $li[0] 994 ▶ foo 995 ~> li = [[foo bar] quux] 996 ~> put $li[0][0] 997 ▶ foo 998 ~> put [[foo bar]][0][0] 999 ▶ foo 1000 ``` 1001 1002 If the expression being indexed evaluates to multiple values, the indexing 1003 operation is applied on each value. Example: 1004 1005 ```elvish-transcript 1006 ~> put (put [foo bar] [lorem ipsum])[0] 1007 ▶ foo 1008 ▶ lorem 1009 ~> put {[foo bar] [lorem ipsum]}[0] 1010 ▶ foo 1011 ▶ lorem 1012 ``` 1013 1014 If there are multiple index expressions, or the index expression evaluates to 1015 multiple values, the indexee is indexed once for each of the index value. 1016 Examples: 1017 1018 ```elvish-transcript 1019 ~> put elv[0 2 0..2] 1020 ▶ e 1021 ▶ v 1022 ▶ el 1023 ~> put [lorem ipsum foo bar][0 2 0..2] 1024 ▶ lorem 1025 ▶ foo 1026 ▶ [lorem ipsum] 1027 ~> put [&a=lorem &b=ipsum &a..b=haha][a a..b] 1028 ▶ lorem 1029 ▶ haha 1030 ``` 1031 1032 If both the indexee and index evaluate to multiple values, the results generated 1033 from the first indexee appear first. Example: 1034 1035 ```elvish-transcript 1036 ~> put {[foo bar] [lorem ipsum]}[0 1] 1037 ▶ foo 1038 ▶ bar 1039 ▶ lorem 1040 ▶ ipsum 1041 ``` 1042 1043 ## Compounding 1044 1045 A **compound expression** is formed by writing several expressions together with 1046 no space in between. A compound expression evaluates to a string concatenation 1047 of all the constituent expressions. Examples: 1048 1049 ```elvish-transcript 1050 ~> put 'a'b"c" # compounding three string literals 1051 ▶ abc 1052 ~> v = value 1053 ~> put '$v is '$v # compounding one string literal with one string variable 1054 ▶ '$v is value' 1055 ``` 1056 1057 When one or more of the constituent expressions evaluate to multiple values, the 1058 result is all possible combinations: 1059 1060 ```elvish-transcript 1061 ~> li = [foo bar] 1062 ~> put {a b}-$li[0 1] 1063 ▶ a-foo 1064 ▶ a-bar 1065 ▶ b-foo 1066 ▶ b-bar 1067 ``` 1068 1069 The order of the combinations is determined by first taking the first value in 1070 the leftmost expression that generates multiple values, and then taking the 1071 second value, and so on. 1072 1073 ## Tilde expansion 1074 1075 An unquoted tilde at the beginning of a compound expression triggers **tilde 1076 expansion**. The remainder of this expression must be a string. The part from 1077 the beginning of the string up to the first `/` (or the end of the word if the 1078 string does not contain `/`), is taken as a user name; and they together 1079 evaluate to the home directory of that user. If the user name is empty, the 1080 current user is assumed. 1081 1082 In the following example, the home directory of the current user is 1083 `/home/xiaq`, while that of the root user is `/root`: 1084 1085 ```elvish-transcript 1086 ~> put ~ 1087 ▶ /home/xiaq 1088 ~> put ~root 1089 ▶ /root 1090 ~> put ~/xxx 1091 ▶ /home/xiaq/xxx 1092 ~> put ~root/xxx 1093 ▶ /root/xxx 1094 ``` 1095 1096 Note that tildes are not special when they appear elsewhere in a word: 1097 1098 ```elvish-transcript 1099 ~> put a~root 1100 ▶ a~root 1101 ``` 1102 1103 If you need them to be, use a [braced list](#braced-list): 1104 1105 ```elvish-transcript 1106 ~> put a{~root} 1107 ▶ a/root 1108 ``` 1109 1110 ## Wildcard expansion 1111 1112 **Wildcard patterns** are expressions that contain **wildcards**. Wildcard 1113 patterns evaluate to all filenames they match. 1114 1115 In examples in this section, we will assume that the current directory has the 1116 following structure: 1117 1118 ``` 1119 .x.conf 1120 a.cc 1121 ax.conf 1122 foo.cc 1123 d/ 1124 |__ .x.conf 1125 |__ ax.conf 1126 |__ y.cc 1127 .d2/ 1128 |__ .x.conf 1129 |__ ax.conf 1130 ``` 1131 1132 Elvish supports the following wildcards: 1133 1134 - `?` matches one arbitrary character except `/`. For example, `?.cc` matches 1135 `a.cc`; 1136 1137 - `*` matches any number of arbitrary characters except `/`. For example, 1138 `*.cc` matches `a.cc` and `foo.cc`; 1139 1140 - `**` matches any number of arbitrary characters including `/`. For example, 1141 `**.cc` matches `a.cc`, `foo.cc` and `b/y.cc`. 1142 1143 The following behaviors are default, although they can be altered by modifiers: 1144 1145 - When the entire wildcard pattern has no match, an error is thrown. 1146 1147 - None of the wildcards matches `.` at the beginning of filenames. For 1148 example: 1149 1150 - `?x.conf` does not match `.x.conf`; 1151 1152 - `d/*.conf` does not match `d/.x.conf`; 1153 1154 - `**.conf` does not match `d/.x.conf`. 1155 1156 Wildcards can be **modified** using the same syntax as indexing. For instance, 1157 in `*[match-hidden]` the `*` wildcard is modified with the `match-hidden` 1158 modifier. Multiple matchers can be chained like `*[set:abc][range:0-9]`. In 1159 which case they are OR'ed together. 1160 1161 There are two kinds of modifiers: 1162 1163 **Global modifiers** apply to the whole pattern and can be placed after any 1164 wildcard: 1165 1166 - `nomatch-ok` tells Elvish not to throw an error when there is no match for 1167 the pattern. For instance, in the example directory `put bad*` will be an 1168 error, but `put bad*[nomatch-ok]` does exactly nothing. 1169 1170 - `but:xxx` (where `xxx` is any filename) excludes the filename from the final 1171 result. 1172 1173 - `type:xxx` (where `xxx` is a recognized file type from the list below). Only 1174 one type modifier is allowed. For example, to find the directories at any 1175 level below the current working directory: `**[type:dir]`. 1176 1177 - `dir` will match if the path is a directory. 1178 1179 - `regular` will match if the path is a regular file. 1180 1181 Although global modifiers affect the entire wildcard pattern, you can add it 1182 after any wildcard, and the effect is the same. For example, 1183 `put */*[nomatch-ok].cpp` and `put *[nomatch-ok]/*.cpp` do the same thing. On 1184 the other hand, you must add it after a wildcard, instead of after the entire 1185 pattern: `put */*.cpp[nomatch-ok]` unfortunately does not do the correct thing. 1186 (This will probably be fixed.) 1187 1188 **Local modifiers** only apply to the wildcard it immediately follows: 1189 1190 - `match-hidden` tells the wildcard to match `.` at the beginning of 1191 filenames, e.g. `*[match-hidden].conf` matches `.x.conf` and `ax.conf`. 1192 1193 Being a local modifier, it only applies to the wildcard it immediately 1194 follows. For instance, `*[match-hidden]/*.conf` matches `d/ax.conf` and 1195 `.d2/ax.conf`, but not `d/.x.conf` or `.d2/.x.conf`. 1196 1197 - Character matchers restrict the characters to match: 1198 1199 - Character sets, like `set:aeoiu`; 1200 1201 - Character ranges like `range:a-z` (including `z`) or `range:a~z` 1202 (excluding `z`); 1203 1204 - Character classes: `control`, `digit`, `graphic`, `letter`, `lower`, 1205 `mark`, `number`, `print`, `punct`, `space`, `symbol`, `title`, and 1206 `upper`. See the Is\* functions [here](https://godoc.org/unicode) for 1207 their definitions. 1208 1209 Note the following caveats: 1210 1211 - Local matchers chained together in separate modifiers are OR'ed. For 1212 instance, `?[set:aeoiu][digit]` matches all files with the chars `aeoiu` or 1213 containing a digit. 1214 1215 - Local matchers combined in the same modifier, such as `?[set:aeoiu digit]`, 1216 behave in a hard to explain manner. Do not use this form as **the behavior 1217 is likely to change in the future.** 1218 1219 - Dots at the beginning of filenames always require an explicit 1220 `match-hidden`, even if the matcher includes `.`. For example, 1221 `?[set:.a]x.conf` does **not** match `.x.conf`; you have to 1222 `?[set:.a match-hidden]x.conf`. 1223 1224 - Likewise, you always need to use `**` to match slashes, even if the matcher 1225 includes `/`. For example `*[set:abc/]` is the same as `*[set:abc]`. 1226 1227 ## Order of evaluation 1228 1229 An expression can use a combination of indexing, tilde expansion, wildcard and 1230 compounding. The order of evaluation is as follows: 1231 1232 1. Literals, variable uses, output captures and exception captures and braced 1233 lists have the highest precedence and are evaluated first. 1234 1235 2. Indexing has the next highest precedence and is then evaluated first. 1236 1237 3. Expression compounding then happens. Tildes and wildcards are kept 1238 unevaluated. 1239 1240 4. If the expression starts with a tilde, tilde expansion happens. If the tilde 1241 is followed by a wildcard, an exception is raised. 1242 1243 5. If the expression contains any wildcard, wildcard expansion happens. 1244 1245 Here an example: in `~/$li[0 1]/*` (where `$li` is a list `[foo bar]`), the 1246 expression is evaluated as follows: 1247 1248 1. The variable use `$li` evaluates to the list `[foo bar]`. 1249 1250 2. The indexing expression `$li[0]` evaluates to two strings `foo` and `bar`. 1251 1252 3. Compounding the expression, the result is `~/foo/*` and `~/bar/*`. 1253 1254 4. Tilde expansion happens; assuming that the user's home directory is 1255 `/home/elf`, the values are now `/home/elf/foo/*` and `/home/elf/bar/*`. 1256 1257 5. Wildcard expansion happens, evaluating the expression to all the filenames 1258 within `/home/elf/foo` and `/home/elf/bar`. If any directory is empty or 1259 nonexistent, an exception is thrown. 1260 1261 To force a particular order of evaluation, group expressions using a 1262 [braced list](#braced-list). 1263 1264 # Command forms 1265 1266 A **command form** is either an [ordinary command](#ordinary-command), a 1267 [special command](#special-command) or an 1268 [legacy assignment form](#legacy-assignment-form). All of three different types 1269 can have [redirections](#redirection). 1270 1271 When Elvish parses a command form, it applies the following process to decide 1272 its type: 1273 1274 - If the command form contains an unquoted equal sign surrounded by inline 1275 whitespaces, it is an ordinary assignment. 1276 1277 - If the first expression in the command form contains a single string 1278 literal, and the string value matches one of the special commands, it is a 1279 special command. 1280 1281 - Otherwise, it is an ordinary command. 1282 1283 ## Ordinary command 1284 1285 An **ordinary command** form consists of a command head, and any number of 1286 arguments and options. 1287 1288 The first expression in an ordinary command is the command **head**. If the head 1289 is a single string literal it is subject to **static resolution**: 1290 1291 - If a variable with name `head~` (where `head` is the value of the head) 1292 exists, the head will evaluate as if it is `$head~`; i.e., a function 1293 invocation. 1294 1295 - Otherwise, the head will evaluate to an external command with the name 1296 `head`. 1297 1298 If the head is not a single string literal, it is evaluated as a normal 1299 expression. The expression must evaluate to one value, and the value must be one 1300 of the following: 1301 1302 - A callable value: a function or external command. 1303 1304 - A string containing at least one slash, in which case it is treated like an 1305 external command with the string value as its path. 1306 1307 Examples of commands using static resolution: 1308 1309 ```elvish-transcript 1310 ~> put x # resolves to builtin function $put~ 1311 ▶ x 1312 ~> f~ = { put 'this is f' } 1313 ~> f # resolves to user-defined function $f~ 1314 ▶ 'this is f' 1315 ~> whoami # resolves to external command whoami 1316 elf 1317 ``` 1318 1319 Examples of commands using a dynamic callable head: 1320 1321 ```elvish-transcript 1322 ~> $put~ x 1323 ▶ x 1324 ~> (external whoami) 1325 elf 1326 ~> { put 'this is a lambda' } 1327 ▶ 'this is a lambda' 1328 ``` 1329 1330 **Note**: The last command resembles a code block in C-like languages in syntax, 1331 but is quite different under the hood: it works by defining a function on the 1332 fly and calling it immediately. 1333 1334 Examples of commands using a dynamic string head: 1335 1336 ```elvish-transcript 1337 ~> x = /bin/whoami 1338 ~> $x 1339 elf 1340 ~> x = whoami 1341 ~> $x # dynamic strings can only used when containing slash 1342 Exception: bad value: command must be callable or string containing slash, but is string 1343 [tty 10], line 1: $x 1344 ``` 1345 1346 The definition of barewords is relaxed when parsing the head, and includes `<`, 1347 `>`, and `*`. These are all names of numeric builtins: 1348 1349 ```elvish-transcript 1350 ~> < 3 5 # less-than 1351 ▶ $true 1352 ~> > 3 5 # greater-than 1353 ▶ $false 1354 ~> * 3 5 # multiplication 1355 ▶ 15 1356 ``` 1357 1358 **Arguments** and **options** can be supplied to commands. Arguments are 1359 arbitrary words, while options have exactly the same syntax as key-value pairs 1360 in [map literals](#map). They are separated by inline whitespaces and may be 1361 intermixed: 1362 1363 ```elvish-transcript 1364 ~> echo &sep=, a b c # &seq=, is an option; a b c are arguments 1365 a,b,c 1366 ~> echo a b &sep=, c # same, with the option mixed within arguments 1367 a,b,c 1368 ``` 1369 1370 **Note**: Since options have the same syntax as key-value pairs in maps, `&key` 1371 is equivalent to `&key=$true`: 1372 1373 ```elvish-transcript 1374 ~> fn f [&opt=$false]{ put $opt } 1375 ~> f &opt 1376 ▶ $true 1377 ``` 1378 1379 ## Special command 1380 1381 A **special command** form has the same syntax with an ordinary command, but how 1382 it is executed depends on the command head. See 1383 [special commands](#special-commands). 1384 1385 ## Legacy assignment form 1386 1387 If any argument in a command form is an unquoted equal sign (`=`), the command 1388 form is treated as an assignment form: the arguments to the left of `=`, 1389 including the head, are treated as lvalues, and the arguments to the right of 1390 `=` are treated as values to assign to those lvalues. 1391 1392 If any lvalue refers to a variable that doesn't yet exist, it is created first. 1393 1394 This is a legacy syntax that will be deprecated in future. Use the [`var`](#var) 1395 special command to declare variables, and the [`set`](#set) special command set 1396 the values of variables. 1397 1398 ## Temporary assignment 1399 1400 You can prepend any command form with **temporary assignments**, which gives 1401 variables temporarily values during the execution of that command. 1402 1403 In the following example, `$x` and `$y` are temporarily assigned 100 and 200: 1404 1405 ```elvish-transcript 1406 ~> x y = 1 2 1407 ~> x=100 y=200 + $x $y 1408 ▶ 300 1409 ~> echo $x $y 1410 1 2 1411 ``` 1412 1413 In contrary to normal assignments, there should be no whitespaces around the 1414 equal sign `=`. To have multiple variables in the left-hand side, use braces: 1415 1416 ```elvish-transcript 1417 ~> x y = 1 2 1418 ~> fn f { put 100 200 } 1419 ~> {x,y}=(f) + $x $y 1420 ▶ 300 1421 ``` 1422 1423 If you use a previously undefined variable in a temporary assignment, its value 1424 will become the empty string after the command finishes. This behavior will 1425 likely change; don't rely on it. 1426 1427 Since ordinary assignments are also command forms, they can also be prepended 1428 with temporary assignments: 1429 1430 ```elvish-transcript 1431 ~> x=1 1432 ~> x=100 y = (+ 133 $x) 1433 ~> put $x $y 1434 ▶ 1 1435 ▶ 233 1436 ``` 1437 1438 Temporary assignments must all appear at the beginning of the command form. As 1439 soon as something that is not a temporary assignments is parsed, Elvish no 1440 longer parses temporary assignments. For instance, in `x=1 echo x=1`, the second 1441 `x=1` is not a temporary assignment, but a bareword. 1442 1443 **Note**: Elvish's behavior differs from bash (or zsh) in one important place. 1444 In bash, temporary assignments to variables do not affect their direct 1445 appearance in the command: 1446 1447 ```sh-transcript 1448 bash-4.4$ x=1 1449 bash-4.4$ x=100 echo $x 1450 1 1451 ``` 1452 1453 **Note**: Elvish currently supports using the syntax of temporary assignments 1454 for ordinary assignments, when they are not followed by a command form; for 1455 example, `a=x` behaves like an ordinary assignment `a = x`. This will likely go 1456 away; don't rely on it. 1457 1458 ## Redirection 1459 1460 <!-- TODO: Describe the syntax and behavior more formally. --> 1461 1462 You can add **redirections** to any command form, to modify the file descriptors 1463 these command form operate with. 1464 1465 The most common form of redirections opens a file and associates it with an FD. 1466 The form consists of an optional destination FD (like `2`), a redirection 1467 operator (like `>`) and a filename (like `error.log`): 1468 1469 - The **destination fd** determines which FD to modify. It can be given either 1470 as a number, or one of `stdin`, `stdout` and `stderr`. There must be no 1471 space between the FD and the redirection operator; otherwise Elvish will 1472 parse it as an argument. 1473 1474 The destination FD can be omitted, in which case it is inferred from the 1475 redirection operator. 1476 1477 - The **redirection operator** determines the mode to open the file, and the 1478 destination FD if it is not explicitly specified. 1479 1480 - The **filename** names the file to open. 1481 1482 Possible redirection operators and their default FDs are: 1483 1484 - `<` for reading. The default FD is 0 (stdin). 1485 1486 - `>` for writing. The default FD is 1 (stdout). 1487 1488 - `>>` for appending. The default FD is 1 (stdout). 1489 1490 - `<>` for reading and writing. The default FD is 1 (stdout). 1491 1492 Examples: 1493 1494 ```elvish-transcript 1495 ~> echo haha > log 1496 ~> cat log 1497 haha 1498 ~> cat < log 1499 haha 1500 ~> ls --bad-arg 2> error 1501 Exception: ls exited with 2 1502 Traceback: 1503 [interactive], line 1: 1504 ls --bad-arg 2> error 1505 ~> cat error 1506 /bin/ls: unrecognized option '--bad-arg' 1507 Try '/bin/ls --help' for more information. 1508 ``` 1509 1510 Redirections can also be used for closing or duplicating FDs. Instead of writing 1511 a filename, use `&fd` (where `fd` is a number, or any of `stdin`, `stdout` and 1512 `stderr`) for duplicating, or `&-` for closing. In this case, the redirection 1513 operator only determines the default destination FD (and is totally irrevelant 1514 if a destination FD is specified). Examples: 1515 1516 ```elvish-transcript 1517 ~> ls >&- # close stdout 1518 /bin/ls: write error: Bad file descriptor 1519 Exception: ls exited with 2 1520 Traceback: 1521 [interactive], line 1: 1522 ls >&- 1523 ``` 1524 1525 If you have multiple related redirections, they are applied in the order they 1526 appear. For instance: 1527 1528 ```elvish-transcript 1529 ~> fn f { echo out; echo err >&2 } # echoes "out" on stdout, "err" on stderr 1530 ~> f >log 2>&1 # use file "log" for stdout, then use (changed) stdout for stderr 1531 ~> cat log 1532 out 1533 err 1534 ``` 1535 1536 Redirections may appear anywhere in the command, except at the beginning, 1537 although this may be restricted in future. It's usually good style to write 1538 redirections at the end of command forms. 1539 1540 **Note:** Elvish only supports reading and writing bytes from/to the target of a 1541 redirection. Attemping to read values from a file or a a 1542 [pipe](builtin.html#pipe) via redirection will produce no values, and all values 1543 written to a file or a pipe will be discarded. Examples: 1544 1545 - Running `put foo > data` will not write anything to the file `data`, other 1546 than truncating it. 1547 1548 - Assuming the file `data` contains a single line `hello`, 1549 `only-values < data` will not do anything. 1550 1551 # Special commands 1552 1553 **Special commands** obey the same syntax rules as normal commands, but have 1554 evaluation rules that are custom to each command. Consider the following 1555 example: 1556 1557 ```elvish-transcript 1558 ~> or ?(echo x) ?(echo y) ?(echo z) 1559 x 1560 ▶ $ok 1561 ``` 1562 1563 In the example, the `or` command first evaluates its first argument, which has 1564 the value `$ok` (a truish value) and the side effect of outputting `x`. Due to 1565 the custom evaluation rule of `or`, the rest of the arguments are not evaluated. 1566 1567 If `or` were a normal command, the code above is still syntactically correct. 1568 However, Elvish would then evaluate all its arguments, with the side effect of 1569 outputting `x`, `y` and `z`, before calling `or`. 1570 1571 ## Declaring variables: `var` {#var} 1572 1573 The `var` special command declares local variables. It takes any number of 1574 unqualified variable names (without the leading `$`). The variables will start 1575 out having value `$nil`. Examples: 1576 1577 ```elvish-transcript 1578 ~> var a 1579 ~> put $a 1580 ▶ $nil 1581 ~> var foo bar 1582 ~> put $foo $bar 1583 ▶ $nil 1584 ▶ $nil 1585 ``` 1586 1587 To set alternative initial values, add an unquoted `=` and the initial values. 1588 Examples: 1589 1590 ```elvish-transcript 1591 ~> var a b = foo bar 1592 ~> put $a $b 1593 ▶ foo 1594 ▶ bar 1595 ``` 1596 1597 Similar to [`set`](#set), at most one of variables may be prefixed with `@` to 1598 function as a rest variable. 1599 1600 When declaring a variable that already exists, the existing variable is 1601 shadowed. The shadowed variable may still be accessed indirectly if it is 1602 referenced by a function. Example: 1603 1604 ```elvish-transcript 1605 ~> var x = old 1606 ~> fn f { put $x } 1607 ~> var x = new 1608 ~> put $x 1609 ▶ new 1610 ~> f 1611 ▶ old 1612 ``` 1613 1614 ## Setting the value of variables or elements: `set` {#set} 1615 1616 The `set` special command sets the value of variables or elements. 1617 1618 It takes any number of **lvalues** (which refer to either variables or 1619 elements), followed by an equal sign (`=`) and any number of expressions. The 1620 equal sign must appear unquoted, as a single argument. 1621 1622 An **lvalue** is one of the following: 1623 1624 - A variable name (without `$`). 1625 1626 - A variable name prefixed with `@`, for packing a variable number of values 1627 into a list and assigning to the variable. 1628 1629 This variant is called a **rest variable**. There could be at most one rest 1630 variable. 1631 1632 **Note**: Schematically this is the reverse operation of exploding a 1633 variable when [using](#variable-use) it, which is why they share the `@` 1634 sign. 1635 1636 - A variable name followed by one or more indices in brackets (`[]`), for 1637 assigning to an element. 1638 1639 The number of values the expressions evaluate to and lvalues must be compatible. 1640 To be more exact: 1641 1642 - If there is no rest variable, the number of values and lvalues must match 1643 exactly. 1644 1645 - If there is a rest variable, the number of values should be at least the 1646 number of lvalues minus one. 1647 1648 All the variables to set must already exist; use the [`var`](#var) special 1649 command to declare new variables. 1650 1651 Examples: 1652 1653 ```elvish-transcript 1654 ~> var x y z 1655 ~> set x = foo 1656 ~> put $x 1657 ▶ foo 1658 ~> x y = lorem ipsum 1659 ~> put $x $y 1660 ▶ lorem 1661 ▶ ipsum 1662 ~> set x @y z = a b 1663 ~> put $x $y $z 1664 ▶ a 1665 ▶ [] 1666 ▶ b 1667 ~> set x @y z = a b c d 1668 ~> put $x $y $z 1669 ▶ a 1670 ▶ [b c] 1671 ▶ d 1672 ~> set y[0] = foo 1673 ~> put $y 1674 ▶ [foo c] 1675 ``` 1676 1677 If the variable name contains any character that may not appear unquoted in 1678 [variable use expressions](#variable-use), it must be quoted even if it is 1679 otherwise a valid bareword: 1680 1681 ```elvish-transcript 1682 ~> var 'a/b' 1683 ~> set a/b = foo 1684 compilation error: lvalue must be valid literal variable names 1685 [tty 23], line 1: a/b = foo 1686 ~> set 'a/b' = foo 1687 ~> put $'a/b' 1688 ▶ foo 1689 ``` 1690 1691 Lists and maps in Elvish are immutable. As a result, when assigning to the 1692 element of a variable that contains a list or map, Elvish does not mutate the 1693 underlying list or map. Instead, Elvish creates a new list or map with the 1694 mutation applied, and assigns it to the variable. Example: 1695 1696 ```elvish-transcript 1697 ~> var li = [foo bar] 1698 ~> var li2 = $li 1699 ~> set li[0] = lorem 1700 ~> put $li $li2 1701 ▶ [lorem bar] 1702 ▶ [foo bar] 1703 ``` 1704 1705 ## Deleting variables or elements: `del` {#del} 1706 1707 The `del` special command can be used to delete variables or map elements. 1708 Operands should be specified without a leading dollar sign, like the left-hand 1709 side of assignments. 1710 1711 Example of deleting variable: 1712 1713 ```elvish-transcript 1714 ~> x = 2 1715 ~> echo $x 1716 2 1717 ~> del x 1718 ~> echo $x 1719 Compilation error: variable $x not found 1720 [tty], line 1: echo $x 1721 ``` 1722 1723 If the variable name contains any character that cannot appear unquoted after 1724 `$`, it must be quoted, even if it is otherwise a valid bareword: 1725 1726 ```elvish-transcript 1727 ~> 'a/b' = foo 1728 ~> del 'a/b' 1729 ``` 1730 1731 Deleting a variable does not affect closures that have already captured it; it 1732 only removes the name. Example: 1733 1734 ```elvish-transcript 1735 ~> x = value 1736 ~> fn f { put $x } 1737 ~> del x 1738 ~> f 1739 ▶ value 1740 ``` 1741 1742 Example of deleting map element: 1743 1744 ```elvish-transcript 1745 ~> m = [&k=v &k2=v2] 1746 ~> del m[k2] 1747 ~> put $m 1748 ▶ [&k=v] 1749 ~> l = [[&k=v &k2=v2]] 1750 ~> del l[0][k2] 1751 ~> put $l 1752 ▶ [[&k=v]] 1753 ``` 1754 1755 ## Logics: `and` and `or` {#and-or} 1756 1757 The `and` special command evaluates its arguments from left to right; as soon as 1758 a booleanly false value is obtained, it outputs the value and stops. When given 1759 no arguments, it outputs `$true`. 1760 1761 The `or` special command is the same except that it stops when a booleanly true 1762 value is obtained. When given no arguments, it outpus `$false`. 1763 1764 ## Condition: `if` {#if} 1765 1766 **TODO**: Document the syntax notation, and add more examples. 1767 1768 Syntax: 1769 1770 ```elvish-transcript 1771 if <condition> { 1772 <body> 1773 } elif <condition> { 1774 <body> 1775 } else { 1776 <else-body> 1777 } 1778 ``` 1779 1780 The `if` special command goes through the conditions one by one: as soon as one 1781 evaluates to a booleanly true value, its corresponding body is executed. If none 1782 of conditions are booleanly true and an else body is supplied, it is executed. 1783 1784 The condition part is an expression, not a command like in other shells. 1785 Example: 1786 1787 ```elvish 1788 fn tell-language [fname]{ 1789 if (has-suffix $fname .go) { 1790 echo $fname" is a Go file!" 1791 } elif (has-suffix $fname .c) { 1792 echo $fname" is a C file!" 1793 } else { 1794 echo $fname" is a mysterious file!" 1795 } 1796 } 1797 ``` 1798 1799 The condition part must be syntactically a single expression, but it can 1800 evaluate to multiple values, in which case they are and'ed: 1801 1802 ```elvish 1803 if (put $true $false) { 1804 echo "will not be executed" 1805 } 1806 ``` 1807 1808 If the expression evaluates to 0 values, it is considered true, consistent with 1809 how `and` works. 1810 1811 Tip: a combination of `if` and `?()` gives you a semantics close to other 1812 shells: 1813 1814 ```elvish 1815 if ?(test -d .git) { 1816 # do something 1817 } 1818 ``` 1819 1820 However, for Elvish's builtin predicates that output values instead of throw 1821 exceptions, the output capture construct `()` should be used. 1822 1823 ## Conditional loop: `while` {#while} 1824 1825 Syntax: 1826 1827 ```elvish-transcript 1828 while <condition> { 1829 <body> 1830 } else { 1831 <else-body> 1832 } 1833 ``` 1834 1835 Execute the body as long as the condition evaluates to a booleanly true value. 1836 1837 The else body, if present, is executed if the body has never been executed (i.e. 1838 the condition evaluates to a booleanly false value in the very beginning). 1839 1840 ## Iterative loop: `for` {#for} 1841 1842 Syntax: 1843 1844 ```elvish-transcript 1845 for <var> <container> { 1846 <body> 1847 } else { 1848 <body> 1849 } 1850 ``` 1851 1852 Iterate the container (e.g. a list). In each iteration, assign the variable to 1853 an element of the container and execute the body. 1854 1855 The else body, if present, is executed if the body has never been executed (i.e. 1856 the iteration value has no elements). 1857 1858 ## Exception control: `try` {#try} 1859 1860 (If you just want to capture the exception, you can use the more concise 1861 exception capture construct `?()` instead.) 1862 1863 Syntax: 1864 1865 ```elvish-transcript 1866 try { 1867 <try-block> 1868 } except except-varname { 1869 <except-block> 1870 } else { 1871 <else-block> 1872 } finally { 1873 <finally-block> 1874 } 1875 ``` 1876 1877 Only `try` and `try-block` are required. This control structure behaves as 1878 follows: 1879 1880 1. The `try-block` is always executed first. 1881 1882 2. If `except` is present and an exception occurs in `try-block`, it is caught 1883 and stored in `except-varname`, and `except-block` is then executed. 1884 Example: 1885 1886 ```elvish-transcript 1887 ~> try { fail bad } except e { put $e } 1888 ▶ ?(fail bad) 1889 ``` 1890 1891 Note that if `except` is not present, exceptions thrown from `try` are not 1892 caught: for instance, `try { fail bad }` throws `bad`; it is equivalent to a 1893 plain `fail bad`. 1894 1895 Note that the word after `except` names a variable, not a matching 1896 condition. Exception matching is not supported yet. For instance, you may 1897 want to only match exceptions that were created with `fail bad` with 1898 `except bad`, but in fact this creates a variable `$bad` that contains 1899 whatever exception was thrown. 1900 1901 3. If no exception occurs and `else` is present, `else-block` is executed. 1902 Example: 1903 1904 ```elvish-transcript 1905 ~> try { nop } else { echo well } 1906 well 1907 ``` 1908 1909 4. If `finally-block` is present, it is executed. Examples: 1910 1911 ```elvish-transcript 1912 ~> try { fail bad } finally { echo final } 1913 final 1914 Exception: bad 1915 Traceback: 1916 [tty], line 1: 1917 try { fail bad } finally { echo final } 1918 ~> try { echo good } finally { echo final } 1919 good 1920 final 1921 ``` 1922 1923 5. If the exception was not caught (i.e. `except` is not present), it is 1924 rethrown. 1925 1926 Exceptions thrown in blocks other than `try-block` are not caught. If an 1927 exception was thrown and either `except-block` or `finally-block` throws another 1928 exception, the original exception is lost. Examples: 1929 1930 ```elvish-transcript 1931 ~> try { fail bad } except e { fail worse } 1932 Exception: worse 1933 Traceback: 1934 [tty], line 1: 1935 try { fail bad } except e { fail worse } 1936 ~> try { fail bad } except e { fail worse } finally { fail worst } 1937 Exception: worst 1938 Traceback: 1939 [tty], line 1: 1940 try { fail bad } except e { fail worse } finally { fail worst } 1941 ``` 1942 1943 ## Function definition: `fn` {#fn} 1944 1945 Syntax: 1946 1947 ```elvish-transcript 1948 fn <name> <lambda> 1949 ``` 1950 1951 Define a function with a given name. The function behaves in the same way to the 1952 lambda used to define it, except that it "captures" `return`. In other words, 1953 `return` will fall through lambdas not defined with `fn`, and continues until it 1954 exits a function defined with `fn`: 1955 1956 ```elvish-transcript 1957 ~> fn f { 1958 { echo a; return } 1959 echo b # will not execute 1960 } 1961 ~> f 1962 a 1963 ~> { 1964 f 1965 echo c # executed, because f "captures" the return 1966 } 1967 a 1968 c 1969 ``` 1970 1971 **TODO**: Find a better way to describe this. Hopefully the example is 1972 illustrative enough, though. 1973 1974 The lambda may refer to the function being defined. This makes it easy to define 1975 recursive functions: 1976 1977 ```elvish-transcript 1978 ~> fn f [n]{ if (== $n 0) { put 1 } else { * $n (f (- $n 1)) } } 1979 ~> f 3 1980 ▶ (float64 6) 1981 ``` 1982 1983 Under the hood, `fn` defines a variable with the given name plus `~` (see 1984 [variable suffix](#variable-suffix)). 1985 1986 # Pipeline 1987 1988 A **pipeline** is formed by joining one or more commands together with the pipe 1989 sign (`|`). 1990 1991 ## IO semantics 1992 1993 For each pair of adjacent commands `a | b`, the output of `a` is connected to 1994 the input of `b`. Both the byte pipe and the value channel are connected, even 1995 if one of them is not used. 1996 1997 Command redirections are applied before the connection happens. For instance, 1998 the following writes `foo` to `a.txt` instead of the output: 1999 2000 ```elvish-transcript 2001 ~> echo foo > a.txt | cat 2002 ~> cat a.txt 2003 foo 2004 ``` 2005 2006 ## Execution flow 2007 2008 All of the commands in a pipeline are executed in parallel, and the execution of 2009 the pipeline finishes when all of its commands finish execution. 2010 2011 If one or more command in a pipeline throws an exception, the other commands 2012 will continue to execute as normal. After all commands finish execution, an 2013 exception is thrown, the value of which depends on the number of commands that 2014 have thrown an exception: 2015 2016 - If only one command has thrown an exception, that exception is rethrown. 2017 2018 - If more than one commands have thrown exceptions, a "composite exception", 2019 containing information all exceptions involved, is thrown. 2020 2021 ## Background pipeline 2022 2023 Adding an ampersand `&` to the end of a pipeline will cause it to be executed in 2024 the background. In this case, the rest of the code chunk will continue to 2025 execute without waiting for the pipeline to finish. Exceptions thrown from the 2026 background pipeline do not affect the code chunk that contains it. 2027 2028 When a background pipeline finishes, a message is printed to the terminal if the 2029 shell is interactive. 2030 2031 # Code Chunk 2032 2033 A **code chunk** is formed by joining zero or more pipelines together, 2034 separating them with either newlines or semicolons. 2035 2036 Pipelines in a code chunk are executed in sequence. If any pipeline throws an 2037 exception, the execution of the whole code chunk stops, propagating that 2038 exception. 2039 2040 # Exception and Flow Commands 2041 2042 Exceptions have similar semantics to those in Python or Java. They can be thrown 2043 with the [fail](builtin.html#fail) command and caught with either exception 2044 capture `?()` or the `try` special command. 2045 2046 If an external command exits with a non-zero status, Elvish treats that as an 2047 exception. 2048 2049 Flow commands -- `break`, `continue` and `return` -- are ordinary builtin 2050 commands that raise special "flow control" exceptions. The `for` and `while` 2051 commands capture `break` and `continue`, while `fn` modifies its closure to 2052 capture `return`. 2053 2054 One interesting implication is that since flow commands are just ordinary 2055 commands you can build functions on top of them. For instance, this function 2056 `break`s randomly: 2057 2058 ```elvish 2059 fn random-break { 2060 if eq (randint 2) 0 { 2061 break 2062 } 2063 } 2064 ``` 2065 2066 The function `random-break` can then be used in for-loops and while-loops. 2067 2068 Note that the `return` flow control exception is only captured by functions 2069 defined with `fn`. It falls through ordinary lambdas: 2070 2071 ```elvish 2072 fn f { 2073 { 2074 # returns f, falling through the innermost lambda 2075 return 2076 } 2077 } 2078 ``` 2079 2080 # Namespaces and Modules 2081 2082 Like other modern programming languages, but unlike traditional shells, Elvish 2083 has a **namespace** mechanism for preventing name collisions. 2084 2085 ## Syntax 2086 2087 Prepend `namespace:` to command names and variable names to specify the 2088 namespace. The following code 2089 2090 ```elvish 2091 e:echo $E:PATH 2092 ``` 2093 2094 uses the `echo` command from the `e:` namespace and the `PATH` variable from the 2095 `E:` namespace. The colon is considered part of the namespace name. 2096 2097 Namespaces may be nested; for example, calling `edit:location:start` first finds 2098 the `edit:` namespace, and then the `location:` namespace inside it, and then 2099 call the `start` function within the nested namespace. 2100 2101 ## Special namespaces 2102 2103 The following namespaces have special meanings to the language: 2104 2105 - `local:` and `up:` refer to lexical scopes, and have been documented above. 2106 2107 - `e:` refers to externals. For instance, `e:ls` refers to the external 2108 command `ls`. 2109 2110 Most of the time you can rely on static resolution rules of 2111 [ordinary commands](#ordinary-command) and do not need to use this 2112 explicitly, unless a function defined by you (or an Elvish builtin) shadows 2113 an external command. 2114 2115 - `E:` refers to environment variables. For instance, `$E:USER` is the 2116 environment variable `USER`. 2117 2118 This **is** always needed, because unlike command resolution, variable 2119 resolution does not fall back onto environment variables. 2120 2121 - `builtin:` refers to builtin functions and variables. 2122 2123 You don't need to use this explicitly unless you have defined names that 2124 shadows builtin counterparts. 2125 2126 ## Modules 2127 2128 Apart from the special namespaces, the most common usage of namespaces is to 2129 reference modules, reusable pieces of code that are either shipped with Elvish 2130 itself or defined by the user. 2131 2132 ### Importing modules with `use` 2133 2134 Modules are imported using the `use` special command, which accepts a **module 2135 spec** and an optional alias: 2136 2137 ```elvish 2138 use $spec $alias? 2139 ``` 2140 2141 Both the module spec and the alias must appear as a single string literal. 2142 2143 The module spec specifies which module to import, and the alias, if given, 2144 specifies the namespace to import the module under. By default, the namespace is 2145 derived from the module spec, by taking the part after the last slash. 2146 2147 Examples: 2148 2149 ```elvish 2150 use str # imports the "str" module as "str:" 2151 use a/b/c # imports the "a/b/c" module as "c:" 2152 use a/b/c foo # imports the "a/b/c" module as "foo:" 2153 ``` 2154 2155 ### Pre-defined modules 2156 2157 Elvish's standard library provides the following pre-defined modules that can be 2158 imported by the `use` command: 2159 2160 - [edit](edit.html) is only available in interactive mode. As a special case 2161 it does not need importing via `use`, but this may change in the future. 2162 - [epm](epm.html) 2163 - [math](math.html) 2164 - [path](path.html) 2165 - [platform](platform.html) 2166 - [re](re.html) 2167 - [readline-binding](readline-binding.html) 2168 - [store](store.html) 2169 - [str](str.html) 2170 - [unix](unix.html) is only available on UNIX-like platforms (see 2171 [`$platform:is-unix`](platform.html#platformis-unix)) 2172 2173 ### User-defined modules 2174 2175 You can define your own modules in Elvish by putting them under `~/.elvish/lib` 2176 and giving them a `.elv` extension. For instance, to define a module named `a`, 2177 store it in `~/.elvish/lib/a.elv`: 2178 2179 ```elvish-transcript 2180 ~> cat ~/.elvish/lib/a.elv 2181 echo "mod a loading" 2182 fn f { 2183 echo "f from mod a" 2184 } 2185 ``` 2186 2187 This module can now be imported by `use a`: 2188 2189 ```elvish-transcript 2190 ~> use a 2191 mod a loading 2192 ~> a:f 2193 f from mod a 2194 ``` 2195 2196 Similarly, a module defined in `~/.elvish/lib/x/y/z.elv` can be imported by 2197 `use x/y/z`: 2198 2199 ```elvish-transcript 2200 ~> cat .elvish/lib/x/y/z.elv 2201 fn f { 2202 echo "f from x/y/z" 2203 } 2204 ~> use x/y/z 2205 ~> z:f 2206 f from x/y/z 2207 ``` 2208 2209 In general, a module defined in namespace will be the same as the file name 2210 (without the `.elv` extension). 2211 2212 ### Circular dependencies 2213 2214 Circular dependencies are allowed but has an important restriction. If a module 2215 `a` contains `use b` and module `b` contains `use a`, the top-level statements 2216 in module `b` will only be able to access variables that are defined before the 2217 `use b` in module `a`; other variables will be `$nil`. 2218 2219 On the other hand, functions in module `b` will have access to bindings in 2220 module `a` after it is fully evaluated. 2221 2222 Examples: 2223 2224 ```elvish-transcript 2225 ~> cat a.elv 2226 var before = before 2227 use ./b 2228 var after = after 2229 ~> cat b.elv 2230 use ./a 2231 put $a:before $a:after 2232 fn f { put $a:before $a:after } 2233 ~> use ./a 2234 ▶ before 2235 ▶ $nil 2236 ~> use ./b 2237 ~> b:f 2238 ▶ before 2239 ▶ after 2240 ``` 2241 2242 Note that this behavior can be different depending on whether the REPL imports 2243 `a` or `b` first. In the previous example, if the REPL imports `b` first, it 2244 will have access to all the variables in `a`: 2245 2246 ```elvish-transcript 2247 ~> use ./b 2248 ▶ before 2249 ▶ after 2250 ``` 2251 2252 **Note**: Elvish caches imported modules. If you are trying this locally, run a 2253 fresh Elvish instance with `exec` first. 2254 2255 When you do need to have circular dependencies, it is best to avoid using 2256 variables from the modules in top-level statements, and only use them in 2257 functions. 2258 2259 ### Relative imports 2260 2261 The module spec may being with `./` or `../`, which introduce **relative 2262 imports**. When `use` is invoked from a file, this will import the file relative 2263 to the location of the file. When `use` is invoked at the interactive prompt, 2264 this will import the file relative to the current working directory. 2265 2266 ### Scoping of imports 2267 2268 Namespace imports are lexically scoped. For instance, if you `use` a module 2269 within an inner scope, it is not available outside that scope: 2270 2271 ```elvish 2272 { 2273 use some-mod 2274 some-mod:some-func 2275 } 2276 some-mod:some-func # not valid 2277 ``` 2278 2279 The imported modules themselves are also evaluated in a separate scope. That 2280 means that functions and variables defined in the module does not pollute the 2281 default namespace, and vice versa. For instance, if you define `ls` as a wrapper 2282 function in `rc.elv`: 2283 2284 ```elvish 2285 fn ls [@a]{ 2286 e:ls --color=auto $@a 2287 } 2288 ``` 2289 2290 That definition is not visible in module files: `ls` will still refer to the 2291 external command `ls`, unless you shadow it in the very same module. 2292 2293 ### Re-importing 2294 2295 Modules are cached after one import. Subsequent imports do not re-execute the 2296 module; they only serve the bring it into the current scope. Moreover, the cache 2297 is keyed by the path of the module, not the name under which it is imported. For 2298 instance, if you have the following in `~/.elvish/lib/a/b.elv`: 2299 2300 ```elvish 2301 echo importing 2302 ``` 2303 2304 The following code only prints one `importing`: 2305 2306 ```elvish 2307 { use a/b } 2308 use a/b # only brings mod into the lexical scope 2309 ``` 2310 2311 As does the following: 2312 2313 ```elvish 2314 use a/b 2315 use a/b alias 2316 ```