github.com/xiaq/elvish@v0.12.0/website/src/ref/language.md (about) 1 <!-- toc number-sections --> 2 3 # Introduction 4 5 This document describes the Elvish programming language. It tries to be both a 6 specification and an advanced tutorial; if it turns out to be impossible to 7 do these two things at the same time, this document will evolve to a formal 8 specification, and more readable tutorials will be created. 9 10 Examples for one construct might use constructs that have not yet been 11 introduced, so some familiarity with the language is assumed. If you are new 12 to Elvish, start with the [learning materials](/learn). 13 14 **Note to the reader**. Like Elvish itself, this document is a work in 15 progress. Some materials are missing, and some are documented sparingly. If 16 you have found something that should be improved -- even if there is already a 17 "TODO" for it -- please feel free to ask on any of the chat channels 18 advertised on the [homepage](/). Some developer will explain to you, and then 19 update the document. Question-driven documentation :) 20 21 22 # Syntax Convention 23 24 Elvish source code must be UTF-8-encoded. In this document, **character** is a 25 synonym of [Unicode codepoint](https://en.wikipedia.org/wiki/Code_point) or 26 its UTF-8 encoding. 27 28 Also like most shells, Elvish uses whitespaces -- instead of commas, periods 29 or semicolons -- to separate constructs. In this document, an **inline 30 whitespace** is any of: 31 32 * A space (ASCII 0x20) or tab (ASCII 0x9, `"\t"`); 33 34 * A comment: starting with `#` and ending before the next newline or end of 35 file; 36 37 * Line continuation: a backslash followed by a newline. 38 39 A **whitespace** is either an **inline whitespace** or a newline (`"\n"`). 40 41 Like most shells, Elvish has a syntax structure that can be divided into two 42 levels: a **statement** level and an **expression** level. For instance, on 43 the expression level, `"echo"` is a quoted string that evaluates to `echo`; 44 but on the statement level, it is a command that outputs an empty line. This 45 distinction is often clear from the context and sometime the verb used. A 46 statements **executes** to produce side effects; an expression **evaluates** 47 to some values. (The traditional terms for the two levels are "commands" and 48 "words", but those terms are quite ambiguous.) 49 50 51 # String 52 53 The most common data structure in shells is the string. String literals can be 54 quoted or unquoted (barewords). 55 56 ## Quoted 57 58 There are two types of quoted strings in Elvish, single-quoted strings and 59 double-quoted strings. 60 61 In single-quoted strings, all characters represent themselves, except single 62 quotes, which need to be doubled. For instance, ``'*\'`` evaluates to ``*\``, 63 and ``'it''s'`` evaluates to ``it's``. 64 65 In double-quoted strings, the backslash ``\`` introduces a **escape 66 sequence**. For instance, ``"\n"`` evaluates to a newline; ``"\\"`` evaluates 67 to a backslash; invalid escape sequences like ``"\*"`` result in a syntax 68 error. 69 70 **TODO**: Document the full list of supported escape sequences. 71 72 Unlike most other shells, double-quoted strings do not support interpolation. 73 For instance, `"$USER"` simply evaluates to the string `$USER`. To get a 74 similar effect, simply concatenate strings: instead of `"my name is $name"`, 75 write `"my name is "$name`. Under the hood this is a [compound 76 expression](#compound-expression-and-braced-lists). 77 78 ## Barewords 79 80 If a string only consists of bareword characters, it can be written without 81 any quote; this is called a **bareword**. Examples are `a.txt`, 82 `long-bareword`, and `/usr/local/bin`. The set of bareword characters include: 83 84 * ASCII letters (a-z and A-Z) and numbers (0-9); 85 86 * The symbols `-_:%+,./@!`; 87 88 * Non-ASCII codepoints that are printable, as defined by 89 [unicode.IsPrint](https://godoc.org/unicode#IsPrint) in Go's standard 90 library. 91 92 The following are bareword characters depending on their position: 93 94 * The tilde `~`, unless it appears at the beginning of a compound 95 expression, in which case it is subject to [tilde 96 expansion](#tilde-expansion); 97 98 * The equal sign `=`, unless it is used for terminating [map keys](#map) or 99 [option keys](#arguments-and-options), or denoting 100 [assignments](#assignment) or [temporary 101 assignments](#temporary-assignment). 102 103 Unlike traditional shells, an unquoted backslash ``\`` does not escape 104 metacharacters; use quoted strings instead. For instance, to echo a star, write 105 `echo "*"` or `echo '*'`, not ``echo \*``. Unquote backslashes are now only 106 used in line continuations; their use elsewhere is reserved will cause a 107 syntax error. 108 109 ## Notes 110 111 The three syntaxes above all evaluate to strings, and they are 112 interchangeable. For instance, `xyz`, `'xyz'` and `"xyz"` are different 113 syntaxes for the same string, and they are always equivalent. 114 115 Elvish does **not** have a separate number type. For instance, in the command 116 `+ 1 2`, both `1` and `2` are strings, and it is the command `+` that knows to 117 treat its arguments as numbers. This design is driven by syntax -- because 118 barewords are always treated as strings, and digits are barewords, we cannot 119 treat words like `1` as number literals. At some point the language may get a 120 dedicated number type (or several number types), but they will likely need to 121 be constructed explicitly, e.g. `(number 1)`. 122 123 124 # List and Map 125 126 Lists and maps are the basic container types in Elvish. 127 128 ## List 129 130 Lists are surround by square brackets `[ ]`, with elements separated by 131 whitespaces. Examples: 132 133 ```elvish-transcript 134 ~> put [lorem ipsum] 135 ▶ [lorem ipsum] 136 ~> put [lorem 137 ipsum 138 foo 139 bar] 140 ▶ [lorem ipsum foo bar] 141 ``` 142 143 Note that commas have no special meanings and are valid bareword characters, 144 so don't use them to separate elements: 145 146 ```elvish-transcript 147 ~> li = [a, b] 148 ~> put $li 149 ▶ [a, b] 150 ~> put $li[0] 151 ▶ a, 152 ``` 153 154 ## Map 155 156 Maps are also surrounded by square brackets; a key/value pair is written 157 `&key=value` (reminiscent to HTTP query parameters), and pairs are separated 158 by whitespaces. Whitespaces are allowed after `=`, but not before `=`. 159 Examples: 160 161 ```elvish-transcript 162 ~> put [&foo=bar &lorem=ipsum] 163 ▶ [&foo=bar &lorem=ipsum] 164 ~> put [&a= 10 165 &b= 23 166 &sum= (+ 10 23)] 167 ▶ [&a=10 &b=23 &sum=33] 168 ``` 169 170 An empty map is written as `[&]`. 171 172 173 # Variable 174 175 Variables are named holders of values. The following characters can be used in 176 variable names (a subset of bareword characters): 177 178 * ASCII letters (a-z and A-Z) and numbers (0-9); 179 180 * The symbols `-_:~`. The colon `:` is special; it is normally used for 181 separating namespaces or denoting namespace variables; 182 183 * Non-ASCII codepoints that are printable, as defined by 184 [unicode.IsPrint](https://godoc.org/unicode#IsPrint) in Go's standard 185 library. 186 187 In most other shells, variables can map directly to environmental variables: 188 `$PATH` is the same as the `PATH` environment variable. This is not the case 189 in Elvish. Instead, environment variables are put in a dedicated `E:` 190 namespace; the environment variable `PATH` is known as `$E:PATH`. The `$PATH` 191 variable, on the other hand, does not exist initially, and if you have defined 192 it, only lives in a certain lexical scope within the Elvish interpreter. 193 194 You will notice that variables sometimes have a leading dollar `$`, and 195 sometimes not. The tradition is that they do when they are used for their 196 values, and do not otherwise (e.g. in assignment). This is consistent with 197 most other shells. 198 199 ## Assignment 200 201 A variable can be assigned by writing its name, `=`, and the value to assign. 202 There must be inline whitespaces both before and after `=`. Example: 203 204 ```elvish-transcript 205 ~> foo = bar 206 ``` 207 208 You can assign multiple values to multiple variables simultaneously, simply by writing several variable names (separated by inline whitespaces) on the left-hand side, and several values on the right-hand side: 209 210 ```elvish-transcript 211 ~> x y = 3 4 212 ``` 213 214 ## Referencing 215 216 Use a variable by adding `$` before the name: 217 218 ```elvish-transcript 219 ~> foo = bar 220 ~> x y = 3 4 221 ~> put $foo 222 ▶ bar 223 ~> put $x 224 ▶ 3 225 ``` 226 227 Variables must be assigned before use. Attempting to use an unassigned 228 variable causes a compilation error: 229 230 ```elvish-transcript 231 ~> echo $x 232 Compilation error: variable $x not found 233 [tty], line 1: echo $x 234 ~> { echo $x } 235 Compilation error: variable $x not found 236 [tty], line 1: { echo $x } 237 ``` 238 239 ## Explosion and Rest Variable 240 241 If a variable contains a list value, you can add `@` before the variable name 242 to get all its element values. This is called **exploding** the variable: 243 244 ```elvish-transcript 245 ~> li = [lorem ipsum foo bar] 246 ~> put $li 247 ▶ [lorem ipsum foo bar] 248 ~> put $@li 249 ▶ lorem 250 ▶ ipsum 251 ▶ foo 252 ▶ bar 253 ``` 254 255 (This notation is restricted to exploding variables. To explode arbitrary values, use the builtin [explode](/ref/builtin.html#explode) command.) 256 257 When assigning variables, if you prefix the name of the last variable with 258 `@`, it gets assigned a list containing all remaining values. That variable is 259 called a **rest variable**. Example: 260 261 ```elvish-transcript 262 ~> a b @rest = 1 2 3 4 5 6 7 263 ~> put $a $b $rest 264 ▶ 1 265 ▶ 2 266 ▶ [3 4 5 6 7] 267 ``` 268 269 Schematically this is a reverse operation to variable explosion, which is why 270 they share the `@` sign. 271 272 273 ## Temporary Assignment 274 275 You can prepend a command with **temporary assignments**, which gives 276 variables temporarily values during the execution of that command. 277 278 In the following 279 example, `$x` and `$y` are temporarily assigned 100 and 200: 280 281 ```elvish-transcript 282 ~> x y = 1 2 283 ~> x=100 y=200 + $x $y 284 ▶ 300 285 ~> echo $x $y 286 1 2 287 ``` 288 289 In contrary to normal assignments, there should be no whitespaces around the 290 equal sign `=`. To have multiple variables in the left-hand side, use braces: 291 292 ```elvish-transcript 293 ~> x y = 1 2 294 ~> fn f { put 100 200 } 295 ~> {x,y}=(f) + $x $y 296 ▶ 300 297 ``` 298 299 If you use a previously undefined variable in a temporary assignment, its 300 value will become the empty string after the command finishes. This behavior 301 will likely change; don't rely on it. 302 303 Since ordinary assignments are also a kind of command, they can also be 304 prepended with temporary assignments: 305 306 ```elvish-transcript 307 ~> x=1 308 ~> x=100 y = (+ 133 $x) 309 ~> put $x $y 310 ▶ 1 311 ▶ 233 312 ``` 313 314 Temporary assignments must all appear before the command. As soon as something 315 that is not a temporary assignments is parsed, Elvish no longer parses 316 temporary assignments. For instance, in `x=1 echo x=1`, the second `x=1` is not 317 a temporary assignment, but a bareword. 318 319 **Note**: Elvish's behavior differs from bash (or zsh) in one important place. 320 In bash, temporary assignments to variables do not affect their direct 321 appearance in the command: 322 323 ```sh-transcript 324 bash-4.4$ x=1 325 bash-4.4$ x=100 echo $x 326 1 327 ``` 328 329 330 ## Scoping rule 331 332 Elvish has lexical scoping. Scopes are introduced by [lambdas](#lambda) or 333 [user-defined modules](#user-defined-modules). 334 335 When you use a variable, Elvish looks for it in the current lexical scope, 336 then its parent lexical scope and so forth, until the outermost scope: 337 338 ```elvish-transcript 339 ~> x = 12 340 ~> { echo $x } # $x is in the global scope 341 12 342 ~> { y = bar; { echo $y } } # $y is in the outer scope 343 bar 344 ``` 345 346 If a variable is not in any of the lexical scopes, Elvish tries to resolve it 347 in the `builtin:` namespace, and if that also fails, cause an error: 348 349 ```elvish-transcript 350 ~> echo $pid # builtin 351 36613 352 ~> echo $nonexistent 353 Compilation error: variable $nonexistent not found 354 [interactive], line 1: 355 echo $nonexistent 356 ``` 357 358 Note that Elvish resolves all variables in a code chunk before starting to 359 execute any of it; that is why the error message above says *compilation 360 error*. This can be more clearly observed in the following example: 361 362 ```elvish-transcript 363 ~> echo pre-error; echo $nonexistent 364 Compilation error: variable $nonexistent not found 365 [tty], line 1: echo pre-error; echo $nonexistent 366 ``` 367 368 When you assign a variable, Elvish does a similar searching. If the variable 369 cannot be found, it will be created in the current scope: 370 371 ```elvish-transcript 372 ~> x = 12 373 ~> { x = 13 } # assigns to x in the global scope 374 ~> echo $x 375 13 376 ~> { z = foo } # creates z in the inner scope 377 ~> echo $z 378 Compilation error: variable $z not found 379 [tty], line 1: echo $z 380 ``` 381 382 One implication of this behavior is that Elvish will not shadow your variable 383 in outer scopes. 384 385 There is a `local:` namespace that always refers to the current scope, and by 386 using it it is possible to force Elvish to shadow variables: 387 388 ```elvish-transcript 389 ~> x = 12 390 ~> { local:x = 13; echo $x } # force shadowing 391 13 392 ~> echo $x 393 12 394 ``` 395 396 After force shadowing, you can still access the variable in the outer scope 397 using the `up:` namespace, which always **skips** the innermost scope: 398 399 ```elvish-transcript 400 ~> x = 12 401 ~> { local:x = 14; echo $x $up:x } 402 14 12 403 ``` 404 405 The `local:` and `up:` namespaces can also be used on unshadowed variables, 406 although they are not useful in those cases: 407 408 ```elvish-transcript 409 ~> foo = a 410 ~> { echo $up:foo } # $up:foo is the same as $foo 411 a 412 ~> { bar = b; echo $local:bar } # $local:bar is the same as $bar 413 b 414 ``` 415 416 It is not possible to refer to a specific outer scope. 417 418 You cannot create new variables in the `builtin:` namespace, although existing 419 variables in it can be assigned new values. 420 421 422 # Lambda 423 424 A function literal, or lambda, is a [code chunk](#code-chunk) surrounded by 425 curly braces: 426 427 ```elvish-transcript 428 ~> f = { echo "Inside a lambda" } 429 ~> put $f 430 ▶ <closure 0x18a1a340> 431 ``` 432 433 One or more whitespace characters after `{` is required: Elvish relies on the 434 presence of whitespace to disambiguate lambda literals and [braced 435 lists](#braced-lists). It is good style to put some whitespace before the 436 closing `}` as well, but this is not required by the syntax. 437 438 Functions are first-class values in Elvish. They can be kept in variables, used 439 as arguments, output on the value channel, and embedded in other data 440 structures. They can also be used as commands: 441 442 ```elvish-transcript 443 ~> $f 444 Inside a lambda 445 ~> { echo "Inside a literal lambda" } 446 Inside a literal lambda 447 ``` 448 449 The last command resembles a code block in C-like languages in syntax. But 450 under the hood, it defines a function on the fly and calls it immediately. 451 452 Functions defined using the basic syntax above do not accept any arguments or 453 options. To do so, you need to write a signature. 454 455 ## Signature 456 457 A **signature** specifies the arguments a function can accept: 458 459 ```elvish-transcript 460 ~> f = [a b]{ put $b $a } 461 ~> $f lorem ipsum 462 ▶ ipsum 463 ▶ lorem 464 ``` 465 466 There should be no space between `]` and `{`; otherwise Elvish will parse the 467 signature as a list, followed by a lambda without signature: 468 469 ```elvish-transcript 470 ~> put [a]{ nop } 471 ▶ <closure 0xc420153d80> 472 ~> put [a] { nop } 473 ▶ [a] 474 ▶ <closure 0xc42004a480> 475 ``` 476 477 Like in the left hand of assignments, if you prefix the last argument with 478 `@`, it becomes a **rest argument**, and its value is a list containing all 479 the remaining arguments: 480 481 ```elvish-transcript 482 ~> f = [a @rest]{ put $a $rest } 483 ~> $f lorem 484 ▶ lorem 485 ▶ [] 486 ~> $f lorem ipsum dolar sit 487 ▶ lorem 488 ▶ [ipsum dolar sit] 489 ``` 490 491 You can also declare options in the signature. The syntax is `&name=default` 492 (like a map pair), where `default` is the default value for the option: 493 494 ```elvish-transcript 495 ~> f = [&opt=default]{ echo "Value of $opt is "$opt } 496 ~> $f 497 Value of $opt is default 498 ~> $f &opt=foobar 499 Value of $opt is foobar 500 ``` 501 502 Options must have default values: Options should be **option**al. 503 504 If you call a function with too few arguments, too many arguments or unknown 505 options, an exception is thrown: 506 507 ```elvish-transcript 508 ~> [a]{ echo $a } foo bar 509 Exception: need 1 arguments, got 2 510 [tty], line 1: [a]{ echo $a } foo bar 511 ~> [a b]{ echo $a $b } foo 512 Exception: need 2 arguments, got 1 513 [tty], line 1: [a b]{ echo $a $b } foo 514 ~> [a b @rest]{ echo $a $b $rest } foo 515 Exception: need 2 or more arguments, got 1 516 [tty], line 1: [a b @rest]{ echo $a $b $rest } foo 517 ~> [&k=v]{ echo $k } &k2=v2 518 Exception: unknown option k2 519 [tty], line 1: [&k=v]{ echo $k } &k2=v2 520 ``` 521 522 523 ## Closure Semantics 524 525 User-defined functions are also known as "closures", because they have 526 [closure 527 semantics](https://en.wikipedia.org/wiki/Closure_(computer_programming)). 528 529 In the following example, the `make-adder` function outputs two functions, 530 both referring to a local variable `$n`. Closure semantics means that: 531 532 1. Both functions can continue to refer to the `$n` variable after 533 `make-adder` has returned. 534 535 2. Multiple calls to the `make-adder` function generates distinct instances 536 of the `$n` variables. 537 538 ```elvish-transcript 539 ~> fn make-adder { 540 n = 0 541 put { put $n } { n = (+ $n 1) } 542 } 543 ~> getter adder = (make-adder) 544 ~> $getter # $getter outputs $n 545 ▶ 0 546 ~> $adder # $adder increments $n 547 ~> $getter # $getter and $setter refer to the same $n 548 ▶ 1 549 ~> getter2 adder2 = (make-adder) 550 ~> $getter2 # $getter2 and $getter refer to different $n 551 ▶ 0 552 ~> $getter 553 ▶ 1 554 ``` 555 556 Variables that get "captured" in closures are called **upvalues**; this is why 557 the pseudo-namespace for variables in outer scopes is called `up:`. When 558 capturing upvalues, Elvish only captures the variables that are used. In the 559 following example, `$m` is not an upvalue of `$g` because it is not used: 560 561 ```elvish-transcript 562 ~> fn f { m = 2; n = 3; put { put $n } } 563 ~> g = (f) 564 ``` 565 566 This effect is not currently observable, but will become so when namespaces 567 [become introspectable](https://github.com/elves/elvish/issues/492). 568 569 570 # Indexing 571 572 Indexing is done by putting one or more **index expressions** in brackets `[]` 573 after a value. 574 575 ## List Indexing 576 577 Lists can be indexed with any of the following: 578 579 * A non-negative integer, an offset counting from the beginning of the list. 580 For example, `$li[0]` is the first element of `$li`. 581 582 * A negative integer, an offset counting from the back of the list. For 583 instance, `$li[-1]` is the last element `$li`. 584 585 * A slice `$a:$b`, where both `$a` and `$b` are integers. The result is 586 sublist of `$li[$a]` up to, but not including, `$li[$b]`. For instance, 587 `$li[4:7]` equals `[$li[4] $li[5] $li[6]]`, while `$li[1:-1]` contains all 588 elements from `$li` except the first and last one. 589 590 Both integers may be omitted; `$a` defaults to 0 while `$b` defaults to the 591 length of the list. For instance, `$li[:2]` is equivalent to `$li[0:2]`, 592 `$li[2:]` is equivalent to `$li[2:(count $li)]`, and `$li[:]` makes a copy 593 of `$li`. The last form is rarely useful, as lists are immutable. 594 595 Note that the slice needs to be a **single** string, so there cannot be 596 any spaces within the slice. For instance, `$li[2:10]` cannot be written 597 as `$li[2: 10]`; the latter contains two indicies and is equivalent to 598 `$li[2:] $li[10]` (see [Multiple Indicies](#multiple-indicies)). 599 600 * Not yet implemented: The string `@`. The result is all the values in the 601 list. Note that this is not the same as `:`: if `$li` has 10 elements, 602 `$li[@]` evaluates to 10 values (all the elements in the list), while 603 `$li[:]` evaluates to just one value (a copy of the list). 604 605 When used on a variable like `$li`, it is equivalent to the explosion 606 construct `$li[@]`. It is useful, however, when used on other constructs, 607 like output capture or other 608 609 Examples: 610 611 ```elvish-transcript 612 ~> li = [lorem ipsum foo bar] 613 ~> put $li[0] 614 ▶ lorem 615 ~> put $li[-1] 616 ▶ bar 617 ~> put $li[0:2] 618 ▶ [lorem ipsum] 619 ``` 620 621 (Negative indicies and slicing are borrowed from Python.) 622 623 ## String indexing 624 625 **NOTE**: String indexing will likely change. 626 627 Strings should always be UTF-8, and they can indexed by **byte indicies at 628 which codepoints start**, and indexing results in **the codepoint that starts 629 there**. This is best explained with examples: 630 631 * In the string `elv`, every codepoint is encoded with only one byte, so 0, 632 1, 2 are all valid indices: 633 634 ```elvish-transcript 635 ~> put elv[0] 636 ▶ e 637 ~> put elv[1] 638 ▶ l 639 ~> put elv[2] 640 ▶ v 641 ``` 642 643 * In the string `世界`, each codepoint is encoded with three bytes. The first 644 codepoint occupies byte 0 through 2, and the second occupies byte 3 through 645 5\. Hence valid indicies are 0 and 3: 646 647 ```elvish-transcript 648 ~> put 世界[0] 649 ▶ 世 650 ~> put 世界[3] 651 ▶ 界 652 ``` 653 654 Strings can also be indexed by slices. 655 656 (This idea of indexing codepoints by their byte positions is borrowed from 657 Julia.) 658 659 ## Map indexing 660 661 Maps are simply indexed by their keys. There is no slice indexing, and `:` does 662 not have a special meaning. Examples: 663 664 ```elvish-transcript 665 ~> map = [&a=lorem &b=ipsum &a:b=haha] 666 ~> echo $map[a] 667 lorem 668 ~> echo $map[a:b] 669 haha 670 ``` 671 672 ## Multiple Indices 673 674 If you put multiple values in the index, you get multiple values: `$li[x y z]` 675 is equivalent to `$li[x] $li[y] $li[z]`. This applies to all indexable values. 676 Examples: 677 678 ```elvish-transcript 679 ~> put elv[0 2 0:2] 680 ▶ e 681 ▶ v 682 ▶ el 683 ~> put [lorem ipsum foo bar][0 2 0:2] 684 ▶ lorem 685 ▶ foo 686 ▶ [lorem ipsum] 687 ~> put [&a=lorem &b=ipsum &a:b=haha][a a:b] 688 ▶ lorem 689 ▶ haha 690 ``` 691 692 693 # Output Capture 694 695 Output capture is formed by putting parentheses `()` around a [code 696 chunk](#code-chunk). It redirects the output of the chunk into an internal 697 pipe, and evaluates to all the values that have been output. 698 699 ```elvish-transcript 700 ~> + 1 10 100 701 ▶ 111 702 ~> x = (+ 1 10 100) 703 ~> put $x 704 ▶ 111 705 ~> put lorem ipsum 706 ▶ lorem 707 ▶ ipsum 708 ~> x y = (put lorem ipsum) 709 ~> put $x 710 ▶ lorem 711 ~> put $y 712 ▶ ipsum 713 ``` 714 715 If the chunk outputs bytes, Elvish strips the last newline (if any), and split them by newlines, and consider each line to be one string value: 716 717 ```elvish-transcript 718 ~> put (echo "a\nb") 719 ▶ a 720 ▶ b 721 ``` 722 723 **Note 1**. Only the last newline is ever removed, so empty lines are 724 preserved; `(echo "a\n")` evaluates to two values, `"a"` and `""`. 725 726 **Note 2**. One consequence of this mechanism is that you can not distinguish 727 outputs that lack a trailing newline from outputs that have one; `(echo what)` 728 evaluates to the same value as `(print what)`. If such a distinction is 729 needed, use [`slurp`](/ref/builtin.html#slurp) to preserve the original 730 bytes output. 731 732 If the chunk outputs both values and bytes, the values of output capture will 733 contain both value outputs and lines. However, the ordering between value 734 output and byte output might not agree with the order in which they happened: 735 736 ```elvish-transcript 737 ~> put (put a; echo b) # value order need not be the same as output order 738 ▶ b 739 ▶ a 740 ``` 741 742 743 # Exception Capture 744 745 Exception capture is formed by putting `?()` around a code chunk. It runs the chunk and evaluates to the exception it throws. 746 747 ```elvish-transcript 748 ~> fail bad 749 Exception: bad 750 Traceback: 751 [interactive], line 1: 752 fail bad 753 ~> put ?(fail bad) 754 ▶ ?(fail bad) 755 ``` 756 757 If there was no error, it evaluates to the special value `$ok`: 758 759 ```elvish-transcript 760 ~> nop 761 ~> put ?(nop) 762 ▶ $ok 763 ``` 764 765 Exceptions are booleanly false and `$ok` is booleanly true. This is useful in 766 `if` (introduced later): 767 768 ```elvish-transcript 769 if ?(test -d ./a) { 770 # ./a is a directory 771 } 772 ``` 773 774 Exception captures do not affect the output of the code chunk. You can combine 775 output capture and exception capture: 776 777 ```elvish 778 output = (error = ?(commands-that-may-fail)) 779 ``` 780 781 782 # Tilde Expansion 783 784 Tildes are special when they appear at the beginning of an expression (the 785 exact meaning of "expression" will be explained later). The string after it, up 786 to the first `/` or the end of the word, is taken as a user name; and they 787 together evaluate to the home directory of that user. If the user name is 788 empty, the current user is assumed. 789 790 In the following example, the home directory of the current user is `/home/xiaq`, while that of the root user is `/root`: 791 792 ```elvish-transcript 793 ~> put ~ 794 ▶ /home/xiaq 795 ~> put ~root 796 ▶ /root 797 ~> put ~/xxx 798 ▶ /home/xiaq/xxx 799 ~> put ~root/xxx 800 ▶ /root/xxx 801 ``` 802 803 Note that tildes are not special when they appear elsewhere in a word: 804 805 ```elvish-transcript 806 ~> put a~root 807 ▶ a~root 808 ``` 809 810 If you need them to be, surround them with braces (the reason this works will be explained later): 811 812 ```elvish-transcript 813 ~> put a{~root} 814 ▶ a/root 815 ``` 816 817 818 # Wildcard Patterns 819 820 **Wildcard patterns** are patterns containing **wildcards**, and they evaluate to all filenames they match. 821 822 We will use this directory tree in examples: 823 824 ``` 825 .x.conf 826 a.cc 827 ax.conf 828 foo.cc 829 d/ 830 |__ .x.conf 831 |__ ax.conf 832 |__ y.cc 833 .d2/ 834 |__ .x.conf 835 |__ ax.conf 836 ``` 837 838 Elvish supports the following wildcards: 839 840 * `?` matches one arbitrary character except `/`. For example, `?.cc` 841 matches `a.cc`; 842 843 * `*` matches any number of arbitrary characters except `/`. For example, 844 `*.cc` matches `a.cc` and `foo.cc`; 845 846 * `**` matches any number of arbitrary characters including `/`. For example, 847 `**.cc` matches `a.cc`, `foo.cc` and `b/y.cc`. 848 849 The following behaviors are default, although they can be altered by modifiers: 850 851 * When the entire wildcard pattern has no match, an error is thrown. 852 853 * None of the wildcards matches `.` at the beginning of filenames. For example: 854 855 * `?x.conf` does not match `.x.conf`; 856 857 * `d/*.conf` does not match `d/.x.conf`; 858 859 * `**.conf` does not match `d/.x.conf`. 860 861 862 ## Modifiers 863 864 Wildcards can be **modified** using the same syntax as indexing. For instance, 865 in `*[match-hidden]` the `*` wildcard is modified with the `match-hidden` 866 modifier. Multiple matchers can be chained like `*[set:abc][range:0-9]`. There 867 are two kinds of modifiers: 868 869 **Global modifiers** apply to the whole pattern and can be placed after any 870 wildcard: 871 872 * `nomatch-ok` tells Elvish not to throw an error when there is no match for 873 the pattern. For instance, in the example directory `put bad*` will be an 874 error, but `put bad*[nomatch-ok]` does exactly nothing. 875 876 * `but:xxx` (where `xxx` is any filename) excludes the filename from the final 877 result. 878 879 Although global modifiers affect the entire wildcard pattern, you can add it 880 after any wildcard, and the effect is the same. For example, `put 881 */*[nomatch-ok].cpp` and `put *[nomatch-ok]/*.cpp` do the same thing. 882 883 On the other hand, you must add it after a wildcard, instead of after the 884 entire pattern: `put */*.cpp[nomatch-ok]` unfortunately does not do the correct 885 thing. (This will probably be fixed.) 886 887 **Local modifiers** only apply to the wildcard it immediately follows: 888 889 * `match-hidden` tells the wildcard to match `.` at the beginning of 890 filenames, e.g. `*[match-hidden].conf` matches `.x.conf` and `ax.conf`. 891 892 Being a local modifier, it only applies to the wildcard it immediately 893 follows. For instance, `*[match-hidden]/*.conf` matches `d/ax.conf` and 894 `.d2/ax.conf`, but not `d/.x.conf` or `.d2/.x.conf`. 895 896 * Character matchers restrict the characters to match: 897 898 * Character sets, like `set:aeoiu`; 899 900 * Character ranges like `range:a-z` (including `z`) or `range:a~z` (excluding `z`); 901 902 * Character classes: `control`, `digit`, `graphic`, `letter`, `lower`, 903 `mark`, `number`, `print`, `punct`, `space`, `symbol`, `title`, and 904 `upper`. See the Is* functions [here](https://godoc.org/unicode) for 905 their definitions. 906 907 Note the following caveats: 908 909 * Multiple matchers, they are OR'ed. For instance, ?[set:aeoiu][digit] 910 matches `aeoiu` and digits. 911 912 * Dots at the beginning of filenames always require an explicit 913 `match-hidden`, even if the matcher includes `.`. For example, 914 `?[set:.a]x.conf` does **not** match `.x.conf`; you have to `?[set:.a 915 match-hidden]x.conf`. 916 917 * Likewise, you always need to use `**` to match slashes, even if the 918 matcher includes `/`. For example `*[set:abc/]` is the same as 919 `*[set:abc]`. 920 921 922 # Compound Expression and Braced Lists 923 924 Writing several expressions together with no space in between will concatenate 925 them. This creates a **compound expression**, because it mimics the formation 926 of compound words in natural languages. Examples: 927 928 ```elvish-transcript 929 ~> put 'a'b"c" # compounding three string literals 930 ▶ abc 931 ~> v = value 932 ~> put '$v is '$v # compounding one string literal with one string variable 933 ▶ '$v is value' 934 ``` 935 936 Many constructs in Elvish can generate multiple values, like indexing with 937 multiple indices and output captures. Compounding multiple values with other 938 values generates all possible combinations: 939 940 ```elvish-transcript 941 ~> put (put a b)-(put 1 2) 942 ▶ a-1 943 ▶ a-2 944 ▶ b-1 945 ▶ b-2 946 ``` 947 948 Note the order of the generated values. The value that comes later changes faster. 949 950 **NOTE**: There is a perhaps a better way to explain the ordering, but you can think of the previous code as equivalent to this: 951 952 ```elvish-transcript 953 for x [a b] { 954 for y [1 2] { 955 put $x-$y 956 } 957 } 958 ``` 959 960 ## Braced Lists 961 962 In practice, you never have to write `(put a b)`: you can use a braced list `{a,b}`: 963 964 ```elvish-transcript 965 ~> put {a,b}-{1,2} 966 ▶ a-1 967 ▶ a-2 968 ▶ b-1 969 ▶ b-2 970 ``` 971 972 Elements in braced lists can also be separated with whitespaces, or a combination of comma and whitespaces (the latter not recommended): 973 974 ```elvish-transcript 975 ~> put {a b , c,d} 976 ▶ a 977 ▶ b 978 ▶ c 979 ▶ d 980 ``` 981 982 (In future, the syntax might be made more strict.) 983 984 Braced list is merely a syntax for grouping multiple values. It is not a data 985 structure. 986 987 988 # Expression Structure and Precedence 989 990 Braced lists are evaluated before being compounded with other values. You can 991 use this to affect the order of evaluation. For instance, `put *.txt` gives you 992 all filenames that end with `.txt` in the current directory; while `put 993 {*}.txt` gives you all filenames in the current directory, appended with 994 `.txt`. 995 996 **TODO**: document evaluation order regarding tilde and wildcards. 997 998 999 # Ordinary Command 1000 1001 The **command** is probably the most important syntax construct in shell 1002 languages, and Elvish is no exception. The word **command** itself, is 1003 overloaded with meanings. In the terminology of this document, the term 1004 **command** include the following: 1005 1006 * An ordinary assignment, introduced above; 1007 1008 * An ordinary command, introduced in this section; 1009 1010 * A special command, introduced in the next section. 1011 1012 An **ordinary command** consists of a compulsory head, and any number of 1013 arguments, options and redirections. 1014 1015 ## Head 1016 1017 The **head** must appear first. It is an arbitrary word that determines what will be run. Examples: 1018 1019 ```elvish-transcript 1020 ~> ls -l # the string ls is the head 1021 (output omitted) 1022 ~> (put [@a]{ ls $@a }) -l 1023 (same output) 1024 ``` 1025 1026 The head must evaluate to one value. For instance, the following does not work: 1027 1028 ```elvish-transcript 1029 ~> (put [@a]{ ls $@a } -l) 1030 Exception: head of command must be a single value; got 2 values 1031 [tty], line 1: (put [@a]{ ls $@a } -l) 1032 ``` 1033 1034 The definition of barewords is relaxed for the head to include `<`, `>`, `*` 1035 and `^`. These are all names of numeric builtins: 1036 1037 ```elvish-transcript 1038 ~> < 3 5 # less-than 1039 ▶ $true 1040 ~> > 3 5 # greater-than 1041 ▶ $false 1042 ~> * 3 5 # multiplication 1043 ▶ 15 1044 ~> ^ 3 5 # power 1045 ▶ 243 1046 ``` 1047 1048 ## Arguments and Options 1049 1050 **Arguments** (args for short) and **options** (opts for short) can be supplied 1051 to commands. Arguments are arbitrary words, while options have the same 1052 syntax as map pairs. They are separated by inline whitespaces: 1053 1054 ```elvish-transcript 1055 ~> echo &sep=, a b c # seq=, is an option; a b c are arguments 1056 a,b,c 1057 ``` 1058 1059 1060 ## Redirections 1061 1062 Redirections are used for modifying file descriptors (FD). 1063 1064 The most common form of redirections opens a file and associates it with an FD. 1065 The form consists of an optional destination FD (like `2`), a redirection 1066 operator (like `>`) and a filename (like `error.log`): 1067 1068 * The **destination fd** determines which FD to modify. If absent, it is 1069 determined from the redirection operator. If present, there must be no 1070 space between the fd and the redirection operator. (Otherwise Elvish parses 1071 it as an argument.) 1072 1073 * The **redirection operator** determines the mode to open the file, and the 1074 destination fd if it is not explicitly specified. 1075 1076 * The **filename** names the file to open. 1077 1078 Possible redirection operators and their default FDs are: 1079 1080 * `<` for reading. The default FD is 0 (stdin). 1081 1082 * `>` for writing. The default FD is 1 (stdout). 1083 1084 * `>>` for appending. The default FD is 1 (stdout). 1085 1086 * `<>` for reading and writing. The default FD is 1 (stdout). 1087 1088 Examples: 1089 1090 ```elvish-transcript 1091 ~> echo haha > log 1092 ~> cat log 1093 haha 1094 ~> cat < log 1095 haha 1096 ~> ls --bad-arg 2> error 1097 Exception: ls exited with 2 1098 Traceback: 1099 [interactive], line 1: 1100 ls --bad-arg 2> error 1101 ~> cat error 1102 /bin/ls: unrecognized option '--bad-arg' 1103 Try '/bin/ls --help' for more information. 1104 ``` 1105 1106 Redirections can also be used for closing or duplicating FDs. Instead of 1107 writing a filename, use `&n` (where `n` is a number) for duplicating, or `&-` 1108 for closing. In this case, the redirection operator only determines the default 1109 destination FD (and is totally irrevelant if a destination FD is specified). 1110 Examples: 1111 1112 ```elvish-transcript 1113 ~> ls >&- # close stdout 1114 /bin/ls: write error: Bad file descriptor 1115 Exception: ls exited with 2 1116 Traceback: 1117 [interactive], line 1: 1118 ls >&- 1119 ``` 1120 1121 If you have multiple related redirections, they are applied in the order they appear. For instance: 1122 1123 ```elvish-transcript 1124 ~> fn f { echo out; echo err >&2 } # echoes "out" on stdout, "err" on stderr 1125 ~> f >log 2>&1 # use file "log" for stdout, then use (changed) stdout for stderr 1126 ~> cat log 1127 out 1128 err 1129 ``` 1130 1131 1132 ## Ordering 1133 1134 Elvish does not impose any ordering of arguments, options and redirections: 1135 they can intermix each other. The only requirement is that the head must come 1136 first. This is different from POSIX shells, where redirections may appear 1137 before the head. For instance, the following two both work in POSIX shell, but 1138 only the former works in Elvish: 1139 1140 1141 ```sh 1142 echo something > file 1143 > file echo something # mistaken for the comparison builtin ">" in Elvish 1144 ``` 1145 1146 1147 # Special Commands 1148 1149 **Special commands** obey the same syntax rules as normal commands (i.e. 1150 syntactically special commands can be treated the same as ordinary commands), 1151 but have evaluation rules that are custom to each command. To explain this, we 1152 use the following example: 1153 1154 ```elvish-transcript 1155 ~> or ?(echo x) ?(echo y) ?(echo z) 1156 x 1157 ▶ $ok 1158 ``` 1159 1160 In the example, the `or` command first evaluates its first argument, which has the value `$ok` (a truish value) and the side effect of outputting `x`. Due to the custom evaluation rule of `or`, the rest of the arguments are not evaluated. 1161 1162 If `or` were a normal command, the code above is still syntactically correct. However, Elvish would then evaluate all its arguments, with the side effect of outputting `x`, `y` and `z`, before calling `or`. 1163 1164 1165 ## Deleting variable or element: `del` 1166 1167 The `del` special command can be used to either delete variables or elements 1168 of lists and maps. Operands should be specified without a leading dollar sign, 1169 like the left-hand side of assignments. 1170 1171 Example of deleting variable: 1172 1173 ```elvish-transcript 1174 ~> x = 2 1175 ~> echo $x 1176 2 1177 ~> del x 1178 ~> echo $x 1179 Compilation error: variable $x not found 1180 [tty], line 1: echo $x 1181 ``` 1182 1183 Example of deleting element: 1184 1185 ```elvish-transcript 1186 ~> m = [&k=v &k2=v2] 1187 ~> del m[k2] 1188 ~> put $m 1189 ▶ [&k=v] 1190 ~> l = [[&k=v &k2=v2]] 1191 ~> del l[0][k2] 1192 ~> put $l 1193 ▶ [[&k=v]] 1194 ``` 1195 1196 1197 ## Logics: `and` and `or` 1198 1199 The `and` special command evaluates its arguments from left to right; as soon 1200 as a booleanly false value is obtained, it outputs the value and stops. When 1201 given no arguments, it outputs `$true`. 1202 1203 The `or` special command is the same except that it stops when a booleanly true 1204 value is obtained. When given no arguments, it outpus `$false`. 1205 1206 1207 ## Condition: `if` 1208 1209 **TODO**: Document the syntax notation, and add more examples. 1210 1211 Syntax: 1212 1213 ```elvish-transcript 1214 if <condition> { 1215 <body> 1216 } elif <condition> { 1217 <body> 1218 } else { 1219 <else-body> 1220 } 1221 ``` 1222 1223 The `if` special command goes through the conditions one by one: as soon as one 1224 evaluates to a booleanly true value, its corresponding body is executed. If 1225 none of conditions are booleanly true and an else body is supplied, it is 1226 executed. 1227 1228 The condition part is an expression, not a command like in other shells. 1229 1230 Tip: a combination of `if` and `?()` gives you a semantics close to other shells: 1231 1232 ```elvish-transcript 1233 if ?(test -d .git) { 1234 # do something 1235 } 1236 ``` 1237 1238 However, for Elvish's builtin predicates that output values instead of throw exceptions, the output capture construct `()` should be used. 1239 1240 **TODO**: add more examples. 1241 1242 ## Conditional Loop: `while` 1243 1244 Syntax: 1245 1246 ```elvish-transcript 1247 while <condition> { 1248 <body> 1249 } else { 1250 <else-body> 1251 } 1252 ``` 1253 1254 Execute the body as long as the condition evaluates to a booleanly true value. 1255 1256 The else body, if present, is executed if the body has never been executed 1257 (i.e. the condition evaluates to a booleanly false value in the very 1258 beginning). 1259 1260 1261 ## Iterative Loop: `for` 1262 1263 Syntax: 1264 1265 ```elvish-transcript 1266 for <var> <container> { 1267 <body> 1268 } else { 1269 <body> 1270 } 1271 ``` 1272 1273 Iterate the container (e.g. a list). In each iteration, assign the variable to 1274 an element of the container and execute the body. 1275 1276 The else body, if present, is executed if the body has never been executed 1277 (i.e. the iteration value has no elements). 1278 1279 1280 ## Exception Control: `try` 1281 1282 (If you just want to capture the exception, you can use the more concise 1283 exception capture construct `?()` instead.) 1284 1285 Syntax: 1286 1287 ```elvish-transcript 1288 try { 1289 <try-block> 1290 } except except-varname { 1291 <except-block> 1292 } else { 1293 <else-block> 1294 } finally { 1295 <finally-block> 1296 } 1297 ``` 1298 1299 Only `try` and `try-block` are required. This control structure behaves as follows: 1300 1301 1. The `try-block` is always executed first. 1302 1303 2. If `except` is present and an exception occurs in `try-block`, it is 1304 caught and stored in `except-varname`, and `except-block` is then 1305 executed. Example: 1306 1307 ```elvish-transcript 1308 ~> try { fail bad } except e { put $e } 1309 ▶ ?(fail bad) 1310 ``` 1311 1312 Note that if `except` is not present, exceptions thrown from `try` are not 1313 caught: for instance, `try { fail bad }` throws `bad`; it is equivalent to 1314 a plain `fail bad`. 1315 1316 Note that the word after `except` names a variable, not a matching 1317 condition. Exception matching is not supported yet. For instance, you may 1318 want to only match exceptions that were created with `fail bad` with 1319 `except bad`, but in fact this creates a variable `$bad` that contains 1320 whatever exception was thrown. 1321 1322 3. If no exception occurs and `else` is present, `else-block` is executed. 1323 Example: 1324 1325 ```elvish-transcript 1326 ~> try { nop } else { echo well } 1327 well 1328 ``` 1329 1330 4. If `finally-block` is present, it is executed. Examples: 1331 1332 ```elvish-transcript 1333 ~> try { fail bad } finally { echo final } 1334 final 1335 Exception: bad 1336 Traceback: 1337 [tty], line 1: 1338 try { fail bad } finally { echo final } 1339 ~> try { echo good } finally { echo final } 1340 good 1341 final 1342 ``` 1343 1344 5. If the exception was not caught (i.e. `except` is not present), it is 1345 rethrown. 1346 1347 Exceptions thrown in blocks other than `try-block` are not caught. If an 1348 exception was thrown and either `except-block` or `finally-block` throws 1349 another exception, the original exception is lost. Examples: 1350 1351 ```elvish-transcript 1352 ~> try { fail bad } except e { fail worse } 1353 Exception: worse 1354 Traceback: 1355 [tty], line 1: 1356 try { fail bad } except e { fail worse } 1357 ~> try { fail bad } except e { fail worse } finally { fail worst } 1358 Exception: worst 1359 Traceback: 1360 [tty], line 1: 1361 try { fail bad } except e { fail worse } finally { fail worst } 1362 ``` 1363 1364 1365 ## Function Definition: `fn` 1366 1367 Syntax: 1368 1369 ```elvish-transcript 1370 fn <name> <lambda> 1371 ``` 1372 1373 Define a function with a given name. The function behaves in the same way to 1374 the lambda used to define it, except that it "captures" `return`. In other 1375 words, `return` will fall through lambdas not defined with `fn`, and continues 1376 until it exits a function defined with `fn`: 1377 1378 ```elvish-transcript 1379 ~> fn f { 1380 { echo a; return } 1381 echo b # will not execute 1382 } 1383 ~> f 1384 a 1385 ~> { 1386 f 1387 echo c # executed, because f "captures" the return 1388 } 1389 a 1390 c 1391 ``` 1392 1393 **TODO**: Find a better way to describe this. Hopefully the example is 1394 illustrative enough, though. 1395 1396 1397 # Command Resolution 1398 1399 When using a literal string as the head of a command, it is first **resolved** 1400 during the compilation phase, using the following order: 1401 1402 1. Special commands. 1403 1404 2. Functions defined on any of the containing lexical scopes, with inner 1405 scopes looked up first. (This is exactly the same process as variable 1406 resolution). 1407 1408 3. The `builtin:` namespace. 1409 1410 4. Should all these steps fail, it is resolved to be an external command. 1411 Determination of the path of the external command does not happen in the 1412 resolution process; that happens during evaluation. 1413 1414 You can use the [resolve](/ref/builtin.html#resolve) command to see which 1415 command Elvish resolves a string to. 1416 1417 During the evaluation phase, external commands are then subject to 1418 **searching**. This can be observed with the 1419 [search-external](/ref/builtin.html#search-builtin) command. 1420 1421 1422 # Pipeline 1423 1424 A **pipeline** is formed by joining one or more commands together with the pipe 1425 sign (`|`). 1426 1427 ## IO Semantics 1428 1429 For each pair of adjacent commands `a | b`, the output of `a` is connected to 1430 the input of `b`. Both the byte pipe and the value channel are connected, even 1431 if one of them is not used. 1432 1433 Command redirections are applied before the connection happens. For instance, 1434 the following writes `foo` to `a.txt` instead of the output: 1435 1436 ```elvish-transcript 1437 ~> echo foo > a.txt | cat 1438 ~> cat a.txt 1439 foo 1440 ``` 1441 1442 ## Execution Flow 1443 1444 All of the commands in a pipeline are executed in parallel, and the execution 1445 of the pipeline finishes when all of its commands finish execution. 1446 1447 If one or more command in a pipeline throws an exception, the other commands 1448 will continue to execute as normal. After all commands finish execution, an 1449 exception is thrown, the value of which depends on the number of commands that 1450 have thrown an exception: 1451 1452 * If only one command has thrown an exception, that exception is rethrown. 1453 1454 * If more than one commands have thrown exceptions, a "composite exception", 1455 containing information all exceptions involved, is thrown. 1456 1457 ## Background Pipeline 1458 1459 Adding an ampersand `&` to the end of a pipeline will cause it to be executed 1460 in the background. In this case, the rest of the code chunk will continue to 1461 execute without waiting for the pipeline to finish. Exceptions thrown from the 1462 background pipeline do not affect the code chunk that contains it. 1463 1464 When a background pipeline finishes, a message is printed to the terminal if 1465 the shell is interactive. 1466 1467 1468 # Code Chunk 1469 1470 A **code chunk** is formed by joining zero or more pipelines together, 1471 separating them with either newlines or semicolons. 1472 1473 Pipelines in a code chunk are executed in sequence. If any pipeline throws an 1474 exception, the execution of the whole code chunk stops, propagating that 1475 exception. 1476 1477 1478 # Exception and Flow Commands 1479 1480 Exceptions have similar semantics to those in Python or Java. They can be 1481 thrown with the [fail](/ref/builtin.html#fail) command and caught with either 1482 exception capture `?()` or the `try` special command. 1483 1484 If an external command exits with a non-zero status, Elvish treats that as an 1485 exception. 1486 1487 Flow commands -- `break`, `continue` and `return` -- are ordinary builtin 1488 commands that raise special "flow control" exceptions. The `for` and `while` 1489 commands capture `break` and `continue`, while `fn` modifies its closure to 1490 capture `return`. 1491 1492 One interesting implication is that since flow commands are just ordinary 1493 commands you can build functions on top of them. For instance, this function 1494 `break`s randomly: 1495 1496 ```elvish 1497 fn random-break { 1498 if eq (randint 2) 0 { 1499 break 1500 } 1501 } 1502 ``` 1503 1504 The function `random-break` can then be used in for-loops and while-loops. 1505 1506 Note that the `return` flow control exception is only captured by functions 1507 defined with `fn`. It falls through ordinary lambdas: 1508 1509 ```elvish 1510 fn f { 1511 { 1512 # returns f, falling through the innermost lambda 1513 return 1514 } 1515 } 1516 ``` 1517 1518 1519 # Namespaces and Modules 1520 1521 Namespace in Elvish helps prevent name collisions and is important for 1522 building modules. 1523 1524 ## Syntax 1525 1526 Prepend `namespace:` to command names and variable names to specify the 1527 namespace. The following code 1528 1529 ```elvish 1530 e:echo $E:PATH 1531 ``` 1532 1533 uses the `echo` command from the `e` namespace and the `PATH` variable from 1534 the `E` namespace. 1535 1536 Names of namespaces can contain colons themselves. For instance, in `$x:y:z` 1537 the namespace is `x:y`. More precisely, when parsing command names and 1538 variable names, everything up to the last colon is considered to be the 1539 namespace. 1540 1541 A convention used in articles is when referring to a namespace is to add a 1542 trailing colon: for instance, `edit:` means "the namespace `edit`". This is 1543 remniscent to the syntax but is not syntactically valid. 1544 1545 ## Special Namespaces 1546 1547 The following namespaces have special meanings to the language: 1548 1549 * `local:` and `up:` refer to lexical scopes, and have been documented above. 1550 1551 * `e:` refers to externals. For instance, `e:ls` refers to the external 1552 command `ls`. 1553 1554 Most of the time you can rely on the rules of [command 1555 resolution](#command-resolution) and do not need to use this explicitly, 1556 unless a function defined by you (or an Elvish builtin) shadows an 1557 external command. 1558 1559 * `E:` refers to environment variables. For instance, `$E:USER` is the 1560 environment variable `USER`. 1561 1562 This **is** always needed, because unlike command resolution, variable 1563 resolution does not fall back onto environment variables. 1564 1565 * `builtin:` refers to builtin functions and variables. 1566 1567 You don't need to use this explicitly unless you have defined names that 1568 shadows builtin counterparts. 1569 1570 ## Pre-Imported Modules 1571 1572 Namespaces that are not special (i,e. one of the above) are also called 1573 **modules**. Aside from these special namespaces, Elvish also comes with the 1574 following modules: 1575 1576 * `edit:` for accessing the Elvish editor. This module is available in 1577 interactive mode. 1578 1579 See [reference](/ref/edit.html). 1580 1581 * `re:` for regular expression facilities. 1582 This module is always available. See [reference](/ref/re.html). 1583 1584 * `daemon:` for manipulating the daemon. This module is always available. 1585 1586 This is not yet documented. 1587 1588 ## User-Defined Modules 1589 1590 You can define your own modules with Elvishscript but putting them under 1591 `~/.elvish/lib` and giving them a `.elv` extension. For instance, to define a 1592 module named `a`, store it in `~/.elvish/lib/a.elv`: 1593 1594 ```elvish-transcript 1595 ~> cat ~/.elvish/lib/a.elv 1596 echo "mod a loading" 1597 fn f { 1598 echo "f from mod a" 1599 } 1600 ``` 1601 1602 To import the module, use `use`: 1603 1604 ```elvish-transcript 1605 ~> use a 1606 mod a loading 1607 ~> a:f 1608 f from mod a 1609 ``` 1610 1611 The argument to `use` is called the **usespec** and will be explained in more 1612 details below. In the simplest case, it is simply the module name. 1613 1614 Modules are evaluated in a seprate scope. That means that functions and 1615 variables defined in the module does not pollute the default namespace, and 1616 vice versa. For instance, if you define `ls` as a wrapper function in 1617 `rc.elv`: 1618 1619 ```elvish 1620 fn ls [@a]{ 1621 e:ls --color=auto $@a 1622 } 1623 ``` 1624 1625 That definition is not visible in module files: `ls` will still refer to the 1626 external command `ls`, unless you shadow it in the very same module. 1627 1628 ## Modules in Nested Directories 1629 1630 It is often useful to put modules under directories. When importing such 1631 modules, you can control which (trailing) parts becomes the module name. 1632 1633 For instance, if you have the following content in `x/y/z.elv` (relative to `~/.elvish/lib`, of course): 1634 1635 ```elvish 1636 fn f { 1637 echo 'In a deeply nested module' 1638 } 1639 ``` 1640 1641 It is possible to import the module as `z`, `y:z`, or `x:y:z`: 1642 1643 ```elvish-transcript 1644 ~> use x/y/z # imports as "z" 1645 ~> z:f 1646 In a deeply nested module 1647 ~> use x/y:z # imports as "y:z" 1648 ~> y:z:f 1649 In a deeply nested module 1650 ~> use x:y:z # imports as "x:y:z" 1651 ~> x:y:z:f 1652 In a deeply nested module 1653 ``` 1654 1655 To be precise: 1656 1657 * The path of the module to import is derived by replacing all `:` with `/` 1658 and adding `.elv`. In the above example, all of `x/y/z`, `x/y:z` and 1659 `x:y:z` have the same path `x/y/z.elv` and refer to the same module 1660 1661 * The part after the last `/` becomes the module name. 1662 1663 ## Lexical Scoping of Imports 1664 1665 Namespace imports are also lexically scoped. For instance, if you `use` a 1666 module within an inner scope, it is not available outside that scope: 1667 1668 ```elvish 1669 { 1670 use some-mod 1671 some-mod:some-func 1672 } 1673 some-mod:some-func # not valid 1674 ``` 1675 1676 ## Re-Importing 1677 1678 Modules are cached after one import. Subsequent imports do not re-execute the 1679 module; they only serve the bring it into the current scope. Moreover, the 1680 cache is keyed by the path of the module, not the name under which it is 1681 imported. For instance, if you have the following in `~/.elvish/lib/a/b.elv`: 1682 1683 ```elvish 1684 echo importing 1685 ``` 1686 1687 The following code only prints one `importing`: 1688 1689 ```elvish 1690 { use a:b } 1691 use a:b # only brings mod into the lexical scope 1692 ``` 1693 1694 As does the following: 1695 1696 ```elvish 1697 use a/b 1698 use a:b 1699 ```