code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
elisp None ### Pop-Up Menus
A Lisp program can pop up a menu so that the user can choose an alternative with the mouse. On a text terminal, if the mouse is not available, the user can choose an alternative using the keyboard motion keys—`C-n`, `C-p`, or up- and down-arrow keys.
Function: **x-popup-menu** *position menu*
This function displays a pop-up menu and returns an indication of what selection the user makes.
The argument position specifies where on the screen to put the top left corner of the menu. It can be either a mouse button event (which says to put the menu where the user actuated the button) or a list of this form:
```
((xoffset yoffset) window)
```
where xoffset and yoffset are coordinates, measured in pixels, counting from the top left corner of window. window may be a window or a frame.
If position is `t`, it means to use the current mouse position (or the top-left corner of the frame if the mouse is not available on a text terminal). If position is `nil`, it means to precompute the key binding equivalents for the keymaps specified in menu, without actually displaying or popping up the menu.
The argument menu says what to display in the menu. It can be a keymap or a list of keymaps (see [Menu Keymaps](menu-keymaps)). In this case, the return value is the list of events corresponding to the user’s choice. This list has more than one element if the choice occurred in a submenu. (Note that `x-popup-menu` does not actually execute the command bound to that sequence of events.) On text terminals and toolkits that support menu titles, the title is taken from the prompt string of menu if menu is a keymap, or from the prompt string of the first keymap in menu if it is a list of keymaps (see [Defining Menus](defining-menus)).
Alternatively, menu can have the following form:
```
(title pane1 pane2...)
```
where each pane is a list of form
```
(title item1 item2...)
```
Each item should be a cons cell, `(line . value)`, where line is a string and value is the value to return if that line is chosen. Unlike in a menu keymap, a `nil` value does not make the menu item non-selectable. Alternatively, each item can be a string rather than a cons cell; this makes a non-selectable menu item.
If the user gets rid of the menu without making a valid choice, for instance by clicking the mouse away from a valid choice or by typing `C-g`, then this normally results in a quit and `x-popup-menu` does not return. But if position is a mouse button event (indicating that the user invoked the menu with the mouse) then no quit occurs and `x-popup-menu` returns `nil`.
**Usage note:** Don’t use `x-popup-menu` to display a menu if you could do the job with a prefix key defined with a menu keymap. If you use a menu keymap to implement a menu, `C-h c` and `C-h a` can see the individual items in that menu and provide help for them. If instead you implement the menu by defining a command that calls `x-popup-menu`, the help facilities cannot know what happens inside that command, so they cannot give any help for the menu’s items.
The menu bar mechanism, which lets you switch between submenus by moving the mouse, cannot look within the definition of a command to see that it calls `x-popup-menu`. Therefore, if you try to implement a submenu using `x-popup-menu`, it cannot work with the menu bar in an integrated fashion. This is why all menu bar submenus are implemented with menu keymaps within the parent menu, and never with `x-popup-menu`. See [Menu Bar](menu-bar).
If you want a menu bar submenu to have contents that vary, you should still use a menu keymap to implement it. To make the contents vary, add a hook function to `menu-bar-update-hook` to update the contents of the menu keymap as necessary.
elisp None ### Sentinels: Detecting Process Status Changes
A *process sentinel* is a function that is called whenever the associated process changes status for any reason, including signals (whether sent by Emacs or caused by the process’s own actions) that terminate, stop, or continue the process. The process sentinel is also called if the process exits. The sentinel receives two arguments: the process for which the event occurred, and a string describing the type of event.
If no sentinel function was specified for a process, it will use the default sentinel function, which inserts a message in the process’s buffer with the process name and the string describing the event.
The string describing the event looks like one of the following (but this is not an exhaustive list of event strings):
* `"finished\n"`.
* `"deleted\n"`.
* `"exited abnormally with code exitcode (core dumped)\n"`. The “core dumped” part is optional, and only appears if the process dumped core.
* `"failed with code fail-code\n"`.
* `"signal-description (core dumped)\n"`. The signal-description is a system-dependent textual description of a signal, e.g., `"killed"` for `SIGKILL`. The “core dumped” part is optional, and only appears if the process dumped core.
* `"open from host-name\n"`.
* `"open\n"`.
* `"run\n"`.
* `"connection broken by remote peer\n"`.
A sentinel runs only while Emacs is waiting (e.g., for terminal input, or for time to elapse, or for process output). This avoids the timing errors that could result from running sentinels at random places in the middle of other Lisp programs. A program can wait, so that sentinels will run, by calling `sit-for` or `sleep-for` (see [Waiting](waiting)), or `accept-process-output` (see [Accepting Output](accepting-output)). Emacs also allows sentinels to run when the command loop is reading input. `delete-process` calls the sentinel when it terminates a running process.
Emacs does not keep a queue of multiple reasons to call the sentinel of one process; it records just the current status and the fact that there has been a change. Therefore two changes in status, coming in quick succession, can call the sentinel just once. However, process termination will always run the sentinel exactly once. This is because the process status can’t change again after termination.
Emacs explicitly checks for output from the process before running the process sentinel. Once the sentinel runs due to process termination, no further output can arrive from the process.
A sentinel that writes the output into the buffer of the process should check whether the buffer is still alive. If it tries to insert into a dead buffer, it will get an error. If the buffer is dead, `(buffer-name (process-buffer process))` returns `nil`.
Quitting is normally inhibited within a sentinel—otherwise, the effect of typing `C-g` at command level or to quit a user command would be unpredictable. If you want to permit quitting inside a sentinel, bind `inhibit-quit` to `nil`. In most cases, the right way to do this is with the macro `with-local-quit`. See [Quitting](quitting).
If an error happens during execution of a sentinel, it is caught automatically, so that it doesn’t stop the execution of whatever programs was running when the sentinel was started. However, if `debug-on-error` is non-`nil`, errors are not caught. This makes it possible to use the Lisp debugger to debug the sentinel. See [Debugger](debugger).
While a sentinel is running, the process sentinel is temporarily set to `nil` so that the sentinel won’t run recursively. For this reason it is not possible for a sentinel to specify a new sentinel.
Note that Emacs automatically saves and restores the match data while executing sentinels. See [Match Data](match-data).
Function: **set-process-sentinel** *process sentinel*
This function associates sentinel with process. If sentinel is `nil`, then the process will have the default sentinel, which inserts a message in the process’s buffer when the process status changes.
Changes in process sentinels take effect immediately—if the sentinel is slated to be run but has not been called yet, and you specify a new sentinel, the eventual call to the sentinel will use the new one.
```
(defun msg-me (process event)
(princ
(format "Process: %s had the event '%s'" process event)))
(set-process-sentinel (get-process "shell") 'msg-me)
⇒ msg-me
```
```
(kill-process (get-process "shell"))
-| Process: #<process shell> had the event 'killed'
⇒ #<process shell>
```
Function: **process-sentinel** *process*
This function returns the sentinel of process.
In case a process status changes need to be passed to several sentinels, you can use `add-function` to combine an existing sentinel with a new one. See [Advising Functions](advising-functions).
Function: **waiting-for-user-input-p**
While a sentinel or filter function is running, this function returns non-`nil` if Emacs was waiting for keyboard input from the user at the time the sentinel or filter function was called, or `nil` if it was not.
elisp None ### Modifying Existing List Structure
You can modify the CAR and CDR contents of a cons cell with the primitives `setcar` and `setcdr`. These are destructive operations because they change existing list structure. Destructive operations should be applied only to mutable lists, that is, lists constructed via `cons`, `list` or similar operations. Lists created by quoting are part of the program and should not be changed by destructive operations. See [Mutability](mutability).
> **Common Lisp note:** Common Lisp uses functions `rplaca` and `rplacd` to alter list structure; they change structure the same way as `setcar` and `setcdr`, but the Common Lisp functions return the cons cell while `setcar` and `setcdr` return the new CAR or CDR.
>
>
>
| | | |
| --- | --- | --- |
| • [Setcar](setcar) | | Replacing an element in a list. |
| • [Setcdr](setcdr) | | Replacing part of the list backbone. This can be used to remove or add elements. |
| • [Rearrangement](rearrangement) | | Reordering the elements in a list; combining lists. |
elisp None #### Examples of Using interactive
Here are some examples of `interactive`:
```
(defun foo1 () ; `foo1` takes no arguments,
(interactive) ; just moves forward two words.
(forward-word 2))
⇒ foo1
```
```
(defun foo2 (n) ; `foo2` takes one argument,
(interactive "^p") ; which is the numeric prefix.
; under `shift-select-mode`,
; will activate or extend region.
(forward-word (* 2 n)))
⇒ foo2
```
```
(defun foo3 (n) ; `foo3` takes one argument,
(interactive "nCount:") ; which is read with the Minibuffer.
(forward-word (* 2 n)))
⇒ foo3
```
```
(defun three-b (b1 b2 b3)
"Select three existing buffers.
Put them into three windows, selecting the last one."
```
```
(interactive "bBuffer1:\nbBuffer2:\nbBuffer3:")
(delete-other-windows)
(split-window (selected-window) 8)
(switch-to-buffer b1)
(other-window 1)
(split-window (selected-window) 8)
(switch-to-buffer b2)
(other-window 1)
(switch-to-buffer b3))
⇒ three-b
```
```
(three-b "*scratch*" "declarations.texi" "*mail*")
⇒ nil
```
elisp None #### How Emacs Chooses a Major Mode
When Emacs visits a file, it automatically selects a major mode for the buffer based on information in the file name or in the file itself. It also processes local variables specified in the file text.
Command: **normal-mode** *&optional find-file*
This function establishes the proper major mode and buffer-local variable bindings for the current buffer. It calls `set-auto-mode` (see below). As of Emacs 26.1, it no longer runs `hack-local-variables`, this now being done in `run-mode-hooks` at the initialization of major modes (see [Mode Hooks](mode-hooks)).
If the find-file argument to `normal-mode` is non-`nil`, `normal-mode` assumes that the `find-file` function is calling it. In this case, it may process local variables in the ‘`-\*-`’ line or at the end of the file. The variable `enable-local-variables` controls whether to do so. See [Local Variables in Files](https://www.gnu.org/software/emacs/manual/html_node/emacs/File-Variables.html#File-Variables) in The GNU Emacs Manual, for the syntax of the local variables section of a file.
If you run `normal-mode` interactively, the argument find-file is normally `nil`. In this case, `normal-mode` unconditionally processes any file local variables.
The function calls `set-auto-mode` to choose and set a major mode. If this does not specify a mode, the buffer stays in the major mode determined by the default value of `major-mode` (see below).
`normal-mode` uses `condition-case` around the call to the major mode command, so errors are caught and reported as a ‘`File mode specification error`’, followed by the original error message.
Function: **set-auto-mode** *&optional keep-mode-if-same*
This function selects and sets the major mode that is appropriate for the current buffer. It bases its decision (in order of precedence) on the ‘`-\*-`’ line, on any ‘`mode:`’ local variable near the end of a file, on the ‘`#!`’ line (using `interpreter-mode-alist`), on the text at the beginning of the buffer (using `magic-mode-alist`), and finally on the visited file name (using `auto-mode-alist`). See [How Major Modes are Chosen](https://www.gnu.org/software/emacs/manual/html_node/emacs/Choosing-Modes.html#Choosing-Modes) in The GNU Emacs Manual. If `enable-local-variables` is `nil`, `set-auto-mode` does not check the ‘`-\*-`’ line, or near the end of the file, for any mode tag.
There are some file types where it is not appropriate to scan the file contents for a mode specifier. For example, a tar archive may happen to contain, near the end of the file, a member file that has a local variables section specifying a mode for that particular file. This should not be applied to the containing tar file. Similarly, a tiff image file might just happen to contain a first line that seems to match the ‘`-\*-`’ pattern. For these reasons, both these file extensions are members of the list `inhibit-local-variables-regexps`. Add patterns to this list to prevent Emacs searching them for local variables of any kind (not just mode specifiers).
If keep-mode-if-same is non-`nil`, this function does not call the mode command if the buffer is already in the proper major mode. For instance, `set-visited-file-name` sets this to `t` to avoid killing buffer local variables that the user may have set.
Function: **set-buffer-major-mode** *buffer*
This function sets the major mode of buffer to the default value of `major-mode`; if that is `nil`, it uses the current buffer’s major mode (if that is suitable). As an exception, if buffer’s name is `\*scratch\*`, it sets the mode to `initial-major-mode`.
The low-level primitives for creating buffers do not use this function, but medium-level commands such as `switch-to-buffer` and `find-file-noselect` use it whenever they create buffers.
User Option: **initial-major-mode**
The value of this variable determines the major mode of the initial `\*scratch\*` buffer. The value should be a symbol that is a major mode command. The default value is `lisp-interaction-mode`.
Variable: **interpreter-mode-alist**
This variable specifies major modes to use for scripts that specify a command interpreter in a ‘`#!`’ line. Its value is an alist with elements of the form `(regexp . mode)`; this says to use mode mode if the file specifies an interpreter which matches `\\`regexp\\'`. For example, one of the default elements is `("python[0-9.]*" . python-mode)`.
Variable: **magic-mode-alist**
This variable’s value is an alist with elements of the form `(regexp . function)`, where regexp is a regular expression and function is a function or `nil`. After visiting a file, `set-auto-mode` calls function if the text at the beginning of the buffer matches regexp and function is non-`nil`; if function is `nil`, `auto-mode-alist` gets to decide the mode.
Variable: **magic-fallback-mode-alist**
This works like `magic-mode-alist`, except that it is handled only if `auto-mode-alist` does not specify a mode for this file.
Variable: **auto-mode-alist**
This variable contains an association list of file name patterns (regular expressions) and corresponding major mode commands. Usually, the file name patterns test for suffixes, such as ‘`.el`’ and ‘`.c`’, but this need not be the case. An ordinary element of the alist looks like `(regexp . mode-function)`.
For example,
```
(("\\`/tmp/fol/" . text-mode)
("\\.texinfo\\'" . texinfo-mode)
("\\.texi\\'" . texinfo-mode)
```
```
("\\.el\\'" . emacs-lisp-mode)
("\\.c\\'" . c-mode)
("\\.h\\'" . c-mode)
…)
```
When you visit a file whose expanded file name (see [File Name Expansion](file-name-expansion)), with version numbers and backup suffixes removed using `file-name-sans-versions` (see [File Name Components](file-name-components)), matches a regexp, `set-auto-mode` calls the corresponding mode-function. This feature enables Emacs to select the proper major mode for most files.
If an element of `auto-mode-alist` has the form `(regexp
function t)`, then after calling function, Emacs searches `auto-mode-alist` again for a match against the portion of the file name that did not match before. This feature is useful for uncompression packages: an entry of the form `("\\.gz\\'"
function t)` can uncompress the file and then put the uncompressed file in the proper mode according to the name sans ‘`.gz`’.
If `auto-mode-alist` has more than one element whose regexp matches the file name, Emacs will use the first match.
Here is an example of how to prepend several pattern pairs to `auto-mode-alist`. (You might use this sort of expression in your init file.)
```
(setq auto-mode-alist
(append
;; File name (within directory) starts with a dot.
'(("/\\.[^/]*\\'" . fundamental-mode)
;; File name has no dot.
("/[^\\./]*\\'" . fundamental-mode)
;; File name ends in ‘`.C`’.
("\\.C\\'" . c++-mode))
auto-mode-alist))
```
elisp None #### Edebug Execution Modes
Edebug supports several execution modes for running the program you are debugging. We call these alternatives *Edebug execution modes*; do not confuse them with major or minor modes. The current Edebug execution mode determines how far Edebug continues execution before stopping—whether it stops at each stop point, or continues to the next breakpoint, for example—and how much Edebug displays the progress of the evaluation before it stops.
Normally, you specify the Edebug execution mode by typing a command to continue the program in a certain mode. Here is a table of these commands; all except for `S` resume execution of the program, at least for a certain distance.
`S`
Stop: don’t execute any more of the program, but wait for more Edebug commands (`edebug-stop`).
`SPC`
Step: stop at the next stop point encountered (`edebug-step-mode`).
`n`
Next: stop at the next stop point encountered after an expression (`edebug-next-mode`). Also see `edebug-forward-sexp` in [Jumping](jumping).
`t`
Trace: pause (normally one second) at each Edebug stop point (`edebug-trace-mode`).
`T`
Rapid trace: update the display at each stop point, but don’t actually pause (`edebug-Trace-fast-mode`).
`g`
Go: run until the next breakpoint (`edebug-go-mode`). See [Breakpoints](breakpoints).
`c`
Continue: pause one second at each breakpoint, and then continue (`edebug-continue-mode`).
`C`
Rapid continue: move point to each breakpoint, but don’t pause (`edebug-Continue-fast-mode`).
`G` Go non-stop: ignore breakpoints (`edebug-Go-nonstop-mode`). You can still stop the program by typing `S`, or any editing command.
In general, the execution modes earlier in the above list run the program more slowly or stop sooner than the modes later in the list.
When you enter a new Edebug level, Edebug will normally stop at the first instrumented function it encounters. If you prefer to stop only at a break point, or not at all (for example, when gathering coverage data), change the value of `edebug-initial-mode` from its default `step` to `go`, or `Go-nonstop`, or one of its other values (see [Edebug Options](edebug-options)). You can do this readily with `C-x C-a C-m` (`edebug-set-initial-mode`):
Command: **edebug-set-initial-mode**
This command, bound to `C-x C-a C-m`, sets `edebug-initial-mode`. It prompts you for a key to indicate the mode. You should enter one of the eight keys listed above, which sets the corresponding mode.
Note that you may reenter the same Edebug level several times if, for example, an instrumented function is called several times from one command.
While executing or tracing, you can interrupt the execution by typing any Edebug command. Edebug stops the program at the next stop point and then executes the command you typed. For example, typing `t` during execution switches to trace mode at the next stop point. You can use `S` to stop execution without doing anything else.
If your function happens to read input, a character you type intending to interrupt execution may be read by the function instead. You can avoid such unintended results by paying attention to when your program wants input.
Keyboard macros containing the commands in this section do not completely work: exiting from Edebug, to resume the program, loses track of the keyboard macro. This is not easy to fix. Also, defining or executing a keyboard macro outside of Edebug does not affect commands inside Edebug. This is usually an advantage. See also the `edebug-continue-kbd-macro` option in [Edebug Options](edebug-options).
User Option: **edebug-sit-for-seconds**
This option specifies how many seconds to wait between execution steps in trace mode or continue mode. The default is 1 second.
| programming_docs |
elisp None #### Text Property Search Functions
In typical use of text properties, most of the time several or many consecutive characters have the same value for a property. Rather than writing your programs to examine characters one by one, it is much faster to process chunks of text that have the same property value.
Here are functions you can use to do this. They use `eq` for comparing property values. In all cases, object defaults to the current buffer.
For good performance, it’s very important to use the limit argument to these functions, especially the ones that search for a single property—otherwise, they may spend a long time scanning to the end of the buffer, if the property you are interested in does not change.
These functions do not move point; instead, they return a position (or `nil`). Remember that a position is always between two characters; the position returned by these functions is between two characters with different properties.
Function: **next-property-change** *pos &optional object limit*
The function scans the text forward from position pos in the string or buffer object until it finds a change in some text property, then returns the position of the change. In other words, it returns the position of the first character beyond pos whose properties are not identical to those of the character just after pos.
If limit is non-`nil`, then the scan ends at position limit. If there is no property change before that point, this function returns limit.
The value is `nil` if the properties remain unchanged all the way to the end of object and limit is `nil`. If the value is non-`nil`, it is a position greater than or equal to pos. The value equals pos only when limit equals pos.
Here is an example of how to scan the buffer by chunks of text within which all properties are constant:
```
(while (not (eobp))
(let ((plist (text-properties-at (point)))
(next-change
(or (next-property-change (point) (current-buffer))
(point-max))))
Process text from point to next-change…
(goto-char next-change)))
```
Function: **previous-property-change** *pos &optional object limit*
This is like `next-property-change`, but scans back from pos instead of forward. If the value is non-`nil`, it is a position less than or equal to pos; it equals pos only if limit equals pos.
Function: **next-single-property-change** *pos prop &optional object limit*
The function scans text for a change in the prop property, then returns the position of the change. The scan goes forward from position pos in the string or buffer object. In other words, this function returns the position of the first character beyond pos whose prop property differs from that of the character just after pos.
If limit is non-`nil`, then the scan ends at position limit. If there is no property change before that point, `next-single-property-change` returns limit.
The value is `nil` if the property remains unchanged all the way to the end of object and limit is `nil`. If the value is non-`nil`, it is a position greater than or equal to pos; it equals pos only if limit equals pos.
Function: **previous-single-property-change** *pos prop &optional object limit*
This is like `next-single-property-change`, but scans back from pos instead of forward. If the value is non-`nil`, it is a position less than or equal to pos; it equals pos only if limit equals pos.
Function: **next-char-property-change** *pos &optional limit*
This is like `next-property-change` except that it considers overlay properties as well as text properties, and if no change is found before the end of the buffer, it returns the maximum buffer position rather than `nil` (in this sense, it resembles the corresponding overlay function `next-overlay-change`, rather than `next-property-change`). There is no object operand because this function operates only on the current buffer. It returns the next address at which either kind of property changes.
Function: **previous-char-property-change** *pos &optional limit*
This is like `next-char-property-change`, but scans back from pos instead of forward, and returns the minimum buffer position if no change is found.
Function: **next-single-char-property-change** *pos prop &optional object limit*
This is like `next-single-property-change` except that it considers overlay properties as well as text properties, and if no change is found before the end of the object, it returns the maximum valid position in object rather than `nil`. Unlike `next-char-property-change`, this function *does* have an object operand; if object is not a buffer, only text-properties are considered.
Function: **previous-single-char-property-change** *pos prop &optional object limit*
This is like `next-single-char-property-change`, but scans back from pos instead of forward, and returns the minimum valid position in object if no change is found.
Function: **text-property-any** *start end prop value &optional object*
This function returns non-`nil` if at least one character between start and end has a property prop whose value is value. More precisely, it returns the position of the first such character. Otherwise, it returns `nil`.
The optional fifth argument, object, specifies the string or buffer to scan. Positions are relative to object. The default for object is the current buffer.
Function: **text-property-not-all** *start end prop value &optional object*
This function returns non-`nil` if at least one character between start and end does not have a property prop with value value. More precisely, it returns the position of the first such character. Otherwise, it returns `nil`.
The optional fifth argument, object, specifies the string or buffer to scan. Positions are relative to object. The default for object is the current buffer.
Function: **text-property-search-forward** *prop &optional value predicate not-current*
Search for the next region that has text property prop set to value according to predicate.
This function is modeled after `search-forward` and friends in that it moves point, but it returns a structure that describes the match instead of returning it in `match-beginning` and friends.
If the text property can’t be found, the function returns `nil`. If it’s found, point is placed at the end of the region that has this text property match, and a `prop-match` structure is returned.
predicate can either be `t` (which is a synonym for `equal`), `nil` (which means “not equal”), or a predicate that will be called with two parameters: The first is value, and the second is the value of the text property we’re inspecting.
If not-current, if point is in a region where we have a match, then skip past that and find the next instance instead.
The `prop-match` structure has the following accessors: `prop-match-beginning` (the start of the match), `prop-match-end` (the end of the match), and `prop-match-value` (the value of property at the start of the match).
In the examples below, imagine that you’re in a buffer that looks like this:
```
This is a bold and here's bolditalic and this is the end.
```
That is, the “bold” words are the `bold` face, and the “italic” word is in the `italic` face.
With point at the start:
```
(while (setq match (text-property-search-forward 'face 'bold t))
(push (buffer-substring (prop-match-beginning match)
(prop-match-end match))
words))
```
This will pick out all the words that use the `bold` face.
```
(while (setq match (text-property-search-forward 'face nil t))
(push (buffer-substring (prop-match-beginning match)
(prop-match-end match))
words))
```
This will pick out all the bits that have no face properties, which will result in the list ‘`("This is a " "and here's " "and this is the end")`’ (only reversed, since we used `push`).
```
(while (setq match (text-property-search-forward 'face nil nil))
(push (buffer-substring (prop-match-beginning match)
(prop-match-end match))
words))
```
This will pick out all the regions where `face` is set to something, but this is split up into where the properties change, so the result here will be ‘`("bold" "bold" "italic")`’.
For a more realistic example where you might use this, consider that you have a buffer where certain sections represent URLs, and these are tagged with `shr-url`.
```
(while (setq match (text-property-search-forward 'shr-url nil nil))
(push (prop-match-value match) urls))
```
This will give you a list of all those URLs.
Function: **text-property-search-backward** *prop &optional value predicate not-current*
This is just like `text-property-search-backward`, but searches backward instead. Point is placed at the beginning of the matched region instead of the end, though.
elisp None ### Quitting Windows
After a command uses `display-buffer` to put a buffer on the screen, the user may decide to hide it and return to the previous configuration of the Emacs display. We call that *quitting the window*. The way to do this is to call `quit-window` while the window used by `display-buffer` is the selected window.
The right way to restore the previous configuration of the display depends on what was done to the window where the buffer now appears. It might be right to delete that window, or delete its frame, or just display another buffer in that window. One complication is that the user may have changed the window configuration since the act of displaying that buffer, and it would be undesirable to undo the user’s explicitly requested changes.
To enable `quit-window` to do the right thing, `display-buffer` saves information about what it did in the window’s `quit-restore` parameter (see [Window Parameters](window-parameters)).
Command: **quit-window** *&optional kill window*
This command quits window and buries its buffer. The argument window must be a live window and defaults to the selected one. With prefix argument kill non-`nil`, it kills the buffer instead of burying it.
The function `quit-window` first runs `quit-window-hook`. Then it calls the function `quit-restore-window`, described next, which does the hard work.
You can get more control by calling `quit-restore-window` instead.
Function: **quit-restore-window** *&optional window bury-or-kill*
This function handles window and its buffer after quitting. The optional argument window must be a live window and defaults to the selected one. The function takes account of the window’s `quit-restore` parameter.
The optional argument bury-or-kill specifies how to deal with window’s buffer. The following values are meaningful:
`nil`
This means to not deal with the buffer in any particular way. As a consequence, if window is not deleted, invoking `switch-to-prev-buffer` will usually show the buffer again.
`append`
This means that if window is not deleted, its buffer is moved to the end of window’s list of previous buffers (see [Window History](window-history)), so it’s less likely that future invocations of `switch-to-prev-buffer` will switch to it. Also, it moves the buffer to the end of the frame’s buffer list (see [Buffer List](buffer-list)).
`bury`
This means that if window is not deleted, its buffer is removed from window’s list of previous buffers. Also, it moves the buffer to the end of the frame’s buffer list. This is the most reliable way to prevent `switch-to-prev-buffer` from switching to this buffer again, short of killing the buffer.
`kill` This means to kill window’s buffer.
The argument bury-or-kill also specifies what to do with window’s frame when window should be deleted, if it is the only window on its frame, and there are other frames on that frame’s terminal. If bury-or-kill equals `kill`, it means to delete the frame. Otherwise, the fate of the frame is determined by calling `frame-auto-hide-function` (see below) with that frame as sole argument.
This function always sets window’s `quit-restore` parameter to `nil` unless it deletes the window.
The window window’s `quit-restore` parameter (see [Window Parameters](window-parameters)) should be `nil` or a list of four elements:
```
(method obuffer owindow this-buffer)
```
The first element, method, is one of the four symbols `window`, `frame`, `same` and `other`. `frame` and `window` control how to delete window, while `same` and `other` control displaying some other buffer in it.
Specifically, `window` means that the window has been specially created by `display-buffer`; `frame` means that a separate frame has been created; `same`, that the window has only ever displayed this buffer; `other`, that the window showed another buffer before.
The second element, obuffer, is either one of the symbols `window` or `frame`, or a list of the form
```
(prev-buffer prev-window-start prev-window-point height)
```
which says which buffer was shown in window before, that buffer’s window start (see [Window Start and End](window-start-and-end)) and window point (see [Window Point](window-point)) positions at that time, and window’s height at that time. If prev-buffer is still live when quitting window, quitting the window may reuse window to display prev-buffer.
The third element, owindow, is the window that was selected just before the displaying was done. If quitting deletes window, it tries to select owindow.
The fourth element, this-buffer, is the buffer whose displaying set the `quit-restore` parameter. Quitting window may delete that window only if it still shows that buffer.
Quitting window tries to delete it if and only if (1) method is either `window` or `frame`, (2) the window has no history of previously-displayed buffers and (3) this-buffer equals the buffer currently displayed in window. If window is part of an atomic window (see [Atomic Windows](atomic-windows)), quitting will try to delete the root of that atomic window instead. In either case, it tries to avoid signaling an error when window cannot be deleted.
If obuffer is a list, and prev-buffer is still live, quitting displays prev-buffer in window according to the rest of the elements of obuffer. This includes resizing the window to height if it was temporarily resized to display this-buffer.
Otherwise, if window was previously used for displaying other buffers (see [Window History](window-history)), the most recent buffer in that history will be displayed.
The following option specifies a function to do the right thing with a frame containing one window when quitting that window.
User Option: **frame-auto-hide-function**
The function specified by this option is called to automatically hide frames. This function is called with one argument—a frame.
The function specified here is called by `bury-buffer` (see [Buffer List](buffer-list)) when the selected window is dedicated and shows the buffer to bury. It is also called by `quit-restore-window` (see above) when the frame of the window to quit has been specially created for displaying that window’s buffer and the buffer is not killed.
The default is to call `iconify-frame` (see [Visibility of Frames](visibility-of-frames)). Alternatively, you may specify either `delete-frame` (see [Deleting Frames](deleting-frames)) to remove the frame from its display, `make-frame-invisible` to make the frame invisible, `ignore` to leave the frame unchanged, or any other function that can take a frame as its sole argument.
Note that the function specified by this option is called only if the specified frame contains just one live window and there is at least one other frame on the same terminal.
For a particular frame, the value specified here may be overridden by that frame’s `auto-hide-function` frame parameter (see [Frame Interaction Parameters](frame-interaction-parameters)).
elisp None #### Syntax Flags
In addition to the classes, entries for characters in a syntax table can specify flags. There are eight possible flags, represented by the characters ‘`1`’, ‘`2`’, ‘`3`’, ‘`4`’, ‘`b`’, ‘`c`’, ‘`n`’, and ‘`p`’.
All the flags except ‘`p`’ are used to describe comment delimiters. The digit flags are used for comment delimiters made up of 2 characters. They indicate that a character can *also* be part of a comment sequence, in addition to the syntactic properties associated with its character class. The flags are independent of the class and each other for the sake of characters such as ‘`\*`’ in C mode, which is a punctuation character, *and* the second character of a start-of-comment sequence (‘`/\*`’), *and* the first character of an end-of-comment sequence (‘`\*/`’). The flags ‘`b`’, ‘`c`’, and ‘`n`’ are used to qualify the corresponding comment delimiter.
Here is a table of the possible flags for a character c, and what they mean:
* ‘`1`’ means c is the start of a two-character comment-start sequence.
* ‘`2`’ means c is the second character of such a sequence.
* ‘`3`’ means c is the start of a two-character comment-end sequence.
* ‘`4`’ means c is the second character of such a sequence.
* ‘`b`’ means that c as a comment delimiter belongs to the alternative “b” comment style. For a two-character comment starter, this flag is only significant on the second char, and for a 2-character comment ender it is only significant on the first char.
* ‘`c`’ means that c as a comment delimiter belongs to the alternative “c” comment style. For a two-character comment delimiter, ‘`c`’ on either character makes it of style “c”.
* ‘`n`’ on a comment delimiter character specifies that this kind of comment can be nested. Inside such a comment, only comments of the same style will be recognized. For a two-character comment delimiter, ‘`n`’ on either character makes it nestable. Emacs supports several comment styles simultaneously in any one syntax table. A comment style is a set of flags ‘`b`’, ‘`c`’, and ‘`n`’, so there can be up to 8 different comment styles, each one named by the set of its flags. Each comment delimiter has a style and only matches comment delimiters of the same style. Thus if a comment starts with the comment-start sequence of style “bn”, it will extend until the next matching comment-end sequence of style “bn”. When the set of flags has neither flag ‘`b`’ nor flag ‘`c`’ set, the resulting style is called the “a” style.
The appropriate comment syntax settings for C++ can be as follows:
‘`/`’ ‘`124`’
‘`\*`’ ‘`23b`’
newline ‘`>`’
This defines four comment-delimiting sequences:
‘`/\*`’
This is a comment-start sequence for “b” style because the second character, ‘`\*`’, has the ‘`b`’ flag.
‘`//`’
This is a comment-start sequence for “a” style because the second character, ‘`/`’, does not have the ‘`b`’ flag.
‘`\*/`’
This is a comment-end sequence for “b” style because the first character, ‘`\*`’, has the ‘`b`’ flag.
newline This is a comment-end sequence for “a” style, because the newline character does not have the ‘`b`’ flag.
* ‘`p`’ identifies an additional prefix character for Lisp syntax. These characters are treated as whitespace when they appear between expressions. When they appear within an expression, they are handled according to their usual syntax classes. The function `backward-prefix-chars` moves back over these characters, as well as over characters whose primary syntax class is prefix (‘`'`’). See [Motion and Syntax](motion-and-syntax).
elisp None #### Abstract Display Functions
In this subsection, ewoc and node stand for the structures described above (see [Abstract Display](abstract-display)), while data stands for an arbitrary Lisp object used as a data element.
Function: **ewoc-create** *pretty-printer &optional header footer nosep*
This constructs and returns a new ewoc, with no nodes (and thus no data elements). pretty-printer should be a function that takes one argument, a data element of the sort you plan to use in this ewoc, and inserts its textual description at point using `insert` (and never `insert-before-markers`, because that would interfere with the Ewoc package’s internal mechanisms).
Normally, a newline is automatically inserted after the header, the footer and every node’s textual description. If nosep is non-`nil`, no newline is inserted. This may be useful for displaying an entire ewoc on a single line, for example, or for making nodes invisible by arranging for pretty-printer to do nothing for those nodes.
An ewoc maintains its text in the buffer that is current when you create it, so switch to the intended buffer before calling `ewoc-create`.
Function: **ewoc-buffer** *ewoc*
This returns the buffer where ewoc maintains its text.
Function: **ewoc-get-hf** *ewoc*
This returns a cons cell `(header . footer)` made from ewoc’s header and footer.
Function: **ewoc-set-hf** *ewoc header footer*
This sets the header and footer of ewoc to the strings header and footer, respectively.
Function: **ewoc-enter-first** *ewoc data*
Function: **ewoc-enter-last** *ewoc data*
These add a new node encapsulating data, putting it, respectively, at the beginning or end of ewoc’s chain of nodes.
Function: **ewoc-enter-before** *ewoc node data*
Function: **ewoc-enter-after** *ewoc node data*
These add a new node encapsulating data, adding it to ewoc before or after node, respectively.
Function: **ewoc-prev** *ewoc node*
Function: **ewoc-next** *ewoc node*
These return, respectively, the previous node and the next node of node in ewoc.
Function: **ewoc-nth** *ewoc n*
This returns the node in ewoc found at zero-based index n. A negative n means count from the end. `ewoc-nth` returns `nil` if n is out of range.
Function: **ewoc-data** *node*
This extracts the data encapsulated by node and returns it.
Function: **ewoc-set-data** *node data*
This sets the data encapsulated by node to data.
Function: **ewoc-locate** *ewoc &optional pos guess*
This determines the node in ewoc which contains point (or pos if specified), and returns that node. If ewoc has no nodes, it returns `nil`. If pos is before the first node, it returns the first node; if pos is after the last node, it returns the last node. The optional third arg guess should be a node that is likely to be near pos; this doesn’t alter the result, but makes the function run faster.
Function: **ewoc-location** *node*
This returns the start position of node.
Function: **ewoc-goto-prev** *ewoc arg*
Function: **ewoc-goto-next** *ewoc arg*
These move point to the previous or next, respectively, argth node in ewoc. `ewoc-goto-prev` does not move if it is already at the first node or if ewoc is empty, whereas `ewoc-goto-next` moves past the last node, returning `nil`. Excepting this special case, these functions return the node moved to.
Function: **ewoc-goto-node** *ewoc node*
This moves point to the start of node in ewoc.
Function: **ewoc-refresh** *ewoc*
This function regenerates the text of ewoc. It works by deleting the text between the header and the footer, i.e., all the data elements’ representations, and then calling the pretty-printer function for each node, one by one, in order.
Function: **ewoc-invalidate** *ewoc &rest nodes*
This is similar to `ewoc-refresh`, except that only nodes in ewoc are updated instead of the entire set.
Function: **ewoc-delete** *ewoc &rest nodes*
This deletes each node in nodes from ewoc.
Function: **ewoc-filter** *ewoc predicate &rest args*
This calls predicate for each data element in ewoc and deletes those nodes for which predicate returns `nil`. Any args are passed to predicate.
Function: **ewoc-collect** *ewoc predicate &rest args*
This calls predicate for each data element in ewoc and returns a list of those elements for which predicate returns non-`nil`. The elements in the list are ordered as in the buffer. Any args are passed to predicate.
Function: **ewoc-map** *map-function ewoc &rest args*
This calls map-function for each data element in ewoc and updates those nodes for which map-function returns non-`nil`. Any args are passed to map-function.
| programming_docs |
elisp None #### Explicit Encoding and Decoding
All the operations that transfer text in and out of Emacs have the ability to use a coding system to encode or decode the text. You can also explicitly encode and decode text using the functions in this section.
The result of encoding, and the input to decoding, are not ordinary text. They logically consist of a series of byte values; that is, a series of ASCII and eight-bit characters. In unibyte buffers and strings, these characters have codes in the range 0 through #xFF (255). In a multibyte buffer or string, eight-bit characters have character codes higher than #xFF (see [Text Representations](text-representations)), but Emacs transparently converts them to their single-byte values when you encode or decode such text.
The usual way to read a file into a buffer as a sequence of bytes, so you can decode the contents explicitly, is with `insert-file-contents-literally` (see [Reading from Files](reading-from-files)); alternatively, specify a non-`nil` rawfile argument when visiting a file with `find-file-noselect`. These methods result in a unibyte buffer.
The usual way to use the byte sequence that results from explicitly encoding text is to copy it to a file or process—for example, to write it with `write-region` (see [Writing to Files](writing-to-files)), and suppress encoding by binding `coding-system-for-write` to `no-conversion`.
Here are the functions to perform explicit encoding or decoding. The encoding functions produce sequences of bytes; the decoding functions are meant to operate on sequences of bytes. All of these functions discard text properties. They also set `last-coding-system-used` to the precise coding system they used.
Command: **encode-coding-region** *start end coding-system &optional destination*
This command encodes the text from start to end according to coding system coding-system. Normally, the encoded text replaces the original text in the buffer, but the optional argument destination can change that. If destination is a buffer, the encoded text is inserted in that buffer after point (point does not move); if it is `t`, the command returns the encoded text as a unibyte string without inserting it.
If encoded text is inserted in some buffer, this command returns the length of the encoded text.
The result of encoding is logically a sequence of bytes, but the buffer remains multibyte if it was multibyte before, and any 8-bit bytes are converted to their multibyte representation (see [Text Representations](text-representations)).
Do *not* use `undecided` for coding-system when encoding text, since that may lead to unexpected results. Instead, use `select-safe-coding-system` (see [select-safe-coding-system](user_002dchosen-coding-systems)) to suggest a suitable encoding, if there’s no obvious pertinent value for coding-system.
Function: **encode-coding-string** *string coding-system &optional nocopy buffer*
This function encodes the text in string according to coding system coding-system. It returns a new string containing the encoded text, except when nocopy is non-`nil`, in which case the function may return string itself if the encoding operation is trivial. The result of encoding is a unibyte string.
Command: **decode-coding-region** *start end coding-system &optional destination*
This command decodes the text from start to end according to coding system coding-system. To make explicit decoding useful, the text before decoding ought to be a sequence of byte values, but both multibyte and unibyte buffers are acceptable (in the multibyte case, the raw byte values should be represented as eight-bit characters). Normally, the decoded text replaces the original text in the buffer, but the optional argument destination can change that. If destination is a buffer, the decoded text is inserted in that buffer after point (point does not move); if it is `t`, the command returns the decoded text as a multibyte string without inserting it.
If decoded text is inserted in some buffer, this command returns the length of the decoded text. If that buffer is a unibyte buffer (see [Selecting a Representation](selecting-a-representation)), the internal representation of the decoded text (see [Text Representations](text-representations)) is inserted into the buffer as individual bytes.
This command puts a `charset` text property on the decoded text. The value of the property states the character set used to decode the original text.
This command detects the encoding of the text if necessary. If coding-system is `undecided`, the command detects the encoding of the text based on the byte sequences it finds in the text, and also detects the type of end-of-line convention used by the text (see [eol type](lisp-and-coding-systems)). If coding-system is `undecided-eol-type`, where eol-type is `unix`, `dos`, or `mac`, then the command detects only the encoding of the text. Any coding-system that doesn’t specify eol-type, as in `utf-8`, causes the command to detect the end-of-line convention; specify the encoding completely, as in `utf-8-unix`, if the EOL convention used by the text is known in advance, to prevent any automatic detection.
Function: **decode-coding-string** *string coding-system &optional nocopy buffer*
This function decodes the text in string according to coding-system. It returns a new string containing the decoded text, except when nocopy is non-`nil`, in which case the function may return string itself if the decoding operation is trivial. To make explicit decoding useful, the contents of string ought to be a unibyte string with a sequence of byte values, but a multibyte string is also acceptable (assuming it contains 8-bit bytes in their multibyte form).
This function detects the encoding of the string if needed, like `decode-coding-region` does.
If optional argument buffer specifies a buffer, the decoded text is inserted in that buffer after point (point does not move). In this case, the return value is the length of the decoded text. If that buffer is a unibyte buffer, the internal representation of the decoded text is inserted into it as individual bytes.
This function puts a `charset` text property on the decoded text. The value of the property states the character set used to decode the original text:
```
(decode-coding-string "Gr\374ss Gott" 'latin-1)
⇒ #("Grüss Gott" 0 9 (charset iso-8859-1))
```
Function: **decode-coding-inserted-region** *from to filename &optional visit beg end replace*
This function decodes the text from from to to as if it were being read from file filename using `insert-file-contents` using the rest of the arguments provided.
The normal way to use this function is after reading text from a file without decoding, if you decide you would rather have decoded it. Instead of deleting the text and reading it again, this time with decoding, you can call this function.
elisp None #### Other Display Specifications
Here are the other sorts of display specifications that you can use in the `display` text property.
`string`
Display string instead of the text that has this property.
Recursive display specifications are not supported—string’s `display` properties, if any, are not used.
`(image . image-props)`
This kind of display specification is an image descriptor (see [Image Descriptors](image-descriptors)). When used as a display specification, it means to display the image instead of the text that has the display specification.
`(slice x y width height)`
This specification together with `image` specifies a *slice* (a partial area) of the image to display. The elements y and x specify the top left corner of the slice, within the image; width and height specify the width and height of the slice. Integers are numbers of pixels. A floating-point number in the range 0.0–1.0 stands for that fraction of the width or height of the entire image.
`((margin nil) string)`
A display specification of this form means to display string instead of the text that has the display specification, at the same position as that text. It is equivalent to using just string, but it is done as a special case of marginal display (see [Display Margins](display-margins)).
`(left-fringe bitmap [face])` `(right-fringe bitmap [face])`
This display specification on any character of a line of text causes the specified bitmap be displayed in the left or right fringes for that line, instead of the characters that have the display specification. The optional face specifies the face whose colors are to be used for the bitmap display. See [Fringe Bitmaps](fringe-bitmaps), for the details.
`(space-width factor)`
This display specification affects all the space characters within the text that has the specification. It displays all of these spaces factor times as wide as normal. The element factor should be an integer or float. Characters other than spaces are not affected at all; in particular, this has no effect on tab characters.
`(height height)`
This display specification makes the text taller or shorter. Here are the possibilities for height:
`(+ n)`
This means to use a font that is n steps larger. A *step* is defined by the set of available fonts—specifically, those that match what was otherwise specified for this text, in all attributes except height. Each size for which a suitable font is available counts as another step. n should be an integer.
`(- n)`
This means to use a font that is n steps smaller.
a number, factor
A number, factor, means to use a font that is factor times as tall as the default font.
a symbol, function
A symbol is a function to compute the height. It is called with the current height as argument, and should return the new height to use.
anything else, form
If the height value doesn’t fit the previous possibilities, it is a form. Emacs evaluates it to get the new height, with the symbol `height` bound to the current specified font height.
`(raise factor)`
This kind of display specification raises or lowers the text it applies to, relative to the baseline of the line. It is mainly meant to support display of subscripts and superscripts.
The factor must be a number, which is interpreted as a multiple of the height of the affected text. If it is positive, that means to display the characters raised. If it is negative, that means to display them lower down.
Note that if the text also has a `height` display specification, which was specified before (i.e. to the left of) `raise`, the latter will affect the amount of raising or lowering in pixels, because that is based on the height of the text being raised. Therefore, if you want to display a sub- or superscript that is smaller than the normal text height, consider specifying `raise` before `height`.
You can make any display specification conditional. To do that, package it in another list of the form `(when condition . spec)`. Then the specification spec applies only when condition evaluates to a non-`nil` value. During the evaluation, `object` is bound to the string or buffer having the conditional `display` property. `position` and `buffer-position` are bound to the position within `object` and the buffer position where the `display` property was found, respectively. Both positions can be different when `object` is a string.
Note that condition will only be evaluated when redisplay examines the text where this display spec is located, so this feature is best suited for conditions that are relatively stable, i.e. yield, for each particular buffer position, the same results on every evaluation. If the results change for the same text location, e.g., if the result depends on the position of point, then the conditional specification might not do what you want, because redisplay examines only those parts of buffer text where it has reasons to assume that something changed since the last display cycle.
elisp None #### Bool-Vector Type
A *bool-vector* is a one-dimensional array whose elements must be `t` or `nil`.
The printed representation of a bool-vector is like a string, except that it begins with ‘`#&`’ followed by the length. The string constant that follows actually specifies the contents of the bool-vector as a bitmap—each character in the string contains 8 bits, which specify the next 8 elements of the bool-vector (1 stands for `t`, and 0 for `nil`). The least significant bits of the character correspond to the lowest indices in the bool-vector.
```
(make-bool-vector 3 t)
⇒ #&3"^G"
(make-bool-vector 3 nil)
⇒ #&3"^@"
```
These results make sense, because the binary code for ‘`C-g`’ is 111 and ‘`C-@`’ is the character with code 0.
If the length is not a multiple of 8, the printed representation shows extra elements, but these extras really make no difference. For instance, in the next example, the two bool-vectors are equal, because only the first 3 bits are used:
```
(equal #&3"\377" #&3"\007")
⇒ t
```
elisp None #### Backtracking in Specifications
If a specification fails to match at some point, this does not necessarily mean a syntax error will be signaled; instead, *backtracking* will take place until all alternatives have been exhausted. Eventually every element of the argument list must be matched by some element in the specification, and every required element in the specification must match some argument.
When a syntax error is detected, it might not be reported until much later, after higher-level alternatives have been exhausted, and with the point positioned further from the real error. But if backtracking is disabled when an error occurs, it can be reported immediately. Note that backtracking is also reenabled automatically in several situations; when a new alternative is established by `&optional`, `&rest`, or `&or`, or at the start of processing a sublist, group, or indirect specification. The effect of enabling or disabling backtracking is limited to the remainder of the level currently being processed and lower levels.
Backtracking is disabled while matching any of the form specifications (that is, `form`, `body`, `def-form`, and `def-body`). These specifications will match any form so any error must be in the form itself rather than at a higher level.
Backtracking is also disabled after successfully matching a quoted symbol, string specification, or `&define` keyword, since this usually indicates a recognized construct. But if you have a set of alternative constructs that all begin with the same symbol, you can usually work around this constraint by factoring the symbol out of the alternatives, e.g., `["foo" &or [first case] [second case] ...]`.
Most needs are satisfied by these two ways that backtracking is automatically disabled, but occasionally it is useful to explicitly disable backtracking by using the `gate` specification. This is useful when you know that no higher alternatives could apply. See the example of the `let` specification.
elisp None ### Minibuffer Commands
This section describes some commands meant for use in the minibuffer.
Command: **exit-minibuffer**
This command exits the active minibuffer. It is normally bound to keys in minibuffer local keymaps. The command throws an error if the current buffer is a minibuffer, but not the active minibuffer.
Command: **self-insert-and-exit**
This command exits the active minibuffer after inserting the last character typed on the keyboard (found in `last-command-event`; see [Command Loop Info](command-loop-info)).
Command: **previous-history-element** *n*
This command replaces the minibuffer contents with the value of the nth previous (older) history element.
Command: **next-history-element** *n*
This command replaces the minibuffer contents with the value of the nth more recent history element. The position in the history can go beyond the current position and invoke “future history” (see [Text from Minibuffer](text-from-minibuffer)).
Command: **previous-matching-history-element** *pattern n*
This command replaces the minibuffer contents with the value of the nth previous (older) history element that matches pattern (a regular expression).
Command: **next-matching-history-element** *pattern n*
This command replaces the minibuffer contents with the value of the nth next (newer) history element that matches pattern (a regular expression).
Command: **previous-complete-history-element** *n*
This command replaces the minibuffer contents with the value of the nth previous (older) history element that completes the current contents of the minibuffer before the point.
Command: **next-complete-history-element** *n*
This command replaces the minibuffer contents with the value of the nth next (newer) history element that completes the current contents of the minibuffer before the point.
Command: **goto-history-element** *nabs*
This function puts element of the minibuffer history in the minibuffer. The argument nabs specifies the absolute history position in descending order, where 0 means the current element and a positive number n means the nth previous element. NABS being a negative number -n means the nth entry of “future history.”
elisp None #### Buffer Text Notation
Some examples describe modifications to the contents of a buffer, by showing the before and after versions of the text. These examples show the contents of the buffer in question between two lines of dashes containing the buffer name. In addition, ‘`∗`’ indicates the location of point. (The symbol for point, of course, is not part of the text in the buffer; it indicates the place *between* two characters where point is currently located.)
```
---------- Buffer: foo ----------
This is the ∗contents of foo.
---------- Buffer: foo ----------
(insert "changed ")
⇒ nil
---------- Buffer: foo ----------
This is the changed ∗contents of foo.
---------- Buffer: foo ----------
```
elisp None ### Defining Customization Variables
*Customizable variables*, also called *user options*, are global Lisp variables whose values can be set through the Customize interface. Unlike other global variables, which are defined with `defvar` (see [Defining Variables](defining-variables)), customizable variables are defined using the `defcustom` macro. In addition to calling `defvar` as a subroutine, `defcustom` states how the variable should be displayed in the Customize interface, the values it is allowed to take, etc.
Macro: **defcustom** *option standard doc [keyword value]…*
This macro declares option as a user option (i.e., a customizable variable). You should not quote option.
The argument standard is an expression that specifies the standard value for option. Evaluating the `defcustom` form evaluates standard, but does not necessarily bind the option to that value. If option already has a default value, it is left unchanged. If the user has already saved a customization for option, the user’s customized value is installed as the default value. Otherwise, the result of evaluating standard is installed as the default value.
Like `defvar`, this macro marks `option` as a special variable, meaning that it should always be dynamically bound. If option is already lexically bound, that lexical binding remains in effect until the binding construct exits. See [Variable Scoping](variable-scoping).
The expression standard can be evaluated at various other times, too—whenever the customization facility needs to know option’s standard value. So be sure to use an expression which is harmless to evaluate at any time.
The argument doc specifies the documentation string for the variable.
If a `defcustom` does not specify any `:group`, the last group defined with `defgroup` in the same file will be used. This way, most `defcustom` do not need an explicit `:group`.
When you evaluate a `defcustom` form with `C-M-x` in Emacs Lisp mode (`eval-defun`), a special feature of `eval-defun` arranges to set the variable unconditionally, without testing whether its value is void. (The same feature applies to `defvar`, see [Defining Variables](defining-variables).) Using `eval-defun` on a defcustom that is already defined calls the `:set` function (see below), if there is one.
If you put a `defcustom` in a pre-loaded Emacs Lisp file (see [Building Emacs](building-emacs)), the standard value installed at dump time might be incorrect, e.g., because another variable that it depends on has not been assigned the right value yet. In that case, use `custom-reevaluate-setting`, described below, to re-evaluate the standard value after Emacs starts up.
In addition to the keywords listed in [Common Keywords](common-keywords), this macro accepts the following keywords:
`:type type`
Use type as the data type for this option. It specifies which values are legitimate, and how to display the value (see [Customization Types](customization-types)). Every `defcustom` should specify a value for this keyword.
`:options value-list`
Specify the list of reasonable values for use in this option. The user is not restricted to using only these values, but they are offered as convenient alternatives.
This is meaningful only for certain types, currently including `hook`, `plist` and `alist`. See the definition of the individual types for a description of how to use `:options`.
Re-evaluating a `defcustom` form with a different `:options` value does not clear the values added by previous evaluations, or added by calls to `custom-add-frequent-value` (see below).
`:set setfunction`
Specify setfunction as the way to change the value of this option when using the Customize interface. The function setfunction should take two arguments, a symbol (the option name) and the new value, and should do whatever is necessary to update the value properly for this option (which may not mean simply setting the option as a Lisp variable); preferably, though, it should not modify its value argument destructively. The default for setfunction is `set-default`.
If you specify this keyword, the variable’s documentation string should describe how to do the same job in hand-written Lisp code.
`:get getfunction`
Specify getfunction as the way to extract the value of this option. The function getfunction should take one argument, a symbol, and should return whatever customize should use as the current value for that symbol (which need not be the symbol’s Lisp value). The default is `default-value`.
You have to really understand the workings of Custom to use `:get` correctly. It is meant for values that are treated in Custom as variables but are not actually stored in Lisp variables. It is almost surely a mistake to specify getfunction for a value that really is stored in a Lisp variable.
`:initialize function`
function should be a function used to initialize the variable when the `defcustom` is evaluated. It should take two arguments, the option name (a symbol) and the value. Here are some predefined functions meant for use in this way:
`custom-initialize-set`
Use the variable’s `:set` function to initialize the variable, but do not reinitialize it if it is already non-void.
`custom-initialize-default`
Like `custom-initialize-set`, but use the function `set-default` to set the variable, instead of the variable’s `:set` function. This is the usual choice for a variable whose `:set` function enables or disables a minor mode; with this choice, defining the variable will not call the minor mode function, but customizing the variable will do so.
`custom-initialize-reset`
Always use the `:set` function to initialize the variable. If the variable is already non-void, reset it by calling the `:set` function using the current value (returned by the `:get` method). This is the default `:initialize` function.
`custom-initialize-changed`
Use the `:set` function to initialize the variable, if it is already set or has been customized; otherwise, just use `set-default`.
`custom-initialize-delay` This function behaves like `custom-initialize-set`, but it delays the actual initialization to the next Emacs start. This should be used in files that are preloaded (or for autoloaded variables), so that the initialization is done in the run-time context rather than the build-time context. This also has the side-effect that the (delayed) initialization is performed with the `:set` function. See [Building Emacs](building-emacs).
`:local value`
If the value is `t`, mark option as automatically buffer-local; if the value is `permanent`, also set options `permanent-local` property to `t`. See [Creating Buffer-Local](creating-buffer_002dlocal).
`:risky value`
Set the variable’s `risky-local-variable` property to value (see [File Local Variables](file-local-variables)).
`:safe function`
Set the variable’s `safe-local-variable` property to function (see [File Local Variables](file-local-variables)).
`:set-after variables`
When setting variables according to saved customizations, make sure to set the variables variables before this one; i.e., delay setting this variable until after those others have been handled. Use `:set-after` if setting this variable won’t work properly unless those other variables already have their intended values.
It is useful to specify the `:require` keyword for an option that turns on a certain feature. This causes Emacs to load the feature, if it is not already loaded, whenever the option is set. See [Common Keywords](common-keywords). Here is an example:
```
(defcustom frobnicate-automatically nil
"Non-nil means automatically frobnicate all buffers."
:type 'boolean
:require 'frobnicate-mode
:group 'frobnicate)
```
If a customization item has a type such as `hook` or `alist`, which supports `:options`, you can add additional values to the list from outside the `defcustom` declaration by calling `custom-add-frequent-value`. For example, if you define a function `my-lisp-mode-initialization` intended to be called from `emacs-lisp-mode-hook`, you might want to add that to the list of reasonable values for `emacs-lisp-mode-hook`, but not by editing its definition. You can do it thus:
```
(custom-add-frequent-value 'emacs-lisp-mode-hook
'my-lisp-mode-initialization)
```
Function: **custom-add-frequent-value** *symbol value*
For the customization option symbol, add value to the list of reasonable values.
The precise effect of adding a value depends on the customization type of symbol.
Since evaluating a `defcustom` form does not clear values added previously, Lisp programs can use this function to add values for user options not yet defined.
Internally, `defcustom` uses the symbol property `standard-value` to record the expression for the standard value, `saved-value` to record the value saved by the user with the customization buffer, and `customized-value` to record the value set by the user with the customization buffer, but not saved. See [Symbol Properties](symbol-properties). In addition, there’s `themed-value`, which is used to record the value set by a theme (see [Custom Themes](custom-themes)). These properties are lists, the car of which is an expression that evaluates to the value.
Function: **custom-reevaluate-setting** *symbol*
This function re-evaluates the standard value of symbol, which should be a user option declared via `defcustom`. If the variable was customized, this function re-evaluates the saved value instead. Then it sets the user option to that value (using the option’s `:set` property if that is defined).
This is useful for customizable options that are defined before their value could be computed correctly. For example, during startup Emacs calls this function for some user options that were defined in pre-loaded Emacs Lisp files, but whose initial values depend on information available only at run-time.
Function: **custom-variable-p** *arg*
This function returns non-`nil` if arg is a customizable variable. A customizable variable is either a variable that has a `standard-value` or `custom-autoload` property (usually meaning it was declared with `defcustom`), or an alias for another customizable variable.
| programming_docs |
elisp None ### Common Problems Using Macros
Macro expansion can have counterintuitive consequences. This section describes some important consequences that can lead to trouble, and rules to follow to avoid trouble.
| | | |
| --- | --- | --- |
| • [Wrong Time](wrong-time) | | Do the work in the expansion, not in the macro. |
| • [Argument Evaluation](argument-evaluation) | | The expansion should evaluate each macro arg once. |
| • [Surprising Local Vars](surprising-local-vars) | | Local variable bindings in the expansion require special care. |
| • [Eval During Expansion](eval-during-expansion) | | Don’t evaluate them; put them in the expansion. |
| • [Repeated Expansion](repeated-expansion) | | Avoid depending on how many times expansion is done. |
elisp None #### Integer Type
Under the hood, there are two kinds of integers—small integers, called *fixnums*, and large integers, called *bignums*.
The range of values for a fixnum depends on the machine. The minimum range is -536,870,912 to 536,870,911 (30 bits; i.e., -2\*\*29 to 2\*\*29 - 1) but many machines provide a wider range.
Bignums can have arbitrary precision. Operations that overflow a fixnum will return a bignum instead.
All numbers can be compared with `eql` or `=`; fixnums can also be compared with `eq`. To test whether an integer is a fixnum or a bignum, you can compare it to `most-negative-fixnum` and `most-positive-fixnum`, or you can use the convenience predicates `fixnump` and `bignump` on any object.
The read syntax for integers is a sequence of (base ten) digits with an optional sign at the beginning and an optional period at the end. The printed representation produced by the Lisp interpreter never has a leading ‘`+`’ or a final ‘`.`’.
```
-1 ; The integer -1.
1 ; The integer 1.
1. ; Also the integer 1.
+1 ; Also the integer 1.
```
See [Numbers](numbers), for more information.
elisp None ### Window Configurations
A *window configuration* records the entire layout of one frame—all windows, their sizes, their decorations, which buffers they contain, how those buffers are scrolled, and their value of point, It also includes the value of `minibuffer-scroll-window`. As a special exception, the window configuration does not record the value of point in the selected window for the current buffer.
You can bring back an entire frame layout by restoring a previously saved window configuration. If you want to record the layout of all frames instead of just one, use a frame configuration instead of a window configuration. See [Frame Configurations](frame-configurations).
Function: **current-window-configuration** *&optional frame*
This function returns a new object representing frame’s current window configuration. The default for frame is the selected frame. The variable `window-persistent-parameters` specifies which window parameters (if any) are saved by this function. See [Window Parameters](window-parameters).
Function: **set-window-configuration** *configuration &optional dont-set-frame dont-set-miniwindow*
This function restores the configuration of windows and buffers as specified by configuration, for the frame that configuration was created for, regardless of whether that frame is selected or not. The argument configuration must be a value that was previously returned by `current-window-configuration` for that frame. Normally the function also selects the frame which is recorded in the configuration, but if dont-set-frame is non-`nil`, it leaves selected the frame which was already selected at the start of the function.
Normally the function restores the saved minibuffer (if any), but if dont-set-miniwindow is non-`nil`, the minibuffer current at the start of the function (if any) remains in the mini-window.
If the frame from which configuration was saved is dead, all this function does is to restore the value of the variable `minibuffer-scroll-window` and to adjust the value returned by `minibuffer-selected-window`. In this case, the function returns `nil`. Otherwise, it returns `t`.
If the buffer of a window of configuration has been killed since configuration was made, that window is, as a rule, removed from the restored configuration. However, if that window is the last window remaining in the restored configuration, another live buffer is shown in it.
Here is a way of using this function to get the same effect as `save-window-excursion`:
```
(let ((config (current-window-configuration)))
(unwind-protect
(progn (split-window-below nil)
…)
(set-window-configuration config)))
```
Macro: **save-window-excursion** *forms…*
This macro records the window configuration of the selected frame, executes forms in sequence, then restores the earlier window configuration. The return value is the value of the final form in forms.
Most Lisp code should not use this macro; `save-selected-window` is typically sufficient. In particular, this macro cannot reliably prevent the code in forms from opening new windows, because new windows might be opened in other frames (see [Choosing Window](choosing-window)), and `save-window-excursion` only saves and restores the window configuration on the current frame.
Function: **window-configuration-p** *object*
This function returns `t` if object is a window configuration.
Function: **compare-window-configurations** *config1 config2*
This function compares two window configurations as regards the structure of windows, but ignores the values of point and the saved scrolling positions—it can return `t` even if those aspects differ.
Function: **window-configuration-frame** *config*
This function returns the frame for which the window configuration config was made.
Other primitives to look inside of window configurations would make sense, but are not implemented because we did not need them. See the file `winner.el` for some more operations on windows configurations.
The objects returned by `current-window-configuration` die together with the Emacs process. In order to store a window configuration on disk and read it back in another Emacs session, you can use the functions described next. These functions are also useful to clone the state of a frame into an arbitrary live window (`set-window-configuration` effectively clones the windows of a frame into the root window of that very frame only).
Function: **window-state-get** *&optional window writable*
This function returns the state of window as a Lisp object. The argument window must be a valid window and defaults to the root window of the selected frame.
If the optional argument writable is non-`nil`, this means to not use markers for sampling positions like `window-point` or `window-start`. This argument should be non-`nil` when the state will be written to disk and read back in another session.
Together, the argument writable and the variable `window-persistent-parameters` specify which window parameters are saved by this function. See [Window Parameters](window-parameters).
The value returned by `window-state-get` can be used in the same session to make a clone of a window in another window. It can be also written to disk and read back in another session. In either case, use the following function to restore the state of the window.
Function: **window-state-put** *state &optional window ignore*
This function puts the window state state into window. The argument state should be the state of a window returned by an earlier invocation of `window-state-get`, see above. The optional argument window can be either a live window or an internal window (see [Windows and Frames](windows-and-frames)). If window is not a live window, it is replaced by a new live window created on the same frame before putting state into it. If window is `nil`, it puts the window state into a new window.
If the optional argument ignore is non-`nil`, it means to ignore minimum window sizes and fixed-size restrictions. If ignore is `safe`, this means windows can get as small as one line and/or two columns.
The functions `window-state-get` and `window-state-put` also allow to exchange the contents of two live windows. The following function does precisely that:
Command: **window-swap-states** *&optional window-1 window-2 size*
This command swaps the states of the two live windows window-1 and window-2. window-1 must specify a live window and defaults to the selected one. window-2 must specify a live window and defaults to the window following window-1 in the cyclic ordering of windows, excluding minibuffer windows and including live windows on all visible frames.
Optional argument size non-`nil` means to try swapping the sizes of window-1 and window-2 as well. A value of `height` means to swap heights only, a value of `width` means to swap widths only, while `t` means to swap both widths and heights, if possible. Frames are not resized by this function.
elisp None ### Which File Defined a Certain Symbol
Function: **symbol-file** *symbol &optional type*
This function returns the name of the file that defined symbol. If type is `nil`, then any kind of definition is acceptable. If type is `defun`, `defvar`, or `defface`, that specifies function definition, variable definition, or face definition only.
The value is normally an absolute file name. It can also be `nil`, if the definition is not associated with any file. If symbol specifies an autoloaded function, the value can be a relative file name without extension.
The basis for `symbol-file` is the data in the variable `load-history`.
Variable: **load-history**
The value of this variable is an alist that associates the names of loaded library files with the names of the functions and variables they defined, as well as the features they provided or required.
Each element in this alist describes one loaded library (including libraries that are preloaded at startup). It is a list whose CAR is the absolute file name of the library (a string). The rest of the list elements have these forms:
`var` The symbol var was defined as a variable.
`(defun . fun)` The function fun was defined.
`(t . fun)` The function fun was previously an autoload before this library redefined it as a function. The following element is always `(defun . fun)`, which represents defining fun as a function.
`(autoload . fun)` The function fun was defined as an autoload.
`(defface . face)` The face face was defined.
`(require . feature)` The feature feature was required.
`(provide . feature)` The feature feature was provided.
`(cl-defmethod method specializers)` The named method was defined by using `cl-defmethod`, with specializers as its specializers.
`(define-type . type)` The type type was defined.
The value of `load-history` may have one element whose CAR is `nil`. This element describes definitions made with `eval-buffer` on a buffer that is not visiting a file.
The command `eval-region` updates `load-history`, but does so by adding the symbols defined to the element for the file being visited, rather than replacing that element. See [Eval](eval).
elisp None ### Moving Marker Positions
This section describes how to change the position of an existing marker. When you do this, be sure you know whether the marker is used outside of your program, and, if so, what effects will result from moving it—otherwise, confusing things may happen in other parts of Emacs.
Function: **set-marker** *marker position &optional buffer*
This function moves marker to position in buffer. If buffer is not provided, it defaults to the current buffer.
If position is `nil` or a marker that points nowhere, then marker is set to point nowhere.
The value returned is marker.
```
(setq m (point-marker))
⇒ #<marker at 4714 in markers.texi>
```
```
(set-marker m 55)
⇒ #<marker at 55 in markers.texi>
```
```
(setq b (get-buffer "foo"))
⇒ #<buffer foo>
```
```
(set-marker m 0 b)
⇒ #<marker at 1 in foo>
```
Function: **move-marker** *marker position &optional buffer*
This is another name for `set-marker`.
elisp None #### Region to Fontify after a Buffer Change
When a buffer is changed, the region that Font Lock refontifies is by default the smallest sequence of whole lines that spans the change. While this works well most of the time, sometimes it doesn’t—for example, when a change alters the syntactic meaning of text on an earlier line.
You can enlarge (or even reduce) the region to refontify by setting the following variable:
Variable: **font-lock-extend-after-change-region-function**
This buffer-local variable is either `nil` or a function for Font Lock mode to call to determine the region to scan and fontify.
The function is given three parameters, the standard beg, end, and old-len from `after-change-functions` (see [Change Hooks](change-hooks)). It should return either a cons of the beginning and end buffer positions (in that order) of the region to fontify, or `nil` (which means choose the region in the standard way). This function needs to preserve point, the match-data, and the current restriction. The region it returns may start or end in the middle of a line.
Since this function is called after every buffer change, it should be reasonably fast.
elisp None #### Customizing Search-Based Fontification
You can use `font-lock-add-keywords` to add additional search-based fontification rules to a major mode, and `font-lock-remove-keywords` to remove rules.
Function: **font-lock-add-keywords** *mode keywords &optional how*
This function adds highlighting keywords, for the current buffer or for major mode mode. The argument keywords should be a list with the same format as the variable `font-lock-keywords`.
If mode is a symbol which is a major mode command name, such as `c-mode`, the effect is that enabling Font Lock mode in mode will add keywords to `font-lock-keywords`. Calling with a non-`nil` value of mode is correct only in your `~/.emacs` file.
If mode is `nil`, this function adds keywords to `font-lock-keywords` in the current buffer. This way of calling `font-lock-add-keywords` is usually used in mode hook functions.
By default, keywords are added at the beginning of `font-lock-keywords`. If the optional argument how is `set`, they are used to replace the value of `font-lock-keywords`. If how is any other non-`nil` value, they are added at the end of `font-lock-keywords`.
Some modes provide specialized support you can use in additional highlighting patterns. See the variables `c-font-lock-extra-types`, `c++-font-lock-extra-types`, and `java-font-lock-extra-types`, for example.
**Warning:** Major mode commands must not call `font-lock-add-keywords` under any circumstances, either directly or indirectly, except through their mode hooks. (Doing so would lead to incorrect behavior for some minor modes.) They should set up their rules for search-based fontification by setting `font-lock-keywords`.
Function: **font-lock-remove-keywords** *mode keywords*
This function removes keywords from `font-lock-keywords` for the current buffer or for major mode mode. As in `font-lock-add-keywords`, mode should be a major mode command name or `nil`. All the caveats and requirements for `font-lock-add-keywords` apply here too. The argument keywords must exactly match the one used by the corresponding `font-lock-add-keywords`.
For example, the following code adds two fontification patterns for C mode: one to fontify the word ‘`FIXME`’, even in comments, and another to fontify the words ‘`and`’, ‘`or`’ and ‘`not`’ as keywords.
```
(font-lock-add-keywords 'c-mode
'(("\\<\\(FIXME\\):" 1 font-lock-warning-face prepend)
("\\<\\(and\\|or\\|not\\)\\>" . font-lock-keyword-face)))
```
This example affects only C mode proper. To add the same patterns to C mode *and* all modes derived from it, do this instead:
```
(add-hook 'c-mode-hook
(lambda ()
(font-lock-add-keywords nil
'(("\\<\\(FIXME\\):" 1 font-lock-warning-face prepend)
("\\<\\(and\\|or\\|not\\)\\>" .
font-lock-keyword-face)))))
```
elisp None #### Global Break Condition
A *global break condition* stops execution when a specified condition is satisfied, no matter where that may occur. Edebug evaluates the global break condition at every stop point; if it evaluates to a non-`nil` value, then execution stops or pauses depending on the execution mode, as if a breakpoint had been hit. If evaluating the condition gets an error, execution does not stop.
The condition expression is stored in `edebug-global-break-condition`. You can specify a new expression using the `X` command from the source code buffer while Edebug is active, or using `C-x X X` from any buffer at any time, as long as Edebug is loaded (`edebug-set-global-break-condition`).
The global break condition is the simplest way to find where in your code some event occurs, but it makes code run much more slowly. So you should reset the condition to `nil` when not using it.
elisp None ### Inline Functions
An *inline function* is a function that works just like an ordinary function, except for one thing: when you byte-compile a call to the function (see [Byte Compilation](byte-compilation)), the function’s definition is expanded into the caller.
The simple way to define an inline function, is to write `defsubst` instead of `defun`. The rest of the definition looks just the same, but using `defsubst` says to make it inline for byte compilation.
Macro: **defsubst** *name args [doc] [declare] [interactive] body…*
This macro defines an inline function. Its syntax is exactly the same as `defun` (see [Defining Functions](defining-functions)).
Making a function inline often makes its function calls run faster. But it also has disadvantages. For one thing, it reduces flexibility; if you change the definition of the function, calls already inlined still use the old definition until you recompile them.
Another disadvantage is that making a large function inline can increase the size of compiled code both in files and in memory. Since the speed advantage of inline functions is greatest for small functions, you generally should not make large functions inline.
Also, inline functions do not behave well with respect to debugging, tracing, and advising (see [Advising Functions](advising-functions)). Since ease of debugging and the flexibility of redefining functions are important features of Emacs, you should not make a function inline, even if it’s small, unless its speed is really crucial, and you’ve timed the code to verify that using `defun` actually has performance problems.
After an inline function is defined, its inline expansion can be performed later on in the same file, just like macros.
It’s possible to use `defmacro` to define a macro to expand into the same code that an inline function would execute (see [Macros](macros)). But the macro would be limited to direct use in expressions—a macro cannot be called with `apply`, `mapcar` and so on. Also, it takes some work to convert an ordinary function into a macro. To convert it into an inline function is easy; just replace `defun` with `defsubst`. Since each argument of an inline function is evaluated exactly once, you needn’t worry about how many times the body uses the arguments, as you do for macros.
Alternatively, you can define a function by providing the code which will inline it as a compiler macro. The following macros make this possible.
Macro: **define-inline** *name args [doc] [declare] body…*
Define a function name by providing code that does its inlining, as a compiler macro. The function will accept the argument list args and will have the specified body.
If present, doc should be the function’s documentation string (see [Function Documentation](function-documentation)); declare, if present, should be a `declare` form (see [Declare Form](declare-form)) specifying the function’s metadata.
Functions defined via `define-inline` have several advantages with respect to macros defined by `defsubst` or `defmacro`:
* - They can be passed to `mapcar` (see [Mapping Functions](mapping-functions)).
* - They are more efficient.
* - They can be used as *place forms* to store values (see [Generalized Variables](generalized-variables)).
* - They behave in a more predictable way than `cl-defsubst` (see [Argument Lists](https://www.gnu.org/software/emacs/manual/html_node/cl/Argument-Lists.html#Argument-Lists) in Common Lisp Extensions for GNU Emacs Lisp).
Like `defmacro`, a function inlined with `define-inline` inherits the scoping rules, either dynamic or lexical, from the call site. See [Variable Scoping](variable-scoping).
The following macros should be used in the body of a function defined by `define-inline`.
Macro: **inline-quote** *expression*
Quote expression for `define-inline`. This is similar to the backquote (see [Backquote](backquote)), but quotes code and accepts only `,`, not `,@`.
Macro: **inline-letevals** *(bindings…) body…*
This provides a convenient way to ensure that the arguments to an inlined function are evaluated exactly once, as well as to create local variables.
It’s similar to `let` (see [Local Variables](local-variables)): It sets up local variables as specified by bindings, and then evaluates body with those bindings in effect.
Each element of bindings should be either a symbol or a list of the form `(var expr)`; the result is to evaluate expr and bind var to the result. However, when an element of bindings is just a symbol var, the result of evaluating var is re-bound to var (which is quite different from the way `let` works).
The tail of bindings can be either `nil` or a symbol which should hold a list of arguments, in which case each argument is evaluated, and the symbol is bound to the resulting list.
Macro: **inline-const-p** *expression*
Return non-`nil` if the value of expression is already known.
Macro: **inline-const-val** *expression*
Return the value of expression.
Macro: **inline-error** *format &rest args*
Signal an error, formatting args according to format.
Here’s an example of using `define-inline`:
```
(define-inline myaccessor (obj)
(inline-letevals (obj)
(inline-quote (if (foo-p ,obj) (aref (cdr ,obj) 3) (aref ,obj 2)))))
```
This is equivalent to
```
(defsubst myaccessor (obj)
(if (foo-p obj) (aref (cdr obj) 3) (aref obj 2)))
```
| programming_docs |
elisp None #### Autoload Type
An *autoload object* is a list whose first element is the symbol `autoload`. It is stored as the function definition of a symbol, where it serves as a placeholder for the real definition. The autoload object says that the real definition is found in a file of Lisp code that should be loaded when necessary. It contains the name of the file, plus some other information about the real definition.
After the file has been loaded, the symbol should have a new function definition that is not an autoload object. The new definition is then called as if it had been there to begin with. From the user’s point of view, the function call works as expected, using the function definition in the loaded file.
An autoload object is usually created with the function `autoload`, which stores the object in the function cell of a symbol. See [Autoload](autoload), for more details.
elisp None #### Mode Line Basics
The contents of each mode line are specified by the buffer-local variable `mode-line-format` (see [Mode Line Top](mode-line-top)). This variable holds a *mode line construct*: a template that controls what is displayed on the buffer’s mode line. The value of `header-line-format` specifies the buffer’s header line in the same way. All windows for the same buffer use the same `mode-line-format` and `header-line-format` unless a `mode-line-format` or `header-line-format` parameter has been specified for that window (see [Window Parameters](window-parameters)).
For efficiency, Emacs does not continuously recompute each window’s mode line and header line. It does so when circumstances appear to call for it—for instance, if you change the window configuration, switch buffers, narrow or widen the buffer, scroll, or modify the buffer. If you alter any of the variables referenced by `mode-line-format` or `header-line-format` (see [Mode Line Variables](mode-line-variables)), or any other data structures that affect how text is displayed (see [Display](display)), you should use the function `force-mode-line-update` to update the display.
Function: **force-mode-line-update** *&optional all*
This function forces Emacs to update the current buffer’s mode line and header line, based on the latest values of all relevant variables, during its next redisplay cycle. If the optional argument all is non-`nil`, it forces an update for all mode lines and header lines.
This function also forces an update of the menu bar and frame title.
The selected window’s mode line is usually displayed in a different color using the face `mode-line`. Other windows’ mode lines appear in the face `mode-line-inactive` instead. See [Faces](faces).
Some modes put a lot of data in the mode line, pushing elements at the end of the mode line off to the right. Emacs can “compress” the mode line if the `mode-line-compact` variable is non-`nil` by turning stretches of spaces into a single space. If this variable is `long`, this is only done when the mode line is wider than the currently selected window. (This computation is approximate, based on the number of characters, and not their displayed width.) This variable can be buffer-local to only compress mode-lines in certain buffers.
elisp None #### Overlay Type
An *overlay* specifies properties that apply to a part of a buffer. Each overlay applies to a specified range of the buffer, and contains a property list (a list whose elements are alternating property names and values). Overlay properties are used to present parts of the buffer temporarily in a different display style. Overlays have no read syntax, and print in hash notation, giving the buffer name and range of positions.
See [Overlays](overlays), for information on how you can create and use overlays.
elisp None ### Access to Documentation Strings
Function: **documentation-property** *symbol property &optional verbatim*
This function returns the documentation string recorded in symbol’s property list under property property. It is most often used to look up the documentation strings of variables, for which property is `variable-documentation`. However, it can also be used to look up other kinds of documentation, such as for customization groups (but for function documentation, use the `documentation` function, below).
If the property value refers to a documentation string stored in the `DOC` file or a byte-compiled file, this function looks up that string and returns it.
If the property value isn’t `nil`, isn’t a string, and doesn’t refer to text in a file, then it is evaluated as a Lisp expression to obtain a string.
Finally, this function passes the string through `substitute-command-keys` to substitute key bindings (see [Keys in Documentation](keys-in-documentation)). It skips this step if verbatim is non-`nil`.
```
(documentation-property 'command-line-processed
'variable-documentation)
⇒ "Non-nil once command line has been processed"
```
```
(symbol-plist 'command-line-processed)
⇒ (variable-documentation 188902)
```
```
(documentation-property 'emacs 'group-documentation)
⇒ "Customization of the One True Editor."
```
Function: **documentation** *function &optional verbatim*
This function returns the documentation string of function. It handles macros, named keyboard macros, and special forms, as well as ordinary functions.
If function is a symbol, this function first looks for the `function-documentation` property of that symbol; if that has a non-`nil` value, the documentation comes from that value (if the value is not a string, it is evaluated).
If function is not a symbol, or if it has no `function-documentation` property, then `documentation` extracts the documentation string from the actual function definition, reading it from a file if called for.
Finally, unless verbatim is non-`nil`, this function calls `substitute-command-keys`. The result is the documentation string to return.
The `documentation` function signals a `void-function` error if function has no function definition. However, it is OK if the function definition has no documentation string. In that case, `documentation` returns `nil`.
Function: **face-documentation** *face*
This function returns the documentation string of face as a face.
Here is an example of using the two functions, `documentation` and `documentation-property`, to display the documentation strings for several symbols in a `\*Help\*` buffer.
```
(defun describe-symbols (pattern)
"Describe the Emacs Lisp symbols matching PATTERN.
All symbols that have PATTERN in their name are described
in the *Help* buffer."
(interactive "sDescribe symbols matching: ")
(let ((describe-func
(lambda (s)
```
```
;; Print description of symbol.
(if (fboundp s) ; It is a function.
(princ
(format "%s\t%s\n%s\n\n" s
(if (commandp s)
(let ((keys (where-is-internal s)))
(if keys
(concat
"Keys: "
(mapconcat 'key-description
keys " "))
"Keys: none"))
"Function")
```
```
(or (documentation s)
"not documented"))))
(if (boundp s) ; It is a variable.
```
```
(princ
(format "%s\t%s\n%s\n\n" s
(if (custom-variable-p s)
"Option " "Variable")
```
```
(or (documentation-property
s 'variable-documentation)
"not documented"))))))
sym-list)
```
```
;; Build a list of symbols that match pattern.
(mapatoms (lambda (sym)
(if (string-match pattern (symbol-name sym))
(setq sym-list (cons sym sym-list)))))
```
```
;; Display the data.
(help-setup-xref (list 'describe-symbols pattern)
(called-interactively-p 'interactive))
(with-help-window (help-buffer)
(mapcar describe-func (sort sym-list 'string<)))))
```
The `describe-symbols` function works like `apropos`, but provides more information.
```
(describe-symbols "goal")
---------- Buffer: *Help* ----------
goal-column Option
Semipermanent goal column for vertical motion, as set by …
```
```
minibuffer-temporary-goal-position Variable
not documented
```
```
set-goal-column Keys: C-x C-n
Set the current horizontal position as a goal for C-n and C-p.
```
```
Those commands will move to this position in the line moved to
rather than trying to keep the same horizontal position.
With a non-nil argument ARG, clears out the goal column
so that C-n and C-p resume vertical motion.
The goal column is stored in the variable ‘goal-column’.
(fn ARG)
```
```
temporary-goal-column Variable
Current goal column for vertical motion.
It is the column where point was at the start of the current run
of vertical motion commands.
When moving by visual lines via the function ‘line-move-visual’, it is a cons
cell (COL . HSCROLL), where COL is the x-position, in pixels,
divided by the default column width, and HSCROLL is the number of
columns by which window is scrolled from left margin.
When the ‘track-eol’ feature is doing its job, the value is
‘most-positive-fixnum’.
---------- Buffer: *Help* ----------
```
Function: **Snarf-documentation** *filename*
This function is used when building Emacs, just before the runnable Emacs is dumped. It finds the positions of the documentation strings stored in the file filename, and records those positions into memory in the function definitions and variable property lists. See [Building Emacs](building-emacs).
Emacs reads the file filename from the `emacs/etc` directory. When the dumped Emacs is later executed, the same file will be looked for in the directory `doc-directory`. Usually filename is `"DOC"`.
Variable: **doc-directory**
This variable holds the name of the directory which should contain the file `"DOC"` that contains documentation strings for built-in and preloaded functions and variables.
In most cases, this is the same as `data-directory`. They may be different when you run Emacs from the directory where you built it, without actually installing it. See [Definition of data-directory](help-functions#Definition-of-data_002ddirectory).
elisp None #### Function Keys
Most keyboards also have *function keys*—keys that have names or symbols that are not characters. Function keys are represented in Emacs Lisp as symbols; the symbol’s name is the function key’s label, in lower case. For example, pressing a key labeled F1 generates an input event represented by the symbol `f1`.
The event type of a function key event is the event symbol itself. See [Classifying Events](classifying-events).
Here are a few special cases in the symbol-naming convention for function keys:
`backspace`, `tab`, `newline`, `return`, `delete`
These keys correspond to common ASCII control characters that have special keys on most keyboards.
In ASCII, `C-i` and TAB are the same character. If the terminal can distinguish between them, Emacs conveys the distinction to Lisp programs by representing the former as the integer 9, and the latter as the symbol `tab`.
Most of the time, it’s not useful to distinguish the two. So normally `local-function-key-map` (see [Translation Keymaps](translation-keymaps)) is set up to map `tab` into 9. Thus, a key binding for character code 9 (the character `C-i`) also applies to `tab`. Likewise for the other symbols in this group. The function `read-char` likewise converts these events into characters.
In ASCII, BS is really `C-h`. But `backspace` converts into the character code 127 (DEL), not into code 8 (BS). This is what most users prefer.
`left`, `up`, `right`, `down`
Cursor arrow keys
`kp-add`, `kp-decimal`, `kp-divide`, … Keypad keys (to the right of the regular keyboard).
`kp-0`, `kp-1`, … Keypad keys with digits.
`kp-f1`, `kp-f2`, `kp-f3`, `kp-f4`
Keypad PF keys.
`kp-home`, `kp-left`, `kp-up`, `kp-right`, `kp-down`
Keypad arrow keys. Emacs normally translates these into the corresponding non-keypad keys `home`, `left`, …
`kp-prior`, `kp-next`, `kp-end`, `kp-begin`, `kp-insert`, `kp-delete`
Additional keypad duplicates of keys ordinarily found elsewhere. Emacs normally translates these into the like-named non-keypad keys.
You can use the modifier keys ALT, CTRL, HYPER, META, SHIFT, and SUPER with function keys. The way to represent them is with prefixes in the symbol name:
‘`A-`’ The alt modifier.
‘`C-`’ The control modifier.
‘`H-`’ The hyper modifier.
‘`M-`’ The meta modifier.
‘`S-`’ The shift modifier.
‘`s-`’ The super modifier.
Thus, the symbol for the key F3 with META held down is `M-f3`. When you use more than one prefix, we recommend you write them in alphabetical order; but the order does not matter in arguments to the key-binding lookup and modification functions.
elisp None ### Tips for Defining Variables Robustly
When you define a variable whose value is a function, or a list of functions, use a name that ends in ‘`-function`’ or ‘`-functions`’, respectively.
There are several other variable name conventions; here is a complete list:
‘`…-hook`’
The variable is a normal hook (see [Hooks](hooks)).
‘`…-function`’
The value is a function.
‘`…-functions`’
The value is a list of functions.
‘`…-form`’
The value is a form (an expression).
‘`…-forms`’
The value is a list of forms (expressions).
‘`…-predicate`’
The value is a predicate—a function of one argument that returns non-`nil` for success and `nil` for failure.
‘`…-flag`’
The value is significant only as to whether it is `nil` or not. Since such variables often end up acquiring more values over time, this convention is not strongly recommended.
‘`…-program`’
The value is a program name.
‘`…-command`’
The value is a whole shell command.
‘`…-switches`’
The value specifies options for a command.
‘`prefix--…`’
The variable is intended for internal use and is defined in the file `prefix.el`. (Emacs code contributed before 2018 may follow other conventions, which are being phased out.)
‘`…-internal`’ The variable is intended for internal use and is defined in C code. (Emacs code contributed before 2018 may follow other conventions, which are being phased out.)
When you define a variable, always consider whether you should mark it as safe or risky; see [File Local Variables](file-local-variables).
When defining and initializing a variable that holds a complicated value (such as a keymap with bindings in it), it’s best to put the entire computation of the value into the `defvar`, like this:
```
(defvar my-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "\C-c\C-a" 'my-command)
…
map)
docstring)
```
This method has several benefits. First, if the user quits while loading the file, the variable is either still uninitialized or initialized properly, never in-between. If it is still uninitialized, reloading the file will initialize it properly. Second, reloading the file once the variable is initialized will not alter it; that is important if the user has run hooks to alter part of the contents (such as, to rebind keys). Third, evaluating the `defvar` form with `C-M-x` will reinitialize the map completely.
Putting so much code in the `defvar` form has one disadvantage: it puts the documentation string far away from the line which names the variable. Here’s a safe way to avoid that:
```
(defvar my-mode-map nil
docstring)
(unless my-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "\C-c\C-a" 'my-command)
…
(setq my-mode-map map)))
```
This has all the same advantages as putting the initialization inside the `defvar`, except that you must type `C-M-x` twice, once on each form, if you do want to reinitialize the variable.
elisp None ### Filling
*Filling* means adjusting the lengths of lines (by moving the line breaks) so that they are nearly (but no greater than) a specified maximum width. Additionally, lines can be *justified*, which means inserting spaces to make the left and/or right margins line up precisely. The width is controlled by the variable `fill-column`. For ease of reading, lines should be no longer than 70 or so columns.
You can use Auto Fill mode (see [Auto Filling](auto-filling)) to fill text automatically as you insert it, but changes to existing text may leave it improperly filled. Then you must fill the text explicitly.
Most of the commands in this section return values that are not meaningful. All the functions that do filling take note of the current left margin, current right margin, and current justification style (see [Margins](margins)). If the current justification style is `none`, the filling functions don’t actually do anything.
Several of the filling functions have an argument justify. If it is non-`nil`, that requests some kind of justification. It can be `left`, `right`, `full`, or `center`, to request a specific style of justification. If it is `t`, that means to use the current justification style for this part of the text (see `current-justification`, below). Any other value is treated as `full`.
When you call the filling functions interactively, using a prefix argument implies the value `full` for justify.
Command: **fill-paragraph** *&optional justify region*
This command fills the paragraph at or after point. If justify is non-`nil`, each line is justified as well. It uses the ordinary paragraph motion commands to find paragraph boundaries. See [Paragraphs](https://www.gnu.org/software/emacs/manual/html_node/emacs/Paragraphs.html#Paragraphs) in The GNU Emacs Manual.
When region is non-`nil`, then if Transient Mark mode is enabled and the mark is active, this command calls `fill-region` to fill all the paragraphs in the region, instead of filling only the current paragraph. When this command is called interactively, region is `t`.
Command: **fill-region** *start end &optional justify nosqueeze to-eop*
This command fills each of the paragraphs in the region from start to end. It justifies as well if justify is non-`nil`.
If nosqueeze is non-`nil`, that means to leave whitespace other than line breaks untouched. If to-eop is non-`nil`, that means to keep filling to the end of the paragraph—or the next hard newline, if `use-hard-newlines` is enabled (see below).
The variable `paragraph-separate` controls how to distinguish paragraphs. See [Standard Regexps](standard-regexps).
Command: **fill-individual-paragraphs** *start end &optional justify citation-regexp*
This command fills each paragraph in the region according to its individual fill prefix. Thus, if the lines of a paragraph were indented with spaces, the filled paragraph will remain indented in the same fashion.
The first two arguments, start and end, are the beginning and end of the region to be filled. The third and fourth arguments, justify and citation-regexp, are optional. If justify is non-`nil`, the paragraphs are justified as well as filled. If citation-regexp is non-`nil`, it means the function is operating on a mail message and therefore should not fill the header lines. If citation-regexp is a string, it is used as a regular expression; if it matches the beginning of a line, that line is treated as a citation marker.
Ordinarily, `fill-individual-paragraphs` regards each change in indentation as starting a new paragraph. If `fill-individual-varying-indent` is non-`nil`, then only separator lines separate paragraphs. That mode can handle indented paragraphs with additional indentation on the first line.
User Option: **fill-individual-varying-indent**
This variable alters the action of `fill-individual-paragraphs` as described above.
Command: **fill-region-as-paragraph** *start end &optional justify nosqueeze squeeze-after*
This command considers a region of text as a single paragraph and fills it. If the region was made up of many paragraphs, the blank lines between paragraphs are removed. This function justifies as well as filling when justify is non-`nil`.
If nosqueeze is non-`nil`, that means to leave whitespace other than line breaks untouched. If squeeze-after is non-`nil`, it specifies a position in the region, and means that whitespace other than line breaks should be left untouched before that position.
In Adaptive Fill mode, this command calls `fill-context-prefix` to choose a fill prefix by default. See [Adaptive Fill](adaptive-fill).
Command: **justify-current-line** *&optional how eop nosqueeze*
This command inserts spaces between the words of the current line so that the line ends exactly at `fill-column`. It returns `nil`.
The argument how, if non-`nil` specifies explicitly the style of justification. It can be `left`, `right`, `full`, `center`, or `none`. If it is `t`, that means to follow specified justification style (see `current-justification`, below). `nil` means to do full justification.
If eop is non-`nil`, that means do only left-justification if `current-justification` specifies full justification. This is used for the last line of a paragraph; even if the paragraph as a whole is fully justified, the last line should not be.
If nosqueeze is non-`nil`, that means do not change interior whitespace.
User Option: **default-justification**
This variable’s value specifies the style of justification to use for text that doesn’t specify a style with a text property. The possible values are `left`, `right`, `full`, `center`, or `none`. The default value is `left`.
Function: **current-justification**
This function returns the proper justification style to use for filling the text around point.
This returns the value of the `justification` text property at point, or the variable `default-justification` if there is no such text property. However, it returns `nil` rather than `none` to mean “don’t justify”.
User Option: **sentence-end-double-space**
If this variable is non-`nil`, a period followed by just one space does not count as the end of a sentence, and the filling functions avoid breaking the line at such a place.
User Option: **sentence-end-without-period**
If this variable is non-`nil`, a sentence can end without a period. This is used for languages like Thai, where sentences end with a double space but without a period.
User Option: **sentence-end-without-space**
If this variable is non-`nil`, it should be a string of characters that can end a sentence without following spaces.
User Option: **fill-separate-heterogeneous-words-with-space**
If this variable is non-`nil`, two words of different kind (e.g., English and CJK) will be separated with a space when concatenating one that is in the end of a line and the other that is in the beginning of the next line for filling.
Variable: **fill-paragraph-function**
This variable provides a way to override the filling of paragraphs. If its value is non-`nil`, `fill-paragraph` calls this function to do the work. If the function returns a non-`nil` value, `fill-paragraph` assumes the job is done, and immediately returns that value.
The usual use of this feature is to fill comments in programming language modes. If the function needs to fill a paragraph in the usual way, it can do so as follows:
```
(let ((fill-paragraph-function nil))
(fill-paragraph arg))
```
Variable: **fill-forward-paragraph-function**
This variable provides a way to override how the filling functions, such as `fill-region` and `fill-paragraph`, move forward to the next paragraph. Its value should be a function, which is called with a single argument n, the number of paragraphs to move, and should return the difference between n and the number of paragraphs actually moved. The default value of this variable is `forward-paragraph`. See [Paragraphs](https://www.gnu.org/software/emacs/manual/html_node/emacs/Paragraphs.html#Paragraphs) in The GNU Emacs Manual.
Variable: **use-hard-newlines**
If this variable is non-`nil`, the filling functions do not delete newlines that have the `hard` text property. These hard newlines act as paragraph separators. See [Hard and Soft Newlines](https://www.gnu.org/software/emacs/manual/html_node/emacs/Hard-and-Soft-Newlines.html#Hard-and-Soft-Newlines) in The GNU Emacs Manual.
| programming_docs |
elisp None #### Modifying and Translating Input Events
Emacs modifies every event it reads according to `extra-keyboard-modifiers`, then translates it through `keyboard-translate-table` (if applicable), before returning it from `read-event`.
Variable: **extra-keyboard-modifiers**
This variable lets Lisp programs “press” the modifier keys on the keyboard. The value is a character. Only the modifiers of the character matter. Each time the user types a keyboard key, it is altered as if those modifier keys were held down. For instance, if you bind `extra-keyboard-modifiers` to `?\C-\M-a`, then all keyboard input characters typed during the scope of the binding will have the control and meta modifiers applied to them. The character `?\C-@`, equivalent to the integer 0, does not count as a control character for this purpose, but as a character with no modifiers. Thus, setting `extra-keyboard-modifiers` to zero cancels any modification.
When using a window system, the program can press any of the modifier keys in this way. Otherwise, only the CTL and META keys can be virtually pressed.
Note that this variable applies only to events that really come from the keyboard, and has no effect on mouse events or any other events.
Variable: **keyboard-translate-table**
This terminal-local variable is the translate table for keyboard characters. It lets you reshuffle the keys on the keyboard without changing any command bindings. Its value is normally a char-table, or else `nil`. (It can also be a string or vector, but this is considered obsolete.)
If `keyboard-translate-table` is a char-table (see [Char-Tables](char_002dtables)), then each character read from the keyboard is looked up in this char-table. If the value found there is non-`nil`, then it is used instead of the actual input character.
Note that this translation is the first thing that happens to a character after it is read from the terminal. Record-keeping features such as `recent-keys` and dribble files record the characters after translation.
Note also that this translation is done before the characters are supplied to input methods (see [Input Methods](input-methods)). Use `translation-table-for-input` (see [Translation of Characters](translation-of-characters)), if you want to translate characters after input methods operate.
Function: **keyboard-translate** *from to*
This function modifies `keyboard-translate-table` to translate character code from into character code to. It creates the keyboard translate table if necessary.
Here’s an example of using the `keyboard-translate-table` to make `C-x`, `C-c` and `C-v` perform the cut, copy and paste operations:
```
(keyboard-translate ?\C-x 'control-x)
(keyboard-translate ?\C-c 'control-c)
(keyboard-translate ?\C-v 'control-v)
(global-set-key [control-x] 'kill-region)
(global-set-key [control-c] 'kill-ring-save)
(global-set-key [control-v] 'yank)
```
On a graphical terminal that supports extended ASCII input, you can still get the standard Emacs meanings of one of those characters by typing it with the shift key. That makes it a different character as far as keyboard translation is concerned, but it has the same usual meaning.
See [Translation Keymaps](translation-keymaps), for mechanisms that translate event sequences at the level of `read-key-sequence`.
elisp None ### Text Representations
Emacs buffers and strings support a large repertoire of characters from many different scripts, allowing users to type and display text in almost any known written language.
To support this multitude of characters and scripts, Emacs closely follows the *Unicode Standard*. The Unicode Standard assigns a unique number, called a *codepoint*, to each and every character. The range of codepoints defined by Unicode, or the Unicode *codespace*, is `0..#x10FFFF` (in hexadecimal notation), inclusive. Emacs extends this range with codepoints in the range `#x110000..#x3FFFFF`, which it uses for representing characters that are not unified with Unicode and *raw 8-bit bytes* that cannot be interpreted as characters. Thus, a character codepoint in Emacs is a 22-bit integer.
To conserve memory, Emacs does not hold fixed-length 22-bit numbers that are codepoints of text characters within buffers and strings. Rather, Emacs uses a variable-length internal representation of characters, that stores each character as a sequence of 1 to 5 8-bit bytes, depending on the magnitude of its codepoint[20](#FOOT20). For example, any ASCII character takes up only 1 byte, a Latin-1 character takes up 2 bytes, etc. We call this representation of text *multibyte*.
Outside Emacs, characters can be represented in many different encodings, such as ISO-8859-1, GB-2312, Big-5, etc. Emacs converts between these external encodings and its internal representation, as appropriate, when it reads text into a buffer or a string, or when it writes text to a disk file or passes it to some other process.
Occasionally, Emacs needs to hold and manipulate encoded text or binary non-text data in its buffers or strings. For example, when Emacs visits a file, it first reads the file’s text verbatim into a buffer, and only then converts it to the internal representation. Before the conversion, the buffer holds encoded text.
Encoded text is not really text, as far as Emacs is concerned, but rather a sequence of raw 8-bit bytes. We call buffers and strings that hold encoded text *unibyte* buffers and strings, because Emacs treats them as a sequence of individual bytes. Usually, Emacs displays unibyte buffers and strings as octal codes such as `\237`. We recommend that you never use unibyte buffers and strings except for manipulating encoded text or binary non-text data.
In a buffer, the buffer-local value of the variable `enable-multibyte-characters` specifies the representation used. The representation for a string is determined and recorded in the string when the string is constructed.
Variable: **enable-multibyte-characters**
This variable specifies the current buffer’s text representation. If it is non-`nil`, the buffer contains multibyte text; otherwise, it contains unibyte encoded text or binary non-text data.
You cannot set this variable directly; instead, use the function `set-buffer-multibyte` to change a buffer’s representation.
Function: **position-bytes** *position*
Buffer positions are measured in character units. This function returns the byte-position corresponding to buffer position position in the current buffer. This is 1 at the start of the buffer, and counts upward in bytes. If position is out of range, the value is `nil`.
Function: **byte-to-position** *byte-position*
Return the buffer position, in character units, corresponding to given byte-position in the current buffer. If byte-position is out of range, the value is `nil`. In a multibyte buffer, an arbitrary value of byte-position can be not at character boundary, but inside a multibyte sequence representing a single character; in this case, this function returns the buffer position of the character whose multibyte sequence includes byte-position. In other words, the value does not change for all byte positions that belong to the same character.
The following two functions are useful when a Lisp program needs to map buffer positions to byte offsets in a file visited by the buffer.
Function: **bufferpos-to-filepos** *position &optional quality coding-system*
This function is similar to `position-bytes`, but instead of byte position in the current buffer it returns the offset from the beginning of the current buffer’s file of the byte that corresponds to the given character position in the buffer. The conversion requires to know how the text is encoded in the buffer’s file; this is what the coding-system argument is for, defaulting to the value of `buffer-file-coding-system`. The optional argument quality specifies how accurate the result should be; it should be one of the following:
`exact` The result must be accurate. The function may need to encode and decode a large part of the buffer, which is expensive and can be slow.
`approximate` The value can be an approximation. The function may avoid expensive processing and return an inexact result.
`nil` If the exact result needs expensive processing, the function will return `nil` rather than an approximation. This is the default if the argument is omitted.
Function: **filepos-to-bufferpos** *byte &optional quality coding-system*
This function returns the buffer position corresponding to a file position specified by byte, a zero-base byte offset from the file’s beginning. The function performs the conversion opposite to what `bufferpos-to-filepos` does. Optional arguments quality and coding-system have the same meaning and values as for `bufferpos-to-filepos`.
Function: **multibyte-string-p** *string*
Return `t` if string is a multibyte string, `nil` otherwise. This function also returns `nil` if string is some object other than a string.
Function: **string-bytes** *string*
This function returns the number of bytes in string. If string is a multibyte string, this can be greater than `(length string)`.
Function: **unibyte-string** *&rest bytes*
This function concatenates all its argument bytes and makes the result a unibyte string.
elisp None #### Debugger Commands
The debugger buffer (in Debugger mode) provides special commands in addition to the usual Emacs commands and to the Backtrace mode commands described in the previous section. The most important use of debugger commands is for stepping through code, so that you can see how control flows. The debugger can step through the control structures of an interpreted function, but cannot do so in a byte-compiled function. If you would like to step through a byte-compiled function, replace it with an interpreted definition of the same function. (To do this, visit the source for the function and type `C-M-x` on its definition.) You cannot use the Lisp debugger to step through a primitive function.
Some of the debugger commands operate on the current frame. If a frame starts with a star, that means that exiting that frame will call the debugger again. This is useful for examining the return value of a function.
Here is a list of Debugger mode commands:
`c`
Exit the debugger and continue execution. This resumes execution of the program as if the debugger had never been entered (aside from any side-effects that you caused by changing variable values or data structures while inside the debugger).
`d`
Continue execution, but enter the debugger the next time any Lisp function is called. This allows you to step through the subexpressions of an expression, seeing what values the subexpressions compute, and what else they do.
The stack frame made for the function call which enters the debugger in this way will be flagged automatically so that the debugger will be called again when the frame is exited. You can use the `u` command to cancel this flag.
`b`
Flag the current frame so that the debugger will be entered when the frame is exited. Frames flagged in this way are marked with stars in the backtrace buffer.
`u`
Don’t enter the debugger when the current frame is exited. This cancels a `b` command on that frame. The visible effect is to remove the star from the line in the backtrace buffer.
`j`
Flag the current frame like `b`. Then continue execution like `c`, but temporarily disable break-on-entry for all functions that are set up to do so by `debug-on-entry`.
`e`
Read a Lisp expression in the minibuffer, evaluate it (with the relevant lexical environment, if applicable), and print the value in the echo area. The debugger alters certain important variables, and the current buffer, as part of its operation; `e` temporarily restores their values from outside the debugger, so you can examine and change them. This makes the debugger more transparent. By contrast, `M-:` does nothing special in the debugger; it shows you the variable values within the debugger.
`R`
Like `e`, but also save the result of evaluation in the buffer `\*Debugger-record\*`.
`q`
Terminate the program being debugged; return to top-level Emacs command execution.
If the debugger was entered due to a `C-g` but you really want to quit, and not debug, use the `q` command.
`r`
Return a value from the debugger. The value is computed by reading an expression with the minibuffer and evaluating it.
The `r` command is useful when the debugger was invoked due to exit from a Lisp call frame (as requested with `b` or by entering the frame with `d`); then the value specified in the `r` command is used as the value of that frame. It is also useful if you call `debug` and use its return value. Otherwise, `r` has the same effect as `c`, and the specified return value does not matter.
You can’t use `r` when the debugger was entered due to an error.
`l`
Display a list of functions that will invoke the debugger when called. This is a list of functions that are set to break on entry by means of `debug-on-entry`.
elisp None #### The Menu Bar
Emacs usually shows a *menu bar* at the top of each frame. See [Menu Bars](https://www.gnu.org/software/emacs/manual/html_node/emacs/Menu-Bars.html#Menu-Bars) in The GNU Emacs Manual. Menu bar items are subcommands of the fake function key MENU-BAR, as defined in the active keymaps.
To add an item to the menu bar, invent a fake function key of your own (let’s call it key), and make a binding for the key sequence `[menu-bar key]`. Most often, the binding is a menu keymap, so that pressing a button on the menu bar item leads to another menu.
When more than one active keymap defines the same function key for the menu bar, the item appears just once. If the user clicks on that menu bar item, it brings up a single, combined menu containing all the subcommands of that item—the global subcommands, the local subcommands, and the minor mode subcommands.
The variable `overriding-local-map` is normally ignored when determining the menu bar contents. That is, the menu bar is computed from the keymaps that would be active if `overriding-local-map` were `nil`. See [Active Keymaps](active-keymaps).
Here’s an example of setting up a menu bar item:
```
;; Make a menu keymap (with a prompt string)
;; and make it the menu bar item’s definition.
(define-key global-map [menu-bar words]
(cons "Words" (make-sparse-keymap "Words")))
```
```
;; Define specific subcommands in this menu.
(define-key global-map
[menu-bar words forward]
'("Forward word" . forward-word))
```
```
(define-key global-map
[menu-bar words backward]
'("Backward word" . backward-word))
```
A local keymap can cancel a menu bar item made by the global keymap by rebinding the same fake function key with `undefined` as the binding. For example, this is how Dired suppresses the ‘`Edit`’ menu bar item:
```
(define-key dired-mode-map [menu-bar edit] 'undefined)
```
Here, `edit` is the symbol produced by a fake function key, it is used by the global map for the ‘`Edit`’ menu bar item. The main reason to suppress a global menu bar item is to regain space for mode-specific items.
Variable: **menu-bar-final-items**
Normally the menu bar shows global items followed by items defined by the local maps.
This variable holds a list of fake function keys for items to display at the end of the menu bar rather than in normal sequence. The default value is `(help-menu)`; thus, the ‘`Help`’ menu item normally appears at the end of the menu bar, following local menu items.
Variable: **menu-bar-update-hook**
This normal hook is run by redisplay to update the menu bar contents, before redisplaying the menu bar. You can use it to update menus whose contents should vary. Since this hook is run frequently, we advise you to ensure that the functions it calls do not take much time in the usual case.
Next to every menu bar item, Emacs displays a key binding that runs the same command (if such a key binding exists). This serves as a convenient hint for users who do not know the key binding. If a command has multiple bindings, Emacs normally displays the first one it finds. You can specify one particular key binding by assigning an `:advertised-binding` symbol property to the command. See [Keys in Documentation](keys-in-documentation).
elisp None #### Components of a Lambda Expression
A lambda expression is a list that looks like this:
```
(lambda (arg-variables…)
[documentation-string]
[interactive-declaration]
body-forms…)
```
The first element of a lambda expression is always the symbol `lambda`. This indicates that the list represents a function. The reason functions are defined to start with `lambda` is so that other lists, intended for other uses, will not accidentally be valid as functions.
The second element is a list of symbols—the argument variable names (see [Argument List](argument-list)). This is called the *lambda list*. When a Lisp function is called, the argument values are matched up against the variables in the lambda list, which are given local bindings with the values provided. See [Local Variables](local-variables).
The documentation string is a Lisp string object placed within the function definition to describe the function for the Emacs help facilities. See [Function Documentation](function-documentation).
The interactive declaration is a list of the form `(interactive
code-string)`. This declares how to provide arguments if the function is used interactively. Functions with this declaration are called *commands*; they can be called using `M-x` or bound to a key. Functions not intended to be called in this way should not have interactive declarations. See [Defining Commands](defining-commands), for how to write an interactive declaration.
The rest of the elements are the *body* of the function: the Lisp code to do the work of the function (or, as a Lisp programmer would say, “a list of Lisp forms to evaluate”). The value returned by the function is the value returned by the last element of the body.
elisp None #### Evaluation of Function Forms
If the first element of a list being evaluated is a Lisp function object, byte-code object or primitive function object, then that list is a *function call*. For example, here is a call to the function `+`:
```
(+ 1 x)
```
The first step in evaluating a function call is to evaluate the remaining elements of the list from left to right. The results are the actual argument values, one value for each list element. The next step is to call the function with this list of arguments, effectively using the function `apply` (see [Calling Functions](calling-functions)). If the function is written in Lisp, the arguments are used to bind the argument variables of the function (see [Lambda Expressions](lambda-expressions)); then the forms in the function body are evaluated in order, and the value of the last body form becomes the value of the function call.
elisp None #### Some Terms
Throughout this manual, the phrases “the Lisp reader” and “the Lisp printer” refer to those routines in Lisp that convert textual representations of Lisp objects into actual Lisp objects, and vice versa. See [Printed Representation](printed-representation), for more details. You, the person reading this manual, are thought of as the programmer and are addressed as “you”. The user is the person who uses Lisp programs, including those you write.
Examples of Lisp code are formatted like this: `(list 1 2 3)`. Names that represent metasyntactic variables, or arguments to a function being described, are formatted like this: first-number.
elisp None #### Properties in the Mode Line
Certain text properties are meaningful in the mode line. The `face` property affects the appearance of text; the `help-echo` property associates help strings with the text, and `keymap` can make the text mouse-sensitive.
There are four ways to specify text properties for text in the mode line:
1. Put a string with a text property directly into the mode line data structure, but see [Mode Line Data](mode-line-data) for caveats for that.
2. Put a text property on a mode line %-construct such as ‘`%12b`’; then the expansion of the %-construct will have that same text property.
3. Use a `(:propertize elt props…)` construct to give elt a text property specified by props.
4. Use a list containing `:eval form` in the mode line data structure, and make form evaluate to a string that has a text property.
You can use the `keymap` property to specify a keymap. This keymap only takes real effect for mouse clicks; binding character keys and function keys to it has no effect, since it is impossible to move point into the mode line.
When the mode line refers to a variable which does not have a non-`nil` `risky-local-variable` property, any text properties given or specified within that variable’s values are ignored. This is because such properties could otherwise specify functions to be called, and those functions could come from file local variables.
| programming_docs |
elisp None #### Skipping Characters
The following two functions move point over a specified set of characters. For example, they are often used to skip whitespace. For related functions, see [Motion and Syntax](motion-and-syntax).
These functions convert the set string to multibyte if the buffer is multibyte, and they convert it to unibyte if the buffer is unibyte, as the search functions do (see [Searching and Matching](searching-and-matching)).
Function: **skip-chars-forward** *character-set &optional limit*
This function moves point in the current buffer forward, skipping over a given set of characters. It examines the character following point, then advances point if the character matches character-set. This continues until it reaches a character that does not match. The function returns the number of characters moved over.
The argument character-set is a string, like the inside of a ‘`[…]`’ in a regular expression except that ‘`]`’ does not terminate it, and ‘`\`’ quotes ‘`^`’, ‘`-`’ or ‘`\`’. Thus, `"a-zA-Z"` skips over all letters, stopping before the first nonletter, and `"^a-zA-Z"` skips nonletters stopping before the first letter (see [Regular Expressions](regular-expressions)). Character classes can also be used, e.g., `"[:alnum:]"` (see [Char Classes](char-classes)).
If limit is supplied (it must be a number or a marker), it specifies the maximum position in the buffer that point can be skipped to. Point will stop at or before limit.
In the following example, point is initially located directly before the ‘`T`’. After the form is evaluated, point is located at the end of that line (between the ‘`t`’ of ‘`hat`’ and the newline). The function skips all letters and spaces, but not newlines.
```
---------- Buffer: foo ----------
I read "∗The cat in the hat
comes back" twice.
---------- Buffer: foo ----------
```
```
(skip-chars-forward "a-zA-Z ")
⇒ 18
---------- Buffer: foo ----------
I read "The cat in the hat∗
comes back" twice.
---------- Buffer: foo ----------
```
Function: **skip-chars-backward** *character-set &optional limit*
This function moves point backward, skipping characters that match character-set, until limit. It is just like `skip-chars-forward` except for the direction of motion.
The return value indicates the distance traveled. It is an integer that is zero or less.
elisp None ### Window Parameters
This section describes the window parameters that can be used to associate additional information with windows.
Function: **window-parameter** *window parameter*
This function returns window’s value for parameter. The default for window is the selected window. If window has no setting for parameter, this function returns `nil`.
Function: **window-parameters** *&optional window*
This function returns all parameters of window and their values. The default for window is the selected window. The return value is either `nil`, or an association list whose elements have the form `(parameter . value)`.
Function: **set-window-parameter** *window parameter value*
This function sets window’s value of parameter to value and returns value. The default for window is the selected window.
By default, the functions that save and restore window configurations or the states of windows (see [Window Configurations](window-configurations)) do not care about window parameters. This means that when you change the value of a parameter within the body of a `save-window-excursion`, the previous value is not restored when that macro exits. It also means that when you restore via `window-state-put` a window state saved earlier by `window-state-get`, all cloned windows have their parameters reset to `nil`. The following variable allows you to override the standard behavior:
Variable: **window-persistent-parameters**
This variable is an alist specifying which parameters get saved by `current-window-configuration` and `window-state-get`, and subsequently restored by `set-window-configuration` and `window-state-put`. See [Window Configurations](window-configurations).
The CAR of each entry of this alist is a symbol specifying the parameter. The CDR should be one of the following:
`nil`
This value means the parameter is saved neither by `window-state-get` nor by `current-window-configuration`.
`t`
This value specifies that the parameter is saved by `current-window-configuration` and (provided its writable argument is `nil`) by `window-state-get`.
`writable` This means that the parameter is saved unconditionally by both `current-window-configuration` and `window-state-get`. This value should not be used for parameters whose values do not have a read syntax. Otherwise, invoking `window-state-put` in another session may fail with an `invalid-read-syntax` error.
Some functions (notably `delete-window`, `delete-other-windows` and `split-window`), may behave specially when the window specified by their window argument has a parameter whose name is equal to the function’s name. You can override such special behavior by binding the following variable to a non-`nil` value:
Variable: **ignore-window-parameters**
If this variable is non-`nil`, some standard functions do not process window parameters. The functions currently affected by this are `split-window`, `delete-window`, `delete-other-windows`, and `other-window`.
An application can bind this variable to a non-`nil` value around calls to these functions. If it does so, the application is fully responsible for correctly assigning the parameters of all involved windows when exiting that function.
The following parameters are currently used by the window management code:
`delete-window`
This parameter affects the execution of `delete-window` (see [Deleting Windows](deleting-windows)).
`delete-other-windows`
This parameter affects the execution of `delete-other-windows` (see [Deleting Windows](deleting-windows)).
`no-delete-other-windows`
This parameter marks the window as not deletable by `delete-other-windows` (see [Deleting Windows](deleting-windows)).
`split-window`
This parameter affects the execution of `split-window` (see [Splitting Windows](splitting-windows)).
`other-window`
This parameter affects the execution of `other-window` (see [Cyclic Window Ordering](cyclic-window-ordering)).
`no-other-window`
This parameter marks the window as not selectable by `other-window` (see [Cyclic Window Ordering](cyclic-window-ordering)).
`clone-of`
This parameter specifies the window that this one has been cloned from. It is installed by `window-state-get` (see [Window Configurations](window-configurations)).
`window-preserved-size`
This parameter specifies a buffer, a direction where `nil` means vertical and `t` horizontal, and a size in pixels. If this window displays the specified buffer and its size in the indicated direction equals the size specified by this parameter, then Emacs will try to preserve the size of this window in the indicated direction. This parameter is installed and updated by the function `window-preserve-size` (see [Preserving Window Sizes](preserving-window-sizes)).
`quit-restore`
This parameter is installed by the buffer display functions (see [Choosing Window](choosing-window)) and consulted by `quit-restore-window` (see [Quitting Windows](quitting-windows)). It is a list of four elements, see the description of `quit-restore-window` in [Quitting Windows](quitting-windows) for details.
`window-side` `window-slot`
These parameters are used internally for implementing side windows (see [Side Windows](side-windows)).
`window-atom`
This parameter is used internally for implementing atomic windows, see [Atomic Windows](atomic-windows).
`mode-line-format`
This parameter replaces the value of the buffer-local variable `mode-line-format` (see [Mode Line Basics](mode-line-basics)) of this window’s buffer whenever this window is displayed. The symbol `none` means to suppress display of a mode line for this window. Display and contents of the mode line on other windows showing this buffer are not affected.
`header-line-format`
This parameter replaces the value of the buffer-local variable `header-line-format` (see [Mode Line Basics](mode-line-basics)) of this window’s buffer whenever this window is displayed. The symbol `none` means to suppress display of a header line for this window. Display and contents of the header line on other windows showing this buffer are not affected.
`tab-line-format`
This parameter replaces the value of the buffer-local variable `tab-line-format` (see [Mode Line Basics](mode-line-basics)) of this window’s buffer whenever this window is displayed. The symbol `none` means to suppress display of a tab line for this window. Display and contents of the tab line on other windows showing this buffer are not affected.
`min-margins`
The value of this parameter is a cons cell whose CAR and CDR, if non-`nil`, specify the minimum values (in columns) for the left and right margin of this window (see [Display Margins](display-margins). When present, Emacs will use these values instead of the actual margin widths for determining whether a window can be split or shrunk horizontally.
Emacs never auto-adjusts the margins of any window after splitting or resizing it. It is the sole responsibility of any application setting this parameter to adjust the margins of this window as well as those of any new window that inherits this window’s margins due to a split. Both `window-configuration-change-hook` and `window-size-change-functions` (see [Window Hooks](window-hooks)) should be employed for this purpose.
This parameter was introduced in Emacs version 25.1 to support applications that use large margins to center buffer text within a window and should be used, with due care, exclusively by those applications. It might be replaced by an improved solution in future versions of Emacs.
elisp None ### Operating on X11 Keysyms
To define system-specific X11 keysyms, set the variable `system-key-alist`.
Variable: **system-key-alist**
This variable’s value should be an alist with one element for each system-specific keysym. Each element has the form `(code
. symbol)`, where code is the numeric keysym code (not including the vendor-specific bit, -2\*\*28), and symbol is the name for the function key.
For example `(168 . mute-acute)` defines a system-specific key (used by HP X servers) whose numeric code is -2\*\*28 + 168.
It is not crucial to exclude from the alist the keysyms of other X servers; those do no harm, as long as they don’t conflict with the ones used by the X server actually in use.
The variable is always local to the current terminal, and cannot be buffer-local. See [Multiple Terminals](multiple-terminals).
You can specify which keysyms Emacs should use for the Control, Meta, Alt, Hyper, and Super modifiers by setting these variables:
Variable: **x-ctrl-keysym**
Variable: **x-alt-keysym**
Variable: **x-meta-keysym**
Variable: **x-hyper-keysym**
Variable: **x-super-keysym**
The name of the keysym that should stand for the Control modifier (respectively, for Alt, Meta, Hyper, and Super). For example, here is how to swap the Meta and Alt modifiers within Emacs:
```
(setq x-alt-keysym 'meta)
(setq x-meta-keysym 'alt)
```
elisp None #### Font and Color Parameters
These frame parameters control the use of fonts and colors.
`font-backend`
A list of symbols, specifying the *font backends* to use for drawing characters on the frame, in order of priority. In Emacs built without Cairo drawing on X, there are currently three potentially available font backends: `x` (the X core font driver), `xft` (the Xft font driver), and `xfthb` (the Xft font driver with HarfBuzz text shaping). If built with Cairo drawing, there are also three potentially available font backends on X: `x`, `ftcr` (the FreeType font driver on Cairo), and `ftcrhb` (the FreeType font driver on Cairo with HarfBuzz text shaping). When Emacs is built with HarfBuzz, the default font driver is `ftcrhb`, although use of the `ftcr` driver is still possible, but not recommended. On MS-Windows, there are currently three available font backends: `gdi` (the core MS-Windows font driver), `uniscribe` (font driver for OTF and TTF fonts with text shaping by the Uniscribe engine), and `harfbuzz` (font driver for OTF and TTF fonts with HarfBuzz text shaping) (see [Windows Fonts](https://www.gnu.org/software/emacs/manual/html_node/emacs/Windows-Fonts.html#Windows-Fonts) in The GNU Emacs Manual). The `harfbuzz` driver is similarly recommended. On other systems, there is only one available font backend, so it does not make sense to modify this frame parameter.
`background-mode`
This parameter is either `dark` or `light`, according to whether the background color is a light one or a dark one.
`tty-color-mode`
This parameter overrides the terminal’s color support as given by the system’s terminal capabilities database in that this parameter’s value specifies the color mode to use on a text terminal. The value can be either a symbol or a number. A number specifies the number of colors to use (and, indirectly, what commands to issue to produce each color). For example, `(tty-color-mode . 8)` specifies use of the ANSI escape sequences for 8 standard text colors. A value of -1 turns off color support.
If the parameter’s value is a symbol, it specifies a number through the value of `tty-color-mode-alist`, and the associated number is used instead.
`screen-gamma`
If this is a number, Emacs performs gamma correction which adjusts the brightness of all colors. The value should be the screen gamma of your display.
Usual PC monitors have a screen gamma of 2.2, so color values in Emacs, and in X windows generally, are calibrated to display properly on a monitor with that gamma value. If you specify 2.2 for `screen-gamma`, that means no correction is needed. Other values request correction, designed to make the corrected colors appear on your screen the way they would have appeared without correction on an ordinary monitor with a gamma value of 2.2.
If your monitor displays colors too light, you should specify a `screen-gamma` value smaller than 2.2. This requests correction that makes colors darker. A screen gamma value of 1.5 may give good results for LCD color displays.
`alpha`
This parameter specifies the opacity of the frame, on graphical displays that support variable opacity. It should be an integer between 0 and 100, where 0 means completely transparent and 100 means completely opaque. It can also have a `nil` value, which tells Emacs not to set the frame opacity (leaving it to the window manager).
To prevent the frame from disappearing completely from view, the variable `frame-alpha-lower-limit` defines a lower opacity limit. If the value of the frame parameter is less than the value of this variable, Emacs uses the latter. By default, `frame-alpha-lower-limit` is 20.
The `alpha` frame parameter can also be a cons cell `(active . inactive)`, where active is the opacity of the frame when it is selected, and inactive is the opacity when it is not selected.
Some window systems do not support the `alpha` parameter for child frames (see [Child Frames](child-frames)).
The following frame parameters are semi-obsolete in that they are automatically equivalent to particular face attributes of particular faces (see [Standard Faces](https://www.gnu.org/software/emacs/manual/html_node/emacs/Standard-Faces.html#Standard-Faces) in The Emacs Manual):
`font`
The name of the font for displaying text in the frame. This is a string, either a valid font name for your system or the name of an Emacs fontset (see [Fontsets](fontsets)). It is equivalent to the `font` attribute of the `default` face.
`foreground-color`
The color to use for characters. It is equivalent to the `:foreground` attribute of the `default` face.
`background-color`
The color to use for the background of characters. It is equivalent to the `:background` attribute of the `default` face.
`mouse-color`
The color for the mouse pointer. It is equivalent to the `:background` attribute of the `mouse` face.
`cursor-color`
The color for the cursor that shows point. It is equivalent to the `:background` attribute of the `cursor` face.
`border-color`
The color for the border of the frame. It is equivalent to the `:background` attribute of the `border` face.
`scroll-bar-foreground`
If non-`nil`, the color for the foreground of scroll bars. It is equivalent to the `:foreground` attribute of the `scroll-bar` face.
`scroll-bar-background` If non-`nil`, the color for the background of scroll bars. It is equivalent to the `:background` attribute of the `scroll-bar` face.
elisp None ### Indenting Macros
Within a macro definition, you can use the `declare` form (see [Defining Macros](defining-macros)) to specify how TAB should indent calls to the macro. An indentation specification is written like this:
```
(declare (indent indent-spec))
```
This results in the `lisp-indent-function` property being set on the macro name.
Here are the possibilities for indent-spec:
`nil` This is the same as no property—use the standard indentation pattern.
`defun` Handle this function like a ‘`def`’ construct: treat the second line as the start of a *body*.
an integer, number
The first number arguments of the function are *distinguished* arguments; the rest are considered the body of the expression. A line in the expression is indented according to whether the first argument on it is distinguished or not. If the argument is part of the body, the line is indented `lisp-body-indent` more columns than the open-parenthesis starting the containing expression. If the argument is distinguished and is either the first or second argument, it is indented *twice* that many extra columns. If the argument is distinguished and not the first or second argument, the line uses the standard pattern.
a symbol, symbol
symbol should be a function name; that function is called to calculate the indentation of a line within this expression. The function receives two arguments:
pos The position at which the line being indented begins.
state The value returned by `parse-partial-sexp` (a Lisp primitive for indentation and nesting computation) when it parses up to the beginning of this line.
It should return either a number, which is the number of columns of indentation for that line, or a list whose car is such a number. The difference between returning a number and returning a list is that a number says that all following lines at the same nesting level should be indented just like this one; a list says that following lines might call for different indentations. This makes a difference when the indentation is being computed by `C-M-q`; if the value is a number, `C-M-q` need not recalculate indentation for the following lines until the end of the list.
elisp None #### Error Messages
Some examples signal errors. This normally displays an error message in the echo area. We show the error message on a line starting with ‘`error→`’. Note that ‘`error→`’ itself does not appear in the echo area.
```
(+ 23 'x)
error→ Wrong type argument: number-or-marker-p, x
```
elisp None #### A Simple Lambda Expression Example
Consider the following example:
```
(lambda (a b c) (+ a b c))
```
We can call this function by passing it to `funcall`, like this:
```
(funcall (lambda (a b c) (+ a b c))
1 2 3)
```
This call evaluates the body of the lambda expression with the variable `a` bound to 1, `b` bound to 2, and `c` bound to 3. Evaluation of the body adds these three numbers, producing the result 6; therefore, this call to the function returns the value 6.
Note that the arguments can be the results of other function calls, as in this example:
```
(funcall (lambda (a b c) (+ a b c))
1 (* 2 3) (- 5 4))
```
This evaluates the arguments `1`, `(* 2 3)`, and `(- 5
4)` from left to right. Then it applies the lambda expression to the argument values 1, 6 and 1 to produce the value 8.
As these examples show, you can use a form with a lambda expression as its CAR to make local variables and give them values. In the old days of Lisp, this technique was the only way to bind and initialize local variables. But nowadays, it is clearer to use the special form `let` for this purpose (see [Local Variables](local-variables)). Lambda expressions are mainly used as anonymous functions for passing as arguments to other functions (see [Anonymous Functions](anonymous-functions)), or stored as symbol function definitions to produce named functions (see [Function Names](function-names)).
| programming_docs |
elisp None #### Frame Type
A *frame* is a screen area that contains one or more Emacs windows; we also use the term “frame” to refer to the Lisp object that Emacs uses to refer to the screen area.
Frames have no read syntax. They print in hash notation, giving the frame’s title, plus its address in core (useful to identify the frame uniquely).
```
(selected-frame)
⇒ #<frame [email protected] 0xdac80>
```
See [Frames](frames), for a description of the functions that work on frames.
elisp None #### Splicing into Lists
The `:inline` feature lets you splice a variable number of elements into the middle of a `list` or `vector` customization type. You use it by adding `:inline t` to a type specification which is contained in a `list` or `vector` specification.
Normally, each entry in a `list` or `vector` type specification describes a single element type. But when an entry contains `:inline t`, the value it matches is merged directly into the containing sequence. For example, if the entry matches a list with three elements, those become three elements of the overall sequence. This is analogous to ‘`,@`’ in a backquote construct (see [Backquote](backquote)).
For example, to specify a list whose first element must be `baz` and whose remaining arguments should be zero or more of `foo` and `bar`, use this customization type:
```
(list (const baz) (set :inline t (const foo) (const bar)))
```
This matches values such as `(baz)`, `(baz foo)`, `(baz bar)` and `(baz foo bar)`.
When the element-type is a `choice`, you use `:inline` not in the `choice` itself, but in (some of) the alternatives of the `choice`. For example, to match a list which must start with a file name, followed either by the symbol `t` or two strings, use this customization type:
```
(list file
(choice (const t)
(list :inline t string string)))
```
If the user chooses the first alternative in the choice, then the overall list has two elements and the second element is `t`. If the user chooses the second alternative, then the overall list has three elements and the second and third must be strings.
The widgets can specify predicates to say whether an inline value matches the widget with the `:match-inline` element.
elisp None ### Read Syntax for Circular Objects
To represent shared or circular structures within a complex of Lisp objects, you can use the reader constructs ‘`#n=`’ and ‘`#n#`’.
Use `#n=` before an object to label it for later reference; subsequently, you can use `#n#` to refer the same object in another place. Here, n is some integer. For example, here is how to make a list in which the first element recurs as the third element:
```
(#1=(a) b #1#)
```
This differs from ordinary syntax such as this
```
((a) b (a))
```
which would result in a list whose first and third elements look alike but are not the same Lisp object. This shows the difference:
```
(prog1 nil
(setq x '(#1=(a) b #1#)))
(eq (nth 0 x) (nth 2 x))
⇒ t
(setq x '((a) b (a)))
(eq (nth 0 x) (nth 2 x))
⇒ nil
```
You can also use the same syntax to make a circular structure, which appears as an element within itself. Here is an example:
```
#1=(a #1#)
```
This makes a list whose second element is the list itself. Here’s how you can see that it really works:
```
(prog1 nil
(setq x '#1=(a #1#)))
(eq x (cadr x))
⇒ t
```
The Lisp printer can produce this syntax to record circular and shared structure in a Lisp object, if you bind the variable `print-circle` to a non-`nil` value. See [Output Variables](output-variables).
elisp None #### Image Cache
Emacs caches images so that it can display them again more efficiently. When Emacs displays an image, it searches the image cache for an existing image specification `equal` to the desired specification. If a match is found, the image is displayed from the cache. Otherwise, Emacs loads the image normally.
Function: **image-flush** *spec &optional frame*
This function removes the image with specification spec from the image cache of frame frame. Image specifications are compared using `equal`. If frame is `nil`, it defaults to the selected frame. If frame is `t`, the image is flushed on all existing frames.
In Emacs’s current implementation, each graphical terminal possesses an image cache, which is shared by all the frames on that terminal (see [Multiple Terminals](multiple-terminals)). Thus, refreshing an image in one frame also refreshes it in all other frames on the same terminal.
One use for `image-flush` is to tell Emacs about a change in an image file. If an image specification contains a `:file` property, the image is cached based on the file’s contents when the image is first displayed. Even if the file subsequently changes, Emacs continues displaying the old version of the image. Calling `image-flush` flushes the image from the cache, forcing Emacs to re-read the file the next time it needs to display that image.
Another use for `image-flush` is for memory conservation. If your Lisp program creates a large number of temporary images over a period much shorter than `image-cache-eviction-delay` (see below), you can opt to flush unused images yourself, instead of waiting for Emacs to do it automatically.
Function: **clear-image-cache** *&optional filter*
This function clears an image cache, removing all the images stored in it. If filter is omitted or `nil`, it clears the cache for the selected frame. If filter is a frame, it clears the cache for that frame. If filter is `t`, all image caches are cleared. Otherwise, filter is taken to be a file name, and all images associated with that file name are removed from all image caches.
If an image in the image cache has not been displayed for a specified period of time, Emacs removes it from the cache and frees the associated memory.
Variable: **image-cache-eviction-delay**
This variable specifies the number of seconds an image can remain in the cache without being displayed. When an image is not displayed for this length of time, Emacs removes it from the image cache.
Under some circumstances, if the number of images in the cache grows too large, the actual eviction delay may be shorter than this.
If the value is `nil`, Emacs does not remove images from the cache except when you explicitly clear it. This mode can be useful for debugging.
Function: **image-cache-size**
This function returns the total size of the current image cache, in bytes. An image of size 200x100 with 24 bits per color will have a cache size of 60000 bytes, for instance.
elisp None ### Sorting Text
The sorting functions described in this section all rearrange text in a buffer. This is in contrast to the function `sort`, which rearranges the order of the elements of a list (see [Rearrangement](rearrangement)). The values returned by these functions are not meaningful.
Function: **sort-subr** *reverse nextrecfun endrecfun &optional startkeyfun endkeyfun predicate*
This function is the general text-sorting routine that subdivides a buffer into records and then sorts them. Most of the commands in this section use this function.
To understand how `sort-subr` works, consider the whole accessible portion of the buffer as being divided into disjoint pieces called *sort records*. The records may or may not be contiguous, but they must not overlap. A portion of each sort record (perhaps all of it) is designated as the sort key. Sorting rearranges the records in order by their sort keys.
Usually, the records are rearranged in order of ascending sort key. If the first argument to the `sort-subr` function, reverse, is non-`nil`, the sort records are rearranged in order of descending sort key.
The next four arguments to `sort-subr` are functions that are called to move point across a sort record. They are called many times from within `sort-subr`.
1. nextrecfun is called with point at the end of a record. This function moves point to the start of the next record. The first record is assumed to start at the position of point when `sort-subr` is called. Therefore, you should usually move point to the beginning of the buffer before calling `sort-subr`. This function can indicate there are no more sort records by leaving point at the end of the buffer.
2. endrecfun is called with point within a record. It moves point to the end of the record.
3. startkeyfun is called to move point from the start of a record to the start of the sort key. This argument is optional; if it is omitted, the whole record is the sort key. If supplied, the function should either return a non-`nil` value to be used as the sort key, or return `nil` to indicate that the sort key is in the buffer starting at point. In the latter case, endkeyfun is called to find the end of the sort key.
4. endkeyfun is called to move point from the start of the sort key to the end of the sort key. This argument is optional. If startkeyfun returns `nil` and this argument is omitted (or `nil`), then the sort key extends to the end of the record. There is no need for endkeyfun if startkeyfun returns a non-`nil` value.
The argument predicate is the function to use to compare keys. It is called with two arguments, the keys to compare, and should return non-`nil` if the first key should come before the second in the sorting order. What exactly are the key arguments depends on what startkeyfun and endkeyfun return. If predicate is omitted or `nil`, it defaults to `<` if the keys are numbers, to `compare-buffer-substrings` if the keys are cons cells (whose `car` and `cdr` are start and end buffer positions of the key), and to `string<` otherwise (with keys assumed to be strings).
As an example of `sort-subr`, here is the complete function definition for `sort-lines`:
```
;; Note that the first two lines of doc string
;; are effectively one line when viewed by a user.
(defun sort-lines (reverse beg end)
"Sort lines in region alphabetically;\
argument means descending order.
Called from a program, there are three arguments:
```
```
REVERSE (non-nil means reverse order),\
BEG and END (region to sort).
The variable `sort-fold-case' determines\
whether alphabetic case affects
the sort order."
```
```
(interactive "P\nr")
(save-excursion
(save-restriction
(narrow-to-region beg end)
(goto-char (point-min))
(let ((inhibit-field-text-motion t))
(sort-subr reverse 'forward-line 'end-of-line)))))
```
Here `forward-line` moves point to the start of the next record, and `end-of-line` moves point to the end of record. We do not pass the arguments startkeyfun and endkeyfun, because the entire record is used as the sort key.
The `sort-paragraphs` function is very much the same, except that its `sort-subr` call looks like this:
```
(sort-subr reverse
(lambda ()
(while (and (not (eobp))
(looking-at paragraph-separate))
(forward-line 1)))
'forward-paragraph)
```
Markers pointing into any sort records are left with no useful position after `sort-subr` returns.
User Option: **sort-fold-case**
If this variable is non-`nil`, `sort-subr` and the other buffer sorting functions ignore case when comparing strings.
Command: **sort-regexp-fields** *reverse record-regexp key-regexp start end*
This command sorts the region between start and end alphabetically as specified by record-regexp and key-regexp. If reverse is a negative integer, then sorting is in reverse order.
Alphabetical sorting means that two sort keys are compared by comparing the first characters of each, the second characters of each, and so on. If a mismatch is found, it means that the sort keys are unequal; the sort key whose character is less at the point of first mismatch is the lesser sort key. The individual characters are compared according to their numerical character codes in the Emacs character set.
The value of the record-regexp argument specifies how to divide the buffer into sort records. At the end of each record, a search is done for this regular expression, and the text that matches it is taken as the next record. For example, the regular expression ‘`^.+$`’, which matches lines with at least one character besides a newline, would make each such line into a sort record. See [Regular Expressions](regular-expressions), for a description of the syntax and meaning of regular expressions.
The value of the key-regexp argument specifies what part of each record is the sort key. The key-regexp could match the whole record, or only a part. In the latter case, the rest of the record has no effect on the sorted order of records, but it is carried along when the record moves to its new position.
The key-regexp argument can refer to the text matched by a subexpression of record-regexp, or it can be a regular expression on its own.
If key-regexp is:
‘`\digit`’
then the text matched by the digitth ‘`\(...\)`’ parenthesis grouping in record-regexp is the sort key.
‘`\&`’
then the whole record is the sort key.
a regular expression then `sort-regexp-fields` searches for a match for the regular expression within the record. If such a match is found, it is the sort key. If there is no match for key-regexp within a record then that record is ignored, which means its position in the buffer is not changed. (The other records may move around it.)
For example, if you plan to sort all the lines in the region by the first word on each line starting with the letter ‘`f`’, you should set record-regexp to ‘`^.\*$`’ and set key-regexp to ‘`\<f\w\*\>`’. The resulting expression looks like this:
```
(sort-regexp-fields nil "^.*$" "\\<f\\w*\\>"
(region-beginning)
(region-end))
```
If you call `sort-regexp-fields` interactively, it prompts for record-regexp and key-regexp in the minibuffer.
Command: **sort-lines** *reverse start end*
This command alphabetically sorts lines in the region between start and end. If reverse is non-`nil`, the sort is in reverse order.
Command: **sort-paragraphs** *reverse start end*
This command alphabetically sorts paragraphs in the region between start and end. If reverse is non-`nil`, the sort is in reverse order.
Command: **sort-pages** *reverse start end*
This command alphabetically sorts pages in the region between start and end. If reverse is non-`nil`, the sort is in reverse order.
Command: **sort-fields** *field start end*
This command sorts lines in the region between start and end, comparing them alphabetically by the fieldth field of each line. Fields are separated by whitespace and numbered starting from 1. If field is negative, sorting is by the -fieldth field from the end of the line. This command is useful for sorting tables.
Command: **sort-numeric-fields** *field start end*
This command sorts lines in the region between start and end, comparing them numerically by the fieldth field of each line. Fields are separated by whitespace and numbered starting from 1. The specified field must contain a number in each line of the region. Numbers starting with 0 are treated as octal, and numbers starting with ‘`0x`’ are treated as hexadecimal.
If field is negative, sorting is by the -fieldth field from the end of the line. This command is useful for sorting tables.
User Option: **sort-numeric-base**
This variable specifies the default radix for `sort-numeric-fields` to parse numbers.
Command: **sort-columns** *reverse &optional beg end*
This command sorts the lines in the region between beg and end, comparing them alphabetically by a certain range of columns. The column positions of beg and end bound the range of columns to sort on.
If reverse is non-`nil`, the sort is in reverse order.
One unusual thing about this command is that the entire line containing position beg, and the entire line containing position end, are included in the region sorted.
Note that `sort-columns` rejects text that contains tabs, because tabs could be split across the specified columns. Use `M-x untabify` to convert tabs to spaces before sorting.
When possible, this command actually works by calling the `sort` utility program.
elisp None #### Basic Concepts of Coding Systems
*Character code conversion* involves conversion between the internal representation of characters used inside Emacs and some other encoding. Emacs supports many different encodings, in that it can convert to and from them. For example, it can convert text to or from encodings such as Latin 1, Latin 2, Latin 3, Latin 4, Latin 5, and several variants of ISO 2022. In some cases, Emacs supports several alternative encodings for the same characters; for example, there are three coding systems for the Cyrillic (Russian) alphabet: ISO, Alternativnyj, and KOI8.
Every coding system specifies a particular set of character code conversions, but the coding system `undecided` is special: it leaves the choice unspecified, to be chosen heuristically for each file or string, based on the file’s or string’s data, when they are decoded or encoded. The coding system `prefer-utf-8` is like `undecided`, but it prefers to choose `utf-8` when possible.
In general, a coding system doesn’t guarantee roundtrip identity: decoding a byte sequence using a coding system, then encoding the resulting text in the same coding system, can produce a different byte sequence. But some coding systems do guarantee that the byte sequence will be the same as what you originally decoded. Here are a few examples:
> iso-8859-1, utf-8, big5, shift\_jis, euc-jp
>
>
>
Encoding buffer text and then decoding the result can also fail to reproduce the original text. For instance, if you encode a character with a coding system which does not support that character, the result is unpredictable, and thus decoding it using the same coding system may produce a different text. Currently, Emacs can’t report errors that result from encoding unsupported characters.
*End of line conversion* handles three different conventions used on various systems for representing end of line in files. The Unix convention, used on GNU and Unix systems, is to use the linefeed character (also called newline). The DOS convention, used on MS-Windows and MS-DOS systems, is to use a carriage return and a linefeed at the end of a line. The Mac convention is to use just carriage return. (This was the convention used in Classic Mac OS.)
*Base coding systems* such as `latin-1` leave the end-of-line conversion unspecified, to be chosen based on the data. *Variant coding systems* such as `latin-1-unix`, `latin-1-dos` and `latin-1-mac` specify the end-of-line conversion explicitly as well. Most base coding systems have three corresponding variants whose names are formed by adding ‘`-unix`’, ‘`-dos`’ and ‘`-mac`’.
The coding system `raw-text` is special in that it prevents character code conversion, and causes the buffer visited with this coding system to be a unibyte buffer. For historical reasons, you can save both unibyte and multibyte text with this coding system. When you use `raw-text` to encode multibyte text, it does perform one character code conversion: it converts eight-bit characters to their single-byte external representation. `raw-text` does not specify the end-of-line conversion, allowing that to be determined as usual by the data, and has the usual three variants which specify the end-of-line conversion.
`no-conversion` (and its alias `binary`) is equivalent to `raw-text-unix`: it specifies no conversion of either character codes or end-of-line.
The coding system `utf-8-emacs` specifies that the data is represented in the internal Emacs encoding (see [Text Representations](text-representations)). This is like `raw-text` in that no code conversion happens, but different in that the result is multibyte data. The name `emacs-internal` is an alias for `utf-8-emacs-unix` (so it forces no conversion of end-of-line, unlike `utf-8-emacs`, which can decode all 3 kinds of end-of-line conventions).
Function: **coding-system-get** *coding-system property*
This function returns the specified property of the coding system coding-system. Most coding system properties exist for internal purposes, but one that you might find useful is `:mime-charset`. That property’s value is the name used in MIME for the character coding which this coding system can read and write. Examples:
```
(coding-system-get 'iso-latin-1 :mime-charset)
⇒ iso-8859-1
(coding-system-get 'iso-2022-cn :mime-charset)
⇒ iso-2022-cn
(coding-system-get 'cyrillic-koi8 :mime-charset)
⇒ koi8-r
```
The value of the `:mime-charset` property is also defined as an alias for the coding system.
Function: **coding-system-aliases** *coding-system*
This function returns the list of aliases of coding-system.
| programming_docs |
elisp None #### Control-Character Syntax
Control characters can be represented using yet another read syntax. This consists of a question mark followed by a backslash, caret, and the corresponding non-control character, in either upper or lower case. For example, both ‘`?\^I`’ and ‘`?\^i`’ are valid read syntax for the character `C-i`, the character whose value is 9.
Instead of the ‘`^`’, you can use ‘`C-`’; thus, ‘`?\C-i`’ is equivalent to ‘`?\^I`’ and to ‘`?\^i`’:
```
?\^I ⇒ 9 ?\C-I ⇒ 9
```
In strings and buffers, the only control characters allowed are those that exist in ASCII; but for keyboard input purposes, you can turn any character into a control character with ‘`C-`’. The character codes for these non-ASCII control characters include the 2\*\*26 bit as well as the code for the corresponding non-control character. Not all text terminals can generate non-ASCII control characters, but it is straightforward to generate them using X and other window systems.
For historical reasons, Emacs treats the DEL character as the control equivalent of `?`:
```
?\^? ⇒ 127 ?\C-? ⇒ 127
```
As a result, it is currently not possible to represent the character `Control-?`, which is a meaningful input character under X, using ‘`\C-`’. It is not easy to change this, as various Lisp files refer to DEL in this way.
For representing control characters to be found in files or strings, we recommend the ‘`^`’ syntax; for control characters in keyboard input, we prefer the ‘`C-`’ syntax. Which one you use does not affect the meaning of the program, but may guide the understanding of people who read it.
elisp None ### Autoload
The *autoload* facility lets you register the existence of a function or macro, but put off loading the file that defines it. The first call to the function automatically loads the proper library, in order to install the real definition and other associated code, then runs the real definition as if it had been loaded all along. Autoloading can also be triggered by looking up the documentation of the function or macro (see [Documentation Basics](documentation-basics)), and completion of variable and function names (see [Autoload by Prefix](autoload-by-prefix) below).
| | | |
| --- | --- | --- |
| • [Autoload by Prefix](autoload-by-prefix) | | Autoload by Prefix. |
| • [When to Autoload](when-to-autoload) | | When to Use Autoload. |
There are two ways to set up an autoloaded function: by calling `autoload`, and by writing a “magic” comment in the source before the real definition. `autoload` is the low-level primitive for autoloading; any Lisp program can call `autoload` at any time. Magic comments are the most convenient way to make a function autoload, for packages installed along with Emacs. These comments do nothing on their own, but they serve as a guide for the command `update-file-autoloads`, which constructs calls to `autoload` and arranges to execute them when Emacs is built.
Function: **autoload** *function filename &optional docstring interactive type*
This function defines the function (or macro) named function so as to load automatically from filename. The string filename specifies the file to load to get the real definition of function.
If filename does not contain either a directory name, or the suffix `.el` or `.elc`, this function insists on adding one of these suffixes, and it will not load from a file whose name is just filename with no added suffix. (The variable `load-suffixes` specifies the exact required suffixes.)
The argument docstring is the documentation string for the function. Specifying the documentation string in the call to `autoload` makes it possible to look at the documentation without loading the function’s real definition. Normally, this should be identical to the documentation string in the function definition itself. If it isn’t, the function definition’s documentation string takes effect when it is loaded.
If interactive is non-`nil`, that says function can be called interactively. This lets completion in `M-x` work without loading function’s real definition. The complete interactive specification is not given here; it’s not needed unless the user actually calls function, and when that happens, it’s time to load the real definition.
If interactive is a list, it is interpreted as a list of modes this command is applicable for.
You can autoload macros and keymaps as well as ordinary functions. Specify type as `macro` if function is really a macro. Specify type as `keymap` if function is really a keymap. Various parts of Emacs need to know this information without loading the real definition.
An autoloaded keymap loads automatically during key lookup when a prefix key’s binding is the symbol function. Autoloading does not occur for other kinds of access to the keymap. In particular, it does not happen when a Lisp program gets the keymap from the value of a variable and calls `define-key`; not even if the variable name is the same symbol function.
If function already has a non-void function definition that is not an autoload object, this function does nothing and returns `nil`. Otherwise, it constructs an autoload object (see [Autoload Type](autoload-type)), and stores it as the function definition for function. The autoload object has this form:
```
(autoload filename docstring interactive type)
```
For example,
```
(symbol-function 'run-prolog)
⇒ (autoload "prolog" 169681 t nil)
```
In this case, `"prolog"` is the name of the file to load, 169681 refers to the documentation string in the `emacs/etc/DOC` file (see [Documentation Basics](documentation-basics)), `t` means the function is interactive, and `nil` that it is not a macro or a keymap.
Function: **autoloadp** *object*
This function returns non-`nil` if object is an autoload object. For example, to check if `run-prolog` is defined as an autoloaded function, evaluate
```
(autoloadp (symbol-function 'run-prolog))
```
The autoloaded file usually contains other definitions and may require or provide one or more features. If the file is not completely loaded (due to an error in the evaluation of its contents), any function definitions or `provide` calls that occurred during the load are undone. This is to ensure that the next attempt to call any function autoloading from this file will try again to load the file. If not for this, then some of the functions in the file might be defined by the aborted load, but fail to work properly for the lack of certain subroutines not loaded successfully because they come later in the file.
If the autoloaded file fails to define the desired Lisp function or macro, then an error is signaled with data `"Autoloading failed to
define function function-name"`.
A magic autoload comment (often called an *autoload cookie*) consists of ‘`;;;###autoload`’, on a line by itself, just before the real definition of the function in its autoloadable source file. The command `M-x update-file-autoloads` writes a corresponding `autoload` call into `loaddefs.el`. (The string that serves as the autoload cookie and the name of the file generated by `update-file-autoloads` can be changed from the above defaults, see below.) Building Emacs loads `loaddefs.el` and thus calls `autoload`. `M-x make-directory-autoloads` is even more powerful; it updates autoloads for all files in the current directory.
The same magic comment can copy any kind of form into `loaddefs.el`. The form following the magic comment is copied verbatim, *except* if it is one of the forms which the autoload facility handles specially (e.g., by conversion into an `autoload` call). The forms which are not copied verbatim are the following:
Definitions for function or function-like objects:
`defun` and `defmacro`; also `cl-defun` and `cl-defmacro` (see [Argument Lists](https://www.gnu.org/software/emacs/manual/html_node/cl/Argument-Lists.html#Argument-Lists) in Common Lisp Extensions), and `define-overloadable-function` (see the commentary in `mode-local.el`).
Definitions for major or minor modes:
`define-minor-mode`, `define-globalized-minor-mode`, `define-generic-mode`, `define-derived-mode`, `easy-mmode-define-minor-mode`, `easy-mmode-define-global-mode`, `define-compilation-mode`, and `define-global-minor-mode`.
Other definition types: `defcustom`, `defgroup`, `defclass` (see [EIEIO](https://www.gnu.org/software/emacs/manual/html_node/eieio/index.html#Top) in EIEIO), and `define-skeleton` (see [Autotyping](https://www.gnu.org/software/emacs/manual/html_node/autotype/index.html#Top) in Autotyping).
You can also use a magic comment to execute a form at build time *without* executing it when the file itself is loaded. To do this, write the form *on the same line* as the magic comment. Since it is in a comment, it does nothing when you load the source file; but `M-x update-file-autoloads` copies it to `loaddefs.el`, where it is executed while building Emacs.
The following example shows how `doctor` is prepared for autoloading with a magic comment:
```
;;;###autoload
(defun doctor ()
"Switch to *doctor* buffer and start giving psychotherapy."
(interactive)
(switch-to-buffer "*doctor*")
(doctor-mode))
```
Here’s what that produces in `loaddefs.el`:
```
(autoload 'doctor "doctor" "\
Switch to *doctor* buffer and start giving psychotherapy.
\(fn)" t nil)
```
The backslash and newline immediately following the double-quote are a convention used only in the preloaded uncompiled Lisp files such as `loaddefs.el`; they tell `make-docfile` to put the documentation string in the `etc/DOC` file. See [Building Emacs](building-emacs). See also the commentary in `lib-src/make-docfile.c`. ‘`(fn)`’ in the usage part of the documentation string is replaced with the function’s name when the various help functions (see [Help Functions](help-functions)) display it.
If you write a function definition with an unusual macro that is not one of the known and recognized function definition methods, use of an ordinary magic autoload comment would copy the whole definition into `loaddefs.el`. That is not desirable. You can put the desired `autoload` call into `loaddefs.el` instead by writing this:
```
;;;###autoload (autoload 'foo "myfile")
(mydefunmacro foo
...)
```
You can use a non-default string as the autoload cookie and have the corresponding autoload calls written into a file whose name is different from the default `loaddefs.el`. Emacs provides two variables to control this:
Variable: **generate-autoload-cookie**
The value of this variable should be a string whose syntax is a Lisp comment. `M-x update-file-autoloads` copies the Lisp form that follows the cookie into the autoload file it generates. The default value of this variable is `";;;###autoload"`.
Variable: **generated-autoload-file**
The value of this variable names an Emacs Lisp file where the autoload calls should go. The default value is `loaddefs.el`, but you can override that, e.g., in the local variables section of a `.el` file (see [File Local Variables](file-local-variables)). The autoload file is assumed to contain a trailer starting with a formfeed character.
The following function may be used to explicitly load the library specified by an autoload object:
Function: **autoload-do-load** *autoload &optional name macro-only*
This function performs the loading specified by autoload, which should be an autoload object. The optional argument name, if non-`nil`, should be a symbol whose function value is autoload; in that case, the return value of this function is the symbol’s new function value. If the value of the optional argument macro-only is `macro`, this function avoids loading a function, only a macro.
elisp None #### Advanced data layout specifications
Bindat type expressions are not limited to the types described earlier. They can also be arbitrary Lisp forms returning Bindat type expressions. For example, the type below describes data which can either contain a 24-bit error code or a vector of bytes:
```
(bindat-type
(len u8)
(payload . (if (zerop len) (uint 24) (vec (1- len)))))
```
Furthermore, while composite types are normally unpacked to (and packed from) association lists, this can be changed via the use of the following special keyword arguments:
`:unpack-val exp`
When the list of fields ends with this keyword argument, then the value returned when unpacking is the value of exp instead of the standard alist. exp can refer to all the previous fields by their name.
`:pack-val exp`
If a field’s type is followed by this keyword argument, then the value packed into this field is returned by exp instead of being extracted from the alist.
`:pack-var name` If the list of fields is preceded by this keyword argument, then all the subsequent `:pack-val` arguments can refer to the overall value to pack into this composite type via the variable named name.
For example, one could describe a 16-bit signed integer as follows:
```
(defconst sint16-bindat-spec
(let* ((max (ash 1 15))
(wrap (+ max max)))
(bindat-type :pack-var v
(n uint 16 :pack-val (if (< v 0) (+ v wrap) v))
:unpack-val (if (>= n max) (- n wrap) n))))
```
Which would then behave as follows:
```
(bindat-pack sint16-bindat-spec -8)
⇒ "\377\370"
(bindat-unpack sint16-bindat-spec "\300\100")
⇒ -16320
```
Finally, you can define new Bindat type forms to use in Bindat type expressions with `bindat-defmacro`:
Macro: **bindat-defmacro** *name args &rest body*
Define a new Bindat type expression named name and taking arguments args. Its behavior follows that of `defmacro`, which the important difference that the new forms can only be used within Bindat type expressions.
elisp None #### Other Font Lock Variables
This section describes additional variables that a major mode can set by means of other-vars in `font-lock-defaults` (see [Font Lock Basics](font-lock-basics)).
Variable: **font-lock-mark-block-function**
If this variable is non-`nil`, it should be a function that is called with no arguments, to choose an enclosing range of text for refontification for the command `M-x font-lock-fontify-block`.
The function should report its choice by placing the region around it. A good choice is a range of text large enough to give proper results, but not too large so that refontification becomes slow. Typical values are `mark-defun` for programming modes or `mark-paragraph` for textual modes.
Variable: **font-lock-extra-managed-props**
This variable specifies additional properties (other than `font-lock-face`) that are being managed by Font Lock mode. It is used by `font-lock-default-unfontify-region`, which normally only manages the `font-lock-face` property. If you want Font Lock to manage other properties as well, you must specify them in a facespec in `font-lock-keywords` as well as add them to this list. See [Search-based Fontification](search_002dbased-fontification).
Variable: **font-lock-fontify-buffer-function**
Function to use for fontifying the buffer. The default value is `font-lock-default-fontify-buffer`.
Variable: **font-lock-unfontify-buffer-function**
Function to use for unfontifying the buffer. This is used when turning off Font Lock mode. The default value is `font-lock-default-unfontify-buffer`.
Variable: **font-lock-fontify-region-function**
Function to use for fontifying a region. It should take two arguments, the beginning and end of the region, and an optional third argument verbose. If verbose is non-`nil`, the function should print status messages. The default value is `font-lock-default-fontify-region`.
Variable: **font-lock-unfontify-region-function**
Function to use for unfontifying a region. It should take two arguments, the beginning and end of the region. The default value is `font-lock-default-unfontify-region`.
Variable: **font-lock-flush-function**
Function to use for declaring that a region’s fontification is out of date. It takes two arguments, the beginning and end of the region. The default value of this variable is `font-lock-after-change-function`.
Variable: **font-lock-ensure-function**
Function to use for making sure a region of the current buffer has been fontified. It is called with two arguments, the beginning and end of the region. The default value of this variable is a function that calls `font-lock-default-fontify-buffer` if the buffer is not fontified; the effect is to make sure the entire accessible portion of the buffer is fontified.
Function: **jit-lock-register** *function &optional contextual*
This function tells Font Lock mode to run the Lisp function function any time it has to fontify or refontify part of the current buffer. It calls function before calling the default fontification functions, and gives it two arguments, start and end, which specify the region to be fontified or refontified. If function performs fontifications, it can return a list of the form `(jit-lock-bounds beg . end)`, to indicate the bounds of the region it actually fontified; Just-In-Time (a.k.a. “JIT”) font-lock will use this information to optimize subsequent redisplay cycles and regions of buffer text it will pass to future calls to function.
The optional argument contextual, if non-`nil`, forces Font Lock mode to always refontify a syntactically relevant part of the buffer, and not just the modified lines. This argument can usually be omitted.
When Font Lock is activated in a buffer, it calls this function with a non-`nil` value of contextual if the value of `font-lock-keywords-only` (see [Syntactic Font Lock](syntactic-font-lock)) is `nil`.
Function: **jit-lock-unregister** *function*
If function was previously registered as a fontification function using `jit-lock-register`, this function unregisters it.
Command: **jit-lock-debug-mode** *&optional arg*
This is a minor mode whose purpose is to help in debugging code that is run by JIT font-lock. When this mode is enabled, most of the code that JIT font-lock normally runs during redisplay cycles, where Lisp errors are suppressed, is instead run by a timer. Thus, this mode allows using debugging aids such as `debug-on-error` (see [Error Debugging](error-debugging)) and Edebug (see [Edebug](edebug)) for finding and fixing problems in font-lock code and any other code run by JIT font-lock.
elisp None #### Indenting an Entire Region
This section describes commands that indent all the lines in the region. They return unpredictable values.
Command: **indent-region** *start end &optional to-column*
This command indents each nonblank line starting between start (inclusive) and end (exclusive). If to-column is `nil`, `indent-region` indents each nonblank line by calling the current mode’s indentation function, the value of `indent-line-function`.
If to-column is non-`nil`, it should be an integer specifying the number of columns of indentation; then this function gives each line exactly that much indentation, by either adding or deleting whitespace.
If there is a fill prefix, `indent-region` indents each line by making it start with the fill prefix.
Variable: **indent-region-function**
The value of this variable is a function that can be used by `indent-region` as a short cut. It should take two arguments, the start and end of the region. You should design the function so that it will produce the same results as indenting the lines of the region one by one, but presumably faster.
If the value is `nil`, there is no short cut, and `indent-region` actually works line by line.
A short-cut function is useful in modes such as C mode and Lisp mode, where the `indent-line-function` must scan from the beginning of the function definition: applying it to each line would be quadratic in time. The short cut can update the scan information as it moves through the lines indenting them; this takes linear time. In a mode where indenting a line individually is fast, there is no need for a short cut.
`indent-region` with a non-`nil` argument to-column has a different meaning and does not use this variable.
Command: **indent-rigidly** *start end count*
This function indents all lines starting between start (inclusive) and end (exclusive) sideways by count columns. This preserves the shape of the affected region, moving it as a rigid unit.
This is useful not only for indenting regions of unindented text, but also for indenting regions of formatted code. For example, if count is 3, this command adds 3 columns of indentation to every line that begins in the specified region.
If called interactively with no prefix argument, this command invokes a transient mode for adjusting indentation rigidly. See [Indentation Commands](https://www.gnu.org/software/emacs/manual/html_node/emacs/Indentation-Commands.html#Indentation-Commands) in The GNU Emacs Manual.
Command: **indent-code-rigidly** *start end columns &optional nochange-regexp*
This is like `indent-rigidly`, except that it doesn’t alter lines that start within strings or comments.
In addition, it doesn’t alter a line if nochange-regexp matches at the beginning of the line (if nochange-regexp is non-`nil`).
| programming_docs |
elisp None #### Standard Symbol Properties
Here, we list the symbol properties which are used for special purposes in Emacs. In the following table, whenever we say “the named function”, that means the function whose name is the relevant symbol; similarly for “the named variable” etc.
`:advertised-binding`
This property value specifies the preferred key binding, when showing documentation, for the named function. See [Keys in Documentation](keys-in-documentation).
`char-table-extra-slots`
The value, if non-`nil`, specifies the number of extra slots in the named char-table type. See [Char-Tables](char_002dtables).
`customized-face` `face-defface-spec` `saved-face` `theme-face`
These properties are used to record a face’s standard, saved, customized, and themed face specs. Do not set them directly; they are managed by `defface` and related functions. See [Defining Faces](defining-faces).
`customized-value` `saved-value` `standard-value` `theme-value`
These properties are used to record a customizable variable’s standard value, saved value, customized-but-unsaved value, and themed values. Do not set them directly; they are managed by `defcustom` and related functions. See [Variable Definitions](variable-definitions).
`disabled`
If the value is non-`nil`, the named function is disabled as a command. See [Disabling Commands](disabling-commands).
`face-documentation`
The value stores the documentation string of the named face. This is set automatically by `defface`. See [Defining Faces](defining-faces).
`history-length`
The value, if non-`nil`, specifies the maximum minibuffer history length for the named history list variable. See [Minibuffer History](minibuffer-history).
`interactive-form`
The value is an interactive form for the named function. Normally, you should not set this directly; use the `interactive` special form instead. See [Interactive Call](interactive-call).
`menu-enable`
The value is an expression for determining whether the named menu item should be enabled in menus. See [Simple Menu Items](simple-menu-items).
`mode-class`
If the value is `special`, the named major mode is special. See [Major Mode Conventions](major-mode-conventions).
`permanent-local`
If the value is non-`nil`, the named variable is a buffer-local variable whose value should not be reset when changing major modes. See [Creating Buffer-Local](creating-buffer_002dlocal).
`permanent-local-hook`
If the value is non-`nil`, the named function should not be deleted from the local value of a hook variable when changing major modes. See [Setting Hooks](setting-hooks).
`pure`
If the value is non-`nil`, the named function is considered to be pure (see [What Is a Function](what-is-a-function)). Calls with constant arguments can be evaluated at compile time. This may shift run time errors to compile time. Not to be confused with pure storage (see [Pure Storage](pure-storage)).
`risky-local-variable`
If the value is non-`nil`, the named variable is considered risky as a file-local variable. See [File Local Variables](file-local-variables).
`safe-function`
If the value is non-`nil`, the named function is considered generally safe for evaluation. See [Function Safety](function-safety).
`safe-local-eval-function`
If the value is non-`nil`, the named function is safe to call in file-local evaluation forms. See [File Local Variables](file-local-variables).
`safe-local-variable`
The value specifies a function for determining safe file-local values for the named variable. See [File Local Variables](file-local-variables).
`side-effect-free`
A non-`nil` value indicates that the named function is free of side effects (see [What Is a Function](what-is-a-function)), so the byte compiler may ignore a call whose value is unused. If the property’s value is `error-free`, the byte compiler may even delete such unused calls. In addition to byte compiler optimizations, this property is also used for determining function safety (see [Function Safety](function-safety)).
`undo-inhibit-region`
If non-`nil`, the named function prevents the `undo` operation from being restricted to the active region, if `undo` is invoked immediately after the function. See [Undo](undo).
`variable-documentation` If non-`nil`, this specifies the named variable’s documentation string. This is set automatically by `defvar` and related functions. See [Defining Faces](defining-faces).
elisp None #### Event Examples
If the user presses and releases the left mouse button over the same location, that generates a sequence of events like this:
```
(down-mouse-1 (#<window 18 on NEWS> 2613 (0 . 38) -864320))
(mouse-1 (#<window 18 on NEWS> 2613 (0 . 38) -864180))
```
While holding the control key down, the user might hold down the second mouse button, and drag the mouse from one line to the next. That produces two events, as shown here:
```
(C-down-mouse-2 (#<window 18 on NEWS> 3440 (0 . 27) -731219))
(C-drag-mouse-2 (#<window 18 on NEWS> 3440 (0 . 27) -731219)
(#<window 18 on NEWS> 3510 (0 . 28) -729648))
```
While holding down the meta and shift keys, the user might press the second mouse button on the window’s mode line, and then drag the mouse into another window. That produces a pair of events like these:
```
(M-S-down-mouse-2 (#<window 18 on NEWS> mode-line (33 . 31) -457844))
(M-S-drag-mouse-2 (#<window 18 on NEWS> mode-line (33 . 31) -457844)
(#<window 20 on carlton-sanskrit.tex> 161 (33 . 3)
-453816))
```
The frame with input focus might not take up the entire screen, and the user might move the mouse outside the scope of the frame. Inside the `track-mouse` special form, that produces an event like this:
```
(mouse-movement (#<frame *ielm* 0x102849a30> nil (563 . 205) 532301936))
```
To handle a SIGUSR1 signal, define an interactive function, and bind it to the `signal usr1` event sequence:
```
(defun usr1-handler ()
(interactive)
(message "Got USR1 signal"))
(global-set-key [signal usr1] 'usr1-handler)
```
elisp None Non-ASCII Characters
--------------------
This chapter covers the special issues relating to characters and how they are stored in strings and buffers.
| | | |
| --- | --- | --- |
| • [Text Representations](text-representations) | | How Emacs represents text. |
| • [Disabling Multibyte](disabling-multibyte) | | Controlling whether to use multibyte characters. |
| • [Converting Representations](converting-representations) | | Converting unibyte to multibyte and vice versa. |
| • [Selecting a Representation](selecting-a-representation) | | Treating a byte sequence as unibyte or multi. |
| • [Character Codes](character-codes) | | How unibyte and multibyte relate to codes of individual characters. |
| • [Character Properties](character-properties) | | Character attributes that define their behavior and handling. |
| • [Character Sets](character-sets) | | The space of possible character codes is divided into various character sets. |
| • [Scanning Charsets](scanning-charsets) | | Which character sets are used in a buffer? |
| • [Translation of Characters](translation-of-characters) | | Translation tables are used for conversion. |
| • [Coding Systems](coding-systems) | | Coding systems are conversions for saving files. |
| • [Input Methods](input-methods) | | Input methods allow users to enter various non-ASCII characters without special keyboards. |
| • [Locales](locales) | | Interacting with the POSIX locale. |
elisp None ### Closures
As explained in [Variable Scoping](variable-scoping), Emacs can optionally enable lexical binding of variables. When lexical binding is enabled, any named function that you create (e.g., with `defun`), as well as any anonymous function that you create using the `lambda` macro or the `function` special form or the `#'` syntax (see [Anonymous Functions](anonymous-functions)), is automatically converted into a *closure*.
A closure is a function that also carries a record of the lexical environment that existed when the function was defined. When it is invoked, any lexical variable references within its definition use the retained lexical environment. In all other respects, closures behave much like ordinary functions; in particular, they can be called in the same way as ordinary functions.
See [Lexical Binding](lexical-binding), for an example of using a closure.
Currently, an Emacs Lisp closure object is represented by a list with the symbol `closure` as the first element, a list representing the lexical environment as the second element, and the argument list and body forms as the remaining elements:
```
;; lexical binding is enabled.
(lambda (x) (* x x))
⇒ (closure (t) (x) (* x x))
```
However, the fact that the internal structure of a closure is exposed to the rest of the Lisp world is considered an internal implementation detail. For this reason, we recommend against directly examining or altering the structure of closure objects.
elisp None #### Dotted Pair Notation
*Dotted pair notation* is a general syntax for cons cells that represents the CAR and CDR explicitly. In this syntax, `(a . b)` stands for a cons cell whose CAR is the object a and whose CDR is the object b. Dotted pair notation is more general than list syntax because the CDR does not have to be a list. However, it is more cumbersome in cases where list syntax would work. In dotted pair notation, the list ‘`(1 2 3)`’ is written as ‘`(1 . (2 . (3 . nil)))`’. For `nil`-terminated lists, you can use either notation, but list notation is usually clearer and more convenient. When printing a list, the dotted pair notation is only used if the CDR of a cons cell is not a list.
Here’s an example using boxes to illustrate dotted pair notation. This example shows the pair `(rose . violet)`:
```
--- ---
| | |--> violet
--- ---
|
|
--> rose
```
You can combine dotted pair notation with list notation to represent conveniently a chain of cons cells with a non-`nil` final CDR. You write a dot after the last element of the list, followed by the CDR of the final cons cell. For example, `(rose violet
. buttercup)` is equivalent to `(rose . (violet . buttercup))`. The object looks like this:
```
--- --- --- ---
| | |--> | | |--> buttercup
--- --- --- ---
| |
| |
--> rose --> violet
```
The syntax `(rose . violet . buttercup)` is invalid because there is nothing that it could mean. If anything, it would say to put `buttercup` in the CDR of a cons cell whose CDR is already used for `violet`.
The list `(rose violet)` is equivalent to `(rose . (violet))`, and looks like this:
```
--- --- --- ---
| | |--> | | |--> nil
--- --- --- ---
| |
| |
--> rose --> violet
```
Similarly, the three-element list `(rose violet buttercup)` is equivalent to `(rose . (violet . (buttercup)))`. It looks like this:
```
--- --- --- --- --- ---
| | |--> | | |--> | | |--> nil
--- --- --- --- --- ---
| | |
| | |
--> rose --> violet --> buttercup
```
As a somewhat peculiar side effect of `(a b . c)` and `(a . (b . c))` being equivalent, for consistency this means that if you replace `b` here with the empty sequence, then it follows that `(a . c)` and `(a . ( . c))` are equivalent, too. This also means that `( . c)` is equivalent to `c`, but this is seldom used.
elisp None #### Problems with Regular Expressions
The Emacs regexp implementation, like many of its kind, is generally robust but occasionally causes trouble in either of two ways: matching may run out of internal stack space and signal an error, and it can take a long time to complete. The advice below will make these symptoms less likely and help alleviate problems that do arise.
* Anchor regexps at the beginning of a line, string or buffer using zero-width assertions (‘`^`’ and `\``). This takes advantage of fast paths in the implementation and can avoid futile matching attempts. Other zero-width assertions may also bring benefits by causing a match to fail early.
* Avoid or-patterns in favor of character alternatives: write ‘`[ab]`’ instead of ‘`a\|b`’. Recall that ‘`\s-`’ and ‘`\sw`’ are equivalent to ‘`[[:space:]]`’ and ‘`[[:word:]]`’, respectively.
* Since the last branch of an or-pattern does not add a backtrack point on the stack, consider putting the most likely matched pattern last. For example, ‘`^\(?:a\|.b\)\*c`’ will run out of stack if trying to match a very long string of ‘`a`’s, but the equivalent ‘`^\(?:.b\|a\)\*c`’ will not. (It is a trade-off: successfully matched or-patterns run faster with the most frequently matched pattern first.)
* Try to ensure that any part of the text can only match in a single way. For example, ‘`a\*a\*`’ will match the same set of strings as ‘`a\*`’, but the former can do so in many ways and will therefore cause slow backtracking if the match fails later on. Make or-pattern branches mutually exclusive if possible, so that matching will not go far into more than one branch before failing. Be especially careful with nested repetitions: they can easily result in very slow matching in the presence of ambiguities. For example, ‘`\(?:a\*b\*\)+c`’ will take a long time attempting to match even a moderately long string of ‘`a`’s before failing. The equivalent ‘`\(?:a\|b\)\*c`’ is much faster, and ‘`[ab]\*c`’ better still.
* Don’t use capturing groups unless they are really needed; that is, use ‘`\(?:…\)`’ instead of ‘`\(…\)`’ for bracketing purposes.
* Consider using `rx` (see [Rx Notation](rx-notation)); it can optimize some or-patterns automatically and will never introduce capturing groups unless explicitly requested.
If you run into regexp stack overflow despite following the above advice, don’t be afraid of performing the matching in multiple function calls, each using a simpler regexp where backtracking can more easily be contained.
elisp None #### Distinguishing Kinds of Files
This section describes how to distinguish various kinds of files, such as directories, symbolic links, and ordinary files.
Symbolic links are ordinarily followed wherever they appear. For example, to interpret the file name `a/b/c`, any of `a`, `a/b`, and `a/b/c` can be symbolic links that are followed, possibly recursively if the link targets are themselves symbolic links. However, a few functions do not follow symbolic links at the end of a file name (`a/b/c` in this example). Such a function is said to *not follow symbolic links*.
Function: **file-symlink-p** *filename*
If the file filename is a symbolic link, this function does not follow it and instead returns its link target as a string. (The link target string is not necessarily the full absolute file name of the target; determining the full file name that the link points to is nontrivial, see below.)
If the file filename is not a symbolic link, or does not exist, or if there is trouble determining whether it is a symbolic link, `file-symlink-p` returns `nil`.
Here are a few examples of using this function:
```
(file-symlink-p "not-a-symlink")
⇒ nil
```
```
(file-symlink-p "sym-link")
⇒ "not-a-symlink"
```
```
(file-symlink-p "sym-link2")
⇒ "sym-link"
```
```
(file-symlink-p "/bin")
⇒ "/pub/bin"
```
Note that in the third example, the function returned `sym-link`, but did not proceed to resolve it, although that file is itself a symbolic link. That is because this function does not follow symbolic links—the process of following the symbolic links does not apply to the last component of the file name.
The string that this function returns is what is recorded in the symbolic link; it may or may not include any leading directories. This function does *not* expand the link target to produce a fully-qualified file name, and in particular does not use the leading directories, if any, of the filename argument if the link target is not an absolute file name. Here’s an example:
```
(file-symlink-p "/foo/bar/baz")
⇒ "some-file"
```
Here, although `/foo/bar/baz` was given as a fully-qualified file name, the result is not, and in fact does not have any leading directories at all. And since `some-file` might itself be a symbolic link, you cannot simply prepend leading directories to it, nor even naively use `expand-file-name` (see [File Name Expansion](file-name-expansion)) to produce its absolute file name.
For this reason, this function is seldom useful if you need to determine more than just the fact that a file is or isn’t a symbolic link. If you actually need the file name of the link target, use `file-chase-links` or `file-truename`, described in [Truenames](truenames).
Function: **file-directory-p** *filename*
This function returns `t` if filename is the name of an existing directory. It returns `nil` if filename does not name a directory, or if there is trouble determining whether it is a directory. This function follows symbolic links.
```
(file-directory-p "~rms")
⇒ t
```
```
(file-directory-p "~rms/lewis/files.texi")
⇒ nil
```
```
(file-directory-p "~rms/lewis/no-such-file")
⇒ nil
```
```
(file-directory-p "$HOME")
⇒ nil
```
```
(file-directory-p
(substitute-in-file-name "$HOME"))
⇒ t
```
Function: **file-regular-p** *filename*
This function returns `t` if the file filename exists and is a regular file (not a directory, named pipe, terminal, or other I/O device). It returns `nil` if filename does not exist or is not a regular file, or if there is trouble determining whether it is a regular file. This function follows symbolic links.
elisp None #### Setting Hooks
Here’s an example that adds a function to a mode hook to turn on Auto Fill mode when in Lisp Interaction mode:
```
(add-hook 'lisp-interaction-mode-hook 'auto-fill-mode)
```
The value of a hook variable should be a list of functions. You can manipulate that list using the normal Lisp facilities, but the modular way is to use the functions `add-hook` and `remove-hook`, defined below. They take care to handle some unusual situations and avoid problems.
It works to put a `lambda`-expression function on a hook, but we recommend avoiding this because it can lead to confusion. If you add the same `lambda`-expression a second time but write it slightly differently, you will get two equivalent but distinct functions on the hook. If you then remove one of them, the other will still be on it.
Function: **add-hook** *hook function &optional depth local*
This function is the handy way to add function function to hook variable hook. You can use it for abnormal hooks as well as for normal hooks. function can be any Lisp function that can accept the proper number of arguments for hook. For example,
```
(add-hook 'text-mode-hook 'my-text-hook-function)
```
adds `my-text-hook-function` to the hook called `text-mode-hook`.
If function is already present in hook (comparing using `equal`), then `add-hook` does not add it a second time.
If function has a non-`nil` property `permanent-local-hook`, then `kill-all-local-variables` (or changing major modes) won’t delete it from the hook variable’s local value.
For a normal hook, hook functions should be designed so that the order in which they are executed does not matter. Any dependence on the order is asking for trouble. However, the order is predictable: normally, function goes at the front of the hook list, so it is executed first (barring another `add-hook` call).
In some cases, it is important to control the relative ordering of functions on the hook. The optional argument depth lets you indicate where the function should be inserted in the list: it should then be a number between -100 and 100 where the higher the value, the closer to the end of the list the function should go. The depth defaults to 0 and for backward compatibility when depth is a non-nil symbol it is interpreted as a depth of 90. Furthermore, when depth is strictly greater than 0 the function is added *after* rather than before functions of the same depth. One should never use a depth of 100 (or -100), because one can never be sure that no other function will ever need to come before (or after) us.
`add-hook` can handle the cases where hook is void or its value is a single function; it sets or changes the value to a list of functions.
If local is non-`nil`, that says to add function to the buffer-local hook list instead of to the global hook list. This makes the hook buffer-local and adds `t` to the buffer-local value. The latter acts as a flag to run the hook functions in the default value as well as in the local value.
Function: **remove-hook** *hook function &optional local*
This function removes function from the hook variable hook. It compares function with elements of hook using `equal`, so it works for both symbols and lambda expressions.
If local is non-`nil`, that says to remove function from the buffer-local hook list instead of from the global hook list.
| programming_docs |
elisp None ### Sending Signals to Processes
*Sending a signal* to a subprocess is a way of interrupting its activities. There are several different signals, each with its own meaning. The set of signals and their names is defined by the operating system. For example, the signal `SIGINT` means that the user has typed `C-c`, or that some analogous thing has happened.
Each signal has a standard effect on the subprocess. Most signals kill the subprocess, but some stop (or resume) execution instead. Most signals can optionally be handled by programs; if the program handles the signal, then we can say nothing in general about its effects.
You can send signals explicitly by calling the functions in this section. Emacs also sends signals automatically at certain times: killing a buffer sends a `SIGHUP` signal to all its associated processes; killing Emacs sends a `SIGHUP` signal to all remaining processes. (`SIGHUP` is a signal that usually indicates that the user “hung up the phone”, i.e., disconnected.)
Each of the signal-sending functions takes two optional arguments: process and current-group.
The argument process must be either a process, a process name, a buffer, a buffer name, or `nil`. A buffer or buffer name stands for a process through `get-buffer-process`. `nil` stands for the process associated with the current buffer. Except with `stop-process` and `continue-process`, an error is signaled if process does not identify an active process, or if it represents a network, serial, or pipe connection.
The argument current-group is a flag that makes a difference when you are running a job-control shell as an Emacs subprocess. If it is non-`nil`, then the signal is sent to the current process-group of the terminal that Emacs uses to communicate with the subprocess. If the process is a job-control shell, this means the shell’s current subjob. If current-group is `nil`, the signal is sent to the process group of the immediate subprocess of Emacs. If the subprocess is a job-control shell, this is the shell itself. If current-group is `lambda`, the signal is sent to the process-group that owns the terminal, but only if it is not the shell itself.
The flag current-group has no effect when a pipe is used to communicate with the subprocess, because the operating system does not support the distinction in the case of pipes. For the same reason, job-control shells won’t work when a pipe is used. See `process-connection-type` in [Asynchronous Processes](asynchronous-processes).
Function: **interrupt-process** *&optional process current-group*
This function interrupts the process process by sending the signal `SIGINT`. Outside of Emacs, typing the interrupt character (normally `C-c` on some systems, and DEL on others) sends this signal. When the argument current-group is non-`nil`, you can think of this function as typing `C-c` on the terminal by which Emacs talks to the subprocess.
Function: **kill-process** *&optional process current-group*
This function kills the process process by sending the signal `SIGKILL`. This signal kills the subprocess immediately, and cannot be handled by the subprocess.
Function: **quit-process** *&optional process current-group*
This function sends the signal `SIGQUIT` to the process process. This signal is the one sent by the quit character (usually `C-\`) when you are not inside Emacs.
Function: **stop-process** *&optional process current-group*
This function stops the specified process. If it is a real subprocess running a program, it sends the signal `SIGTSTP` to that subprocess. If process represents a network, serial, or pipe connection, this function inhibits handling of the incoming data from the connection; for a network server, this means not accepting new connections. Use `continue-process` to resume normal execution.
Outside of Emacs, on systems with job control, the stop character (usually `C-z`) normally sends the `SIGTSTP` signal to a subprocess. When current-group is non-`nil`, you can think of this function as typing `C-z` on the terminal Emacs uses to communicate with the subprocess.
Function: **continue-process** *&optional process current-group*
This function resumes execution of the process process. If it is a real subprocess running a program, it sends the signal `SIGCONT` to that subprocess; this presumes that process was stopped previously. If process represents a network, serial, or pipe connection, this function resumes handling of the incoming data from the connection. For serial connections, data that arrived during the time the process was stopped might be lost.
Command: **signal-process** *process signal*
This function sends a signal to process process. The argument signal specifies which signal to send; it should be an integer, or a symbol whose name is a signal.
The process argument can be a system process ID (an integer); that allows you to send signals to processes that are not children of Emacs. See [System Processes](system-processes).
Sometimes, it is necessary to send a signal to a non-local asynchronous process. This is possible by writing an own `interrupt-process` implementation. This function must be added then to `interrupt-process-functions`.
Variable: **interrupt-process-functions**
This variable is a list of functions to be called for `interrupt-process`. The arguments of the functions are the same as for `interrupt-process`. These functions are called in the order of the list, until one of them returns non-`nil`. The default function, which shall always be the last in this list, is `internal-default-interrupt-process`.
This is the mechanism, how Tramp implements `interrupt-process`.
elisp None #### Search-based Fontification
The variable which directly controls search-based fontification is `font-lock-keywords`, which is typically specified via the keywords element in `font-lock-defaults`.
Variable: **font-lock-keywords**
The value of this variable is a list of the keywords to highlight. Lisp programs should not set this variable directly. Normally, the value is automatically set by Font Lock mode, using the keywords element in `font-lock-defaults`. The value can also be altered using the functions `font-lock-add-keywords` and `font-lock-remove-keywords` (see [Customizing Keywords](customizing-keywords)).
Each element of `font-lock-keywords` specifies how to find certain cases of text, and how to highlight those cases. Font Lock mode processes the elements of `font-lock-keywords` one by one, and for each element, it finds and handles all matches. Ordinarily, once part of the text has been fontified already, this cannot be overridden by a subsequent match in the same text; but you can specify different behavior using the override element of a subexp-highlighter.
Each element of `font-lock-keywords` should have one of these forms:
`regexp`
Highlight all matches for regexp using `font-lock-keyword-face`. For example,
```
;; Highlight occurrences of the word ‘`foo`’
;; using `font-lock-keyword-face`.
"\\<foo\\>"
```
Be careful when composing these regular expressions; a poorly written pattern can dramatically slow things down! The function `regexp-opt` (see [Regexp Functions](regexp-functions)) is useful for calculating optimal regular expressions to match several keywords.
`function`
Find text by calling function, and highlight the matches it finds using `font-lock-keyword-face`.
When function is called, it receives one argument, the limit of the search; it should begin searching at point, and not search beyond the limit. It should return non-`nil` if it succeeds, and set the match data to describe the match that was found. Returning `nil` indicates failure of the search.
Fontification will call function repeatedly with the same limit, and with point where the previous invocation left it, until function fails. On failure, function need not reset point in any particular way.
`(matcher . subexp)`
In this kind of element, matcher is either a regular expression or a function, as described above. The CDR, subexp, specifies which subexpression of matcher should be highlighted (instead of the entire text that matcher matched).
```
;; Highlight the ‘`bar`’ in each occurrence of ‘`fubar`’,
;; using `font-lock-keyword-face`.
("fu\\(bar\\)" . 1)
```
`(matcher . facespec)`
In this kind of element, facespec is an expression whose value specifies the face to use for highlighting. In the simplest case, facespec is a Lisp variable (a symbol) whose value is a face name.
```
;; Highlight occurrences of ‘`fubar`’,
;; using the face which is the value of `fubar-face`.
("fubar" . fubar-face)
```
However, facespec can also evaluate to a list of this form:
```
(subexp
(face face prop1 val1 prop2 val2…))
```
to specify the face face and various additional text properties to put on the text that matches. If you do this, be sure to add the other text property names that you set in this way to the value of `font-lock-extra-managed-props` so that the properties will also be cleared out when they are no longer appropriate. Alternatively, you can set the variable `font-lock-unfontify-region-function` to a function that clears these properties. See [Other Font Lock Variables](other-font-lock-variables).
`(matcher . subexp-highlighter)`
In this kind of element, subexp-highlighter is a list which specifies how to highlight matches found by matcher. It has the form:
```
(subexp facespec [override [laxmatch]])
```
The CAR, subexp, is an integer specifying which subexpression of the match to fontify (0 means the entire matching text). The second subelement, facespec, is an expression whose value specifies the face, as described above.
The last two values in subexp-highlighter, override and laxmatch, are optional flags. If override is `t`, this element can override existing fontification made by previous elements of `font-lock-keywords`. If it is `keep`, then each character is fontified if it has not been fontified already by some other element. If it is `prepend`, the face specified by facespec is added to the beginning of the `font-lock-face` property. If it is `append`, the face is added to the end of the `font-lock-face` property.
If laxmatch is non-`nil`, it means there should be no error if there is no subexpression numbered subexp in matcher. Obviously, fontification of the subexpression numbered subexp will not occur. However, fontification of other subexpressions (and other regexps) will continue. If laxmatch is `nil`, and the specified subexpression is missing, then an error is signaled which terminates search-based fontification.
Here are some examples of elements of this kind, and what they do:
```
;; Highlight occurrences of either ‘`foo`’ or ‘`bar`’, using
;; `foo-bar-face`, even if they have already been highlighted.
;; `foo-bar-face` should be a variable whose value is a face.
("foo\\|bar" 0 foo-bar-face t)
;; Highlight the first subexpression within each occurrence
;; that the function `fubar-match` finds,
;; using the face which is the value of `fubar-face`.
(fubar-match 1 fubar-face)
```
`(matcher . anchored-highlighter)`
In this kind of element, anchored-highlighter specifies how to highlight text that follows a match found by matcher. So a match found by matcher acts as the anchor for further searches specified by anchored-highlighter. anchored-highlighter is a list of the following form:
```
(anchored-matcher pre-form post-form
subexp-highlighters…)
```
Here, anchored-matcher, like matcher, is either a regular expression or a function. After a match of matcher is found, point is at the end of the match. Now, Font Lock evaluates the form pre-form. Then it searches for matches of anchored-matcher and uses subexp-highlighters to highlight these. A subexp-highlighter is as described above. Finally, Font Lock evaluates post-form.
The forms pre-form and post-form can be used to initialize before, and cleanup after, anchored-matcher is used. Typically, pre-form is used to move point to some position relative to the match of matcher, before starting with anchored-matcher. post-form might be used to move back, before resuming with matcher.
After Font Lock evaluates pre-form, it does not search for anchored-matcher beyond the end of the line. However, if pre-form returns a buffer position that is greater than the position of point after pre-form is evaluated, then the position returned by pre-form is used as the limit of the search instead. It is generally a bad idea to return a position greater than the end of the line; in other words, the anchored-matcher search should not span lines.
For example,
```
;; Highlight occurrences of the word ‘`item`’ following
;; an occurrence of the word ‘`anchor`’ (on the same line)
;; in the value of `item-face`.
("\\<anchor\\>" "\\<item\\>" nil nil (0 item-face))
```
Here, pre-form and post-form are `nil`. Therefore searching for ‘`item`’ starts at the end of the match of ‘`anchor`’, and searching for subsequent instances of ‘`anchor`’ resumes from where searching for ‘`item`’ concluded.
`(matcher highlighters…)`
This sort of element specifies several highlighter lists for a single matcher. A highlighter list can be of the type subexp-highlighter or anchored-highlighter as described above.
For example,
```
;; Highlight occurrences of the word ‘`anchor`’ in the value
;; of `anchor-face`, and subsequent occurrences of the word
;; ‘`item`’ (on the same line) in the value of `item-face`.
("\\<anchor\\>" (0 anchor-face)
("\\<item\\>" nil nil (0 item-face)))
```
`(eval . form)` Here form is an expression to be evaluated the first time this value of `font-lock-keywords` is used in a buffer. Its value should have one of the forms described in this table.
**Warning:** Do not design an element of `font-lock-keywords` to match text which spans lines; this does not work reliably. For details, see [Multiline Font Lock](multiline-font-lock).
You can use case-fold in `font-lock-defaults` to specify the value of `font-lock-keywords-case-fold-search` which says whether search-based fontification should be case-insensitive.
Variable: **font-lock-keywords-case-fold-search**
Non-`nil` means that regular expression matching for the sake of `font-lock-keywords` should be case-insensitive.
elisp None #### Extended Menu Items
An extended-format menu item is a more flexible and also cleaner alternative to the simple format. You define an event type with a binding that’s a list starting with the symbol `menu-item`. For a non-selectable string, the binding looks like this:
```
(menu-item item-name)
```
A string starting with two or more dashes specifies a separator line; see [Menu Separators](menu-separators).
To define a real menu item which can be selected, the extended format binding looks like this:
```
(menu-item item-name real-binding
. item-property-list)
```
Here, item-name is an expression which evaluates to the menu item string. Thus, the string need not be a constant.
The third element, real-binding, can be the command to execute (in which case you get a normal menu item). It can also be a keymap, which will result in a submenu, and item-name is used as the submenu name. Finally, it can be `nil`, in which case you will get a non-selectable menu item. This is mostly useful when creating separator lines and the like.
The tail of the list, item-property-list, has the form of a property list which contains other information.
Here is a table of the properties that are supported:
`:enable form`
The result of evaluating form determines whether the item is enabled (non-`nil` means yes). If the item is not enabled, you can’t really click on it.
`:visible form`
The result of evaluating form determines whether the item should actually appear in the menu (non-`nil` means yes). If the item does not appear, then the menu is displayed as if this item were not defined at all.
`:help help`
The value of this property, help, specifies a help-echo string to display while the mouse is on that item. This is displayed in the same way as `help-echo` text properties (see [Help display](special-properties#Help-display)). Note that this must be a constant string, unlike the `help-echo` property for text and overlays.
`:button (type . selected)`
This property provides a way to define radio buttons and toggle buttons. The CAR, type, says which: it should be `:toggle` or `:radio`. The CDR, selected, should be a form; the result of evaluating it says whether this button is currently selected.
A *toggle* is a menu item which is labeled as either on or off according to the value of selected. The command itself should toggle selected, setting it to `t` if it is `nil`, and to `nil` if it is `t`. Here is how the menu item to toggle the `debug-on-error` flag is defined:
```
(menu-item "Debug on Error" toggle-debug-on-error
:button (:toggle
. (and (boundp 'debug-on-error)
debug-on-error)))
```
This works because `toggle-debug-on-error` is defined as a command which toggles the variable `debug-on-error`.
*Radio buttons* are a group of menu items, in which at any time one and only one is selected. There should be a variable whose value says which one is selected at any time. The selected form for each radio button in the group should check whether the variable has the right value for selecting that button. Clicking on the button should set the variable so that the button you clicked on becomes selected.
`:key-sequence key-sequence`
This property specifies which key sequence to display as keyboard equivalent. Before Emacs displays key-sequence in the menu, it verifies that key-sequence is really equivalent to this menu item, so it only has an effect if you specify a correct key sequence. Specifying `nil` for key-sequence is equivalent to the `:key-sequence` attribute being absent.
`:keys string`
This property specifies that string is the string to display as the keyboard equivalent for this menu item. You can use the ‘`\\[...]`’ documentation construct in string.
`:filter filter-fn`
This property provides a way to compute the menu item dynamically. The property value filter-fn should be a function of one argument; when it is called, its argument will be real-binding. The function should return the binding to use instead.
Emacs can call this function at any time that it does redisplay or operates on menu data structures, so you should write it so it can safely be called at any time.
elisp None #### Truenames
The *truename* of a file is the name that you get by following symbolic links at all levels until none remain, then simplifying away ‘`.`’ and ‘`..`’ appearing as name components. This results in a sort of canonical name for the file. A file does not always have a unique truename; the number of distinct truenames a file has is equal to the number of hard links to the file. However, truenames are useful because they eliminate symbolic links as a cause of name variation.
Function: **file-truename** *filename*
This function returns the truename of the file filename. If the argument is not an absolute file name, this function first expands it against `default-directory`.
This function does not expand environment variables. Only `substitute-in-file-name` does that. See [Definition of substitute-in-file-name](file-name-expansion#Definition-of-substitute_002din_002dfile_002dname).
If you may need to follow symbolic links preceding ‘`..`’ appearing as a name component, call `file-truename` without prior direct or indirect calls to `expand-file-name`. Otherwise, the file name component immediately preceding ‘`..`’ will be simplified away before `file-truename` is called. To eliminate the need for a call to `expand-file-name`, `file-truename` handles ‘`~`’ in the same way that `expand-file-name` does.
If the target of a symbolic links has remote file name syntax, `file-truename` returns it quoted. See [Functions that Expand Filenames](file-name-expansion).
Function: **file-chase-links** *filename &optional limit*
This function follows symbolic links, starting with filename, until it finds a file name which is not the name of a symbolic link. Then it returns that file name. This function does *not* follow symbolic links at the level of parent directories.
If you specify a number for limit, then after chasing through that many links, the function just returns what it has even if that is still a symbolic link.
To illustrate the difference between `file-chase-links` and `file-truename`, suppose that `/usr/foo` is a symbolic link to the directory `/home/foo`, and `/home/foo/hello` is an ordinary file (or at least, not a symbolic link) or nonexistent. Then we would have:
```
(file-chase-links "/usr/foo/hello")
;; This does not follow the links in the parent directories.
⇒ "/usr/foo/hello"
(file-truename "/usr/foo/hello")
;; Assuming that `/home` is not a symbolic link.
⇒ "/home/foo/hello"
```
Function: **file-equal-p** *file1 file2*
This function returns `t` if the files file1 and file2 name the same file. This is similar to comparing their truenames, except that remote file names are also handled in an appropriate manner. If file1 or file2 does not exist, the return value is unspecified.
Function: **file-name-case-insensitive-p** *filename*
Sometimes file names or their parts need to be compared as strings, in which case it’s important to know whether the underlying filesystem is case-insensitive. This function returns `t` if file filename is on a case-insensitive filesystem. It always returns `t` on MS-DOS and MS-Windows. On Cygwin and macOS, filesystems may or may not be case-insensitive, and the function tries to determine case-sensitivity by a runtime test. If the test is inconclusive, the function returns `t` on Cygwin and `nil` on macOS.
Currently this function always returns `nil` on platforms other than MS-DOS, MS-Windows, Cygwin, and macOS. It does not detect case-insensitivity of mounted filesystems, such as Samba shares or NFS-mounted Windows volumes. On remote hosts, it assumes `t` for the ‘`smb`’ method. For all other connection methods, runtime tests are performed.
Function: **file-in-directory-p** *file dir*
This function returns `t` if file is a file in directory dir, or in a subdirectory of dir. It also returns `t` if file and dir are the same directory. It compares the truenames of the two directories. If dir does not name an existing directory, the return value is `nil`.
Function: **vc-responsible-backend** *file*
This function determines the responsible VC backend of the given file. For example, if `emacs.c` is a file tracked by Git, `(vc-responsible-backend "emacs.c")` returns ‘`Git`’. Note that if file is a symbolic link, `vc-responsible-backend` will not resolve it—the backend of the symbolic link file itself is reported. To get the backend VC of the file to which file refers, wrap file with a symbolic link resolving function such as `file-chase-links`:
```
(vc-responsible-backend (file-chase-links "emacs.c"))
```
| programming_docs |
elisp None #### Piecemeal Specification
In contrast to the round-trip specification described in the previous subsection (see [Format Conversion Round-Trip](format-conversion-round_002dtrip)), you can use the variables `after-insert-file-functions` and `write-region-annotate-functions` to separately control the respective reading and writing conversions.
Conversion starts with one representation and produces another representation. When there is only one conversion to do, there is no conflict about what to start with. However, when there are multiple conversions involved, conflict may arise when two conversions need to start with the same data.
This situation is best understood in the context of converting text properties during `write-region`. For example, the character at position 42 in a buffer is ‘`X`’ with a text property `foo`. If the conversion for `foo` is done by inserting into the buffer, say, ‘`FOO:`’, then that changes the character at position 42 from ‘`X`’ to ‘`F`’. The next conversion will start with the wrong data straight away.
To avoid conflict, cooperative conversions do not modify the buffer, but instead specify *annotations*, a list of elements of the form `(position . string)`, sorted in order of increasing position.
If there is more than one conversion, `write-region` merges their annotations destructively into one sorted list. Later, when the text from the buffer is actually written to the file, it intermixes the specified annotations at the corresponding positions. All this takes place without modifying the buffer.
In contrast, when reading, the annotations intermixed with the text are handled immediately. `insert-file-contents` sets point to the beginning of some text to be converted, then calls the conversion functions with the length of that text. These functions should always return with point at the beginning of the inserted text. This approach makes sense for reading because annotations removed by the first converter can’t be mistakenly processed by a later converter. Each conversion function should scan for the annotations it recognizes, remove the annotation, modify the buffer text (to set a text property, for example), and return the updated length of the text, as it stands after those changes. The value returned by one function becomes the argument to the next function.
Variable: **write-region-annotate-functions**
A list of functions for `write-region` to call. Each function in the list is called with two arguments: the start and end of the region to be written. These functions should not alter the contents of the buffer. Instead, they should return annotations.
As a special case, a function may return with a different buffer current. Emacs takes this to mean that the current buffer contains altered text to be output. It therefore changes the start and end arguments of the `write-region` call, giving them the values of `point-min` and `point-max` in the new buffer, respectively. It also discards all previous annotations, because they should have been dealt with by this function.
Variable: **write-region-post-annotation-function**
The value of this variable, if non-`nil`, should be a function. This function is called, with no arguments, after `write-region` has completed.
If any function in `write-region-annotate-functions` returns with a different buffer current, Emacs calls `write-region-post-annotation-function` more than once. Emacs calls it with the last buffer that was current, and again with the buffer before that, and so on back to the original buffer.
Thus, a function in `write-region-annotate-functions` can create a buffer, give this variable the local value of `kill-buffer` in that buffer, set up the buffer with altered text, and make the buffer current. The buffer will be killed after `write-region` is done.
Variable: **after-insert-file-functions**
Each function in this list is called by `insert-file-contents` with one argument, the number of characters inserted, and with point at the beginning of the inserted text. Each function should leave point unchanged, and return the new character count describing the inserted text as modified by the function.
We invite users to write Lisp programs to store and retrieve text properties in files, using these hooks, and thus to experiment with various data formats and find good ones. Eventually we hope users will produce good, general extensions we can install in Emacs.
We suggest not trying to handle arbitrary Lisp objects as text property names or values—because a program that general is probably difficult to write, and slow. Instead, choose a set of possible data types that are reasonably flexible, and not too hard to encode.
elisp None Compilation of Lisp to Native Code
----------------------------------
In addition to the byte-compilation, described in [the previous chapter](byte-compilation), Emacs can also optionally compile Lisp function definitions into a true compiled code, known as *native code*. This feature uses the `libgccjit` library, which is part of the GCC distribution, and requires that Emacs be built with support for using that library. It also requires to have GCC and Binutils (the assembler and linker) available on your system for you to be able to native-compile Lisp code.
To determine whether the current Emacs process can produce and load natively-compiled Lisp code, call `native-comp-available-p` (see [Native-Compilation Functions](native_002dcompilation-functions)).
Unlike byte-compiled code, natively-compiled Lisp code is executed directly by the machine’s hardware, and therefore runs at full speed that the host CPU can provide. The resulting speedup generally depends on what the Lisp code does, but is usually 2.5 to 5 times faster than the corresponding byte-compiled code.
Since native code is generally incompatible between different systems, the natively-compiled code is *not* transportable from one machine to another, it can only be used on the same machine where it was produced or on very similar ones (having the same CPU and run-time libraries). The transportability of natively-compiled code is the same as that of shared libraries (`.so` or `.dll` files).
Libraries of natively-compiled code include crucial dependencies on Emacs Lisp primitives (see [What Is a Function](what-is-a-function)) and their calling conventions, and thus Emacs usually won’t load natively-compiled code produced by earlier or later Emacs versions; native compilation of the same Lisp code by a different Emacs version will usually produce a natively-compiled library under a unique file name that only that version of Emacs will be able to load. However, the use of unique file names allows to have in the same directory several versions of the same Lisp library natively-compiled by several different versions of Emacs.
A non-`nil` file-local variable binding of `no-byte-compile` (see [Byte Compilation](byte-compilation)) also disables the native compilation of that file. In addition, a similar variable `no-native-compile` disables just the native compilation of the file. If both `no-byte-compile` and `no-native-compile` are specified, the former takes precedence.
| | | |
| --- | --- | --- |
| • [Native-Compilation Functions](native_002dcompilation-functions) | | Functions to natively-compile Lisp. |
| • [Native-Compilation Variables](native_002dcompilation-variables) | | Variables controlling native compilation. |
elisp None ### The Match Data
Emacs keeps track of the start and end positions of the segments of text found during a search; this is called the *match data*. Thanks to the match data, you can search for a complex pattern, such as a date in a mail message, and then extract parts of the match under control of the pattern.
Because the match data normally describe the most recent search only, you must be careful not to do another search inadvertently between the search you wish to refer back to and the use of the match data. If you can’t avoid another intervening search, you must save and restore the match data around it, to prevent it from being overwritten.
Notice that all functions are allowed to overwrite the match data unless they’re explicitly documented not to do so. A consequence is that functions that are run implicitly in the background (see [Timers](timers), and [Idle Timers](idle-timers)) should likely save and restore the match data explicitly.
| | | |
| --- | --- | --- |
| • [Replacing Match](replacing-match) | | Replacing a substring that was matched. |
| • [Simple Match Data](simple-match-data) | | Accessing single items of match data, such as where a particular subexpression started. |
| • [Entire Match Data](entire-match-data) | | Accessing the entire match data at once, as a list. |
| • [Saving Match Data](saving-match-data) | | Saving and restoring the match data. |
elisp None #### Syntax for Strings
The read syntax for a string is a double-quote, an arbitrary number of characters, and another double-quote, `"like this"`. To include a double-quote in a string, precede it with a backslash; thus, `"\""` is a string containing just one double-quote character. Likewise, you can include a backslash by preceding it with another backslash, like this: `"this \\ is a single embedded
backslash"`.
The newline character is not special in the read syntax for strings; if you write a new line between the double-quotes, it becomes a character in the string. But an escaped newline—one that is preceded by ‘`\`’—does not become part of the string; i.e., the Lisp reader ignores an escaped newline while reading a string. An escaped space ‘`\` ’ is likewise ignored.
```
"It is useful to include newlines
in documentation strings,
but the newline is \
ignored if escaped."
⇒ "It is useful to include newlines
in documentation strings,
but the newline is ignored if escaped."
```
elisp None ### Automatic Indentation of code
For programming languages, an important feature of a major mode is to provide automatic indentation. There are two parts: one is to decide what is the right indentation of a line, and the other is to decide when to reindent a line. By default, Emacs reindents a line whenever you type a character in `electric-indent-chars`, which by default only includes Newline. Major modes can add chars to `electric-indent-chars` according to the syntax of the language.
Deciding what is the right indentation is controlled in Emacs by `indent-line-function` (see [Mode-Specific Indent](mode_002dspecific-indent)). For some modes, the *right* indentation cannot be known reliably, typically because indentation is significant so several indentations are valid but with different meanings. In that case, the mode should set `electric-indent-inhibit` to make sure the line is not constantly re-indented against the user’s wishes.
Writing a good indentation function can be difficult and to a large extent it is still a black art. Many major mode authors will start by writing a simple indentation function that works for simple cases, for example by comparing with the indentation of the previous text line. For most programming languages that are not really line-based, this tends to scale very poorly: improving such a function to let it handle more diverse situations tends to become more and more difficult, resulting in the end with a large, complex, unmaintainable indentation function which nobody dares to touch.
A good indentation function will usually need to actually parse the text, according to the syntax of the language. Luckily, it is not necessary to parse the text in as much detail as would be needed for a compiler, but on the other hand, the parser embedded in the indentation code will want to be somewhat friendly to syntactically incorrect code.
Good maintainable indentation functions usually fall into two categories: either parsing forward from some safe starting point until the position of interest, or parsing backward from the position of interest. Neither of the two is a clearly better choice than the other: parsing backward is often more difficult than parsing forward because programming languages are designed to be parsed forward, but for the purpose of indentation it has the advantage of not needing to guess a safe starting point, and it generally enjoys the property that only a minimum of text will be analyzed to decide the indentation of a line, so indentation will tend to be less affected by syntax errors in some earlier unrelated piece of code. Parsing forward on the other hand is usually easier and has the advantage of making it possible to reindent efficiently a whole region at a time, with a single parse.
Rather than write your own indentation function from scratch, it is often preferable to try and reuse some existing ones or to rely on a generic indentation engine. There are sadly few such engines. The CC-mode indentation code (used with C, C++, Java, Awk and a few other such modes) has been made more generic over the years, so if your language seems somewhat similar to one of those languages, you might try to use that engine. Another one is SMIE which takes an approach in the spirit of Lisp sexps and adapts it to non-Lisp languages.
| | | |
| --- | --- | --- |
| • [SMIE](smie) | | A simple minded indentation engine. |
elisp None ### Text Properties
Each character position in a buffer or a string can have a *text property list*, much like the property list of a symbol (see [Property Lists](property-lists)). The properties belong to a particular character at a particular place, such as, the letter ‘`T`’ at the beginning of this sentence or the first ‘`o`’ in ‘`foo`’—if the same character occurs in two different places, the two occurrences in general have different properties.
Each property has a name and a value. Both of these can be any Lisp object, but the name is normally a symbol. Typically each property name symbol is used for a particular purpose; for instance, the text property `face` specifies the faces for displaying the character (see [Special Properties](special-properties)). The usual way to access the property list is to specify a name and ask what value corresponds to it.
If a character has a `category` property, we call it the *property category* of the character. It should be a symbol. The properties of the symbol serve as defaults for the properties of the character.
Copying text between strings and buffers preserves the properties along with the characters; this includes such diverse functions as `substring`, `insert`, and `buffer-substring`.
| | | |
| --- | --- | --- |
| • [Examining Properties](examining-properties) | | Looking at the properties of one character. |
| • [Changing Properties](changing-properties) | | Setting the properties of a range of text. |
| • [Property Search](property-search) | | Searching for where a property changes value. |
| • [Special Properties](special-properties) | | Particular properties with special meanings. |
| • [Format Properties](format-properties) | | Properties for representing formatting of text. |
| • [Sticky Properties](sticky-properties) | | How inserted text gets properties from neighboring text. |
| • [Lazy Properties](lazy-properties) | | Computing text properties in a lazy fashion only when text is examined. |
| • [Clickable Text](clickable-text) | | Using text properties to make regions of text do something when you click on them. |
| • [Fields](fields) | | The `field` property defines fields within the buffer. |
| • [Not Intervals](not-intervals) | | Why text properties do not use Lisp-visible text intervals. |
elisp None ### Tooltips
*Tooltips* are special frames (see [Frames](frames)) that are used to display helpful hints (a.k.a. “tips”) related to the current position of the mouse pointer. Emacs uses tooltips to display help strings about active portions of text (see [Special Properties](special-properties)) and about various UI elements, such as menu items (see [Extended Menu Items](extended-menu-items)) and tool-bar buttons (see [Tool Bar](tool-bar)).
Function: **tooltip-mode**
Tooltip Mode is a minor mode that enables display of tooltips. Turning off this mode causes the tooltips be displayed in the echo area. On text-mode (a.k.a. “TTY”) frames, tooltips are always displayed in the echo area.
When Emacs is built with GTK+ support, it by default displays tooltips using GTK+ functions, and the appearance of the tooltips is then controlled by GTK+ settings. GTK+ tooltips can be disabled by changing the value of the variable `x-gtk-use-system-tooltips` to `nil`. The rest of this subsection describes how to control non-GTK+ tooltips, which are presented by Emacs itself.
Tooltips are displayed in special frames called tooltip frames, which have their own frame parameters (see [Frame Parameters](frame-parameters)). Unlike other frames, the default parameters for tooltip frames are stored in a special variable.
User Option: **tooltip-frame-parameters**
This customizable option holds the default frame parameters used for displaying tooltips. Any font and color parameters are ignored, and the corresponding attributes of the `tooltip` face are used instead. If `left` or `top` parameters are included, they are used as absolute frame-relative coordinates where the tooltip should be shown. (Mouse-relative position of the tooltip can be customized using the variables described in [Tooltips](https://www.gnu.org/software/emacs/manual/html_node/emacs/Tooltips.html#Tooltips) in The GNU Emacs Manual.) Note that the `left` and `top` parameters, if present, override the values of mouse-relative offsets.
The `tooltip` face determines the appearance of text shown in tooltips. It should generally use a variable-pitch font of size that is preferably smaller than the default frame font.
Variable: **tooltip-functions**
This abnormal hook is a list of functions to call when Emacs needs to display a tooltip. Each function is called with a single argument event which is a copy of the last mouse movement event. If a function on this list actually displays the tooltip, it should return non-`nil`, and then the rest of the functions will not be called. The default value of this variable is a single function `tooltip-help-tips`.
If you write your own function to be put on the `tooltip-functions` list, you may need to know the buffer of the mouse event that triggered the tooltip display. The following function provides that information.
Function: **tooltip-event-buffer** *event*
This function returns the buffer over which event occurred. Call it with the argument of the function from `tooltip-functions` to obtain the buffer whose text triggered the tooltip. Note that the event might occur not over a buffer (e.g., over the tool bar), in which case this function will return `nil`.
Other aspects of tooltip display are controlled by several customizable settings; see [Tooltips](https://www.gnu.org/software/emacs/manual/html_node/emacs/Tooltips.html#Tooltips) in The GNU Emacs Manual.
elisp None ### The display Property
The `display` text property (or overlay property) is used to insert images into text, and to control other aspects of how text displays. The value of the `display` property should be a display specification, or a list or vector containing several display specifications. Display specifications in the same `display` property value generally apply in parallel to the text they cover.
If several sources (overlays and/or a text property) specify values for the `display` property, only one of the values takes effect, following the rules of `get-char-property`. See [Examining Properties](examining-properties).
Some of the display specifications allow inclusion of Lisp forms, which are evaluated at display time. This could be unsafe in certain situations, e.g., when the display specification was generated by some external program/agent. Wrapping a display specification in a list that begins with the special symbol `disable-eval`, as in `(disable-eval spec)`, will disable evaluation of any Lisp in spec, while still supporting all the other display property features.
The rest of this section describes several kinds of display specifications and what they mean.
| | | |
| --- | --- | --- |
| • [Replacing Specs](replacing-specs) | | Display specs that replace the text. |
| • [Specified Space](specified-space) | | Displaying one space with a specified width. |
| • [Pixel Specification](pixel-specification) | | Specifying space width or height in pixels. |
| • [Other Display Specs](other-display-specs) | | Displaying an image; adjusting the height, spacing, and other properties of text. |
| • [Display Margins](display-margins) | | Displaying text or images to the side of the main text. |
| programming_docs |
elisp None #### Defining new setf forms
This section describes how to define new forms that `setf` can operate on.
Macro: **gv-define-simple-setter** *name setter &optional fix-return*
This macro enables you to easily define `setf` methods for simple cases. name is the name of a function, macro, or special form. You can use this macro whenever name has a directly corresponding setter function that updates it, e.g., `(gv-define-simple-setter car setcar)`.
This macro translates a call of the form
```
(setf (name args…) value)
```
into
```
(setter args… value)
```
Such a `setf` call is documented to return value. This is no problem with, e.g., `car` and `setcar`, because `setcar` returns the value that it set. If your setter function does not return value, use a non-`nil` value for the fix-return argument of `gv-define-simple-setter`. This expands into something equivalent to
```
(let ((temp value))
(setter args… temp)
temp)
```
so ensuring that it returns the correct result.
Macro: **gv-define-setter** *name arglist &rest body*
This macro allows for more complex `setf` expansions than the previous form. You may need to use this form, for example, if there is no simple setter function to call, or if there is one but it requires different arguments to the place form.
This macro expands the form `(setf (name args…) value)` by first binding the `setf` argument forms `(value args…)` according to arglist, and then executing body. body should return a Lisp form that does the assignment, and finally returns the value that was set. An example of using this macro is:
```
(gv-define-setter caar (val x) `(setcar (car ,x) ,val))
```
Macro: **gv-define-expander** *name handler*
For more control over the expansion, the `gv-define-expander` macro can be used. For instance, a settable `substring` could be implemented this way:
```
(gv-define-expander substring
(lambda (do place from &optional to)
(gv-letplace (getter setter) place
(macroexp-let2* nil ((start from) (end to))
(funcall do `(substring ,getter ,start ,end)
(lambda (v)
(macroexp-let2 nil v v
`(progn
,(funcall setter `(cl--set-substring
,getter ,start ,end ,v))
,v))))))))
```
Macro: **gv-letplace** *(getter setter) place &rest body*
The macro `gv-letplace` can be useful in defining macros that perform similarly to `setf`; for example, the `incf` macro of Common Lisp could be implemented this way:
```
(defmacro incf (place &optional n)
(gv-letplace (getter setter) place
(macroexp-let2 nil v (or n 1)
(funcall setter `(+ ,v ,getter)))))
```
getter will be bound to a copyable expression that returns the value of place. setter will be bound to a function that takes an expression v and returns a new expression that sets place to v. body should return a Emacs Lisp expression manipulating place via getter and setter.
Consult the source file `gv.el` for more details.
> **Common Lisp note:** Common Lisp defines another way to specify the `setf` behavior of a function, namely `setf` functions, whose names are lists `(setf name)` rather than symbols. For example, `(defun (setf foo) …)` defines the function that is used when `setf` is applied to `foo`. Emacs does not support this. It is a compile-time error to use `setf` on a form that has not already had an appropriate expansion defined. In Common Lisp, this is not an error since the function `(setf
> func)` might be defined later.
>
>
>
elisp None ### Variables that Never Change
In Emacs Lisp, certain symbols normally evaluate to themselves. These include `nil` and `t`, as well as any symbol whose name starts with ‘`:`’ (these are called *keywords*). These symbols cannot be rebound, nor can their values be changed. Any attempt to set or bind `nil` or `t` signals a `setting-constant` error. The same is true for a keyword (a symbol whose name starts with ‘`:`’), if it is interned in the standard obarray, except that setting such a symbol to itself is not an error.
```
nil ≡ 'nil
⇒ nil
```
```
(setq nil 500)
error→ Attempt to set constant symbol: nil
```
Function: **keywordp** *object*
function returns `t` if object is a symbol whose name starts with ‘`:`’, interned in the standard obarray, and returns `nil` otherwise.
These constants are fundamentally different from the constants defined using the `defconst` special form (see [Defining Variables](defining-variables)). A `defconst` form serves to inform human readers that you do not intend to change the value of a variable, but Emacs does not raise an error if you actually change it.
A small number of additional symbols are made read-only for various practical reasons. These include `enable-multibyte-characters`, `most-positive-fixnum`, `most-negative-fixnum`, and a few others. Any attempt to set or bind these also signals a `setting-constant` error.
elisp None ### Arrays
An *array* object has slots that hold a number of other Lisp objects, called the elements of the array. Any element of an array may be accessed in constant time. In contrast, the time to access an element of a list is proportional to the position of that element in the list.
Emacs defines four types of array, all one-dimensional: *strings* (see [String Type](string-type)), *vectors* (see [Vector Type](vector-type)), *bool-vectors* (see [Bool-Vector Type](bool_002dvector-type)), and *char-tables* (see [Char-Table Type](char_002dtable-type)). Vectors and char-tables can hold elements of any type, but strings can only hold characters, and bool-vectors can only hold `t` and `nil`.
All four kinds of array share these characteristics:
* The first element of an array has index zero, the second element has index 1, and so on. This is called *zero-origin* indexing. For example, an array of four elements has indices 0, 1, 2, and 3.
* The length of the array is fixed once you create it; you cannot change the length of an existing array.
* For purposes of evaluation, the array is a constant—i.e., it evaluates to itself.
* The elements of an array may be referenced or changed with the functions `aref` and `aset`, respectively (see [Array Functions](array-functions)).
When you create an array, other than a char-table, you must specify its length. You cannot specify the length of a char-table, because that is determined by the range of character codes.
In principle, if you want an array of text characters, you could use either a string or a vector. In practice, we always choose strings for such applications, for four reasons:
* They occupy one-fourth the space of a vector of the same elements.
* Strings are printed in a way that shows the contents more clearly as text.
* Strings can hold text properties. See [Text Properties](text-properties).
* Many of the specialized editing and I/O facilities of Emacs accept only strings. For example, you cannot insert a vector of characters into a buffer the way you can insert a string. See [Strings and Characters](strings-and-characters).
By contrast, for an array of keyboard input characters (such as a key sequence), a vector may be necessary, because many keyboard input characters are outside the range that will fit in a string. See [Key Sequence Input](key-sequence-input).
elisp None ### User-Level Insertion Commands
This section describes higher-level commands for inserting text, commands intended primarily for the user but useful also in Lisp programs.
Command: **insert-buffer** *from-buffer-or-name*
This command inserts the entire accessible contents of from-buffer-or-name (which must exist) into the current buffer after point. It leaves the mark after the inserted text. The value is `nil`.
Command: **self-insert-command** *count &optional char*
This command inserts the character char (the last character typed); it does so count times, before point, and returns `nil`. Most printing characters are bound to this command. In routine use, `self-insert-command` is the most frequently called function in Emacs, but programs rarely use it except to install it on a keymap.
In an interactive call, count is the numeric prefix argument.
Self-insertion translates the input character through `translation-table-for-input`. See [Translation of Characters](translation-of-characters).
This command calls `auto-fill-function` whenever that is non-`nil` and the character inserted is in the table `auto-fill-chars` (see [Auto Filling](auto-filling)).
This command performs abbrev expansion if Abbrev mode is enabled and the inserted character does not have word-constituent syntax. (See [Abbrevs](abbrevs), and [Syntax Class Table](syntax-class-table).) It is also responsible for calling `blink-paren-function` when the inserted character has close parenthesis syntax (see [Blinking](blinking)).
The final thing this command does is to run the hook `post-self-insert-hook`. You could use this to automatically reindent text as it is typed, for example. If any function on this hook needs to act on the region (see [The Region](the-region)), it should make sure Delete Selection mode (see [Delete Selection](https://www.gnu.org/software/emacs/manual/html_node/emacs/Using-Region.html#Using-Region) in The GNU Emacs Manual) doesn’t delete the region before `post-self-insert-hook` functions are invoked. The way to do so is to add a function that returns `nil` to `self-insert-uses-region-functions`, a special hook that tells Delete Selection mode it should not delete the region.
Do not try substituting your own definition of `self-insert-command` for the standard one. The editor command loop handles this function specially.
Command: **newline** *&optional number-of-newlines interactive*
This command inserts newlines into the current buffer before point. If number-of-newlines is supplied, that many newline characters are inserted. In an interactive call, number-of-newlines is the numeric prefix argument.
This command calls `self-insert-command` to insert newlines, which may subsequently break the preceding line by calling `auto-fill-function` (see [Auto Filling](auto-filling)). Typically what `auto-fill-function` does is insert a newline; thus, the overall result in this case is to insert two newlines at different places: one at point, and another earlier in the line. `newline` does not auto-fill if number-of-newlines is non-`nil`.
This command does not run the hook `post-self-insert-hook` unless called interactively or interactive is non-`nil`.
This command indents to the left margin if that is not zero. See [Margins](margins).
The value returned is `nil`.
Variable: **overwrite-mode**
This variable controls whether overwrite mode is in effect. The value should be `overwrite-mode-textual`, `overwrite-mode-binary`, or `nil`. `overwrite-mode-textual` specifies textual overwrite mode (treats newlines and tabs specially), and `overwrite-mode-binary` specifies binary overwrite mode (treats newlines and tabs like any other characters).
elisp None ### Overview of Markers
A marker specifies a buffer and a position in that buffer. A marker can be used to represent a position in functions that require one, just as an integer could be used. In that case, the marker’s buffer is normally ignored. Of course, a marker used in this way usually points to a position in the buffer that the function operates on, but that is entirely the programmer’s responsibility. See [Positions](positions), for a complete description of positions.
A marker has three attributes: the marker position, the marker buffer, and the insertion type. The marker position is an integer that is equivalent (at a given time) to the marker as a position in that buffer. But the marker’s position value can change during the life of the marker, and often does. Insertion and deletion of text in the buffer relocate the marker. The idea is that a marker positioned between two characters remains between those two characters despite insertion and deletion elsewhere in the buffer. Relocation changes the integer equivalent of the marker.
Deleting text around a marker’s position leaves the marker between the characters immediately before and after the deleted text. Inserting text at the position of a marker normally leaves the marker either in front of or after the new text, depending on the marker’s *insertion type* (see [Marker Insertion Types](marker-insertion-types))—unless the insertion is done with `insert-before-markers` (see [Insertion](insertion)).
Insertion and deletion in a buffer must check all the markers and relocate them if necessary. This slows processing in a buffer with a large number of markers. For this reason, it is a good idea to make a marker point nowhere if you are sure you don’t need it any more. Markers that can no longer be accessed are eventually removed (see [Garbage Collection](garbage-collection)).
Because it is common to perform arithmetic operations on a marker position, most of these operations (including `+` and `-`) accept markers as arguments. In such cases, the marker stands for its current position.
Here are examples of creating markers, setting markers, and moving point to markers:
```
;; Make a new marker that initially does not point anywhere:
(setq m1 (make-marker))
⇒ #<marker in no buffer>
```
```
;; Set `m1` to point between the 99th and 100th characters
;; in the current buffer:
(set-marker m1 100)
⇒ #<marker at 100 in markers.texi>
```
```
;; Now insert one character at the beginning of the buffer:
(goto-char (point-min))
⇒ 1
(insert "Q")
⇒ nil
```
```
;; `m1` is updated appropriately.
m1
⇒ #<marker at 101 in markers.texi>
```
```
;; Two markers that point to the same position
;; are not `eq`, but they are `equal`.
(setq m2 (copy-marker m1))
⇒ #<marker at 101 in markers.texi>
(eq m1 m2)
⇒ nil
(equal m1 m2)
⇒ t
```
```
;; When you are finished using a marker, make it point nowhere.
(set-marker m1 nil)
⇒ #<marker in no buffer>
```
elisp None #### Breaks
Edebug’s step mode stops execution when the next stop point is reached. There are three other ways to stop Edebug execution once it has started: breakpoints, the global break condition, and source breakpoints.
| | | |
| --- | --- | --- |
| • [Breakpoints](breakpoints) | | Breakpoints at stop points. |
| • [Global Break Condition](global-break-condition) | | Breaking on an event. |
| • [Source Breakpoints](source-breakpoints) | | Embedding breakpoints in source code. |
elisp None #### Properties with Special Meanings
Here is a table of text property names that have special built-in meanings. The following sections list a few additional special property names that control filling and property inheritance. All other names have no standard meaning, and you can use them as you like.
Note: the properties `composition`, `display`, `invisible` and `intangible` can also cause point to move to an acceptable place, after each Emacs command. See [Adjusting Point](adjusting-point).
`category`
If a character has a `category` property, we call it the *property category* of the character. It should be a symbol. The properties of this symbol serve as defaults for the properties of the character.
`face`
The `face` property controls the appearance of the character (see [Faces](faces)). The value of the property can be the following:
* A face name (a symbol or string).
* An anonymous face: a property list of the form `(keyword
value …)`, where each keyword is a face attribute name and value is a value for that attribute.
* A list of faces. Each list element should be either a face name or an anonymous face. This specifies a face which is an aggregate of the attributes of each of the listed faces. Faces occurring earlier in the list have higher priority.
* A cons cell of the form `(foreground-color . color-name)` or `(background-color . color-name)`. This specifies the foreground or background color, similar to `(:foreground
color-name)` or `(:background color-name)`. This form is supported for backward compatibility only, and should be avoided.
* A cons cell of the form `(:filtered filter face-spec)`, that specifies the face given by face-spec, but only if filter matches when the face is used for display. The face-spec can use any of the forms mentioned above. The filter should be of the form `(:window param value)`, which matches for windows whose parameter param is `eq` to value. If the variable `face-filters-always-match` is non-`nil`, all face filters are deemed to have matched.
Font Lock mode (see [Font Lock Mode](font-lock-mode)) works in most buffers by dynamically updating the `face` property of characters based on the context.
The `add-face-text-property` function provides a convenient way to set this text property. See [Changing Properties](changing-properties).
`font-lock-face`
This property specifies a value for the `face` property that Font Lock mode should apply to the underlying text. It is one of the fontification methods used by Font Lock mode, and is useful for special modes that implement their own highlighting. See [Precalculated Fontification](precalculated-fontification). When Font Lock mode is disabled, `font-lock-face` has no effect.
`mouse-face`
This property is used instead of `face` when the mouse is on or near the character. For this purpose, “near” means that all text between the character and where the mouse is have the same `mouse-face` property value.
Emacs ignores all face attributes from the `mouse-face` property that alter the text size (e.g., `:height`, `:weight`, and `:slant`). Those attributes are always the same as for the unhighlighted text.
`fontified`
This property says whether the text is ready for display. If `nil`, Emacs’s redisplay routine calls the functions in `fontification-functions` (see [Auto Faces](auto-faces)) to prepare this part of the buffer before it is displayed. It is used internally by the just-in-time font locking code.
`display`
This property activates various features that change the way text is displayed. For example, it can make text appear taller or shorter, higher or lower, wider or narrow, or replaced with an image. See [Display Property](display-property).
`help-echo`
If text has a string as its `help-echo` property, then when you move the mouse onto that text, Emacs displays that string in the echo area, or in the tooltip window (see [Tooltips](tooltips)), after passing it through `substitute-command-keys`.
If the value of the `help-echo` property is a function, that function is called with three arguments, window, object and pos and should return a help string or `nil` for none. The first argument, window is the window in which the help was found. The second, object, is the buffer, overlay or string which had the `help-echo` property. The pos argument is as follows:
* If object is a buffer, pos is the position in the buffer.
* If object is an overlay, that overlay has a `help-echo` property, and pos is the position in the overlay’s buffer.
* If object is a string (an overlay string or a string displayed with the `display` property), pos is the position in that string.
If the value of the `help-echo` property is neither a function nor a string, it is evaluated to obtain a help string.
You can alter the way help text is displayed by setting the variable `show-help-function` (see [Help display](#Help-display)).
This feature is used in the mode line and for other active text.
`help-echo-inhibit-substitution`
If the first character of a `help-echo` string has a non-`nil` `help-echo-inhibit-substitution` property, then it is displayed as-is by `show-help-function`, without being passed through `substitute-command-keys`.
`keymap`
The `keymap` property specifies an additional keymap for commands. When this keymap applies, it is used for key lookup before the minor mode keymaps and before the buffer’s local map. See [Active Keymaps](active-keymaps). If the property value is a symbol, the symbol’s function definition is used as the keymap.
The property’s value for the character before point applies if it is non-`nil` and rear-sticky, and the property’s value for the character after point applies if it is non-`nil` and front-sticky. (For mouse clicks, the position of the click is used instead of the position of point.)
`local-map`
This property works like `keymap` except that it specifies a keymap to use *instead of* the buffer’s local map. For most purposes (perhaps all purposes), it is better to use the `keymap` property.
`syntax-table`
The `syntax-table` property overrides what the syntax table says about this particular character. See [Syntax Properties](syntax-properties).
`read-only`
If a character has the property `read-only`, then modifying that character is not allowed. Any command that would do so gets an error, `text-read-only`. If the property value is a string, that string is used as the error message.
Insertion next to a read-only character is an error if inserting ordinary text there would inherit the `read-only` property due to stickiness. Thus, you can control permission to insert next to read-only text by controlling the stickiness. See [Sticky Properties](sticky-properties).
Since changing properties counts as modifying the buffer, it is not possible to remove a `read-only` property unless you know the special trick: bind `inhibit-read-only` to a non-`nil` value and then remove the property. See [Read Only Buffers](read-only-buffers).
`inhibit-read-only`
Characters that have the property `inhibit-read-only` can be edited even in read-only buffers. See [Read Only Buffers](read-only-buffers).
`invisible`
A non-`nil` `invisible` property can make a character invisible on the screen. See [Invisible Text](invisible-text), for details.
`intangible`
If a group of consecutive characters have equal and non-`nil` `intangible` properties, then you cannot place point between them. If you try to move point forward into the group, point actually moves to the end of the group. If you try to move point backward into the group, point actually moves to the start of the group.
If consecutive characters have unequal non-`nil` `intangible` properties, they belong to separate groups; each group is separately treated as described above.
When the variable `inhibit-point-motion-hooks` is non-`nil` (as it is by default), the `intangible` property is ignored.
Beware: this property operates at a very low level, and affects a lot of code in unexpected ways. So use it with extreme caution. A common misuse is to put an intangible property on invisible text, which is actually unnecessary since the command loop will move point outside of the invisible text at the end of each command anyway. See [Adjusting Point](adjusting-point). For these reasons, this property is obsolete; use the `cursor-intangible` property instead.
`cursor-intangible`
When the minor mode `cursor-intangible-mode` is turned on, point is moved away from any position that has a non-`nil` `cursor-intangible` property, just before redisplay happens.
When the variable `cursor-sensor-inhibit` is non-`nil`, the `cursor-intangible` property and the `cursor-sensor-functions` property (described below) are ignored.
`field`
Consecutive characters with the same `field` property constitute a *field*. Some motion functions including `forward-word` and `beginning-of-line` stop moving at a field boundary. See [Fields](fields).
`cursor`
Normally, the cursor is displayed at the beginning or the end of any overlay and text property strings present at the current buffer position. You can instead tell Emacs to place the cursor on any desired character of these strings by giving that character a non-`nil` `cursor` text property. In addition, if the value of the `cursor` property is an integer, it specifies the number of buffer’s character positions, starting with the position where the overlay or the `display` property begins, for which the cursor should be displayed on that character. Specifically, if the value of the `cursor` property of a character is the number n, the cursor will be displayed on this character for any buffer position in the range `[ovpos..ovpos+n)`, where ovpos is the overlay’s starting position given by `overlay-start` (see [Managing Overlays](managing-overlays)), or the position where the `display` text property begins in the buffer.
In other words, the string character with the `cursor` property of any non-`nil` value is the character where to display the cursor when the overlay or display string make point not visible on display. The value of the property says for which buffer positions to display the cursor there. If the value is an integer n, the cursor is displayed there when point is anywhere between the beginning of the overlay or `display` property and n positions after that. If the value is anything else and non-`nil`, the cursor is displayed there only when point is at the buffer position that is the beginning of the `display` property, or at `overlay-start` if that position is not visible on display. Note that an integer value of the `cursor` property could mean that the cursor is displayed on that character even when point is visible on display.
One subtlety of this property is that it doesn’t work to put this property on a newline character that is part of a display or overlay string. That’s because the newline doesn’t have a graphic representation on the screen for Emacs to find when it looks for a character on display with that `cursor` property.
When the buffer has many overlay strings (e.g., see [before-string](overlay-properties)) that conceal some of the buffer text or `display` properties that are strings, it is a good idea to use the `cursor` property on these strings to cue the Emacs display about the places where to put the cursor while traversing these strings. This directly communicates to the display engine where the Lisp program wants to put the cursor, or where the user would expect the cursor, when point is located on some buffer position that is “covered” by the display or overlay string.
`pointer`
This specifies a specific pointer shape when the mouse pointer is over this text or image. See [Pointer Shape](pointer-shape), for possible pointer shapes.
`line-spacing`
A newline can have a `line-spacing` text or overlay property that controls the height of the display line ending with that newline. The property value overrides the default frame line spacing and the buffer local `line-spacing` variable. See [Line Height](line-height).
`line-height`
A newline can have a `line-height` text or overlay property that controls the total height of the display line ending in that newline. See [Line Height](line-height).
`wrap-prefix`
If text has a `wrap-prefix` property, the prefix it defines will be added at display time to the beginning of every continuation line due to text wrapping (so if lines are truncated, the wrap-prefix is never used). It may be a string or an image (see [Other Display Specs](other-display-specs)), or a stretch of whitespace such as specified by the `:width` or `:align-to` display properties (see [Specified Space](specified-space)).
A wrap-prefix may also be specified for an entire buffer using the `wrap-prefix` buffer-local variable (however, a `wrap-prefix` text-property takes precedence over the value of the `wrap-prefix` variable). See [Truncation](truncation).
`line-prefix`
If text has a `line-prefix` property, the prefix it defines will be added at display time to the beginning of every non-continuation line. It may be a string or an image (see [Other Display Specs](other-display-specs)), or a stretch of whitespace such as specified by the `:width` or `:align-to` display properties (see [Specified Space](specified-space)).
A line-prefix may also be specified for an entire buffer using the `line-prefix` buffer-local variable (however, a `line-prefix` text-property takes precedence over the value of the `line-prefix` variable). See [Truncation](truncation).
`modification-hooks`
If a character has the property `modification-hooks`, then its value should be a list of functions; modifying that character calls all of those functions before the actual modification. Each function receives two arguments: the beginning and end of the part of the buffer being modified. Note that if a particular modification hook function appears on several characters being modified by a single primitive, you can’t predict how many times the function will be called. Furthermore, insertion will not modify any existing character, so this hook will only be run when removing some characters, replacing them with others, or changing their text-properties.
Unlike with other similar hooks, when Emacs calls these functions, `inhibit-modification-hooks` does *not* get bound to non-`nil`. If the functions modify the buffer, you should consider binding this variable to non-`nil` to prevent any buffer changes running the change hooks. Otherwise, you must be prepared for recursive calls. See [Change Hooks](change-hooks).
Overlays also support the `modification-hooks` property, but the details are somewhat different (see [Overlay Properties](overlay-properties)).
`insert-in-front-hooks` `insert-behind-hooks`
The operation of inserting text in a buffer also calls the functions listed in the `insert-in-front-hooks` property of the following character and in the `insert-behind-hooks` property of the preceding character. These functions receive two arguments, the beginning and end of the inserted text. The functions are called *after* the actual insertion takes place.
When these functions are called, `inhibit-modification-hooks` is bound to non-`nil`. If the functions modify the buffer, you might want to bind `inhibit-modification-hooks` to `nil`, so as to cause the change hooks to run for these modifications. However, doing this may call your own change hook recursively, so be sure to prepare for that.
See also [Change Hooks](change-hooks), for other hooks that are called when you change text in a buffer.
`point-entered` `point-left`
The special properties `point-entered` and `point-left` record hook functions that report motion of point. Each time point moves, Emacs compares these two property values:
* the `point-left` property of the character after the old location, and
* the `point-entered` property of the character after the new location.
If these two values differ, each of them is called (if not `nil`) with two arguments: the old value of point, and the new one.
The same comparison is made for the characters before the old and new locations. The result may be to execute two `point-left` functions (which may be the same function) and/or two `point-entered` functions (which may be the same function). In any case, all the `point-left` functions are called first, followed by all the `point-entered` functions.
It is possible to use `char-after` to examine characters at various buffer positions without moving point to those positions. Only an actual change in the value of point runs these hook functions.
The variable `inhibit-point-motion-hooks` by default inhibits running the `point-left` and `point-entered` hooks, see [Inhibit point motion hooks](#Inhibit-point-motion-hooks).
These properties are obsolete; please use `cursor-sensor-functions` instead.
`cursor-sensor-functions`
This special property records a list of functions that react to cursor motion. Each function in the list is called, just before redisplay, with 3 arguments: the affected window, the previous known position of the cursor, and one of the symbols `entered` or `left`, depending on whether the cursor is entering the text that has this property or leaving it. The functions are called only when the minor mode `cursor-sensor-mode` is turned on.
When the variable `cursor-sensor-inhibit` is non-`nil`, the `cursor-sensor-functions` property is ignored.
`composition`
This text property is used to display a sequence of characters as a single glyph composed from components. But the value of the property itself is completely internal to Emacs and should not be manipulated directly by, for instance, `put-text-property`.
`minibuffer-message`
This text property tells where to display temporary messages in an active minibuffer. Specifically, the first character of the minibuffer text which has this property will have the temporary message displayed before it. The default is to display temporary messages at the end of the minibuffer text. This text property is used by the function that is the default value of `set-message-function` (see [Displaying Messages](displaying-messages)).
Variable: **inhibit-point-motion-hooks**
When this obsolete variable is non-`nil`, `point-left` and `point-entered` hooks are not run, and the `intangible` property has no effect. Do not set this variable globally; bind it with `let`. Since the affected properties are obsolete, this variable’s default value is `t`, to effectively disable them.
Variable: **show-help-function**
If this variable is non-`nil`, it specifies a function called to display help strings. These may be `help-echo` properties, menu help strings (see [Simple Menu Items](simple-menu-items), see [Extended Menu Items](extended-menu-items)), or tool bar help strings (see [Tool Bar](tool-bar)). The specified function is called with one argument, the help string to display, which is passed through `substitute-command-keys` before being given to the function, unless the help string has a non-`nil` `help-echo-inhibit-substitution` property on its first character; see [Keys in Documentation](keys-in-documentation). See the code of Tooltip mode (see [Tooltips](https://www.gnu.org/software/emacs/manual/html_node/emacs/Tooltips.html#Tooltips) in The GNU Emacs Manual) for an example of a mode that uses `show-help-function`.
Variable: **face-filters-always-match**
If this variable is non-`nil`, face filters that specify attributes applied only when certain conditions are met will be deemed to match always.
| programming_docs |
elisp None ### Running a function when a variable is changed.
It is sometimes useful to take some action when a variable changes its value. The *variable watchpoint* facility provides the means to do so. Some possible uses for this feature include keeping display in sync with variable settings, and invoking the debugger to track down unexpected changes to variables (see [Variable Debugging](variable-debugging)).
The following functions may be used to manipulate and query the watch functions for a variable.
Function: **add-variable-watcher** *symbol watch-function*
This function arranges for watch-function to be called whenever symbol is modified. Modifications through aliases (see [Variable Aliases](variable-aliases)) will have the same effect.
watch-function will be called, just before changing the value of symbol, with 4 arguments: symbol, newval, operation, and where. symbol is the variable being changed. newval is the value it will be changed to. (The old value is available to watch-function as the value of symbol, since it was not yet changed to newval.) operation is a symbol representing the kind of change, one of: `set`, `let`, `unlet`, `makunbound`, or `defvaralias`. where is a buffer if the buffer-local value of the variable is being changed, `nil` otherwise.
Function: **remove-variable-watcher** *symbol watch-function*
This function removes watch-function from symbol’s list of watchers.
Function: **get-variable-watchers** *symbol*
This function returns the list of symbol’s active watcher functions.
#### Limitations
There are a couple of ways in which a variable could be modified (or at least appear to be modified) without triggering a watchpoint.
Since watchpoints are attached to symbols, modification to the objects contained within variables (e.g., by a list modification function see [Modifying Lists](modifying-lists)) is not caught by this mechanism.
Additionally, C code can modify the value of variables directly, bypassing the watchpoint mechanism.
A minor limitation of this feature, again because it targets symbols, is that only variables of dynamic scope may be watched. This poses little difficulty, since modifications to lexical variables can be discovered easily by inspecting the code within the scope of the variable (unlike dynamic variables, which can be modified by any code at all, see [Variable Scoping](variable-scoping)).
elisp None ### Accessing Other Processes
In addition to accessing and manipulating processes that are subprocesses of the current Emacs session, Emacs Lisp programs can also access other processes running on the same machine. We call these *system processes*, to distinguish them from Emacs subprocesses.
Emacs provides several primitives for accessing system processes. Not all platforms support these primitives; on those which don’t, these primitives return `nil`.
Function: **list-system-processes**
This function returns a list of all the processes running on the system. Each process is identified by its PID, a numerical process ID that is assigned by the OS and distinguishes the process from all the other processes running on the same machine at the same time.
Function: **process-attributes** *pid*
This function returns an alist of attributes for the process specified by its process ID pid. Each association in the alist is of the form `(key . value)`, where key designates the attribute and value is the value of that attribute. The various attribute keys that this function can return are listed below. Not all platforms support all of these attributes; if an attribute is not supported, its association will not appear in the returned alist.
`euid`
The effective user ID of the user who invoked the process. The corresponding value is a number. If the process was invoked by the same user who runs the current Emacs session, the value is identical to what `user-uid` returns (see [User Identification](user-identification)).
`user`
User name corresponding to the process’s effective user ID, a string.
`egid`
The group ID of the effective user ID, a number.
`group`
Group name corresponding to the effective user’s group ID, a string.
`comm`
The name of the command that runs in the process. This is a string that usually specifies the name of the executable file of the process, without the leading directories. However, some special system processes can report strings that do not correspond to an executable file of a program.
`state`
The state code of the process. This is a short string that encodes the scheduling state of the process. Here’s a list of the most frequently seen codes:
`"D"` uninterruptible sleep (usually I/O)
`"R"` running
`"S"` interruptible sleep (waiting for some event)
`"T"` stopped, e.g., by a job control signal
`"Z"` zombie: a process that terminated, but was not reaped by its parent
For the full list of the possible states, see the manual page of the `ps` command.
`ppid`
The process ID of the parent process, a number.
`pgrp`
The process group ID of the process, a number.
`sess`
The session ID of the process. This is a number that is the process ID of the process’s *session leader*.
`ttname`
A string that is the name of the process’s controlling terminal. On Unix and GNU systems, this is normally the file name of the corresponding terminal device, such as `/dev/pts65`.
`tpgid`
The numerical process group ID of the foreground process group that uses the process’s terminal.
`minflt`
The number of minor page faults caused by the process since its beginning. (Minor page faults are those that don’t involve reading from disk.)
`majflt`
The number of major page faults caused by the process since its beginning. (Major page faults require a disk to be read, and are thus more expensive than minor page faults.)
`cminflt` `cmajflt`
Like `minflt` and `majflt`, but include the number of page faults for all the child processes of the given process.
`utime`
Time spent by the process in the user context, for running the application’s code. The corresponding value is a Lisp timestamp (see [Time of Day](time-of-day)).
`stime`
Time spent by the process in the system (kernel) context, for processing system calls. The corresponding value is a Lisp timestamp.
`time`
The sum of `utime` and `stime`. The corresponding value is a Lisp timestamp.
`cutime` `cstime` `ctime`
Like `utime`, `stime`, and `time`, but include the times of all the child processes of the given process.
`pri`
The numerical priority of the process.
`nice`
The *nice value* of the process, a number. (Processes with smaller nice values get scheduled more favorably.)
`thcount`
The number of threads in the process.
`start`
The time when the process was started, as a Lisp timestamp.
`etime`
The time elapsed since the process started, as a Lisp timestamp.
`vsize`
The virtual memory size of the process, measured in kilobytes.
`rss`
The size of the process’s *resident set*, the number of kilobytes occupied by the process in the machine’s physical memory.
`pcpu`
The percentage of the CPU time used by the process since it started. The corresponding value is a floating-point number between 0 and 100.
`pmem`
The percentage of the total physical memory installed on the machine used by the process’s resident set. The value is a floating-point number between 0 and 100.
`args` The command-line with which the process was invoked. This is a string in which individual command-line arguments are separated by blanks; whitespace characters that are embedded in the arguments are quoted as appropriate for the system’s shell: escaped by backslash characters on GNU and Unix, and enclosed in double quote characters on Windows. Thus, this command-line string can be directly used in primitives such as `shell-command`.
elisp None ### Basic Concepts of Emacs Windows
A *window* is an area of the screen that can be used to display a buffer (see [Buffers](buffers)). Windows are grouped into frames (see [Frames](frames)). Each frame contains at least one window; the user can subdivide a frame into multiple, non-overlapping windows to view several buffers at once. Lisp programs can use multiple windows for a variety of purposes. In Rmail, for example, you can view a summary of message titles in one window, and the contents of the selected message in another window.
Emacs uses the term “window” with a different meaning than in graphical desktop environments and window systems, such as the X Window System. When Emacs is run on X, each graphical X window owned by the Emacs process corresponds to one Emacs frame. When Emacs is run on a text terminal, each Emacs frame fills the entire terminal screen. In either case, the frame may contain one or more Emacs windows. For disambiguation, we use the term *window-system window* when we mean the window-system window corresponding to an Emacs frame.
Unlike X windows, Emacs windows are *tiled*; they never overlap within the area of their frame. When a window is created, resized, or deleted, the change in window space is taken from or given to other windows on the same frame, so that the total area of the frame is unchanged.
In Emacs Lisp, windows are represented by a special Lisp object type (see [Window Type](window-type)).
Function: **windowp** *object*
This function returns `t` if object is a window (whether or not it displays a buffer). Otherwise, it returns `nil`.
A *live window* is one that is actually displaying a buffer in a frame.
Function: **window-live-p** *object*
This function returns `t` if object is a live window and `nil` otherwise. A live window is one that displays a buffer.
The windows in each frame are organized into a *window tree*. See [Windows and Frames](windows-and-frames). The leaf nodes of each window tree are live windows—the ones actually displaying buffers. The internal nodes of the window tree are *internal windows*, which are not live.
A *valid window* is one that is either live or internal. A valid window can be *deleted*, i.e., removed from its frame (see [Deleting Windows](deleting-windows)); then it is no longer valid, but the Lisp object representing it might be still referenced from other Lisp objects. A deleted window may be made valid again by restoring a saved window configuration (see [Window Configurations](window-configurations)).
You can distinguish valid windows from deleted windows with `window-valid-p`.
Function: **window-valid-p** *object*
This function returns `t` if object is a live window, or an internal window in a window tree. Otherwise, it returns `nil`, including for the case where object is a deleted window.
The following schematic shows the structure of a live window:
```
____________________________________________
|________________ Tab Line _______________|RD| ^
|______________ Header Line ______________| | |
^ |LS|LM|LF| |RF|RM|RS| | |
| | | | | | | | | | |
Window | | | | | | | | | Window
Body | | | | | Window Body | | | | | Total
Height | | | | | | | | | Height
| | | | |<- Window Body Width ->| | | | | |
v |__|__|__|_______________________|__|__|__| | |
|_________ Horizontal Scroll Bar _________| | |
|_______________ Mode Line _______________|__| |
|_____________ Bottom Divider _______________| v
<---------- Window Total Width ------------>
```
At the center of that window is the *body*, where the buffer text is displayed. The body can be surrounded by a series of optional areas which we will call *window decorations*. On the left and right, from innermost to outermost, these are the left and right fringes, denoted by LF and RF (see [Fringes](fringes)); the left and right margins, denoted by LM and RM in the schematic (see [Display Margins](display-margins)); the left or right vertical scroll bar, only one of which is present at any time, denoted by LS and RS (see [Scroll Bars](scroll-bars)); and the right divider, denoted by RD (see [Window Dividers](window-dividers)). Together these are the window’s *left and right decorations*.
At the top of the window are the tab line and the header line (see [Header Lines](header-lines)). The *text area* of the window includes the header line and the tab line, if they are present in the window. At the bottom of the window are the horizontal scroll bar (see [Scroll Bars](scroll-bars)); the mode line (see [Mode Line Format](mode-line-format)); and the bottom divider (see [Window Dividers](window-dividers)). Together these form the window’s *top and bottom decorations*.
There are two special areas omitted in the schematic:
* When any of the fringes is missing, the display engine may use one character cell in its place for showing a continuation or truncation glyph provided a text line doesn’t fit in a window.
* When both, the vertical scroll bar and the right divider are missing, the display engine usurps one pixel for drawing a vertical divider line between this window and the window on its right, provided such a window exists. On a text terminal, this divider always occupies an entire character cell.
In either case, the resulting artifact is considered part of the window’s body although its screen space cannot be used for displaying buffer text.
Note also, that line numbers (and their surrounding whitespace) as displayed by `display-line-numbers-mode` (see [Display Custom](https://www.gnu.org/software/emacs/manual/html_node/emacs/Display-Custom.html#Display-Custom) in The GNU Emacs Manual) do not count as decorations either; they are part of the window’s body too.
Internal windows neither show any text nor do they have decorations. Hence, the concept of “body” does not make sense for them. In fact, most functions operating on the body of a window will yield an error when applied to an internal window.
By default, an Emacs frame exhibits one special live window that is used for displaying messages and accepting user input—the *minibuffer window* (see [Minibuffer Windows](minibuffer-windows)). Since the minibuffer window is used for displaying text, it has a body but it does not have a tab or header line or any margins. Finally, a *tooltip window* which is used for displaying a tooltip in a tooltip frame (see [Tooltips](tooltips)) has a body too but no decorations at all.
elisp None #### Button Types
Every button has a *button type*, which defines default values for the button’s properties. Button types are arranged in a hierarchy, with specialized types inheriting from more general types, so that it’s easy to define special-purpose types of buttons for specific tasks.
Function: **define-button-type** *name &rest properties*
Define a button type called name (a symbol). The remaining arguments form a sequence of property value pairs, specifying default property values for buttons with this type (a button’s type may be set by giving it a `type` property when creating the button, using the `:type` keyword argument).
In addition, the keyword argument `:supertype` may be used to specify a button-type from which name inherits its default property values. Note that this inheritance happens only when name is defined; subsequent changes to a supertype are not reflected in its subtypes.
Using `define-button-type` to define default properties for buttons is not necessary—buttons without any specified type use the built-in button-type `button`—but it is encouraged, since doing so usually makes the resulting code clearer and more efficient.
elisp None #### Miscellaneous Convenience Functions for Modules
This subsection describes a few convenience functions provided by the module API. Like the functions described in previous subsections, all of them are actually function pointers, and need to be called via the `emacs_env` pointer. Description of functions that were introduced after Emacs 25 calls out the first version where they became available.
Function: *bool* **eq** *(emacs\_env \*env, emacs\_value a, emacs\_value b)*
This function returns `true` if the Lisp objects represented by a and b are identical, `false` otherwise. This is the same as the Lisp function `eq` (see [Equality Predicates](equality-predicates)), but avoids the need to intern the objects represented by the arguments.
There are no API functions for other equality predicates, so you will need to use `intern` and `funcall`, described below, to perform more complex equality tests.
Function: *bool* **is\_not\_nil** *(emacs\_env \*env, emacs\_value arg)*
This function tests whether the Lisp object represented by arg is non-`nil`; it returns `true` or `false` accordingly.
Note that you could implement an equivalent test by using `intern` to get an `emacs_value` representing `nil`, then use `eq`, described above, to test for equality. But using this function is more convenient.
Function: *emacs\_value* **type\_of** *(emacs\_env \*env, emacs\_value `arg`)*
This function returns the type of arg as a value that represents a symbol: `string` for a string, `integer` for an integer, `process` for a process, etc. See [Type Predicates](type-predicates). You can use `intern` and `eq` to compare against known type symbols, if your code needs to depend on the object type.
Function: *emacs\_value* **intern** *(emacs\_env \*env, const char \*name)*
This function returns an interned Emacs symbol whose name is name, which should be an ASCII null-terminated string. It creates a new symbol if one does not already exist.
Together with `funcall`, described below, this function provides a means for invoking any Lisp-callable Emacs function, provided that its name is a pure ASCII string. For example, here’s how to intern a symbol whose name `name_str` is non-ASCII, by calling the more powerful Emacs `intern` function (see [Creating Symbols](creating-symbols)):
```
emacs_value fintern = env->intern (env, "intern");
emacs_value sym_name =
env->make_string (env, name_str, strlen (name_str));
emacs_value symbol = env->funcall (env, fintern, 1, &sym_name);
```
Function: *emacs\_value* **funcall** *(emacs\_env \*env, emacs\_value func, ptrdiff\_t nargs, emacs\_value \*args)*
This function calls the specified func passing it nargs arguments from the array pointed to by args. The argument func can be a function symbol (e.g., returned by `intern` described above), a module function returned by `make_function` (see [Module Functions](module-functions)), a subroutine written in C, etc. If nargs is zero, args can be a `NULL` pointer.
The function returns the value that func returned.
If your module includes potentially long-running code, it is a good idea to check from time to time in that code whether the user wants to quit, e.g., by typing `C-g` (see [Quitting](quitting)). The following function, which is available since Emacs 26.1, is provided for that purpose.
Function: *bool* **should\_quit** *(emacs\_env \*env)*
This function returns `true` if the user wants to quit. In that case, we recommend that your module function aborts any on-going processing and returns as soon as possible. In most cases, use `process_input` instead.
To process input events in addition to checking whether the user wants to quit, use the following function, which is available since Emacs 27.1.
Function: *enum emacs\_process\_input\_result* **process\_input** *(emacs\_env \*env)*
This function processes pending input events. It returns `emacs_process_input_quit` if the user wants to quit or an error occurred while processing signals. In that case, we recommend that your module function aborts any on-going processing and returns as soon as possible. If the module code may continue running, `process_input` returns `emacs_process_input_continue`. The return value is `emacs_process_input_continue` if and only if there is no pending nonlocal exit in `env`. If the module continues after calling `process_input`, global state such as variable values and buffer content may have been modified in arbitrary ways.
Function: *int* **open\_channel** *(emacs\_env \*env, emacs\_value pipe\_process)*
This function, which is available since Emacs 28, opens a channel to an existing pipe process. pipe\_process must refer to an existing pipe process created by `make-pipe-process`. [Pipe Processes](asynchronous-processes#Pipe-Processes). If successful, the return value will be a new file descriptor that you can use to write to the pipe. Unlike all other module functions, you can use the returned file descriptor from arbitrary threads, even if no module environment is active. You can use the `write` function to write to the file descriptor. Once done, close the file descriptor using `close`. [(libc)Low-Level I/O](https://www.gnu.org/software/libc/manual/html_node/Low_002dLevel-I_002fO.html#Low_002dLevel-I_002fO).
| programming_docs |
elisp None ### Edebug
Edebug is a source-level debugger for Emacs Lisp programs, with which you can:
* Step through evaluation, stopping before and after each expression.
* Set conditional or unconditional breakpoints.
* Stop when a specified condition is true (the global break event).
* Trace slow or fast, stopping briefly at each stop point, or at each breakpoint.
* Display expression results and evaluate expressions as if outside of Edebug.
* Automatically re-evaluate a list of expressions and display their results each time Edebug updates the display.
* Output trace information on function calls and returns.
* Stop when an error occurs.
* Display a backtrace, omitting Edebug’s own frames.
* Specify argument evaluation for macros and defining forms.
* Obtain rudimentary coverage testing and frequency counts.
The first three sections below should tell you enough about Edebug to start using it.
| | | |
| --- | --- | --- |
| • [Using Edebug](using-edebug) | | Introduction to use of Edebug. |
| • [Instrumenting](instrumenting) | | You must instrument your code in order to debug it with Edebug. |
| • [Modes](edebug-execution-modes) | | Execution modes, stopping more or less often. |
| • [Jumping](jumping) | | Commands to jump to a specified place. |
| • [Misc](edebug-misc) | | Miscellaneous commands. |
| • [Breaks](breaks) | | Setting breakpoints to make the program stop. |
| • [Trapping Errors](trapping-errors) | | Trapping errors with Edebug. |
| • [Views](edebug-views) | | Views inside and outside of Edebug. |
| • [Eval](edebug-eval) | | Evaluating expressions within Edebug. |
| • [Eval List](eval-list) | | Expressions whose values are displayed each time you enter Edebug. |
| • [Printing in Edebug](printing-in-edebug) | | Customization of printing. |
| • [Trace Buffer](trace-buffer) | | How to produce trace output in a buffer. |
| • [Coverage Testing](coverage-testing) | | How to test evaluation coverage. |
| • [The Outside Context](the-outside-context) | | Data that Edebug saves and restores. |
| • [Edebug and Macros](edebug-and-macros) | | Specifying how to handle macro calls. |
| • [Options](edebug-options) | | Option variables for customizing Edebug. |
elisp None ### Caveats
This manual has gone through numerous drafts. It is nearly complete but not flawless. There are a few topics that are not covered, either because we consider them secondary (such as most of the individual modes) or because they are yet to be written. Because we are not able to deal with them completely, we have left out several parts intentionally.
The manual should be fully correct in what it does cover, and it is therefore open to criticism on anything it says—from specific examples and descriptive text, to the ordering of chapters and sections. If something is confusing, or you find that you have to look at the sources or experiment to learn something not covered in the manual, then perhaps the manual should be fixed. Please let us know.
As you use this manual, we ask that you send corrections as soon as you find them. If you think of a simple, real life example for a function or group of functions, please make an effort to write it up and send it in. Please reference any comments to the node name and function or variable name, as appropriate. Also state the number of the edition you are criticizing.
Please send comments and corrections using `M-x report-emacs-bug`. If you wish to contribute new code (or send a patch to fix a problem), use `M-x submit-emacs-patch`.
elisp None ### Auto Filling
Auto Fill mode is a minor mode that fills lines automatically as text is inserted. See [Auto Fill](https://www.gnu.org/software/emacs/manual/html_node/emacs/Auto-Fill.html#Auto-Fill) in The GNU Emacs Manual. This section describes some variables used by Auto Fill mode. For a description of functions that you can call explicitly to fill and justify existing text, see [Filling](filling).
Auto Fill mode also enables the functions that change the margins and justification style to refill portions of the text. See [Margins](margins).
Variable: **auto-fill-function**
The value of this buffer-local variable should be a function (of no arguments) to be called after self-inserting a character from the table `auto-fill-chars`, see below. It may be `nil`, in which case nothing special is done in that case.
The value of `auto-fill-function` is `do-auto-fill` when Auto Fill mode is enabled. That is a function whose sole purpose is to implement the usual strategy for breaking a line.
Variable: **normal-auto-fill-function**
This variable specifies the function to use for `auto-fill-function`, if and when Auto Fill is turned on. Major modes can set buffer-local values for this variable to alter how Auto Fill works.
Variable: **auto-fill-chars**
A char table of characters which invoke `auto-fill-function` when self-inserted—space and newline in most language environments. They have an entry `t` in the table.
User Option: **comment-auto-fill-only-comments**
This variable, if non-`nil`, means to fill lines automatically within comments only. More precisely, this means that if a comment syntax was defined for the current buffer, then self-inserting a character outside of a comment will not call `auto-fill-function`.
elisp None ### Multi-file Packages
A multi-file package is less convenient to create than a single-file package, but it offers more features: it can include multiple Emacs Lisp files, an Info manual, and other file types (such as images).
Prior to installation, a multi-file package is stored in a package archive as a tar file. The tar file must be named `name-version.tar`, where name is the package name and version is the version number. Its contents, once extracted, must all appear in a directory named `name-version`, the *content directory* (see [Packaging Basics](packaging-basics)). Files may also extract into subdirectories of the content directory.
One of the files in the content directory must be named `name-pkg.el`. It must contain a single Lisp form, consisting of a call to the function `define-package`, described below. This defines the package’s attributes: version, brief description, and requirements.
For example, if we distribute version 1.3 of the superfrobnicator as a multi-file package, the tar file would be `superfrobnicator-1.3.tar`. Its contents would extract into the directory `superfrobnicator-1.3`, and one of these would be the file `superfrobnicator-pkg.el`.
Function: **define-package** *name version &optional docstring requirements*
This function defines a package. name is the package name, a string. version is the version, as a string of a form that can be understood by the function `version-to-list`. docstring is the brief description.
requirements is a list of required packages and their versions. Each element in this list should have the form `(dep-name
dep-version)`, where dep-name is a symbol whose name is the dependency’s package name, and dep-version is the dependency’s version (a string).
If the content directory contains a file named `README`, this file is used as the long description (overriding any ‘`;;; Commentary:`’ section).
If the content directory contains a file named `dir`, this is assumed to be an Info directory file made with `install-info`. See [Invoking install-info](https://www.gnu.org/software/texinfo/manual/texinfo/html_node/Invoking-install_002dinfo.html#Invoking-install_002dinfo) in Texinfo. The relevant Info files should also be present in the content directory. In this case, Emacs will automatically add the content directory to `Info-directory-list` when the package is activated.
Do not include any `.elc` files in the package. Those are created when the package is installed. Note that there is no way to control the order in which files are byte-compiled.
Do not include any file named `name-autoloads.el`. This file is reserved for the package’s autoload definitions (see [Packaging Basics](packaging-basics)). It is created automatically when the package is installed, by searching all the Lisp files in the package for autoload magic comments.
If the multi-file package contains auxiliary data files (such as images), the package’s Lisp code can refer to these files via the variable `load-file-name` (see [Loading](loading)). Here is an example:
```
(defconst superfrobnicator-base (file-name-directory load-file-name))
(defun superfrobnicator-fetch-image (file)
(expand-file-name file superfrobnicator-base))
```
elisp None ### Interfacing to an archive web server
A web server providing access to a package archive must support the following queries:
archive-contents
Return a lisp form describing the archive contents. The form is a list of ’package-desc’ structures (see `package.el`), except the first element of the list is the archive version.
<package name>-readme.txt
Return the long description of the package.
<file name>.sig
Return the signature for the file.
<file name>
Return the file. This will be the tarball for a multi-file package, or the single file for a simple package.
elisp None ### Minor Modes
A *minor mode* provides optional features that users may enable or disable independently of the choice of major mode. Minor modes can be enabled individually or in combination.
Most minor modes implement features that are independent of the major mode, and can thus be used with most major modes. For example, Auto Fill mode works with any major mode that permits text insertion. A few minor modes, however, are specific to a particular major mode. For example, Diff Auto Refine mode is a minor mode that is intended to be used only with Diff mode.
Ideally, a minor mode should have its desired effect regardless of the other minor modes in effect. It should be possible to activate and deactivate minor modes in any order.
Variable: **local-minor-modes**
This buffer-local variable lists the currently enabled minor modes in the current buffer, and is a list of symbols.
Variable: **global-minor-modes**
This variable lists the currently enabled global minor modes, and is a list of symbols.
Variable: **minor-mode-list**
The value of this variable is a list of all minor mode commands.
| | | |
| --- | --- | --- |
| • [Minor Mode Conventions](minor-mode-conventions) | | Tips for writing a minor mode. |
| • [Keymaps and Minor Modes](keymaps-and-minor-modes) | | How a minor mode can have its own keymap. |
| • [Defining Minor Modes](defining-minor-modes) | | A convenient facility for defining minor modes. |
elisp None #### Tool bars
A *tool bar* is a row of clickable icons at the top of a frame, just below the menu bar. See [Tool Bars](https://www.gnu.org/software/emacs/manual/html_node/emacs/Tool-Bars.html#Tool-Bars) in The GNU Emacs Manual. Emacs normally shows a tool bar on graphical displays.
On each frame, the frame parameter `tool-bar-lines` controls how many lines’ worth of height to reserve for the tool bar. A zero value suppresses the tool bar. If the value is nonzero, and `auto-resize-tool-bars` is non-`nil`, the tool bar expands and contracts automatically as needed to hold the specified contents. If the value is `grow-only`, the tool bar expands automatically, but does not contract automatically.
The tool bar contents are controlled by a menu keymap attached to a fake function key called TOOL-BAR (much like the way the menu bar is controlled). So you define a tool bar item using `define-key`, like this:
```
(define-key global-map [tool-bar key] item)
```
where key is a fake function key to distinguish this item from other items, and item is a menu item key binding (see [Extended Menu Items](extended-menu-items)), which says how to display this item and how it behaves.
The usual menu keymap item properties, `:visible`, `:enable`, `:button`, and `:filter`, are useful in tool bar bindings and have their normal meanings. The real-binding in the item must be a command, not a keymap; in other words, it does not work to define a tool bar icon as a prefix key.
The `:help` property specifies a help-echo string to display while the mouse is on that item. This is displayed in the same way as `help-echo` text properties (see [Help display](special-properties#Help-display)).
In addition, you should use the `:image` property; this is how you specify the image to display in the tool bar:
`:image image`
image is either a single image specification (see [Images](images)) or a vector of four image specifications. If you use a vector of four, one of them is used, depending on circumstances:
item 0 Used when the item is enabled and selected.
item 1 Used when the item is enabled and deselected.
item 2 Used when the item is disabled and selected.
item 3 Used when the item is disabled and deselected.
The GTK+ and NS versions of Emacs ignores items 1 to 3, because disabled and/or deselected images are autocomputed from item 0.
If image is a single image specification, Emacs draws the tool bar button in disabled state by applying an edge-detection algorithm to the image.
The `:rtl` property specifies an alternative image to use for right-to-left languages. Only the GTK+ version of Emacs supports this at present.
Like the menu bar, the tool bar can display separators (see [Menu Separators](menu-separators)). Tool bar separators are vertical rather than horizontal, though, and only a single style is supported. They are represented in the tool bar keymap by `(menu-item "--")` entries; properties like `:visible` are not supported for tool bar separators. Separators are rendered natively in GTK+ and Nextstep tool bars; in the other cases, they are rendered using an image of a vertical line.
The default tool bar is defined so that items specific to editing do not appear for major modes whose command symbol has a `mode-class` property of `special` (see [Major Mode Conventions](major-mode-conventions)). Major modes may add items to the global bar by binding `[tool-bar
foo]` in their local map. It makes sense for some major modes to replace the default tool bar items completely, since not many can be accommodated conveniently, and the default bindings make this easy by using an indirection through `tool-bar-map`.
Variable: **tool-bar-map**
By default, the global map binds `[tool-bar]` as follows:
```
(global-set-key [tool-bar]
`(menu-item ,(purecopy "tool bar") ignore
:filter tool-bar-make-keymap))
```
The function `tool-bar-make-keymap`, in turn, derives the actual tool bar map dynamically from the value of the variable `tool-bar-map`. Hence, you should normally adjust the default (global) tool bar by changing that map. Some major modes, such as Info mode, completely replace the global tool bar by making `tool-bar-map` buffer-local and setting it to a different keymap.
There are two convenience functions for defining tool bar items, as follows.
Function: **tool-bar-add-item** *icon def key &rest props*
This function adds an item to the tool bar by modifying `tool-bar-map`. The image to use is defined by icon, which is the base name of an XPM, XBM or PBM image file to be located by `find-image`. Given a value ‘`"exit"`’, say, `exit.xpm`, `exit.pbm` and `exit.xbm` would be searched for in that order on a color display. On a monochrome display, the search order is ‘`.pbm`’, ‘`.xbm`’ and ‘`.xpm`’. The binding to use is the command def, and key is the fake function key symbol in the prefix keymap. The remaining arguments props are additional property list elements to add to the menu item specification.
To define items in some local map, bind `tool-bar-map` with `let` around calls of this function:
```
(defvar foo-tool-bar-map
(let ((tool-bar-map (make-sparse-keymap)))
(tool-bar-add-item …)
…
tool-bar-map))
```
Function: **tool-bar-add-item-from-menu** *command icon &optional map &rest props*
This function is a convenience for defining tool bar items which are consistent with existing menu bar bindings. The binding of command is looked up in the menu bar in map (default `global-map`) and modified to add an image specification for icon, which is found in the same way as by `tool-bar-add-item`. The resulting binding is then placed in `tool-bar-map`, so use this function only for global tool bar items.
map must contain an appropriate keymap bound to `[menu-bar]`. The remaining arguments props are additional property list elements to add to the menu item specification.
Function: **tool-bar-local-item-from-menu** *command icon in-map &optional from-map &rest props*
This function is used for making non-global tool bar items. Use it like `tool-bar-add-item-from-menu` except that in-map specifies the local map to make the definition in. The argument from-map is like the map argument of `tool-bar-add-item-from-menu`.
Variable: **auto-resize-tool-bars**
If this variable is non-`nil`, the tool bar automatically resizes to show all defined tool bar items—but not larger than a quarter of the frame’s height.
If the value is `grow-only`, the tool bar expands automatically, but does not contract automatically. To contract the tool bar, the user has to redraw the frame by entering `C-l`.
If Emacs is built with GTK+ or Nextstep, the tool bar can only show one line, so this variable has no effect.
Variable: **auto-raise-tool-bar-buttons**
If this variable is non-`nil`, tool bar items display in raised form when the mouse moves over them.
Variable: **tool-bar-button-margin**
This variable specifies an extra margin to add around tool bar items. The value is an integer, a number of pixels. The default is 4.
Variable: **tool-bar-button-relief**
This variable specifies the shadow width for tool bar items. The value is an integer, a number of pixels. The default is 1.
Variable: **tool-bar-border**
This variable specifies the height of the border drawn below the tool bar area. An integer specifies height as a number of pixels. If the value is one of `internal-border-width` (the default) or `border-width`, the tool bar border height corresponds to the corresponding frame parameter.
You can define a special meaning for clicking on a tool bar item with the shift, control, meta, etc., modifiers. You do this by setting up additional items that relate to the original item through the fake function keys. Specifically, the additional items should use the modified versions of the same fake function key used to name the original item.
Thus, if the original item was defined this way,
```
(define-key global-map [tool-bar shell]
'(menu-item "Shell" shell
:image (image :type xpm :file "shell.xpm")))
```
then here is how you can define clicking on the same tool bar image with the shift modifier:
```
(define-key global-map [tool-bar S-shell] 'some-command)
```
See [Function Keys](function-keys), for more information about how to add modifiers to function keys.
If you have functions that change whether a tool bar item is enabled or not, this status is not necessarily updated visually immediately. To force recalculation of the tool bar, call `force-mode-line-update` (see [Mode Line Format](mode-line-format)).
elisp None ### Packing and Unpacking Byte Arrays
This section describes how to pack and unpack arrays of bytes, usually for binary network protocols. These functions convert byte arrays to alists, and vice versa. The byte array can be represented as a unibyte string or as a vector of integers, while the alist associates symbols either with fixed-size objects or with recursive sub-alists. To use the functions referred to in this section, load the `bindat` library.
Conversion from byte arrays to nested alists is also known as *deserializing* or *unpacking*, while going in the opposite direction is also known as *serializing* or *packing*.
| | | |
| --- | --- | --- |
| • [Bindat Types](bindat-types) | | Describing data layout. |
| • [Bindat Functions](bindat-functions) | | Doing the unpacking and packing. |
| • [Bindat Computed Types](bindat-computed-types) | | Advanced data layout specifications. |
| programming_docs |
elisp None #### Customizing Indentation
If you are using a mode whose indentation is provided by SMIE, you can customize the indentation to suit your preferences. You can do this on a per-mode basis (using the option `smie-config`), or a per-file basis (using the function `smie-config-local` in a file-local variable specification).
User Option: **smie-config**
This option lets you customize indentation on a per-mode basis. It is an alist with elements of the form `(mode . rules)`. For the precise form of rules, see the variable’s documentation; but you may find it easier to use the command `smie-config-guess`.
Command: **smie-config-guess**
This command tries to work out appropriate settings to produce your preferred style of indentation. Simply call the command while visiting a file that is indented with your style.
Command: **smie-config-save**
Call this command after using `smie-config-guess`, to save your settings for future sessions.
Command: **smie-config-show-indent** *&optional move*
This command displays the rules that are used to indent the current line.
Command: **smie-config-set-indent**
This command adds a local rule to adjust the indentation of the current line.
Function: **smie-config-local** *rules*
This function adds rules as indentation rules for the current buffer. These add to any mode-specific rules defined by the `smie-config` option. To specify custom indentation rules for a specific file, add an entry to the file’s local variables of the form: `eval: (smie-config-local '(rules))`.
elisp None ### Lists and Cons Cells
Lists in Lisp are not a primitive data type; they are built up from *cons cells* (see [Cons Cell Type](cons-cell-type)). A cons cell is a data object that represents an ordered pair. That is, it has two slots, and each slot *holds*, or *refers to*, some Lisp object. One slot is known as the CAR, and the other is known as the CDR. (These names are traditional; see [Cons Cell Type](cons-cell-type).) CDR is pronounced “could-er”.
We say that “the CAR of this cons cell is” whatever object its CAR slot currently holds, and likewise for the CDR.
A list is a series of cons cells chained together, so that each cell refers to the next one. There is one cons cell for each element of the list. By convention, the CARs of the cons cells hold the elements of the list, and the CDRs are used to chain the list (this asymmetry between CAR and CDR is entirely a matter of convention; at the level of cons cells, the CAR and CDR slots have similar properties). Hence, the CDR slot of each cons cell in a list refers to the following cons cell.
Also by convention, the CDR of the last cons cell in a list is `nil`. We call such a `nil`-terminated structure a *proper list*[4](#FOOT4). In Emacs Lisp, the symbol `nil` is both a symbol and a list with no elements. For convenience, the symbol `nil` is considered to have `nil` as its CDR (and also as its CAR).
Hence, the CDR of a proper list is always a proper list. The CDR of a nonempty proper list is a proper list containing all the elements except the first.
If the CDR of a list’s last cons cell is some value other than `nil`, we call the structure a *dotted list*, since its printed representation would use dotted pair notation (see [Dotted Pair Notation](dotted-pair-notation)). There is one other possibility: some cons cell’s CDR could point to one of the previous cons cells in the list. We call that structure a *circular list*.
For some purposes, it does not matter whether a list is proper, circular or dotted. If a program doesn’t look far enough down the list to see the CDR of the final cons cell, it won’t care. However, some functions that operate on lists demand proper lists and signal errors if given a dotted list. Most functions that try to find the end of a list enter infinite loops if given a circular list.
Because most cons cells are used as part of lists, we refer to any structure made out of cons cells as a *list structure*.
elisp None ### Faces
A *face* is a collection of graphical attributes for displaying text: font, foreground color, background color, optional underlining, etc. Faces control how Emacs displays text in buffers, as well as other parts of the frame such as the mode line.
One way to represent a face is as a property list of attributes, like `(:foreground "red" :weight bold)`. Such a list is called an *anonymous face*. For example, you can assign an anonymous face as the value of the `face` text property, and Emacs will display the underlying text with the specified attributes. See [Special Properties](special-properties).
More commonly, a face is referred to via a *face name*: a Lisp symbol associated with a set of face attributes[25](#FOOT25). Named faces are defined using the `defface` macro (see [Defining Faces](defining-faces)). Emacs comes with several standard named faces (see [Basic Faces](basic-faces)).
Some parts of Emacs require named faces (e.g., the functions documented in [Attribute Functions](attribute-functions)). Unless otherwise stated, we will use the term *face* to refer only to named faces.
Function: **facep** *object*
This function returns a non-`nil` value if object is a named face: a Lisp symbol or string which serves as a face name. Otherwise, it returns `nil`.
| | | |
| --- | --- | --- |
| • [Face Attributes](face-attributes) | | What is in a face? |
| • [Defining Faces](defining-faces) | | How to define a face. |
| • [Attribute Functions](attribute-functions) | | Functions to examine and set face attributes. |
| • [Displaying Faces](displaying-faces) | | How Emacs combines the faces specified for a character. |
| • [Face Remapping](face-remapping) | | Remapping faces to alternative definitions. |
| • [Face Functions](face-functions) | | How to define and examine faces. |
| • [Auto Faces](auto-faces) | | Hook for automatic face assignment. |
| • [Basic Faces](basic-faces) | | Faces that are defined by default. |
| • [Font Selection](font-selection) | | Finding the best available font for a face. |
| • [Font Lookup](font-lookup) | | Looking up the names of available fonts and information about them. |
| • [Fontsets](fontsets) | | A fontset is a collection of fonts that handle a range of character sets. |
| • [Low-Level Font](low_002dlevel-font) | | Lisp representation for character display fonts. |
elisp None ### Telling the Compiler that a Function is Defined
Byte-compiling a file often produces warnings about functions that the compiler doesn’t know about (see [Compiler Errors](compiler-errors)). Sometimes this indicates a real problem, but usually the functions in question are defined in other files which would be loaded if that code is run. For example, byte-compiling `simple.el` used to warn:
```
simple.el:8727:1:Warning: the function ‘shell-mode’ is not known to be
defined.
```
In fact, `shell-mode` is used only in a function that executes `(require 'shell)` before calling `shell-mode`, so `shell-mode` will be defined properly at run-time. When you know that such a warning does not indicate a real problem, it is good to suppress the warning. That makes new warnings which might mean real problems more visible. You do that with `declare-function`.
All you need to do is add a `declare-function` statement before the first use of the function in question:
```
(declare-function shell-mode "shell" ())
```
This says that `shell-mode` is defined in `shell.el` (the ‘`.el`’ can be omitted). The compiler takes for granted that that file really defines the function, and does not check.
The optional third argument specifies the argument list of `shell-mode`. In this case, it takes no arguments (`nil` is different from not specifying a value). In other cases, this might be something like `(file &optional overwrite)`. You don’t have to specify the argument list, but if you do the byte compiler can check that the calls match the declaration.
Macro: **declare-function** *function file &optional arglist fileonly*
Tell the byte compiler to assume that function is defined in the file file. The optional third argument arglist is either `t`, meaning the argument list is unspecified, or a list of formal parameters in the same style as `defun`. An omitted arglist defaults to `t`, not `nil`; this is atypical behavior for omitted arguments, and it means that to supply a fourth but not third argument one must specify `t` for the third-argument placeholder instead of the usual `nil`. The optional fourth argument fileonly non-`nil` means check only that file exists, not that it actually defines function.
To verify that these functions really are declared where `declare-function` says they are, use `check-declare-file` to check all `declare-function` calls in one source file, or use `check-declare-directory` check all the files in and under a certain directory.
These commands find the file that ought to contain a function’s definition using `locate-library`; if that finds no file, they expand the definition file name relative to the directory of the file that contains the `declare-function` call.
You can also say that a function is a primitive by specifying a file name ending in ‘`.c`’ or ‘`.m`’. This is useful only when you call a primitive that is defined only on certain systems. Most primitives are always defined, so they will never give you a warning.
Sometimes a file will optionally use functions from an external package. If you prefix the filename in the `declare-function` statement with ‘`ext:`’, then it will be checked if it is found, otherwise skipped without error.
There are some function definitions that ‘`check-declare`’ does not understand (e.g., `defstruct` and some other macros). In such cases, you can pass a non-`nil` fileonly argument to `declare-function`, meaning to only check that the file exists, not that it actually defines the function. Note that to do this without having to specify an argument list, you should set the arglist argument to `t` (because `nil` means an empty argument list, as opposed to an unspecified one).
elisp None ### Invisible Text
You can make characters *invisible*, so that they do not appear on the screen, with the `invisible` property. This can be either a text property (see [Text Properties](text-properties)) or an overlay property (see [Overlays](overlays)). Cursor motion also partly ignores these characters; if the command loop finds that point is inside a range of invisible text after a command, it relocates point to the other side of the text.
In the simplest case, any non-`nil` `invisible` property makes a character invisible. This is the default case—if you don’t alter the default value of `buffer-invisibility-spec`, this is how the `invisible` property works. You should normally use `t` as the value of the `invisible` property if you don’t plan to set `buffer-invisibility-spec` yourself.
More generally, you can use the variable `buffer-invisibility-spec` to control which values of the `invisible` property make text invisible. This permits you to classify the text into different subsets in advance, by giving them different `invisible` values, and subsequently make various subsets visible or invisible by changing the value of `buffer-invisibility-spec`.
Controlling visibility with `buffer-invisibility-spec` is especially useful in a program to display the list of entries in a database. It permits the implementation of convenient filtering commands to view just a part of the entries in the database. Setting this variable is very fast, much faster than scanning all the text in the buffer looking for properties to change.
Variable: **buffer-invisibility-spec**
This variable specifies which kinds of `invisible` properties actually make a character invisible. Setting this variable makes it buffer-local.
`t`
A character is invisible if its `invisible` property is non-`nil`. This is the default.
a list
Each element of the list specifies a criterion for invisibility; if a character’s `invisible` property fits any one of these criteria, the character is invisible. The list can have two kinds of elements:
`atom`
A character is invisible if its `invisible` property value is atom or if it is a list with atom as a member; comparison is done with `eq`.
`(atom . t)` A character is invisible if its `invisible` property value is atom or if it is a list with atom as a member; comparison is done with `eq`. Moreover, a sequence of such characters displays as an ellipsis.
Two functions are specifically provided for adding elements to `buffer-invisibility-spec` and removing elements from it.
Function: **add-to-invisibility-spec** *element*
This function adds the element element to `buffer-invisibility-spec`. If `buffer-invisibility-spec` was `t`, it changes to a list, `(t)`, so that text whose `invisible` property is `t` remains invisible.
Function: **remove-from-invisibility-spec** *element*
This removes the element element from `buffer-invisibility-spec`. This does nothing if element is not in the list.
A convention for use of `buffer-invisibility-spec` is that a major mode should use the mode’s own name as an element of `buffer-invisibility-spec` and as the value of the `invisible` property:
```
;; If you want to display an ellipsis:
(add-to-invisibility-spec '(my-symbol . t))
;; If you don’t want ellipsis:
(add-to-invisibility-spec 'my-symbol)
(overlay-put (make-overlay beginning end)
'invisible 'my-symbol)
;; When done with the invisibility:
(remove-from-invisibility-spec '(my-symbol . t))
;; Or respectively:
(remove-from-invisibility-spec 'my-symbol)
```
You can check for invisibility using the following function:
Function: **invisible-p** *pos-or-prop*
If pos-or-prop is a marker or number, this function returns a non-`nil` value if the text at that position is currently invisible.
If pos-or-prop is any other kind of Lisp object, that is taken to mean a possible value of the `invisible` text or overlay property. In that case, this function returns a non-`nil` value if that value would cause text to become invisible, based on the current value of `buffer-invisibility-spec`.
The return value of this function is `t` if the text would be completely hidden on display, or a non-`nil`, non-`t` value if the text would be replaced by an ellipsis.
Ordinarily, functions that operate on text or move point do not care whether the text is invisible, they process invisible characters and visible characters alike. The user-level line motion commands, such as `next-line`, `previous-line`, ignore invisible newlines if `line-move-ignore-invisible` is non-`nil` (the default), i.e., behave like these invisible newlines didn’t exist in the buffer, but only because they are explicitly programmed to do so.
If a command ends with point inside or at the boundary of invisible text, the main editing loop relocates point to one of the two ends of the invisible text. Emacs chooses the direction of relocation so that it is the same as the overall movement direction of the command; if in doubt, it prefers a position where an inserted char would not inherit the `invisible` property. Additionally, if the text is not replaced by an ellipsis and the command only moved within the invisible text, then point is moved one extra character so as to try and reflect the command’s movement by a visible movement of the cursor.
Thus, if the command moved point back to an invisible range (with the usual stickiness), Emacs moves point back to the beginning of that range. If the command moved point forward into an invisible range, Emacs moves point forward to the first visible character that follows the invisible text and then forward one more character.
These *adjustments* of point that ended up in the middle of invisible text can be disabled by setting `disable-point-adjustment` to a non-`nil` value. See [Adjusting Point](adjusting-point).
Incremental search can make invisible overlays visible temporarily and/or permanently when a match includes invisible text. To enable this, the overlay should have a non-`nil` `isearch-open-invisible` property. The property value should be a function to be called with the overlay as an argument. This function should make the overlay visible permanently; it is used when the match overlaps the overlay on exit from the search.
During the search, such overlays are made temporarily visible by temporarily modifying their invisible and intangible properties. If you want this to be done differently for a certain overlay, give it an `isearch-open-invisible-temporary` property which is a function. The function is called with two arguments: the first is the overlay, and the second is `nil` to make the overlay visible, or `t` to make it invisible again.
elisp None ### Equality Predicates
Here we describe functions that test for equality between two objects. Other functions test equality of contents between objects of specific types, e.g., strings. For these predicates, see the appropriate chapter describing the data type.
Function: **eq** *object1 object2*
This function returns `t` if object1 and object2 are the same object, and `nil` otherwise.
If object1 and object2 are symbols with the same name, they are normally the same object—but see [Creating Symbols](creating-symbols) for exceptions. For other non-numeric types (e.g., lists, vectors, strings), two arguments with the same contents or elements are not necessarily `eq` to each other: they are `eq` only if they are the same object, meaning that a change in the contents of one will be reflected by the same change in the contents of the other.
If object1 and object2 are numbers with differing types or values, then they cannot be the same object and `eq` returns `nil`. If they are fixnums with the same value, then they are the same object and `eq` returns `t`. If they were computed separately but happen to have the same value and the same non-fixnum numeric type, then they might or might not be the same object, and `eq` returns `t` or `nil` depending on whether the Lisp interpreter created one object or two.
```
(eq 'foo 'foo)
⇒ t
```
```
(eq ?A ?A)
⇒ t
```
```
(eq 3.0 3.0)
⇒ t or nil
;; Equal floats may or may not be the same object.
```
```
(eq (make-string 3 ?A) (make-string 3 ?A))
⇒ nil
```
```
(eq "asdf" "asdf")
⇒ t or nil
;; Equal string constants or may not be the same object.
```
```
(eq '(1 (2 (3))) '(1 (2 (3))))
⇒ nil
```
```
(setq foo '(1 (2 (3))))
⇒ (1 (2 (3)))
(eq foo foo)
⇒ t
(eq foo '(1 (2 (3))))
⇒ nil
```
```
(eq [(1 2) 3] [(1 2) 3])
⇒ nil
```
```
(eq (point-marker) (point-marker))
⇒ nil
```
The `make-symbol` function returns an uninterned symbol, distinct from the symbol that is used if you write the name in a Lisp expression. Distinct symbols with the same name are not `eq`. See [Creating Symbols](creating-symbols).
```
(eq (make-symbol "foo") 'foo)
⇒ nil
```
The Emacs Lisp byte compiler may collapse identical literal objects, such as literal strings, into references to the same object, with the effect that the byte-compiled code will compare such objects as `eq`, while the interpreted version of the same code will not. Therefore, your code should never rely on objects with the same literal contents being either `eq` or not `eq`, it should instead use functions that compare object contents such as `equal`, described below. Similarly, your code should not modify literal objects (e.g., put text properties on literal strings), since doing that might affect other literal objects of the same contents, if the byte compiler collapses them.
Function: **equal** *object1 object2*
This function returns `t` if object1 and object2 have equal components, and `nil` otherwise. Whereas `eq` tests if its arguments are the same object, `equal` looks inside nonidentical arguments to see if their elements or contents are the same. So, if two objects are `eq`, they are `equal`, but the converse is not always true.
```
(equal 'foo 'foo)
⇒ t
```
```
(equal 456 456)
⇒ t
```
```
(equal "asdf" "asdf")
⇒ t
```
```
(eq "asdf" "asdf")
⇒ nil
```
```
(equal '(1 (2 (3))) '(1 (2 (3))))
⇒ t
```
```
(eq '(1 (2 (3))) '(1 (2 (3))))
⇒ nil
```
```
(equal [(1 2) 3] [(1 2) 3])
⇒ t
```
```
(eq [(1 2) 3] [(1 2) 3])
⇒ nil
```
```
(equal (point-marker) (point-marker))
⇒ t
```
```
(eq (point-marker) (point-marker))
⇒ nil
```
Comparison of strings is case-sensitive, but does not take account of text properties—it compares only the characters in the strings. See [Text Properties](text-properties). Use `equal-including-properties` to also compare text properties. For technical reasons, a unibyte string and a multibyte string are `equal` if and only if they contain the same sequence of character codes and all these codes are in the range 0 through 127 (ASCII).
```
(equal "asdf" "ASDF")
⇒ nil
```
The `equal` function recursively compares the contents of objects if they are integers, strings, markers, vectors, bool-vectors, byte-code function objects, char-tables, records, or font objects. Other objects are considered `equal` only if they are `eq`. For example, two distinct buffers are never considered `equal`, even if their textual contents are the same.
For `equal`, equality is defined recursively; for example, given two cons cells x and y, `(equal x y)` returns `t` if and only if both the expressions below return `t`:
```
(equal (car x) (car y))
(equal (cdr x) (cdr y))
```
Comparing circular lists may therefore cause deep recursion that leads to an error, and this may result in counterintuitive behavior such as `(equal a b)` returning `t` whereas `(equal b a)` signals an error.
Function: **equal-including-properties** *object1 object2*
This function behaves like `equal` in all cases but also requires that for two strings to be equal, they have the same text properties.
```
(equal "asdf" (propertize "asdf" 'asdf t))
⇒ t
```
```
(equal-including-properties "asdf"
(propertize "asdf" 'asdf t))
⇒ nil
```
| programming_docs |
elisp None #### Functions for Yanking
This section describes higher-level commands for yanking, which are intended primarily for the user but useful also in Lisp programs. Both `yank` and `yank-pop` honor the `yank-excluded-properties` variable and `yank-handler` text property (see [Yanking](yanking)).
Command: **yank** *&optional arg*
This command inserts before point the text at the front of the kill ring. It sets the mark at the beginning of that text, using `push-mark` (see [The Mark](the-mark)), and puts point at the end.
If arg is a non-`nil` list (which occurs interactively when the user types `C-u` with no digits), then `yank` inserts the text as described above, but puts point before the yanked text and sets the mark after it.
If arg is a number, then `yank` inserts the argth most recently killed text—the argth element of the kill ring list, counted cyclically from the front, which is considered the first element for this purpose.
`yank` does not alter the contents of the kill ring, unless it used text provided by another program, in which case it pushes that text onto the kill ring. However if arg is an integer different from one, it rotates the kill ring to place the yanked string at the front.
`yank` returns `nil`.
Command: **yank-pop** *&optional arg*
When invoked immediately after a `yank` or another `yank-pop`, this command replaces the just-yanked entry from the kill ring with a different entry from the kill ring. When this command is invoked like that, the region contains text that was just inserted by another yank command. `yank-pop` deletes that text and inserts in its place a different piece of killed text. It does not add the deleted text to the kill ring, since it is already in the kill ring somewhere. It does however rotate the kill ring to place the newly yanked string at the front.
If arg is `nil`, then the replacement text is the previous element of the kill ring. If arg is numeric, the replacement is the argth previous kill. If arg is negative, a more recent kill is the replacement.
The sequence of kills in the kill ring wraps around, so if `yank-pop` is invoked repeatedly and reaches the oldest kill, the one that comes after it is the newest one, and the one before the newest one is the oldest one.
This command can also be invoked after a command that is not a yank command. In that case, it prompts in the minibuffer for a kill-ring entry, with completion, and uses the kill ring elements as the minibuffer history (see [Minibuffer History](minibuffer-history)). This allows the user to interactively select one of the previous kills recorded in the kill ring.
The return value is always `nil`.
Variable: **yank-undo-function**
If this variable is non-`nil`, the function `yank-pop` uses its value instead of `delete-region` to delete the text inserted by the previous `yank` or `yank-pop` command. The value must be a function of two arguments, the start and end of the current region.
The function `insert-for-yank` automatically sets this variable according to the undo element of the `yank-handler` text property, if there is one.
elisp None ### Iteration
Iteration means executing part of a program repetitively. For example, you might want to repeat some computation once for each element of a list, or once for each integer from 0 to n. You can do this in Emacs Lisp with the special form `while`:
Special Form: **while** *condition forms…*
`while` first evaluates condition. If the result is non-`nil`, it evaluates forms in textual order. Then it reevaluates condition, and if the result is non-`nil`, it evaluates forms again. This process repeats until condition evaluates to `nil`.
There is no limit on the number of iterations that may occur. The loop will continue until either condition evaluates to `nil` or until an error or `throw` jumps out of it (see [Nonlocal Exits](nonlocal-exits)).
The value of a `while` form is always `nil`.
```
(setq num 0)
⇒ 0
```
```
(while (< num 4)
(princ (format "Iteration %d." num))
(setq num (1+ num)))
-| Iteration 0.
-| Iteration 1.
-| Iteration 2.
-| Iteration 3.
⇒ nil
```
To write a repeat-until loop, which will execute something on each iteration and then do the end-test, put the body followed by the end-test in a `progn` as the first argument of `while`, as shown here:
```
(while (progn
(forward-line 1)
(not (looking-at "^$"))))
```
This moves forward one line and continues moving by lines until it reaches an empty line. It is peculiar in that the `while` has no body, just the end test (which also does the real work of moving point).
The `dolist` and `dotimes` macros provide convenient ways to write two common kinds of loops.
Macro: **dolist** *(var list [result]) body…*
This construct executes body once for each element of list, binding the variable var locally to hold the current element. Then it returns the value of evaluating result, or `nil` if result is omitted. For example, here is how you could use `dolist` to define the `reverse` function:
```
(defun reverse (list)
(let (value)
(dolist (elt list value)
(setq value (cons elt value)))))
```
Macro: **dotimes** *(var count [result]) body…*
This construct executes body once for each integer from 0 (inclusive) to count (exclusive), binding the variable var to the integer for the current iteration. Then it returns the value of evaluating result, or `nil` if result is omitted. Use of result is deprecated. Here is an example of using `dotimes` to do something 100 times:
```
(dotimes (i 100)
(insert "I will not obey absurd orders\n"))
```
elisp None #### Evaluating Macro Arguments Repeatedly
When defining a macro you must pay attention to the number of times the arguments will be evaluated when the expansion is executed. The following macro (used to facilitate iteration) illustrates the problem. This macro allows us to write a for-loop construct.
```
(defmacro for (var from init to final do &rest body)
"Execute a simple \"for\" loop.
For example, (for i from 1 to 10 do (print i))."
(list 'let (list (list var init))
(cons 'while
(cons (list '<= var final)
(append body (list (list 'inc var)))))))
```
```
(for i from 1 to 3 do
(setq square (* i i))
(princ (format "\n%d %d" i square)))
→
```
```
(let ((i 1))
(while (<= i 3)
(setq square (* i i))
(princ (format "\n%d %d" i square))
(inc i)))
```
```
-|1 1
-|2 4
-|3 9
⇒ nil
```
The arguments `from`, `to`, and `do` in this macro are syntactic sugar; they are entirely ignored. The idea is that you will write noise words (such as `from`, `to`, and `do`) in those positions in the macro call.
Here’s an equivalent definition simplified through use of backquote:
```
(defmacro for (var from init to final do &rest body)
"Execute a simple \"for\" loop.
For example, (for i from 1 to 10 do (print i))."
`(let ((,var ,init))
(while (<= ,var ,final)
,@body
(inc ,var))))
```
Both forms of this definition (with backquote and without) suffer from the defect that final is evaluated on every iteration. If final is a constant, this is not a problem. If it is a more complex form, say `(long-complex-calculation x)`, this can slow down the execution significantly. If final has side effects, executing it more than once is probably incorrect.
A well-designed macro definition takes steps to avoid this problem by producing an expansion that evaluates the argument expressions exactly once unless repeated evaluation is part of the intended purpose of the macro. Here is a correct expansion for the `for` macro:
```
(let ((i 1)
(max 3))
(while (<= i max)
(setq square (* i i))
(princ (format "%d %d" i square))
(inc i)))
```
Here is a macro definition that creates this expansion:
```
(defmacro for (var from init to final do &rest body)
"Execute a simple for loop: (for i from 1 to 10 do (print i))."
`(let ((,var ,init)
(max ,final))
(while (<= ,var max)
,@body
(inc ,var))))
```
Unfortunately, this fix introduces another problem, described in the following section.
elisp None ### Raising, Lowering and Restacking Frames
Most window systems use a desktop metaphor. Part of this metaphor is the idea that system-level windows (representing, e.g., Emacs frames) are stacked in a notional third dimension perpendicular to the screen surface. The order induced by stacking is total and usually referred to as stacking (or Z-) order. Where the areas of two windows overlap, the one higher up in that order will (partially) cover the one underneath.
You can *raise* a frame to the top of that order or *lower* a frame to its bottom by using the functions `raise-frame` and `lower-frame`. You can *restack* a frame directly above or below another frame using the function `frame-restack`.
Note that all functions described below will respect the adherence of frames (and all other window-system windows) to their respective z-group (see [Position Parameters](position-parameters)). For example, you usually cannot lower a frame below that of the desktop window and you cannot raise a frame whose `z-group` parameter is `nil` above the window-system’s taskbar or tooltip window.
Command: **raise-frame** *&optional frame*
This function raises frame frame (default, the selected frame) above all other frames belonging to the same or a lower z-group as frame. If frame is invisible or iconified, this makes it visible. If frame is a child frame (see [Child Frames](child-frames)), this raises frame above all other child frames of its parent.
Command: **lower-frame** *&optional frame*
This function lowers frame frame (default, the selected frame) below all other frames belonging to the same or a higher z-group as frame. If frame is a child frame (see [Child Frames](child-frames)), this lowers frame below all other child frames of its parent.
Function: **frame-restack** *frame1 frame2 &optional above*
This function restacks frame1 below frame2. This implies that if both frames are visible and their display areas overlap, frame2 will (partially) obscure frame1. If the optional third argument above is non-`nil`, this function restacks frame1 above frame2. This means that if both frames are visible and their display areas overlap, frame1 will (partially) obscure frame2.
Technically, this function may be thought of as an atomic action performed in two steps: The first step removes frame1’s window-system window from the display. The second step reinserts frame1’s window into the display below (above if above is true) that of frame2. Hence the position of frame2 in its display’s Z (stacking) order relative to all other frames excluding frame1 remains unaltered.
Some window managers may refuse to restack windows.
Note that the effect of restacking will only hold as long as neither of the involved frames is iconified or made invisible. You can use the `z-group` (see [Position Parameters](position-parameters)) frame parameter to add a frame to a group of frames permanently shown above or below other frames. As long as a frame belongs to one of these groups, restacking it will only affect its relative stacking position within that group. The effect of restacking frames belonging to different z-groups is undefined. You can list frames in their current stacking order with the function `frame-list-z-order` (see [Finding All Frames](finding-all-frames)).
User Option: **minibuffer-auto-raise**
If this is non-`nil`, activation of the minibuffer raises the frame that the minibuffer window is in.
On window systems, you can also enable auto-raising (on frame selection) or auto-lowering (on frame deselection) using frame parameters. See [Management Parameters](management-parameters).
The concept of raising and lowering frames also applies to text terminal frames. On each text terminal, only the top frame is displayed at any one time.
Function: **tty-top-frame** *&optional terminal*
This function returns the top frame on terminal. terminal should be a terminal object, a frame (meaning that frame’s terminal), or `nil` (meaning the selected frame’s terminal). If it does not refer to a text terminal, the return value is `nil`.
elisp None ### Reverting
If you have made extensive changes to a file and then change your mind about them, you can get rid of them by reading in the previous version of the file with the `revert-buffer` command. See [Reverting a Buffer](https://www.gnu.org/software/emacs/manual/html_node/emacs/Reverting.html#Reverting) in The GNU Emacs Manual.
Command: **revert-buffer** *&optional ignore-auto noconfirm preserve-modes*
This command replaces the buffer text with the text of the visited file on disk. This action undoes all changes since the file was visited or saved.
By default, if the latest auto-save file is more recent than the visited file, and the argument ignore-auto is `nil`, `revert-buffer` asks the user whether to use that auto-save instead. When you invoke this command interactively, ignore-auto is `t` if there is no numeric prefix argument; thus, the interactive default is not to check the auto-save file.
Normally, `revert-buffer` asks for confirmation before it changes the buffer; but if the argument noconfirm is non-`nil`, `revert-buffer` does not ask for confirmation.
Normally, this command reinitializes the buffer’s major and minor modes using `normal-mode`. But if preserve-modes is non-`nil`, the modes remain unchanged.
Reverting tries to preserve marker positions in the buffer by using the replacement feature of `insert-file-contents`. If the buffer contents and the file contents are identical before the revert operation, reverting preserves all the markers. If they are not identical, reverting does change the buffer; in that case, it preserves the markers in the unchanged text (if any) at the beginning and end of the buffer. Preserving any additional markers would be problematic.
When reverting from non-file sources, markers are usually not preserved, but this is up to the specific `revert-buffer-function` implementation.
Variable: **revert-buffer-in-progress-p**
`revert-buffer` binds this variable to a non-`nil` value while it is working.
You can customize how `revert-buffer` does its work by setting the variables described in the rest of this section.
User Option: **revert-without-query**
This variable holds a list of files that should be reverted without query. The value is a list of regular expressions. If the visited file name matches one of these regular expressions, and the file has changed on disk but the buffer is not modified, then `revert-buffer` reverts the file without asking the user for confirmation.
Some major modes customize `revert-buffer` by making buffer-local bindings for these variables:
Variable: **revert-buffer-function**
The value of this variable is the function to use to revert this buffer. It should be a function with two optional arguments to do the work of reverting. The two optional arguments, ignore-auto and noconfirm, are the arguments that `revert-buffer` received.
Modes such as Dired mode, in which the text being edited does not consist of a file’s contents but can be regenerated in some other fashion, can give this variable a buffer-local value that is a special function to regenerate the contents.
Variable: **revert-buffer-insert-file-contents-function**
The value of this variable specifies the function to use to insert the updated contents when reverting this buffer. The function receives two arguments: first the file name to use; second, `t` if the user has asked to read the auto-save file.
The reason for a mode to change this variable instead of `revert-buffer-function` is to avoid duplicating or replacing the rest of what `revert-buffer` does: asking for confirmation, clearing the undo list, deciding the proper major mode, and running the hooks listed below.
Variable: **before-revert-hook**
This normal hook is run by the default `revert-buffer-function` before inserting the modified contents. A custom `revert-buffer-function` may or may not run this hook.
Variable: **after-revert-hook**
This normal hook is run by the default `revert-buffer-function` after inserting the modified contents. A custom `revert-buffer-function` may or may not run this hook.
Emacs can revert buffers automatically. It does that by default for buffers visiting files. The following describes how to add support for auto-reverting new types of buffers.
First, such buffers must have a suitable `revert-buffer-function` and `buffer-stale-function` defined.
Variable: **buffer-stale-function**
The value of this variable specifies a function to call to check whether a buffer needs reverting. The default value only handles buffers that are visiting files, by checking their modification time. Buffers that are not visiting files require a custom function of one optional argument noconfirm. The function should return non-`nil` if the buffer should be reverted. The buffer is current when this function is called.
While this function is mainly intended for use in auto-reverting, it could be used for other purposes as well. For instance, if auto-reverting is not enabled, it could be used to warn the user that the buffer needs reverting. The idea behind the noconfirm argument is that it should be `t` if the buffer is going to be reverted without asking the user and `nil` if the function is just going to be used to warn the user that the buffer is out of date. In particular, for use in auto-reverting, noconfirm is `t`. If the function is only going to be used for auto-reverting, you can ignore the noconfirm argument.
If you just want to automatically auto-revert every `auto-revert-interval` seconds (like the Buffer Menu), use:
```
(setq-local buffer-stale-function
(lambda (&optional noconfirm) 'fast))
```
in the buffer’s mode function.
The special return value ‘`fast`’ tells the caller that the need for reverting was not checked, but that reverting the buffer is fast. It also tells Auto Revert not to print any revert messages, even if `auto-revert-verbose` is non-`nil`. This is important, as getting revert messages every `auto-revert-interval` seconds can be very annoying. The information provided by this return value could also be useful if the function is consulted for purposes other than auto-reverting.
Once the buffer has a suitable `revert-buffer-function` and `buffer-stale-function`, several problems usually remain.
The buffer will only auto-revert if it is marked unmodified. Hence, you will have to make sure that various functions mark the buffer modified if and only if either the buffer contains information that might be lost by reverting, or there is reason to believe that the user might be inconvenienced by auto-reverting, because he is actively working on the buffer. The user can always override this by manually adjusting the modified status of the buffer. To support this, calling the `revert-buffer-function` on a buffer that is marked unmodified should always keep the buffer marked unmodified.
It is important to assure that point does not continuously jump around as a consequence of auto-reverting. Of course, moving point might be inevitable if the buffer radically changes.
You should make sure that the `revert-buffer-function` does not print messages that unnecessarily duplicate Auto Revert’s own messages, displayed if `auto-revert-verbose` is `t`, and effectively override a `nil` value for `auto-revert-verbose`. Hence, adapting a mode for auto-reverting often involves getting rid of such messages. This is especially important for buffers that automatically revert every `auto-revert-interval` seconds.
If the new auto-reverting is part of Emacs, you should mention it in the documentation string of `global-auto-revert-non-file-buffers`.
Similarly, you should document the additions in the Emacs manual.
| programming_docs |
elisp None ### Other Topics Related to Functions
Here is a table of several functions that do things related to function calling and function definitions. They are documented elsewhere, but we provide cross references here.
`apply`
See [Calling Functions](calling-functions).
`autoload`
See [Autoload](autoload).
`call-interactively`
See [Interactive Call](interactive-call).
`called-interactively-p`
See [Distinguish Interactive](distinguish-interactive).
`commandp`
See [Interactive Call](interactive-call).
`documentation`
See [Accessing Documentation](accessing-documentation).
`eval`
See [Eval](eval).
`funcall`
See [Calling Functions](calling-functions).
`function`
See [Anonymous Functions](anonymous-functions).
`ignore`
See [Calling Functions](calling-functions).
`indirect-function`
See [Function Indirection](function-indirection).
`interactive`
See [Using Interactive](using-interactive).
`interactive-p`
See [Distinguish Interactive](distinguish-interactive).
`mapatoms`
See [Creating Symbols](creating-symbols).
`mapcar`
See [Mapping Functions](mapping-functions).
`map-char-table`
See [Char-Tables](char_002dtables).
`mapconcat`
See [Mapping Functions](mapping-functions).
`undefined` See [Functions for Key Lookup](functions-for-key-lookup).
elisp None ### Menu Keymaps
A keymap can operate as a menu as well as defining bindings for keyboard keys and mouse buttons. Menus are usually actuated with the mouse, but they can function with the keyboard also. If a menu keymap is active for the next input event, that activates the keyboard menu feature.
| | | |
| --- | --- | --- |
| • [Defining Menus](defining-menus) | | How to make a keymap that defines a menu. |
| • [Mouse Menus](mouse-menus) | | How users actuate the menu with the mouse. |
| • [Keyboard Menus](keyboard-menus) | | How users actuate the menu with the keyboard. |
| • [Menu Example](menu-example) | | Making a simple menu. |
| • [Menu Bar](menu-bar) | | How to customize the menu bar. |
| • [Tool Bar](tool-bar) | | A tool bar is a row of images. |
| • [Modifying Menus](modifying-menus) | | How to add new items to a menu. |
| • [Easy Menu](easy-menu) | | A convenience macro for making menus. |
elisp None #### Window Header Lines
A window can have a *header line* at the top, just as it can have a mode line at the bottom. The header line feature works just like the mode line feature, except that it’s controlled by `header-line-format`:
Variable: **header-line-format**
This variable, local in every buffer, specifies how to display the header line, for windows displaying the buffer. The format of the value is the same as for `mode-line-format` (see [Mode Line Data](mode-line-data)). It is normally `nil`, so that ordinary buffers have no header line.
Function: **window-header-line-height** *&optional window*
This function returns the height in pixels of window’s header line. window must be a live window, and defaults to the selected window.
A window that is just one line tall never displays a header line. A window that is two lines tall cannot display both a mode line and a header line at once; if it has a mode line, then it does not display a header line.
elisp None ### The Current Buffer
There are, in general, many buffers in an Emacs session. At any time, one of them is designated the *current buffer*—the buffer in which most editing takes place. Most of the primitives for examining or changing text operate implicitly on the current buffer (see [Text](text)).
Normally, the buffer displayed in the selected window (see [Selecting Windows](selecting-windows)) is the current buffer, but this is not always so: a Lisp program can temporarily designate any buffer as current in order to operate on its contents, without changing what is displayed on the screen. The most basic function for designating a current buffer is `set-buffer`.
Function: **current-buffer**
This function returns the current buffer.
```
(current-buffer)
⇒ #<buffer buffers.texi>
```
Function: **set-buffer** *buffer-or-name*
This function makes buffer-or-name the current buffer. buffer-or-name must be an existing buffer or the name of an existing buffer. The return value is the buffer made current.
This function does not display the buffer in any window, so the user cannot necessarily see the buffer. But Lisp programs will now operate on it.
When an editing command returns to the editor command loop, Emacs automatically calls `set-buffer` on the buffer shown in the selected window (see [Selecting Windows](selecting-windows)). This is to prevent confusion: it ensures that the buffer that the cursor is in, when Emacs reads a command, is the buffer to which that command applies (see [Command Loop](command-loop)). Thus, you should not use `set-buffer` to switch visibly to a different buffer; for that, use the functions described in [Switching Buffers](switching-buffers).
When writing a Lisp function, do *not* rely on this behavior of the command loop to restore the current buffer after an operation. Editing commands can also be called as Lisp functions by other programs, not just from the command loop; it is convenient for the caller if the subroutine does not change which buffer is current (unless, of course, that is the subroutine’s purpose).
To operate temporarily on another buffer, put the `set-buffer` within a `save-current-buffer` form. Here, as an example, is a simplified version of the command `append-to-buffer`:
```
(defun append-to-buffer (buffer start end)
"Append the text of the region to BUFFER."
(interactive "BAppend to buffer: \nr")
(let ((oldbuf (current-buffer)))
(save-current-buffer
(set-buffer (get-buffer-create buffer))
(insert-buffer-substring oldbuf start end))))
```
Here, we bind a local variable to record the current buffer, and then `save-current-buffer` arranges to make it current again later. Next, `set-buffer` makes the specified buffer current, and `insert-buffer-substring` copies the string from the original buffer to the specified (and now current) buffer.
Alternatively, we can use the `with-current-buffer` macro:
```
(defun append-to-buffer (buffer start end)
"Append the text of the region to BUFFER."
(interactive "BAppend to buffer: \nr")
(let ((oldbuf (current-buffer)))
(with-current-buffer (get-buffer-create buffer)
(insert-buffer-substring oldbuf start end))))
```
In either case, if the buffer appended to happens to be displayed in some window, the next redisplay will show how its text has changed. If it is not displayed in any window, you will not see the change immediately on the screen. The command causes the buffer to become current temporarily, but does not cause it to be displayed.
If you make local bindings (with `let` or function arguments) for a variable that may also have buffer-local bindings, make sure that the same buffer is current at the beginning and at the end of the local binding’s scope. Otherwise you might bind it in one buffer and unbind it in another!
Do not rely on using `set-buffer` to change the current buffer back, because that won’t do the job if a quit happens while the wrong buffer is current. For instance, in the previous example, it would have been wrong to do this:
```
(let ((oldbuf (current-buffer)))
(set-buffer (get-buffer-create buffer))
(insert-buffer-substring oldbuf start end)
(set-buffer oldbuf))
```
Using `save-current-buffer` or `with-current-buffer`, as we did, correctly handles quitting, errors, and `throw`, as well as ordinary evaluation.
Special Form: **save-current-buffer** *body…*
The `save-current-buffer` special form saves the identity of the current buffer, evaluates the body forms, and finally restores that buffer as current. The return value is the value of the last form in body. The current buffer is restored even in case of an abnormal exit via `throw` or error (see [Nonlocal Exits](nonlocal-exits)).
If the buffer that used to be current has been killed by the time of exit from `save-current-buffer`, then it is not made current again, of course. Instead, whichever buffer was current just before exit remains current.
Macro: **with-current-buffer** *buffer-or-name body…*
The `with-current-buffer` macro saves the identity of the current buffer, makes buffer-or-name current, evaluates the body forms, and finally restores the current buffer. buffer-or-name must specify an existing buffer or the name of an existing buffer.
The return value is the value of the last form in body. The current buffer is restored even in case of an abnormal exit via `throw` or error (see [Nonlocal Exits](nonlocal-exits)).
Macro: **with-temp-buffer** *body…*
The `with-temp-buffer` macro evaluates the body forms with a temporary buffer as the current buffer. It saves the identity of the current buffer, creates a temporary buffer and makes it current, evaluates the body forms, and finally restores the previous current buffer while killing the temporary buffer.
By default, undo information (see [Undo](undo)) is not recorded in the buffer created by this macro (but body can enable that, if needed). The temporary buffer also does not run the hooks `kill-buffer-hook`, `kill-buffer-query-functions` (see [Killing Buffers](killing-buffers)), and `buffer-list-update-hook` (see [Buffer List](buffer-list)).
The return value is the value of the last form in body. You can return the contents of the temporary buffer by using `(buffer-string)` as the last form.
The current buffer is restored even in case of an abnormal exit via `throw` or error (see [Nonlocal Exits](nonlocal-exits)).
See also `with-temp-file` in [Writing to Files](writing-to-files#Definition-of-with_002dtemp_002dfile).
elisp None #### Trapping Errors
Emacs normally displays an error message when an error is signaled and not handled with `condition-case`. While Edebug is active and executing instrumented code, it normally responds to all unhandled errors. You can customize this with the options `edebug-on-error` and `edebug-on-quit`; see [Edebug Options](edebug-options).
When Edebug responds to an error, it shows the last stop point encountered before the error. This may be the location of a call to a function which was not instrumented, and within which the error actually occurred. For an unbound variable error, the last known stop point might be quite distant from the offending variable reference. In that case, you might want to display a full backtrace (see [Edebug Misc](edebug-misc)).
If you change `debug-on-error` or `debug-on-quit` while Edebug is active, these changes will be forgotten when Edebug becomes inactive. Furthermore, during Edebug’s recursive edit, these variables are bound to the values they had outside of Edebug.
elisp None #### Internals of the Kill Ring
The variable `kill-ring` holds the kill ring contents, in the form of a list of strings. The most recent kill is always at the front of the list.
The `kill-ring-yank-pointer` variable points to a link in the kill ring list, whose CAR is the text to yank next. We say it identifies the front of the ring. Moving `kill-ring-yank-pointer` to a different link is called *rotating the kill ring*. We call the kill ring a “ring” because the functions that move the yank pointer wrap around from the end of the list to the beginning, or vice-versa. Rotation of the kill ring is virtual; it does not change the value of `kill-ring`.
Both `kill-ring` and `kill-ring-yank-pointer` are Lisp variables whose values are normally lists. The word “pointer” in the name of the `kill-ring-yank-pointer` indicates that the variable’s purpose is to identify one element of the list for use by the next yank command.
The value of `kill-ring-yank-pointer` is always `eq` to one of the links in the kill ring list. The element it identifies is the CAR of that link. Kill commands, which change the kill ring, also set this variable to the value of `kill-ring`. The effect is to rotate the ring so that the newly killed text is at the front.
Here is a diagram that shows the variable `kill-ring-yank-pointer` pointing to the second entry in the kill ring `("some text" "a
different piece of text" "yet older text")`.
```
kill-ring ---- kill-ring-yank-pointer
| |
| v
| --- --- --- --- --- ---
--> | | |------> | | |--> | | |--> nil
--- --- --- --- --- ---
| | |
| | |
| | -->"yet older text"
| |
| --> "a different piece of text"
|
--> "some text"
```
This state of affairs might occur after `C-y` (`yank`) immediately followed by `M-y` (`yank-pop`).
Variable: **kill-ring**
This variable holds the list of killed text sequences, most recently killed first.
Variable: **kill-ring-yank-pointer**
This variable’s value indicates which element of the kill ring is at the front of the ring for yanking. More precisely, the value is a tail of the value of `kill-ring`, and its CAR is the kill string that `C-y` should yank.
User Option: **kill-ring-max**
The value of this variable is the maximum length to which the kill ring can grow, before elements are thrown away at the end. The default value for `kill-ring-max` is 60.
elisp None #### Basic Faces
If your Emacs Lisp program needs to assign some faces to text, it is often a good idea to use certain existing faces or inherit from them, rather than defining entirely new faces. This way, if other users have customized the basic faces to give Emacs a certain look, your program will fit in without additional customization.
Some of the basic faces defined in Emacs are listed below. In addition to these, you might want to make use of the Font Lock faces for syntactic highlighting, if highlighting is not already handled by Font Lock mode, or if some Font Lock faces are not in use. See [Faces for Font Lock](faces-for-font-lock).
`default`
The default face, whose attributes are all specified. All other faces implicitly inherit from it: any unspecified attribute defaults to the attribute on this face (see [Face Attributes](face-attributes)).
`bold` `italic` `bold-italic` `underline` `fixed-pitch` `fixed-pitch-serif` `variable-pitch`
These have the attributes indicated by their names (e.g., `bold` has a bold `:weight` attribute), with all other attributes unspecified (and so given by `default`).
`shadow`
For dimmed-out text. For example, it is used for the ignored part of a filename in the minibuffer (see [Minibuffers for File Names](https://www.gnu.org/software/emacs/manual/html_node/emacs/Minibuffer-File.html#Minibuffer-File) in The GNU Emacs Manual).
`link` `link-visited`
For clickable text buttons that send the user to a different buffer or location.
`highlight`
For stretches of text that should temporarily stand out. For example, it is commonly assigned to the `mouse-face` property for cursor highlighting (see [Special Properties](special-properties)).
`match` `isearch` `lazy-highlight`
For text matching (respectively) permanent search matches, interactive search matches, and lazy highlighting other matches than the current interactive one.
`error` `warning` `success` For text concerning errors, warnings, or successes. For example, these are used for messages in `\*Compilation\*` buffers.
elisp None ### The Lisp Debugger
The ordinary *Lisp debugger* provides the ability to suspend evaluation of a form. While evaluation is suspended (a state that is commonly known as a *break*), you may examine the run time stack, examine the values of local or global variables, or change those values. Since a break is a recursive edit, all the usual editing facilities of Emacs are available; you can even run programs that will enter the debugger recursively. See [Recursive Editing](recursive-editing).
| | | |
| --- | --- | --- |
| • [Error Debugging](error-debugging) | | Entering the debugger when an error happens. |
| • [Infinite Loops](infinite-loops) | | Stopping and debugging a program that doesn’t exit. |
| • [Function Debugging](function-debugging) | | Entering it when a certain function is called. |
| • [Variable Debugging](variable-debugging) | | Entering it when a variable is modified. |
| • [Explicit Debug](explicit-debug) | | Entering it at a certain point in the program. |
| • [Using Debugger](using-debugger) | | What the debugger does. |
| • [Backtraces](backtraces) | | What you see while in the debugger. |
| • [Debugger Commands](debugger-commands) | | Commands used while in the debugger. |
| • [Invoking the Debugger](invoking-the-debugger) | | How to call the function `debug`. |
| • [Internals of Debugger](internals-of-debugger) | | Subroutines of the debugger, and global variables. |
elisp None ### Programming Types
There are two general categories of types in Emacs Lisp: those having to do with Lisp programming, and those having to do with editing. The former exist in many Lisp implementations, in one form or another. The latter are unique to Emacs Lisp.
| | | |
| --- | --- | --- |
| • [Integer Type](integer-type) | | Numbers without fractional parts. |
| • [Floating-Point Type](floating_002dpoint-type) | | Numbers with fractional parts and with a large range. |
| • [Character Type](character-type) | | The representation of letters, numbers and control characters. |
| • [Symbol Type](symbol-type) | | A multi-use object that refers to a function, variable, or property list, and has a unique identity. |
| • [Sequence Type](sequence-type) | | Both lists and arrays are classified as sequences. |
| • [Cons Cell Type](cons-cell-type) | | Cons cells, and lists (which are made from cons cells). |
| • [Array Type](array-type) | | Arrays include strings and vectors. |
| • [String Type](string-type) | | An (efficient) array of characters. |
| • [Vector Type](vector-type) | | One-dimensional arrays. |
| • [Char-Table Type](char_002dtable-type) | | One-dimensional sparse arrays indexed by characters. |
| • [Bool-Vector Type](bool_002dvector-type) | | One-dimensional arrays of `t` or `nil`. |
| • [Hash Table Type](hash-table-type) | | Super-fast lookup tables. |
| • [Function Type](function-type) | | A piece of executable code you can call from elsewhere. |
| • [Macro Type](macro-type) | | A method of expanding an expression into another expression, more fundamental but less pretty. |
| • [Primitive Function Type](primitive-function-type) | | A function written in C, callable from Lisp. |
| • [Byte-Code Type](byte_002dcode-type) | | A function written in Lisp, then compiled. |
| • [Record Type](record-type) | | Compound objects with programmer-defined types. |
| • [Type Descriptors](type-descriptors) | | Objects holding information about types. |
| • [Autoload Type](autoload-type) | | A type used for automatically loading seldom-used functions. |
| • [Finalizer Type](finalizer-type) | | Runs code when no longer reachable. |
| |
elisp None #### When to Use Autoload
Do not add an autoload comment unless it is really necessary. Autoloading code means it is always globally visible. Once an item is autoloaded, there is no compatible way to transition back to it not being autoloaded (after people become accustomed to being able to use it without an explicit load).
* The most common items to autoload are the interactive entry points to a library. For example, if `python.el` is a library defining a major-mode for editing Python code, autoload the definition of the `python-mode` function, so that people can simply use `M-x python-mode` to load the library.
* Variables usually don’t need to be autoloaded. An exception is if the variable on its own is generally useful without the whole defining library being loaded. (An example of this might be something like `find-exec-terminator`.)
* Don’t autoload a user option just so that a user can set it.
* Never add an autoload *comment* to silence a compiler warning in another file. In the file that produces the warning, use `(defvar foo)` to silence an undefined variable warning, and `declare-function` (see [Declaring Functions](declaring-functions)) to silence an undefined function warning; or require the relevant library; or use an explicit autoload *statement*.
| programming_docs |
elisp None Buffers
-------
A *buffer* is a Lisp object containing text to be edited. Buffers are used to hold the contents of files that are being visited; there may also be buffers that are not visiting files. While several buffers may exist at one time, only one buffer is designated the *current buffer* at any time. Most editing commands act on the contents of the current buffer. Each buffer, including the current buffer, may or may not be displayed in any windows.
| | | |
| --- | --- | --- |
| • [Buffer Basics](buffer-basics) | | What is a buffer? |
| • [Current Buffer](current-buffer) | | Designating a buffer as current so that primitives will access its contents. |
| • [Buffer Names](buffer-names) | | Accessing and changing buffer names. |
| • [Buffer File Name](buffer-file-name) | | The buffer file name indicates which file is visited. |
| • [Buffer Modification](buffer-modification) | | A buffer is *modified* if it needs to be saved. |
| • [Modification Time](modification-time) | | Determining whether the visited file was changed behind Emacs’s back. |
| • [Read Only Buffers](read-only-buffers) | | Modifying text is not allowed in a read-only buffer. |
| • [Buffer List](buffer-list) | | How to look at all the existing buffers. |
| • [Creating Buffers](creating-buffers) | | Functions that create buffers. |
| • [Killing Buffers](killing-buffers) | | Buffers exist until explicitly killed. |
| • [Indirect Buffers](indirect-buffers) | | An indirect buffer shares text with some other buffer. |
| • [Swapping Text](swapping-text) | | Swapping text between two buffers. |
| • [Buffer Gap](buffer-gap) | | The gap in the buffer. |
elisp None #### Writing Code to Handle Errors
The usual effect of signaling an error is to terminate the command that is running and return immediately to the Emacs editor command loop. You can arrange to trap errors occurring in a part of your program by establishing an error handler, with the special form `condition-case`. A simple example looks like this:
```
(condition-case nil
(delete-file filename)
(error nil))
```
This deletes the file named filename, catching any error and returning `nil` if an error occurs. (You can use the macro `ignore-errors` for a simple case like this; see below.)
The `condition-case` construct is often used to trap errors that are predictable, such as failure to open a file in a call to `insert-file-contents`. It is also used to trap errors that are totally unpredictable, such as when the program evaluates an expression read from the user.
The second argument of `condition-case` is called the *protected form*. (In the example above, the protected form is a call to `delete-file`.) The error handlers go into effect when this form begins execution and are deactivated when this form returns. They remain in effect for all the intervening time. In particular, they are in effect during the execution of functions called by this form, in their subroutines, and so on. This is a good thing, since, strictly speaking, errors can be signaled only by Lisp primitives (including `signal` and `error`) called by the protected form, not by the protected form itself.
The arguments after the protected form are handlers. Each handler lists one or more *condition names* (which are symbols) to specify which errors it will handle. The error symbol specified when an error is signaled also defines a list of condition names. A handler applies to an error if they have any condition names in common. In the example above, there is one handler, and it specifies one condition name, `error`, which covers all errors.
The search for an applicable handler checks all the established handlers starting with the most recently established one. Thus, if two nested `condition-case` forms offer to handle the same error, the inner of the two gets to handle it.
If an error is handled by some `condition-case` form, this ordinarily prevents the debugger from being run, even if `debug-on-error` says this error should invoke the debugger.
If you want to be able to debug errors that are caught by a `condition-case`, set the variable `debug-on-signal` to a non-`nil` value. You can also specify that a particular handler should let the debugger run first, by writing `debug` among the conditions, like this:
```
(condition-case nil
(delete-file filename)
((debug error) nil))
```
The effect of `debug` here is only to prevent `condition-case` from suppressing the call to the debugger. Any given error will invoke the debugger only if `debug-on-error` and the other usual filtering mechanisms say it should. See [Error Debugging](error-debugging).
Macro: **condition-case-unless-debug** *var protected-form handlers…*
The macro `condition-case-unless-debug` provides another way to handle debugging of such forms. It behaves exactly like `condition-case`, unless the variable `debug-on-error` is non-`nil`, in which case it does not handle any errors at all.
Once Emacs decides that a certain handler handles the error, it returns control to that handler. To do so, Emacs unbinds all variable bindings made by binding constructs that are being exited, and executes the cleanups of all `unwind-protect` forms that are being exited. Once control arrives at the handler, the body of the handler executes normally.
After execution of the handler body, execution returns from the `condition-case` form. Because the protected form is exited completely before execution of the handler, the handler cannot resume execution at the point of the error, nor can it examine variable bindings that were made within the protected form. All it can do is clean up and proceed.
Error signaling and handling have some resemblance to `throw` and `catch` (see [Catch and Throw](catch-and-throw)), but they are entirely separate facilities. An error cannot be caught by a `catch`, and a `throw` cannot be handled by an error handler (though using `throw` when there is no suitable `catch` signals an error that can be handled).
Special Form: **condition-case** *var protected-form handlers…*
This special form establishes the error handlers handlers around the execution of protected-form. If protected-form executes without error, the value it returns becomes the value of the `condition-case` form (in the absence of a success handler; see below). In this case, the `condition-case` has no effect. The `condition-case` form makes a difference when an error occurs during protected-form.
Each of the handlers is a list of the form `(conditions
body…)`. Here conditions is an error condition name to be handled, or a list of condition names (which can include `debug` to allow the debugger to run before the handler). A condition name of `t` matches any condition. body is one or more Lisp expressions to be executed when this handler handles an error. Here are examples of handlers:
```
(error nil)
(arith-error (message "Division by zero"))
((arith-error file-error)
(message
"Either division by zero or failure to open a file"))
```
Each error that occurs has an *error symbol* that describes what kind of error it is, and which describes also a list of condition names (see [Error Symbols](error-symbols)). Emacs searches all the active `condition-case` forms for a handler that specifies one or more of these condition names; the innermost matching `condition-case` handles the error. Within this `condition-case`, the first applicable handler handles the error.
After executing the body of the handler, the `condition-case` returns normally, using the value of the last form in the handler body as the overall value.
The argument var is a variable. `condition-case` does not bind this variable when executing the protected-form, only when it handles an error. At that time, it binds var locally to an *error description*, which is a list giving the particulars of the error. The error description has the form `(error-symbol
. data)`. The handler can refer to this list to decide what to do. For example, if the error is for failure opening a file, the file name is the second element of data—the third element of the error description.
If var is `nil`, that means no variable is bound. Then the error symbol and associated data are not available to the handler.
As a special case, one of the handlers can be a list of the form `(:success body…)`, where body is executed with var (if non-`nil`) bound to the return value of protected-form when that expression terminates without error.
Sometimes it is necessary to re-throw a signal caught by `condition-case`, for some outer-level handler to catch. Here’s how to do that:
```
(signal (car err) (cdr err))
```
where `err` is the error description variable, the first argument to `condition-case` whose error condition you want to re-throw. See [Definition of signal](signaling-errors#Definition-of-signal).
Function: **error-message-string** *error-descriptor*
This function returns the error message string for a given error descriptor. It is useful if you want to handle an error by printing the usual error message for that error. See [Definition of signal](signaling-errors#Definition-of-signal).
Here is an example of using `condition-case` to handle the error that results from dividing by zero. The handler displays the error message (but without a beep), then returns a very large number.
```
(defun safe-divide (dividend divisor)
(condition-case err
;; Protected form.
(/ dividend divisor)
```
```
;; The handler.
(arith-error ; Condition.
;; Display the usual message for this error.
(message "%s" (error-message-string err))
1000000)))
⇒ safe-divide
```
```
(safe-divide 5 0)
-| Arithmetic error: (arith-error)
⇒ 1000000
```
The handler specifies condition name `arith-error` so that it will handle only division-by-zero errors. Other kinds of errors will not be handled (by this `condition-case`). Thus:
```
(safe-divide nil 3)
error→ Wrong type argument: number-or-marker-p, nil
```
Here is a `condition-case` that catches all kinds of errors, including those from `error`:
```
(setq baz 34)
⇒ 34
```
```
(condition-case err
(if (eq baz 35)
t
;; This is a call to the function `error`.
(error "Rats! The variable %s was %s, not 35" 'baz baz))
;; This is the handler; it is not a form.
(error (princ (format "The error was: %s" err))
2))
-| The error was: (error "Rats! The variable baz was 34, not 35")
⇒ 2
```
Macro: **ignore-errors** *body…*
This construct executes body, ignoring any errors that occur during its execution. If the execution is without error, `ignore-errors` returns the value of the last form in body; otherwise, it returns `nil`.
Here’s the example at the beginning of this subsection rewritten using `ignore-errors`:
```
(ignore-errors
(delete-file filename))
```
Macro: **ignore-error** *condition body…*
This macro is like `ignore-errors`, but will only ignore the specific error condition specified.
```
(ignore-error end-of-file
(read ""))
```
condition can also be a list of error conditions.
Macro: **with-demoted-errors** *format body…*
This macro is like a milder version of `ignore-errors`. Rather than suppressing errors altogether, it converts them into messages. It uses the string format to format the message. format should contain a single ‘`%`’-sequence; e.g., `"Error: %S"`. Use `with-demoted-errors` around code that is not expected to signal errors, but should be robust if one does occur. Note that this macro uses `condition-case-unless-debug` rather than `condition-case`.
elisp None ### Reading Text Strings with the Minibuffer
The most basic primitive for minibuffer input is `read-from-minibuffer`, which can be used to read either a string or a Lisp object in textual form. The function `read-regexp` is used for reading regular expressions (see [Regular Expressions](regular-expressions)), which are a special kind of string. There are also specialized functions for reading commands, variables, file names, etc. (see [Completion](completion)).
In most cases, you should not call minibuffer input functions in the middle of a Lisp function. Instead, do all minibuffer input as part of reading the arguments for a command, in the `interactive` specification. See [Defining Commands](defining-commands).
Function: **read-from-minibuffer** *prompt &optional initial keymap read history default inherit-input-method*
This function is the most general way to get input from the minibuffer. By default, it accepts arbitrary text and returns it as a string; however, if read is non-`nil`, then it uses `read` to convert the text into a Lisp object (see [Input Functions](input-functions)).
The first thing this function does is to activate a minibuffer and display it with prompt (which must be a string) as the prompt. Then the user can edit text in the minibuffer.
When the user types a command to exit the minibuffer, `read-from-minibuffer` constructs the return value from the text in the minibuffer. Normally it returns a string containing that text. However, if read is non-`nil`, `read-from-minibuffer` reads the text and returns the resulting Lisp object, unevaluated. (See [Input Functions](input-functions), for information about reading.)
The argument default specifies default values to make available through the history commands. It should be a string, a list of strings, or `nil`. The string or strings become the minibuffer’s “future history”, available to the user with `M-n`.
If read is non-`nil`, then default is also used as the input to `read`, if the user enters empty input. If default is a list of strings, the first string is used as the input. If default is `nil`, empty input results in an `end-of-file` error. However, in the usual case (where read is `nil`), `read-from-minibuffer` ignores default when the user enters empty input and returns an empty string, `""`. In this respect, it differs from all the other minibuffer input functions in this chapter.
If keymap is non-`nil`, that keymap is the local keymap to use in the minibuffer. If keymap is omitted or `nil`, the value of `minibuffer-local-map` is used as the keymap. Specifying a keymap is the most important way to customize the minibuffer for various applications such as completion.
The argument history specifies a history list variable to use for saving the input and for history commands used in the minibuffer. It defaults to `minibuffer-history`. If history is the symbol `t`, history is not recorded. You can optionally specify a starting position in the history list as well. See [Minibuffer History](minibuffer-history).
If the variable `minibuffer-allow-text-properties` is non-`nil`, then the string that is returned includes whatever text properties were present in the minibuffer. Otherwise all the text properties are stripped when the value is returned.
The text properties in `minibuffer-prompt-properties` are applied to the prompt. By default, this property list defines a face to use for the prompt. This face, if present, is applied to the end of the face list and merged before display.
If the user wants to completely control the look of the prompt, the most convenient way to do that is to specify the `default` face at the end of all face lists. For instance:
```
(read-from-minibuffer
(concat
(propertize "Bold" 'face '(bold default))
(propertize " and normal: " 'face '(default))))
```
If the argument inherit-input-method is non-`nil`, then the minibuffer inherits the current input method (see [Input Methods](input-methods)) and the setting of `enable-multibyte-characters` (see [Text Representations](text-representations)) from whichever buffer was current before entering the minibuffer.
Use of initial is mostly deprecated; we recommend using a non-`nil` value only in conjunction with specifying a cons cell for history. See [Initial Input](initial-input).
Function: **read-string** *prompt &optional initial history default inherit-input-method*
This function reads a string from the minibuffer and returns it. The arguments prompt, initial, history and inherit-input-method are used as in `read-from-minibuffer`. The keymap used is `minibuffer-local-map`.
The optional argument default is used as in `read-from-minibuffer`, except that, if non-`nil`, it also specifies a default value to return if the user enters null input. As in `read-from-minibuffer` it should be a string, a list of strings, or `nil`, which is equivalent to an empty string. When default is a string, that string is the default value. When it is a list of strings, the first string is the default value. (All these strings are available to the user in the “future minibuffer history”.)
This function works by calling the `read-from-minibuffer` function:
```
(read-string prompt initial history default inherit)
≡
(let ((value
(read-from-minibuffer prompt initial nil nil
history default inherit)))
(if (and (equal value "") default)
(if (consp default) (car default) default)
value))
```
Function: **read-regexp** *prompt &optional defaults history*
This function reads a regular expression as a string from the minibuffer and returns it. If the minibuffer prompt string prompt does not end in ‘`:`’ (followed by optional whitespace), the function adds ‘`:` ’ to the end, preceded by the default return value (see below), if that is non-empty.
The optional argument defaults controls the default value to return if the user enters null input, and should be one of: a string; `nil`, which is equivalent to an empty string; a list of strings; or a symbol.
If defaults is a symbol, `read-regexp` consults the value of the variable `read-regexp-defaults-function` (see below), and if that is non-`nil` uses it in preference to defaults. The value in this case should be either:
* - `regexp-history-last`, which means to use the first element of the appropriate minibuffer history list (see below).
* - A function of no arguments, whose return value (which should be `nil`, a string, or a list of strings) becomes the value of defaults.
`read-regexp` now ensures that the result of processing defaults is a list (i.e., if the value is `nil` or a string, it converts it to a list of one element). To this list, `read-regexp` then appends a few potentially useful candidates for input. These are:
* - The word or symbol at point.
* - The last regexp used in an incremental search.
* - The last string used in an incremental search.
* - The last string or pattern used in query-replace commands.
The function now has a list of regular expressions that it passes to `read-from-minibuffer` to obtain the user’s input. The first element of the list is the default result in case of empty input. All elements of the list are available to the user as the “future minibuffer history” list (see [future list](https://www.gnu.org/software/emacs/manual/html_node/emacs/Minibuffer-History.html#Minibuffer-History) in The GNU Emacs Manual).
The optional argument history, if non-`nil`, is a symbol specifying a minibuffer history list to use (see [Minibuffer History](minibuffer-history)). If it is omitted or `nil`, the history list defaults to `regexp-history`.
User Option: **read-regexp-defaults-function**
The function `read-regexp` may use the value of this variable to determine its list of default regular expressions. If non-`nil`, the value of this variable should be either:
* - The symbol `regexp-history-last`.
* - A function of no arguments that returns either `nil`, a string, or a list of strings.
See `read-regexp` above for details of how these values are used.
Variable: **minibuffer-allow-text-properties**
If this variable is `nil`, then `read-from-minibuffer` and `read-string` strip all text properties from the minibuffer input before returning it. However, `read-no-blanks-input` (see below), as well as `read-minibuffer` and related functions (see [Reading Lisp Objects With the Minibuffer](object-from-minibuffer)), and all functions that do minibuffer input with completion, remove the `face` property unconditionally, regardless of the value of this variable.
If this variable is non-`nil`, most text properties on strings from the completion table are preserved—but only on the part of the strings that were completed.
```
(let ((minibuffer-allow-text-properties t))
(completing-read "String: " (list (propertize "foobar" 'data 'zot))))
=> #("foobar" 3 6 (data zot))
```
In this example, the user typed ‘`foo`’ and then hit the `TAB` key, so the text properties are only preserved on the last three characters.
Variable: **minibuffer-local-map**
This is the default local keymap for reading from the minibuffer. By default, it makes the following bindings:
`C-j`
`exit-minibuffer`
RET
`exit-minibuffer`
`M-<`
`minibuffer-beginning-of-buffer`
`C-g`
`abort-recursive-edit`
`M-n` DOWN
`next-history-element`
`M-p` UP
`previous-history-element`
`M-s`
`next-matching-history-element`
`M-r`
`previous-matching-history-element`
Function: **read-no-blanks-input** *prompt &optional initial inherit-input-method*
This function reads a string from the minibuffer, but does not allow whitespace characters as part of the input: instead, those characters terminate the input. The arguments prompt, initial, and inherit-input-method are used as in `read-from-minibuffer`.
This is a simplified interface to the `read-from-minibuffer` function, and passes the value of the `minibuffer-local-ns-map` keymap as the keymap argument for that function. Since the keymap `minibuffer-local-ns-map` does not rebind `C-q`, it *is* possible to put a space into the string, by quoting it.
This function discards text properties, regardless of the value of `minibuffer-allow-text-properties`.
```
(read-no-blanks-input prompt initial)
≡
(let (minibuffer-allow-text-properties)
(read-from-minibuffer prompt initial minibuffer-local-ns-map))
```
Variable: **minibuffer-local-ns-map**
This built-in variable is the keymap used as the minibuffer local keymap in the function `read-no-blanks-input`. By default, it makes the following bindings, in addition to those of `minibuffer-local-map`:
SPC
`exit-minibuffer`
TAB
`exit-minibuffer`
`?`
`self-insert-and-exit`
Function: **format-prompt** *prompt default &rest format-args*
Format prompt with default value default according to the `minibuffer-default-prompt-format` variable.
`minibuffer-default-prompt-format` is a format string (defaulting to ‘`" (default %s)"`’ that says how the “default” bit in prompts like ‘`"Local filename (default somefile): "`’ are to be formatted.
To allow the users to customize how this is displayed, code that prompts the user for a value (and has a default) should look something along the lines of this code snippet:
```
(read-file-name
(format-prompt "Local filename" file)
nil file)
```
If format-args is `nil`, prompt is used as a literal string. If format-args is non-`nil`, prompt is used as a format control string, and prompt and format-args are passed to `format` (see [Formatting Strings](formatting-strings)).
`minibuffer-default-prompt-format` can be ‘`""`’, in which case no default values are displayed.
If default is `nil`, there is no default value, and therefore no “default value” string is included in the result value. If default is a non-`nil` list, the first element of the list is used in the prompt.
Variable: **read-minibuffer-restore-windows**
If this option is non-`nil` (the default), getting input from the minibuffer will restore, on exit, the window configurations of the frame where the minibuffer was entered from and, if it is different, the frame that owns the minibuffer window. This means that if, for example, a user splits a window while getting input from the minibuffer on the same frame, that split will be undone when exiting the minibuffer.
If this option is `nil`, no such restorations are done. Hence, the window split mentioned above will persist after exiting the minibuffer.
| programming_docs |
elisp None ### Buffer Basics
A *buffer* is a Lisp object containing text to be edited. Buffers are used to hold the contents of files that are being visited; there may also be buffers that are not visiting files. Although several buffers normally exist, only one buffer is designated the *current buffer* at any time. Most editing commands act on the contents of the current buffer. Each buffer, including the current buffer, may or may not be displayed in any windows.
Buffers in Emacs editing are objects that have distinct names and hold text that can be edited. Buffers appear to Lisp programs as a special data type. You can think of the contents of a buffer as a string that you can extend; insertions and deletions may occur in any part of the buffer. See [Text](text).
A Lisp buffer object contains numerous pieces of information. Some of this information is directly accessible to the programmer through variables, while other information is accessible only through special-purpose functions. For example, the visited file name is directly accessible through a variable, while the value of point is accessible only through a primitive function.
Buffer-specific information that is directly accessible is stored in *buffer-local* variable bindings, which are variable values that are effective only in a particular buffer. This feature allows each buffer to override the values of certain variables. Most major modes override variables such as `fill-column` or `comment-column` in this way. For more information about buffer-local variables and functions related to them, see [Buffer-Local Variables](buffer_002dlocal-variables).
For functions and variables related to visiting files in buffers, see [Visiting Files](visiting-files) and [Saving Buffers](saving-buffers). For functions and variables related to the display of buffers in windows, see [Buffers and Windows](buffers-and-windows).
Function: **bufferp** *object*
This function returns `t` if object is a buffer, `nil` otherwise.
elisp None ### Variables with Restricted Values
Ordinary Lisp variables can be assigned any value that is a valid Lisp object. However, certain Lisp variables are not defined in Lisp, but in C. Most of these variables are defined in the C code using `DEFVAR_LISP`. Like variables defined in Lisp, these can take on any value. However, some variables are defined using `DEFVAR_INT` or `DEFVAR_BOOL`. See [Writing Emacs Primitives](writing-emacs-primitives#Defining-Lisp-variables-in-C), in particular the description of functions of the type `syms_of_filename`, for a brief discussion of the C implementation.
Variables of type `DEFVAR_BOOL` can only take on the values `nil` or `t`. Attempting to assign them any other value will set them to `t`:
```
(let ((display-hourglass 5))
display-hourglass)
⇒ t
```
Variable: **byte-boolean-vars**
This variable holds a list of all variables of type `DEFVAR_BOOL`.
Variables of type `DEFVAR_INT` can take on only integer values. Attempting to assign them any other value will result in an error:
```
(setq undo-limit 1000.0)
error→ Wrong type argument: integerp, 1000.0
```
elisp None ### Remapping Commands
A special kind of key binding can be used to *remap* one command to another, without having to refer to the key sequence(s) bound to the original command. To use this feature, make a key binding for a key sequence that starts with the dummy event `remap`, followed by the command name you want to remap; for the binding, specify the new definition (usually a command name, but possibly any other valid definition for a key binding).
For example, suppose My mode provides a special command `my-kill-line`, which should be invoked instead of `kill-line`. To establish this, its mode keymap should contain the following remapping:
```
(define-key my-mode-map [remap kill-line] 'my-kill-line)
```
Then, whenever `my-mode-map` is active, if the user types `C-k` (the default global key sequence for `kill-line`) Emacs will instead run `my-kill-line`.
Note that remapping only takes place through active keymaps; for example, putting a remapping in a prefix keymap like `ctl-x-map` typically has no effect, as such keymaps are not themselves active. In addition, remapping only works through a single level; in the following example,
```
(define-key my-mode-map [remap kill-line] 'my-kill-line)
(define-key my-mode-map [remap my-kill-line] 'my-other-kill-line)
```
`kill-line` is *not* remapped to `my-other-kill-line`. Instead, if an ordinary key binding specifies `kill-line`, it is remapped to `my-kill-line`; if an ordinary binding specifies `my-kill-line`, it is remapped to `my-other-kill-line`.
To undo the remapping of a command, remap it to `nil`; e.g.,
```
(define-key my-mode-map [remap kill-line] nil)
```
Function: **command-remapping** *command &optional position keymaps*
This function returns the remapping for command (a symbol), given the current active keymaps. If command is not remapped (which is the usual situation), or not a symbol, the function returns `nil`. `position` can optionally specify a buffer position or an event position to determine the keymaps to use, as in `key-binding`.
If the optional argument `keymaps` is non-`nil`, it specifies a list of keymaps to search in. This argument is ignored if `position` is non-`nil`.
elisp None ### Idle Timers
Here is how to set up a timer that runs when Emacs is idle for a certain length of time. Aside from how to set them up, idle timers work just like ordinary timers.
Command: **run-with-idle-timer** *secs repeat function &rest args*
Set up a timer which runs the next time Emacs is idle for secs seconds. The value of secs may be a number or a value of the type returned by `current-idle-time`.
If repeat is `nil`, the timer runs just once, the first time Emacs remains idle for a long enough time. More often repeat is non-`nil`, which means to run the timer *each time* Emacs remains idle for secs seconds.
The function `run-with-idle-timer` returns a timer value which you can use in calling `cancel-timer` (see [Timers](timers)).
Emacs becomes *idle* when it starts waiting for user input (unless it waits for input with a timeout, see [Reading One Event](reading-one-event)), and it remains idle until the user provides some input. If a timer is set for five seconds of idleness, it runs approximately five seconds after Emacs first becomes idle. Even if repeat is non-`nil`, this timer will not run again as long as Emacs remains idle, because the duration of idleness will continue to increase and will not go down to five seconds again.
Emacs can do various things while idle: garbage collect, autosave or handle data from a subprocess. But these interludes during idleness do not interfere with idle timers, because they do not reset the clock of idleness to zero. An idle timer set for 600 seconds will run when ten minutes have elapsed since the last user command was finished, even if subprocess output has been accepted thousands of times within those ten minutes, and even if there have been garbage collections and autosaves.
When the user supplies input, Emacs becomes non-idle while executing the input. Then it becomes idle again, and all the idle timers that are set up to repeat will subsequently run another time, one by one.
Do not write an idle timer function containing a loop which does a certain amount of processing each time around, and exits when `(input-pending-p)` is non-`nil`. This approach seems very natural but has two problems:
* It blocks out all process output (since Emacs accepts process output only while waiting).
* It blocks out any idle timers that ought to run during that time.
Similarly, do not write an idle timer function that sets up another idle timer (including the same idle timer) with secs argument less than or equal to the current idleness time. Such a timer will run almost immediately, and continue running again and again, instead of waiting for the next time Emacs becomes idle. The correct approach is to reschedule with an appropriate increment of the current value of the idleness time, as described below.
Function: **current-idle-time**
If Emacs is idle, this function returns the length of time Emacs has been idle, using the same format as `current-time` (see [Time of Day](time-of-day)).
When Emacs is not idle, `current-idle-time` returns `nil`. This is a convenient way to test whether Emacs is idle.
The main use of `current-idle-time` is when an idle timer function wants to “take a break” for a while. It can set up another idle timer to call the same function again, after a few seconds more idleness. Here’s an example:
```
(defvar my-resume-timer nil
"Timer for `my-timer-function' to reschedule itself, or nil.")
(defun my-timer-function ()
;; If the user types a command while `my-resume-timer`
;; is active, the next time this function is called from
;; its main idle timer, deactivate `my-resume-timer`.
(when my-resume-timer
(cancel-timer my-resume-timer))
...do the work for a while...
(when taking-a-break
(setq my-resume-timer
(run-with-idle-timer
;; Compute an idle time break-length
;; more than the current value.
(time-add (current-idle-time) break-length)
nil
'my-timer-function))))
```
elisp None #### Multi-Frame Images
Some image files can contain more than one image. We say that there are multiple “frames” in the image. At present, Emacs supports multiple frames for GIF, TIFF, and certain ImageMagick formats such as DJVM.
The frames can be used either to represent multiple pages (this is usually the case with multi-frame TIFF files, for example), or to create animation (usually the case with multi-frame GIF files).
A multi-frame image has a property `:index`, whose value is an integer (counting from 0) that specifies which frame is being displayed.
Function: **image-multi-frame-p** *image*
This function returns non-`nil` if image contains more than one frame. The actual return value is a cons `(nimages
. delay)`, where nimages is the number of frames and delay is the delay in seconds between them, or `nil` if the image does not specify a delay. Images that are intended to be animated usually specify a frame delay, whereas ones that are intended to be treated as multiple pages do not.
Function: **image-current-frame** *image*
This function returns the index of the current frame number for image, counting from 0.
Function: **image-show-frame** *image n &optional nocheck*
This function switches image to frame number n. It replaces a frame number outside the valid range with that of the end of the range, unless nocheck is non-`nil`. If image does not contain a frame with the specified number, the image displays as a hollow box.
Function: **image-animate** *image &optional index limit*
This function animates image. The optional integer index specifies the frame from which to start (default 0). The optional argument limit controls the length of the animation. If omitted or `nil`, the image animates once only; if `t` it loops forever; if a number animation stops after that many seconds.
Animation operates by means of a timer. Note that Emacs imposes a minimum frame delay of 0.01 (`image-minimum-frame-delay`) seconds. If the image itself does not specify a delay, Emacs uses `image-default-frame-delay`.
Function: **image-animate-timer** *image*
This function returns the timer responsible for animating image, if there is one.
elisp None #### Motion to an End of the Buffer
To move point to the beginning of the buffer, write:
```
(goto-char (point-min))
```
Likewise, to move to the end of the buffer, use:
```
(goto-char (point-max))
```
Here are two commands that users use to do these things. They are documented here to warn you not to use them in Lisp programs, because they set the mark and display messages in the echo area.
Command: **beginning-of-buffer** *&optional n*
This function moves point to the beginning of the buffer (or the limits of the accessible portion, when narrowing is in effect), setting the mark at the previous position (except in Transient Mark mode, if the mark is already active, it does not set the mark.)
If n is non-`nil`, then it puts point n tenths of the way from the beginning of the accessible portion of the buffer. In an interactive call, n is the numeric prefix argument, if provided; otherwise n defaults to `nil`.
**Warning:** Don’t use this function in Lisp programs!
Command: **end-of-buffer** *&optional n*
This function moves point to the end of the buffer (or the limits of the accessible portion, when narrowing is in effect), setting the mark at the previous position (except in Transient Mark mode when the mark is already active). If n is non-`nil`, then it puts point n tenths of the way from the end of the accessible portion of the buffer.
In an interactive call, n is the numeric prefix argument, if provided; otherwise n defaults to `nil`.
**Warning:** Don’t use this function in Lisp programs!
elisp None ### Dedicated Windows
Functions for displaying a buffer can be told to not use specific windows by marking these windows as *dedicated* to their buffers. `display-buffer` (see [Choosing Window](choosing-window)) never uses a dedicated window for displaying another buffer in it. `get-lru-window` and `get-largest-window` (see [Cyclic Window Ordering](cyclic-window-ordering)) do not consider dedicated windows as candidates when their dedicated argument is non-`nil`. The behavior of `set-window-buffer` (see [Buffers and Windows](buffers-and-windows)) with respect to dedicated windows is slightly different, see below.
Functions supposed to remove a buffer from a window or a window from a frame can behave specially when a window they operate on is dedicated. We will distinguish four basic cases, namely where (1) the window is not the only window on its frame, (2) the window is the only window on its frame but there are other frames on the same terminal left, (3) the window is the only window on the only frame on the same terminal, and (4) the dedication’s value is `side` (see [Displaying Buffers in Side Windows](displaying-buffers-in-side-windows)).
In particular, `delete-windows-on` (see [Deleting Windows](deleting-windows)) handles case (2) by deleting the associated frame and cases (3) and (4) by showing another buffer in that frame’s only window. The function `replace-buffer-in-windows` (see [Buffers and Windows](buffers-and-windows)) which is called when a buffer gets killed, deletes the window in case (1) and behaves like `delete-windows-on` otherwise.
When `bury-buffer` (see [Buffer List](buffer-list)) operates on the selected window (which shows the buffer that shall be buried), it handles case (2) by calling `frame-auto-hide-function` (see [Quitting Windows](quitting-windows)) to deal with the selected frame. The other two cases are handled as with `replace-buffer-in-windows`.
Function: **window-dedicated-p** *&optional window*
This function returns non-`nil` if window is dedicated to its buffer and `nil` otherwise. More precisely, the return value is the value assigned by the last call of `set-window-dedicated-p` for window, or `nil` if that function was never called with window as its argument. The default for window is the selected window.
Function: **set-window-dedicated-p** *window flag*
This function marks window as dedicated to its buffer if flag is non-`nil`, and non-dedicated otherwise.
As a special case, if flag is `t`, window becomes *strongly* dedicated to its buffer. `set-window-buffer` signals an error when the window it acts upon is strongly dedicated to its buffer and does not already display the buffer it is asked to display. Other functions do not treat `t` differently from any non-`nil` value.
You can also tell `display-buffer` to mark a window it creates as dedicated to its buffer by providing a suitable `dedicated` action alist entry (see [Buffer Display Action Alists](buffer-display-action-alists)).
elisp None ### Motion
Motion functions change the value of point, either relative to the current value of point, relative to the beginning or end of the buffer, or relative to the edges of the selected window. See [Point](point).
| | | |
| --- | --- | --- |
| • [Character Motion](character-motion) | | Moving in terms of characters. |
| • [Word Motion](word-motion) | | Moving in terms of words. |
| • [Buffer End Motion](buffer-end-motion) | | Moving to the beginning or end of the buffer. |
| • [Text Lines](text-lines) | | Moving in terms of lines of text. |
| • [Screen Lines](screen-lines) | | Moving in terms of lines as displayed. |
| • [List Motion](list-motion) | | Moving by parsing lists and sexps. |
| • [Skipping Characters](skipping-characters) | | Skipping characters belonging to a certain set. |
elisp None ### Visiting Files
Visiting a file means reading a file into a buffer. Once this is done, we say that the buffer is *visiting* that file, and call the file *the visited file* of the buffer.
A file and a buffer are two different things. A file is information recorded permanently in the computer (unless you delete it). A buffer, on the other hand, is information inside of Emacs that will vanish at the end of the editing session (or when you kill the buffer). When a buffer is visiting a file, it contains information copied from the file. The copy in the buffer is what you modify with editing commands. Changes to the buffer do not change the file; to make the changes permanent, you must *save* the buffer, which means copying the altered buffer contents back into the file.
Despite the distinction between files and buffers, people often refer to a file when they mean a buffer and vice-versa. Indeed, we say, “I am editing a file”, rather than, “I am editing a buffer that I will soon save as a file of the same name”. Humans do not usually need to make the distinction explicit. When dealing with a computer program, however, it is good to keep the distinction in mind.
| | | |
| --- | --- | --- |
| • [Visiting Functions](visiting-functions) | | The usual interface functions for visiting. |
| • [Subroutines of Visiting](subroutines-of-visiting) | | Lower-level subroutines that they use. |
elisp None #### Entering the Debugger on a Function Call
To investigate a problem that happens in the middle of a program, one useful technique is to enter the debugger whenever a certain function is called. You can do this to the function in which the problem occurs, and then step through the function, or you can do this to a function called shortly before the problem, step quickly over the call to that function, and then step through its caller.
Command: **debug-on-entry** *function-name*
This function requests function-name to invoke the debugger each time it is called.
Any function or macro defined as Lisp code may be set to break on entry, regardless of whether it is interpreted code or compiled code. If the function is a command, it will enter the debugger when called from Lisp and when called interactively (after the reading of the arguments). You can also set debug-on-entry for primitive functions (i.e., those written in C) this way, but it only takes effect when the primitive is called from Lisp code. Debug-on-entry is not allowed for special forms.
When `debug-on-entry` is called interactively, it prompts for function-name in the minibuffer. If the function is already set up to invoke the debugger on entry, `debug-on-entry` does nothing. `debug-on-entry` always returns function-name.
Here’s an example to illustrate use of this function:
```
(defun fact (n)
(if (zerop n) 1
(* n (fact (1- n)))))
⇒ fact
```
```
(debug-on-entry 'fact)
⇒ fact
```
```
(fact 3)
```
```
------ Buffer: *Backtrace* ------
Debugger entered--entering a function:
* fact(3)
eval((fact 3))
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
------ Buffer: *Backtrace* ------
```
Command: **cancel-debug-on-entry** *&optional function-name*
This function undoes the effect of `debug-on-entry` on function-name. When called interactively, it prompts for function-name in the minibuffer. If function-name is omitted or `nil`, it cancels break-on-entry for all functions. Calling `cancel-debug-on-entry` does nothing to a function which is not currently set up to break on entry.
| programming_docs |
elisp None ### Accessing Variable Values
The usual way to reference a variable is to write the symbol which names it. See [Symbol Forms](symbol-forms).
Occasionally, you may want to reference a variable which is only determined at run time. In that case, you cannot specify the variable name in the text of the program. You can use the `symbol-value` function to extract the value.
Function: **symbol-value** *symbol*
This function returns the value stored in symbol’s value cell. This is where the variable’s current (dynamic) value is stored. If the variable has no local binding, this is simply its global value. If the variable is void, a `void-variable` error is signaled.
If the variable is lexically bound, the value reported by `symbol-value` is not necessarily the same as the variable’s lexical value, which is determined by the lexical environment rather than the symbol’s value cell. See [Variable Scoping](variable-scoping).
```
(setq abracadabra 5)
⇒ 5
```
```
(setq foo 9)
⇒ 9
```
```
;; Here the symbol `abracadabra`
;; is the symbol whose value is examined.
(let ((abracadabra 'foo))
(symbol-value 'abracadabra))
⇒ foo
```
```
;; Here, the value of `abracadabra`,
;; which is `foo`,
;; is the symbol whose value is examined.
(let ((abracadabra 'foo))
(symbol-value abracadabra))
⇒ 9
```
```
(symbol-value 'abracadabra)
⇒ 5
```
elisp None #### Size Parameters
Frame parameters usually specify frame sizes in character units. On graphical displays, the `default` face determines the actual pixel sizes of these character units (see [Face Attributes](face-attributes)).
`width`
This parameter specifies the width of the frame. It can be specified as in the following ways:
an integer
A positive integer specifies the width of the frame’s text area (see [Frame Geometry](frame-geometry)) in characters.
a cons cell
If this is a cons cell with the symbol `text-pixels` in its CAR, the CDR of that cell specifies the width of the frame’s text area in pixels.
a floating-point value
A floating-point number between 0.0 and 1.0 can be used to specify the width of a frame via its *width ratio*—the ratio of its outer width (see [Frame Geometry](frame-geometry)) to the width of the frame’s workarea (see [Multiple Terminals](multiple-terminals)) or its parent frame’s (see [Child Frames](child-frames)) native frame. Thus, a value of 0.5 makes the frame occupy half of the width of its workarea or parent frame, a value of 1.0 the full width. Similarly, the *height ratio* of a frame is the ratio of its outer height to the height of its workarea or its parent’s native frame.
Emacs will try to keep the width and height ratio of a child frame unaltered if that frame has a non-`nil` `keep-ratio` parameter (see [Frame Interaction Parameters](frame-interaction-parameters)) and its parent frame is resized.
Since the outer size of a frame is usually unavailable before a frame has been made visible, it is generally not advisable to use floating-point values when creating decorated frames. Floating-point values are more suited to ensure that a child frame always fits within the area of its parent frame as, for example, when customizing `display-buffer-alist` (see [Choosing Window](choosing-window)) via `display-buffer-in-child-frame`.
Regardless of how this parameter was specified, functions reporting the value of this parameter like `frame-parameters` always report the width of the frame’s text area in characters as an integer rounded, if necessary, to a multiple of the frame’s default character width. That value is also used by the desktop saving routines.
`height`
This parameter specifies the height of the frame. It works just like `width`, except vertically instead of horizontally.
`user-size`
This does for the size parameters `height` and `width` what the `user-position` parameter (see [user-position](position-parameters)) does for the position parameters `top` and `left`.
`min-width`
This parameter specifies the minimum native width (see [Frame Geometry](frame-geometry)) of the frame, in characters. Normally, the functions that establish a frame’s initial width or resize a frame horizontally make sure that all the frame’s windows, vertical scroll bars, fringes, margins and vertical dividers can be displayed. This parameter, if non-`nil` allows to make a frame narrower than that with the consequence that any components that do not fit will be clipped by the window manager.
`min-height`
This parameter specifies the minimum native height (see [Frame Geometry](frame-geometry)) of the frame, in characters. Normally, the functions that establish a frame’s initial size or resize a frame make sure that all the frame’s windows, horizontal scroll bars and dividers, mode and header lines, the echo area and the internal menu and tool bar can be displayed. This parameter, if non-`nil` allows to make a frame smaller than that with the consequence that any components that do not fit will be clipped by the window manager.
`fullscreen`
This parameter specifies whether to maximize the frame’s width, height or both. Its value can be `fullwidth`, `fullheight`, `fullboth`, or `maximized`. A *fullwidth* frame is as wide as possible, a *fullheight* frame is as tall as possible, and a *fullboth* frame is both as wide and as tall as possible. A *maximized* frame is like a “fullboth” frame, except that it usually keeps its title bar and the buttons for resizing and closing the frame. Also, maximized frames typically avoid hiding any task bar or panels displayed on the desktop. A “fullboth” frame, on the other hand, usually omits the title bar and occupies the entire available screen space.
Full-height and full-width frames are more similar to maximized frames in this regard. However, these typically display an external border which might be absent with maximized frames. Hence the heights of maximized and full-height frames and the widths of maximized and full-width frames often differ by a few pixels.
With some window managers you may have to customize the variable `frame-resize-pixelwise` (see [Frame Size](frame-size)) in order to make a frame truly appear maximized or full-screen. Moreover, some window managers might not support smooth transition between the various full-screen or maximization states. Customizing the variable `x-frame-normalize-before-maximize` can help to overcome that.
Full-screen on macOS hides both the tool-bar and the menu-bar, however both will be displayed if the mouse pointer is moved to the top of the screen.
`fullscreen-restore`
This parameter specifies the desired fullscreen state of the frame after invoking the `toggle-frame-fullscreen` command (see [Frame Commands](https://www.gnu.org/software/emacs/manual/html_node/emacs/Frame-Commands.html#Frame-Commands) in The GNU Emacs Manual) in the “fullboth” state. Normally this parameter is installed automatically by that command when toggling the state to fullboth. If, however, you start Emacs in the “fullboth” state, you have to specify the desired behavior in your initial file as, for example
```
(setq default-frame-alist
'((fullscreen . fullboth)
(fullscreen-restore . fullheight)))
```
This will give a new frame full height after typing in it F11 for the first time.
`fit-frame-to-buffer-margins`
This parameter allows to override the value of the option `fit-frame-to-buffer-margins` when fitting this frame to the buffer of its root window with `fit-frame-to-buffer` (see [Resizing Windows](resizing-windows)).
`fit-frame-to-buffer-sizes` This parameter allows to override the value of the option `fit-frame-to-buffer-sizes` when fitting this frame to the buffer of its root window with `fit-frame-to-buffer` (see [Resizing Windows](resizing-windows)).
elisp None ### Integer Basics
The Lisp reader reads an integer as a nonempty sequence of decimal digits with optional initial sign and optional final period.
```
1 ; The integer 1.
1. ; The integer 1.
+1 ; Also the integer 1.
-1 ; The integer -1.
0 ; The integer 0.
-0 ; The integer 0.
```
The syntax for integers in bases other than 10 consists of ‘`#`’ followed by a radix indication followed by one or more digits. The radix indications are ‘`b`’ for binary, ‘`o`’ for octal, ‘`x`’ for hex, and ‘`radixr`’ for radix radix. Thus, ‘`#binteger`’ reads integer in binary, and ‘`#radixrinteger`’ reads integer in radix radix. Allowed values of radix run from 2 to 36, and allowed digits are the first radix characters taken from ‘`0`’–‘`9`’, ‘`A`’–‘`Z`’. Letter case is ignored and there is no initial sign or final period. For example:
```
#b101100 ⇒ 44
#o54 ⇒ 44
#x2c ⇒ 44
#24r1k ⇒ 44
```
To understand how various functions work on integers, especially the bitwise operators (see [Bitwise Operations](bitwise-operations)), it is often helpful to view the numbers in their binary form.
In binary, the decimal integer 5 looks like this:
```
…000101
```
(The ellipsis ‘`…`’ stands for a conceptually infinite number of bits that match the leading bit; here, an infinite number of 0 bits. Later examples also use this ‘`…`’ notation.)
The integer -1 looks like this:
```
…111111
```
-1 is represented as all ones. (This is called *two’s complement* notation.)
Subtracting 4 from -1 returns the negative integer -5. In binary, the decimal integer 4 is 100. Consequently, -5 looks like this:
```
…111011
```
Many of the functions described in this chapter accept markers for arguments in place of numbers. (See [Markers](markers).) Since the actual arguments to such functions may be either numbers or markers, we often give these arguments the name number-or-marker. When the argument value is a marker, its position value is used and its buffer is ignored.
In Emacs Lisp, text characters are represented by integers. Any integer between zero and the value of `(max-char)`, inclusive, is considered to be valid as a character. See [Character Codes](character-codes).
Integers in Emacs Lisp are not limited to the machine word size. Under the hood, though, there are two kinds of integers: smaller ones, called *fixnums*, and larger ones, called *bignums*. Although Emacs Lisp code ordinarily should not depend on whether an integer is a fixnum or a bignum, older Emacs versions support only fixnums, some functions in Emacs still accept only fixnums, and older Emacs Lisp code may have trouble when given bignums. For example, while older Emacs Lisp code could safely compare integers for numeric equality with `eq`, the presence of bignums means that equality predicates like `eql` and `=` should now be used to compare integers.
The range of values for bignums is limited by the amount of main memory, by machine characteristics such as the size of the word used to represent a bignum’s exponent, and by the `integer-width` variable. These limits are typically much more generous than the limits for fixnums. A bignum is never numerically equal to a fixnum; Emacs always represents an integer in fixnum range as a fixnum, not a bignum.
The range of values for a fixnum depends on the machine. The minimum range is -536,870,912 to 536,870,911 (30 bits; i.e., -2\*\*29 to 2\*\*29 - 1), but many machines provide a wider range.
Variable: **most-positive-fixnum**
The value of this variable is the greatest “small” integer that Emacs Lisp can handle. Typical values are 2\*\*29 - 1 on 32-bit and 2\*\*61 - 1 on 64-bit platforms.
Variable: **most-negative-fixnum**
The value of this variable is the numerically least “small” integer that Emacs Lisp can handle. It is negative. Typical values are -2\*\*29 on 32-bit and -2\*\*61 on 64-bit platforms.
Variable: **integer-width**
The value of this variable is a nonnegative integer that controls whether Emacs signals a range error when a large integer would be calculated. Integers with absolute values less than 2\*\*n, where n is this variable’s value, do not signal a range error. Attempts to create larger integers typically signal a range error, although there might be no signal if a larger integer can be created cheaply. Setting this variable to a large number can be costly if a computation creates huge integers.
elisp None #### Levels of Font Lock
Some major modes offer three different levels of fontification. You can define multiple levels by using a list of symbols for keywords in `font-lock-defaults`. Each symbol specifies one level of fontification; it is up to the user to choose one of these levels, normally by setting `font-lock-maximum-decoration` (see [Font Lock](https://www.gnu.org/software/emacs/manual/html_node/emacs/Font-Lock.html#Font-Lock) in the GNU Emacs Manual). The chosen level’s symbol value is used to initialize `font-lock-keywords`.
Here are the conventions for how to define the levels of fontification:
* Level 1: highlight function declarations, file directives (such as include or import directives), strings and comments. The idea is speed, so only the most important and top-level components are fontified.
* Level 2: in addition to level 1, highlight all language keywords, including type names that act like keywords, as well as named constant values. The idea is that all keywords (either syntactic or semantic) should be fontified appropriately.
* Level 3: in addition to level 2, highlight the symbols being defined in function and variable declarations, and all builtin function names, wherever they appear.
elisp None ### Sequencing
Evaluating forms in the order they appear is the most common way control passes from one form to another. In some contexts, such as in a function body, this happens automatically. Elsewhere you must use a control structure construct to do this: `progn`, the simplest control construct of Lisp.
A `progn` special form looks like this:
```
(progn a b c …)
```
and it says to execute the forms a, b, c, and so on, in that order. These forms are called the *body* of the `progn` form. The value of the last form in the body becomes the value of the entire `progn`. `(progn)` returns `nil`.
In the early days of Lisp, `progn` was the only way to execute two or more forms in succession and use the value of the last of them. But programmers found they often needed to use a `progn` in the body of a function, where (at that time) only one form was allowed. So the body of a function was made into an implicit `progn`: several forms are allowed just as in the body of an actual `progn`. Many other control structures likewise contain an implicit `progn`. As a result, `progn` is not used as much as it was many years ago. It is needed now most often inside an `unwind-protect`, `and`, `or`, or in the then-part of an `if`.
Special Form: **progn** *forms…*
This special form evaluates all of the forms, in textual order, returning the result of the final form.
```
(progn (print "The first form")
(print "The second form")
(print "The third form"))
-| "The first form"
-| "The second form"
-| "The third form"
⇒ "The third form"
```
Two other constructs likewise evaluate a series of forms but return different values:
Special Form: **prog1** *form1 forms…*
This special form evaluates form1 and all of the forms, in textual order, returning the result of form1.
```
(prog1 (print "The first form")
(print "The second form")
(print "The third form"))
-| "The first form"
-| "The second form"
-| "The third form"
⇒ "The first form"
```
Here is a way to remove the first element from a list in the variable `x`, then return the value of that former element:
```
(prog1 (car x) (setq x (cdr x)))
```
Special Form: **prog2** *form1 form2 forms…*
This special form evaluates form1, form2, and all of the following forms, in textual order, returning the result of form2.
```
(prog2 (print "The first form")
(print "The second form")
(print "The third form"))
-| "The first form"
-| "The second form"
-| "The third form"
⇒ "The second form"
```
elisp None #### Edebug and Macros
To make Edebug properly instrument expressions that call macros, some extra care is needed. This subsection explains the details.
| | | |
| --- | --- | --- |
| • [Instrumenting Macro Calls](instrumenting-macro-calls) | | The basic problem. |
| • [Specification List](specification-list) | | How to specify complex patterns of evaluation. |
| • [Backtracking](backtracking) | | What Edebug does when matching fails. |
| • [Specification Examples](specification-examples) | | To help understand specifications. |
elisp None ### Naming a Function
A symbol can serve as the name of a function. This happens when the symbol’s *function cell* (see [Symbol Components](symbol-components)) contains a function object (e.g., a lambda expression). Then the symbol itself becomes a valid, callable function, equivalent to the function object in its function cell.
The contents of the function cell are also called the symbol’s *function definition*. The procedure of using a symbol’s function definition in place of the symbol is called *symbol function indirection*; see [Function Indirection](function-indirection). If you have not given a symbol a function definition, its function cell is said to be *void*, and it cannot be used as a function.
In practice, nearly all functions have names, and are referred to by their names. You can create a named Lisp function by defining a lambda expression and putting it in a function cell (see [Function Cells](function-cells)). However, it is more common to use the `defun` special form, described in the next section. See [Defining Functions](defining-functions).
We give functions names because it is convenient to refer to them by their names in Lisp expressions. Also, a named Lisp function can easily refer to itself—it can be recursive. Furthermore, primitives can only be referred to textually by their names, since primitive function objects (see [Primitive Function Type](primitive-function-type)) have no read syntax.
A function need not have a unique name. A given function object *usually* appears in the function cell of only one symbol, but this is just a convention. It is easy to store it in several symbols using `fset`; then each of the symbols is a valid name for the same function.
Note that a symbol used as a function name may also be used as a variable; these two uses of a symbol are independent and do not conflict. (This is not the case in some dialects of Lisp, like Scheme.)
By convention, if a function’s symbol consists of two names separated by ‘`--`’, the function is intended for internal use and the first part names the file defining the function. For example, a function named `vc-git--rev-parse` is an internal function defined in `vc-git.el`. Internal-use functions written in C have names ending in ‘`-internal`’, e.g., `bury-buffer-internal`. Emacs code contributed before 2018 may follow other internal-use naming conventions, which are being phased out.
elisp None ### Window Systems
Emacs works with several window systems, most notably the X Window System. Both Emacs and X use the term “window”, but use it differently. An Emacs frame is a single window as far as X is concerned; the individual Emacs windows are not known to X at all.
Variable: **window-system**
This terminal-local variable tells Lisp programs what window system Emacs is using for displaying the frame. The possible values are
`x`
Emacs is displaying the frame using X.
`w32` Emacs is displaying the frame using native MS-Windows GUI.
`ns` Emacs is displaying the frame using the Nextstep interface (used on GNUstep and macOS).
`pc` Emacs is displaying the frame using MS-DOS direct screen writes.
`nil` Emacs is displaying the frame on a character-based terminal.
Variable: **initial-window-system**
This variable holds the value of `window-system` used for the first frame created by Emacs during startup. (When Emacs is invoked as a daemon, it does not create any initial frames, so `initial-window-system` is `nil`, except on MS-Windows, where it is still `w32`. See [daemon](https://www.gnu.org/software/emacs/manual/html_node/emacs/Initial-Options.html#Initial-Options) in The GNU Emacs Manual.)
Function: **window-system** *&optional frame*
This function returns a symbol whose name tells what window system is used for displaying frame (which defaults to the currently selected frame). The list of possible symbols it returns is the same one documented for the variable `window-system` above.
Do *not* use `window-system` and `initial-window-system` as predicates or boolean flag variables, if you want to write code that works differently on text terminals and graphic displays. That is because `window-system` is not a good indicator of Emacs capabilities on a given display type. Instead, use `display-graphic-p` or any of the other `display-*-p` predicates described in [Display Feature Testing](display-feature-testing).
| programming_docs |
elisp None #### Operator Precedence Grammars
SMIE’s precedence grammars simply give to each token a pair of precedences: the left-precedence and the right-precedence. We say `T1 < T2` if the right-precedence of token `T1` is less than the left-precedence of token `T2`. A good way to read this `<` is as a kind of parenthesis: if we find `... T1 something
T2 ...` then that should be parsed as `... T1 (something T2 ...` rather than as `... T1 something) T2 ...`. The latter interpretation would be the case if we had `T1 > T2`. If we have `T1 = T2`, it means that token T2 follows token T1 in the same syntactic construction, so typically we have `"begin" = "end"`. Such pairs of precedences are sufficient to express left-associativity or right-associativity of infix operators, nesting of tokens like parentheses and many other cases.
Function: **smie-prec2->grammar** *table*
This function takes a *prec2* grammar table and returns an alist suitable for use in `smie-setup`. The *prec2* table is itself meant to be built by one of the functions below.
Function: **smie-merge-prec2s** *&rest tables*
This function takes several *prec2* tables and merges them into a new *prec2* table.
Function: **smie-precs->prec2** *precs*
This function builds a *prec2* table from a table of precedences precs. precs should be a list, sorted by precedence (for example `"+"` will come before `"*"`), of elements of the form `(assoc op ...)`, where each op is a token that acts as an operator; assoc is their associativity, which can be either `left`, `right`, `assoc`, or `nonassoc`. All operators in a given element share the same precedence level and associativity.
Function: **smie-bnf->prec2** *bnf &rest resolvers*
This function lets you specify the grammar using a BNF notation. It accepts a bnf description of the grammar along with a set of conflict resolution rules resolvers, and returns a *prec2* table.
bnf is a list of nonterminal definitions of the form `(nonterm rhs1 rhs2 ...)` where each rhs is a (non-empty) list of terminals (aka tokens) or non-terminals.
Not all grammars are accepted:
* An rhs cannot be an empty list (an empty list is never needed, since SMIE allows all non-terminals to match the empty string anyway).
* An rhs cannot have 2 consecutive non-terminals: each pair of non-terminals needs to be separated by a terminal (aka token). This is a fundamental limitation of operator precedence grammars.
Additionally, conflicts can occur:
* The returned *prec2* table holds constraints between pairs of tokens, and for any given pair only one constraint can be present: T1 < T2, T1 = T2, or T1 > T2.
* A token can be an `opener` (something similar to an open-paren), a `closer` (like a close-paren), or `neither` of the two (e.g., an infix operator, or an inner token like `"else"`).
Precedence conflicts can be resolved via resolvers, which is a list of *precs* tables (see `smie-precs->prec2`): for each precedence conflict, if those `precs` tables specify a particular constraint, then the conflict is resolved by using this constraint instead, else a conflict is reported and one of the conflicting constraints is picked arbitrarily and the others are simply ignored.
elisp None ### Keymaps for Translating Sequences of Events
When the `read-key-sequence` function reads a key sequence (see [Key Sequence Input](key-sequence-input)), it uses *translation keymaps* to translate certain event sequences into others. The translation keymaps are `input-decode-map`, `local-function-key-map`, and `key-translation-map` (in order of priority).
Translation keymaps have the same structure as other keymaps, but are used differently: they specify translations to make while reading key sequences, rather than bindings for complete key sequences. As each key sequence is read, it is checked against each translation keymap. If one of the translation keymaps binds k to a vector v, then whenever k appears as a sub-sequence *anywhere* in a key sequence, that sub-sequence is replaced with the events in v.
For example, VT100 terminals send `ESC O P` when the keypad key PF1 is pressed. On such terminals, Emacs must translate that sequence of events into a single event `pf1`. This is done by binding `ESC O P` to `[pf1]` in `input-decode-map`. Thus, when you type `C-c PF1` on the terminal, the terminal emits the character sequence `C-c ESC O P`, and `read-key-sequence` translates this back into `C-c PF1` and returns it as the vector `[?\C-c pf1]`.
Translation keymaps take effect only after Emacs has decoded the keyboard input (via the input coding system specified by `keyboard-coding-system`). See [Terminal I/O Encoding](terminal-i_002fo-encoding).
Variable: **input-decode-map**
This variable holds a keymap that describes the character sequences sent by function keys on an ordinary character terminal.
The value of `input-decode-map` is usually set up automatically according to the terminal’s Terminfo or Termcap entry, but sometimes those need help from terminal-specific Lisp files. Emacs comes with terminal-specific files for many common terminals; their main purpose is to make entries in `input-decode-map` beyond those that can be deduced from Termcap and Terminfo. See [Terminal-Specific](terminal_002dspecific).
Variable: **local-function-key-map**
This variable holds a keymap similar to `input-decode-map` except that it describes key sequences which should be translated to alternative interpretations that are usually preferred. It applies after `input-decode-map` and before `key-translation-map`.
Entries in `local-function-key-map` are ignored if they conflict with bindings made in the minor mode, local, or global keymaps. I.e., the remapping only applies if the original key sequence would otherwise not have any binding.
`local-function-key-map` inherits from `function-key-map`. The latter should only be altered if you want the binding to apply in all terminals, so using the former is almost always preferred.
Variable: **key-translation-map**
This variable is another keymap used just like `input-decode-map` to translate input events into other events. It differs from `input-decode-map` in that it goes to work after `local-function-key-map` is finished rather than before; it receives the results of translation by `local-function-key-map`.
Just like `input-decode-map`, but unlike `local-function-key-map`, this keymap is applied regardless of whether the input key-sequence has a normal binding. Note however that actual key bindings can have an effect on `key-translation-map`, even though they are overridden by it. Indeed, actual key bindings override `local-function-key-map` and thus may alter the key sequence that `key-translation-map` receives. Clearly, it is better to avoid this type of situation.
The intent of `key-translation-map` is for users to map one character set to another, including ordinary characters normally bound to `self-insert-command`.
You can use `input-decode-map`, `local-function-key-map`, and `key-translation-map` for more than simple aliases, by using a function, instead of a key sequence, as the translation of a key. Then this function is called to compute the translation of that key.
The key translation function receives one argument, which is the prompt that was specified in `read-key-sequence`—or `nil` if the key sequence is being read by the editor command loop. In most cases you can ignore the prompt value.
If the function reads input itself, it can have the effect of altering the event that follows. For example, here’s how to define `C-c h` to turn the character that follows into a Hyper character:
```
(defun hyperify (prompt)
(let ((e (read-event)))
(vector (if (numberp e)
(logior (ash 1 24) e)
(if (memq 'hyper (event-modifiers e))
e
(add-event-modifier "H-" e))))))
(defun add-event-modifier (string e)
(let ((symbol (if (symbolp e) e (car e))))
(setq symbol (intern (concat string
(symbol-name symbol))))
(if (symbolp e)
symbol
(cons symbol (cdr e)))))
(define-key local-function-key-map "\C-ch" 'hyperify)
```
#### Interaction with normal keymaps
The end of a key sequence is detected when that key sequence either is bound to a command, or when Emacs determines that no additional event can lead to a sequence that is bound to a command.
This means that, while `input-decode-map` and `key-translation-map` apply regardless of whether the original key sequence would have a binding, the presence of such a binding can still prevent translation from taking place. For example, let us return to our VT100 example above and add a binding for `C-c ESC` to the global map; now when the user hits `C-c PF1` Emacs will fail to decode `C-c ESC O P` into `C-c PF1` because it will stop reading keys right after `C-c ESC`, leaving `O P` for later. This is in case the user really hit `C-c ESC`, in which case Emacs should not sit there waiting for the next key to decide whether the user really pressed `ESC` or `PF1`.
For that reason, it is better to avoid binding commands to key sequences where the end of the key sequence is a prefix of a key translation. The main such problematic suffixes/prefixes are `ESC`, `M-O` (which is really `ESC O`) and `M-[` (which is really `ESC [`).
elisp None #### Geometry
Here’s how to examine the data in an X-style window geometry specification:
Function: **x-parse-geometry** *geom*
The function `x-parse-geometry` converts a standard X window geometry string to an alist that you can use as part of the argument to `make-frame`.
The alist describes which parameters were specified in geom, and gives the values specified for them. Each element looks like `(parameter . value)`. The possible parameter values are `left`, `top`, `width`, and `height`.
For the size parameters, the value must be an integer. The position parameter names `left` and `top` are not totally accurate, because some values indicate the position of the right or bottom edges instead. The value possibilities for the position parameters are: an integer, a list `(+ pos)`, or a list `(- pos)`; as previously described (see [Position Parameters](position-parameters)).
Here is an example:
```
(x-parse-geometry "35x70+0-0")
⇒ ((height . 70) (width . 35)
(top - 0) (left . 0))
```
elisp None #### Entering the debugger when a variable is modified
Sometimes a problem with a function is due to a wrong setting of a variable. Setting up the debugger to trigger whenever the variable is changed is a quick way to find the origin of the setting.
Command: **debug-on-variable-change** *variable*
This function arranges for the debugger to be called whenever variable is modified.
It is implemented using the watchpoint mechanism, so it inherits the same characteristics and limitations: all aliases of variable will be watched together, only dynamic variables can be watched, and changes to the objects referenced by variables are not detected. For details, see [Watching Variables](watching-variables).
Command: **cancel-debug-on-variable-change** *&optional variable*
This function undoes the effect of `debug-on-variable-change` on variable. When called interactively, it prompts for variable in the minibuffer. If variable is omitted or `nil`, it cancels break-on-change for all variables. Calling `cancel-debug-on-variable-change` does nothing to a variable which is not currently set up to break on change.
elisp None #### Backup by Renaming or by Copying?
There are two ways that Emacs can make a backup file:
* Emacs can rename the original file so that it becomes a backup file, and then write the buffer being saved into a new file. After this procedure, any other names (i.e., hard links) of the original file now refer to the backup file. The new file is owned by the user doing the editing, and its group is the default for new files written by the user in that directory.
* Emacs can copy the original file into a backup file, and then overwrite the original file with new contents. After this procedure, any other names (i.e., hard links) of the original file continue to refer to the current (updated) version of the file. The file’s owner and group will be unchanged.
The first method, renaming, is the default.
The variable `backup-by-copying`, if non-`nil`, says to use the second method, which is to copy the original file and overwrite it with the new buffer contents. The variable `file-precious-flag`, if non-`nil`, also has this effect (as a sideline of its main significance). See [Saving Buffers](saving-buffers).
User Option: **backup-by-copying**
If this variable is non-`nil`, Emacs always makes backup files by copying. The default is `nil`.
The following three variables, when non-`nil`, cause the second method to be used in certain special cases. They have no effect on the treatment of files that don’t fall into the special cases.
User Option: **backup-by-copying-when-linked**
If this variable is non-`nil`, Emacs makes backups by copying for files with multiple names (hard links). The default is `nil`.
This variable is significant only if `backup-by-copying` is `nil`, since copying is always used when that variable is non-`nil`.
User Option: **backup-by-copying-when-mismatch**
If this variable is non-`nil` (the default), Emacs makes backups by copying in cases where renaming would change either the owner or the group of the file.
The value has no effect when renaming would not alter the owner or group of the file; that is, for files which are owned by the user and whose group matches the default for a new file created there by the user.
This variable is significant only if `backup-by-copying` is `nil`, since copying is always used when that variable is non-`nil`.
User Option: **backup-by-copying-when-privileged-mismatch**
This variable, if non-`nil`, specifies the same behavior as `backup-by-copying-when-mismatch`, but only for certain user-id and group-id values: namely, those less than or equal to a certain number. You set this variable to that number.
Thus, if you set `backup-by-copying-when-privileged-mismatch` to 0, backup by copying is done for the superuser and group 0 only, when necessary to prevent a change in the owner of the file.
The default is 200.
elisp None #### Conventions for Writing Minor Modes
There are conventions for writing minor modes just as there are for major modes (see [Major Modes](major-modes)). These conventions are described below. The easiest way to follow them is to use the macro `define-minor-mode`. See [Defining Minor Modes](defining-minor-modes).
* Define a variable whose name ends in ‘`-mode`’. We call this the *mode variable*. The minor mode command should set this variable. The value will be `nil` if the mode is disabled, and non-`nil` if the mode is enabled. The variable should be buffer-local if the minor mode is buffer-local. This variable is used in conjunction with the `minor-mode-alist` to display the minor mode name in the mode line. It also determines whether the minor mode keymap is active, via `minor-mode-map-alist` (see [Controlling Active Maps](controlling-active-maps)). Individual commands or hooks can also check its value.
* Define a command, called the *mode command*, whose name is the same as the mode variable. Its job is to set the value of the mode variable, plus anything else that needs to be done to actually enable or disable the mode’s features. The mode command should accept one optional argument. If called interactively with no prefix argument, it should toggle the mode (i.e., enable if it is disabled, and disable if it is enabled). If called interactively with a prefix argument, it should enable the mode if the argument is positive and disable it otherwise.
If the mode command is called from Lisp (i.e., non-interactively), it should enable the mode if the argument is omitted or `nil`; it should toggle the mode if the argument is the symbol `toggle`; otherwise it should treat the argument in the same way as for an interactive call with a numeric prefix argument, as described above.
The following example shows how to implement this behavior (it is similar to the code generated by the `define-minor-mode` macro):
```
(interactive (list (or current-prefix-arg 'toggle)))
(let ((enable
(if (eq arg 'toggle)
(not foo-mode) ; this is the mode’s mode variable
(> (prefix-numeric-value arg) 0))))
(if enable
do-enable
do-disable))
```
The reason for this somewhat complex behavior is that it lets users easily toggle the minor mode interactively, and also lets the minor mode be easily enabled in a mode hook, like this:
```
(add-hook 'text-mode-hook 'foo-mode)
```
This behaves correctly whether or not `foo-mode` was already enabled, since the `foo-mode` mode command unconditionally enables the minor mode when it is called from Lisp with no argument. Disabling a minor mode in a mode hook is a little uglier:
```
(add-hook 'text-mode-hook (lambda () (foo-mode -1)))
```
However, this is not very commonly done.
Enabling or disabling a minor mode twice in direct succession should not fail and should do the same thing as enabling or disabling it only once. In other words, the minor mode command should be idempotent.
* Add an element to `minor-mode-alist` for each minor mode (see [Definition of minor-mode-alist](mode-line-variables#Definition-of-minor_002dmode_002dalist)), if you want to indicate the minor mode in the mode line. This element should be a list of the following form:
```
(mode-variable string)
```
Here mode-variable is the variable that controls enabling of the minor mode, and string is a short string, starting with a space, to represent the mode in the mode line. These strings must be short so that there is room for several of them at once.
When you add an element to `minor-mode-alist`, use `assq` to check for an existing element, to avoid duplication. For example:
```
(unless (assq 'leif-mode minor-mode-alist)
(push '(leif-mode " Leif") minor-mode-alist))
```
or like this, using `add-to-list` (see [List Variables](list-variables)):
```
(add-to-list 'minor-mode-alist '(leif-mode " Leif"))
```
In addition, several major mode conventions (see [Major Mode Conventions](major-mode-conventions)) apply to minor modes as well: those regarding the names of global symbols, the use of a hook at the end of the initialization function, and the use of keymaps and other tables.
The minor mode should, if possible, support enabling and disabling via Custom (see [Customization](customization)). To do this, the mode variable should be defined with `defcustom`, usually with `:type 'boolean`. If just setting the variable is not sufficient to enable the mode, you should also specify a `:set` method which enables the mode by invoking the mode command. Note in the variable’s documentation string that setting the variable other than via Custom may not take effect. Also, mark the definition with an autoload cookie (see [autoload cookie](autoload#autoload-cookie)), and specify a `:require` so that customizing the variable will load the library that defines the mode. For example:
```
;;;###autoload
(defcustom msb-mode nil
"Toggle msb-mode.
Setting this variable directly does not take effect;
use either \\[customize] or the function `msb-mode'."
:set 'custom-set-minor-mode
:initialize 'custom-initialize-default
:version "20.4"
:type 'boolean
:group 'msb
:require 'msb)
```
elisp None #### Finalizer Type
A *finalizer object* helps Lisp code clean up after objects that are no longer needed. A finalizer holds a Lisp function object. When a finalizer object becomes unreachable after a garbage collection pass, Emacs calls the finalizer’s associated function object. When deciding whether a finalizer is reachable, Emacs does not count references from finalizer objects themselves, allowing you to use finalizers without having to worry about accidentally capturing references to finalized objects themselves.
Errors in finalizers are printed to `*Messages*`. Emacs runs a given finalizer object’s associated function exactly once, even if that function fails.
Function: **make-finalizer** *function*
Make a finalizer that will run function. function will be called after garbage collection when the returned finalizer object becomes unreachable. If the finalizer object is reachable only through references from finalizer objects, it does not count as reachable for the purpose of deciding whether to run function. function will be run once per finalizer object.
| programming_docs |
elisp None #### General Escape Syntax
In addition to the specific escape sequences for special important control characters, Emacs provides several types of escape syntax that you can use to specify non-ASCII text characters.
1. You can specify characters by their Unicode names, if any. `?\N{NAME}` represents the Unicode character named NAME. Thus, ‘`?\N{LATIN SMALL LETTER A WITH GRAVE}`’ is equivalent to `?à` and denotes the Unicode character U+00E0. To simplify entering multi-line strings, you can replace spaces in the names by non-empty sequences of whitespace (e.g., newlines).
2. You can specify characters by their Unicode values. `?\N{U+X}` represents a character with Unicode code point X, where X is a hexadecimal number. Also, `?\uxxxx` and `?\Uxxxxxxxx` represent code points xxxx and xxxxxxxx, respectively, where each x is a single hexadecimal digit. For example, `?\N{U+E0}`, `?\u00e0` and `?\U000000E0` are all equivalent to `?à` and to ‘`?\N{LATIN SMALL LETTER A WITH GRAVE}`’. The Unicode Standard defines code points only up to ‘`U+10ffff`’, so if you specify a code point higher than that, Emacs signals an error.
3. You can specify characters by their hexadecimal character codes. A hexadecimal escape sequence consists of a backslash, ‘`x`’, and the hexadecimal character code. Thus, ‘`?\x41`’ is the character `A`, ‘`?\x1`’ is the character `C-a`, and `?\xe0` is the character `à` (`a` with grave accent). You can use any number of hex digits, so you can represent any character code in this way.
4. You can specify characters by their character code in octal. An octal escape sequence consists of a backslash followed by up to three octal digits; thus, ‘`?\101`’ for the character `A`, ‘`?\001`’ for the character `C-a`, and `?\002` for the character `C-b`. Only characters up to octal code 777 can be specified this way.
These escape sequences may also be used in strings. See [Non-ASCII in Strings](non_002dascii-in-strings).
elisp None #### Living With a Weak Parser
The parsing technique used by SMIE does not allow tokens to behave differently in different contexts. For most programming languages, this manifests itself by precedence conflicts when converting the BNF grammar.
Sometimes, those conflicts can be worked around by expressing the grammar slightly differently. For example, for Modula-2 it might seem natural to have a BNF grammar that looks like this:
```
...
(inst ("IF" exp "THEN" insts "ELSE" insts "END")
("CASE" exp "OF" cases "END")
...)
(cases (cases "|" cases)
(caselabel ":" insts)
("ELSE" insts))
...
```
But this will create conflicts for `"ELSE"`: on the one hand, the IF rule implies (among many other things) that `"ELSE" = "END"`; but on the other hand, since `"ELSE"` appears within `cases`, which appears left of `"END"`, we also have `"ELSE" > "END"`. We can solve the conflict either by using:
```
...
(inst ("IF" exp "THEN" insts "ELSE" insts "END")
("CASE" exp "OF" cases "END")
("CASE" exp "OF" cases "ELSE" insts "END")
...)
(cases (cases "|" cases) (caselabel ":" insts))
...
```
or
```
...
(inst ("IF" exp "THEN" else "END")
("CASE" exp "OF" cases "END")
...)
(else (insts "ELSE" insts))
(cases (cases "|" cases) (caselabel ":" insts) (else))
...
```
Reworking the grammar to try and solve conflicts has its downsides, tho, because SMIE assumes that the grammar reflects the logical structure of the code, so it is preferable to keep the BNF closer to the intended abstract syntax tree.
Other times, after careful consideration you may conclude that those conflicts are not serious and simply resolve them via the resolvers argument of `smie-bnf->prec2`. Usually this is because the grammar is simply ambiguous: the conflict does not affect the set of programs described by the grammar, but only the way those programs are parsed. This is typically the case for separators and associative infix operators, where you want to add a resolver like `'((assoc "|"))`. Another case where this can happen is for the classic *dangling else* problem, where you will use `'((assoc
"else" "then"))`. It can also happen for cases where the conflict is real and cannot really be resolved, but it is unlikely to pose a problem in practice.
Finally, in many cases some conflicts will remain despite all efforts to restructure the grammar. Do not despair: while the parser cannot be made more clever, you can make the lexer as smart as you want. So, the solution is then to look at the tokens involved in the conflict and to split one of those tokens into 2 (or more) different tokens. E.g., if the grammar needs to distinguish between two incompatible uses of the token `"begin"`, make the lexer return different tokens (say `"begin-fun"` and `"begin-plain"`) depending on which kind of `"begin"` it finds. This pushes the work of distinguishing the different cases to the lexer, which will thus have to look at the surrounding text to find ad-hoc clues.
elisp None #### Cons Cell and List Types
A *cons cell* is an object that consists of two slots, called the CAR slot and the CDR slot. Each slot can *hold* any Lisp object. We also say that the CAR of this cons cell is whatever object its CAR slot currently holds, and likewise for the CDR.
A *list* is a series of cons cells, linked together so that the CDR slot of each cons cell holds either the next cons cell or the empty list. The empty list is actually the symbol `nil`. See [Lists](lists), for details. Because most cons cells are used as part of lists, we refer to any structure made out of cons cells as a *list structure*.
> A note to C programmers: a Lisp list thus works as a *linked list* built up of cons cells. Because pointers in Lisp are implicit, we do not distinguish between a cons cell slot holding a value versus pointing to the value.
>
>
>
Because cons cells are so central to Lisp, we also have a word for an object which is not a cons cell. These objects are called *atoms*.
The read syntax and printed representation for lists are identical, and consist of a left parenthesis, an arbitrary number of elements, and a right parenthesis. Here are examples of lists:
```
(A 2 "A") ; A list of three elements.
() ; A list of no elements (the empty list).
nil ; A list of no elements (the empty list).
("A ()") ; A list of one element: the string `"A ()"`.
(A ()) ; A list of two elements: `A` and the empty list.
(A nil) ; Equivalent to the previous.
((A B C)) ; A list of one element
; (which is a list of three elements).
```
Upon reading, each object inside the parentheses becomes an element of the list. That is, a cons cell is made for each element. The CAR slot of the cons cell holds the element, and its CDR slot refers to the next cons cell of the list, which holds the next element in the list. The CDR slot of the last cons cell is set to hold `nil`.
The names CAR and CDR derive from the history of Lisp. The original Lisp implementation ran on an IBM 704 computer which divided words into two parts, the address and the decrement; CAR was an instruction to extract the contents of the address part of a register, and CDR an instruction to extract the contents of the decrement. By contrast, cons cells are named for the function `cons` that creates them, which in turn was named for its purpose, the construction of cells.
| | | |
| --- | --- | --- |
| • [Box Diagrams](box-diagrams) | | Drawing pictures of lists. |
| • [Dotted Pair Notation](dotted-pair-notation) | | A general syntax for cons cells. |
| • [Association List Type](association-list-type) | | A specially constructed list. |
elisp None #### Cursor Parameters
This frame parameter controls the way the cursor looks.
`cursor-type`
How to display the cursor. Legitimate values are:
`box` Display a filled box. (This is the default.)
`(box . size)` Display a filled box. However, display it as a hollow box if point is under masked image larger than size pixels in either dimension.
`hollow` Display a hollow box.
`nil` Don’t display a cursor.
`bar` Display a vertical bar between characters.
`(bar . width)` Display a vertical bar width pixels wide between characters.
`hbar` Display a horizontal bar.
`(hbar . height)` Display a horizontal bar height pixels high.
The `cursor-type` frame parameter may be overridden by the variables `cursor-type` and `cursor-in-non-selected-windows`:
User Option: **cursor-type**
This buffer-local variable controls how the cursor looks in a selected window showing the buffer. If its value is `t`, that means to use the cursor specified by the `cursor-type` frame parameter. Otherwise, the value should be one of the cursor types listed above, and it overrides the `cursor-type` frame parameter.
User Option: **cursor-in-non-selected-windows**
This buffer-local variable controls how the cursor looks in a window that is not selected. It supports the same values as the `cursor-type` frame parameter; also, `nil` means don’t display a cursor in nonselected windows, and `t` (the default) means use a standard modification of the usual cursor type (solid box becomes hollow box, and bar becomes a narrower bar).
User Option: **x-stretch-cursor**
This variable controls the width of the block cursor displayed on extra-wide glyphs such as a tab or a stretch of white space. By default, the block cursor is only as wide as the font’s default character, and will not cover all of the width of the glyph under it if that glyph is extra-wide. A non-`nil` value of this variable means draw the block cursor as wide as the glyph under it. The default value is `nil`.
This variable has no effect on text-mode frames, since the text-mode cursor is drawn by the terminal out of Emacs’s control.
User Option: **blink-cursor-alist**
This variable specifies how to blink the cursor. Each element has the form `(on-state . off-state)`. Whenever the cursor type equals on-state (comparing using `equal`), the corresponding off-state specifies what the cursor looks like when it blinks off. Both on-state and off-state should be suitable values for the `cursor-type` frame parameter.
There are various defaults for how to blink each type of cursor, if the type is not mentioned as an on-state here. Changes in this variable do not take effect immediately, only when you specify the `cursor-type` frame parameter.
elisp None #### Creating and Deleting Buffer-Local Bindings
Command: **make-local-variable** *variable*
This function creates a buffer-local binding in the current buffer for variable (a symbol). Other buffers are not affected. The value returned is variable.
The buffer-local value of variable starts out as the same value variable previously had. If variable was void, it remains void.
```
;; In buffer ‘`b1`’:
(setq foo 5) ; Affects all buffers.
⇒ 5
```
```
(make-local-variable 'foo) ; Now it is local in ‘`b1`’.
⇒ foo
```
```
foo ; That did not change
⇒ 5 ; the value.
```
```
(setq foo 6) ; Change the value
⇒ 6 ; in ‘`b1`’.
```
```
foo
⇒ 6
```
```
;; In buffer ‘`b2`’, the value hasn’t changed.
(with-current-buffer "b2"
foo)
⇒ 5
```
Making a variable buffer-local within a `let`-binding for that variable does not work reliably, unless the buffer in which you do this is not current either on entry to or exit from the `let`. This is because `let` does not distinguish between different kinds of bindings; it knows only which variable the binding was made for.
It is an error to make a constant or a read-only variable buffer-local. See [Constant Variables](constant-variables).
If the variable is terminal-local (see [Multiple Terminals](multiple-terminals)), this function signals an error. Such variables cannot have buffer-local bindings as well.
**Warning:** do not use `make-local-variable` for a hook variable. The hook variables are automatically made buffer-local as needed if you use the local argument to `add-hook` or `remove-hook`.
Macro: **setq-local** *&rest pairs*
pairs is a list of variable and value pairs. This macro creates a buffer-local binding in the current buffer for each of the variables, and gives them a buffer-local value. It is equivalent to calling `make-local-variable` followed by `setq` for each of the variables. The variables should be unquoted symbols.
```
(setq-local var1 "value1"
var2 "value2")
```
Command: **make-variable-buffer-local** *variable*
This function marks variable (a symbol) automatically buffer-local, so that any subsequent attempt to set it will make it local to the current buffer at the time. Unlike `make-local-variable`, with which it is often confused, this cannot be undone, and affects the behavior of the variable in all buffers.
A peculiar wrinkle of this feature is that binding the variable (with `let` or other binding constructs) does not create a buffer-local binding for it. Only setting the variable (with `set` or `setq`), while the variable does not have a `let`-style binding that was made in the current buffer, does so.
If variable does not have a default value, then calling this command will give it a default value of `nil`. If variable already has a default value, that value remains unchanged. Subsequently calling `makunbound` on variable will result in a void buffer-local value and leave the default value unaffected.
The value returned is variable.
It is an error to make a constant or a read-only variable buffer-local. See [Constant Variables](constant-variables).
**Warning:** Don’t assume that you should use `make-variable-buffer-local` for user-option variables, simply because users *might* want to customize them differently in different buffers. Users can make any variable local, when they wish to. It is better to leave the choice to them.
The time to use `make-variable-buffer-local` is when it is crucial that no two buffers ever share the same binding. For example, when a variable is used for internal purposes in a Lisp program which depends on having separate values in separate buffers, then using `make-variable-buffer-local` can be the best solution.
Macro: **defvar-local** *variable value &optional docstring*
This macro defines variable as a variable with initial value value and docstring, and marks it as automatically buffer-local. It is equivalent to calling `defvar` followed by `make-variable-buffer-local`. variable should be an unquoted symbol.
Function: **local-variable-p** *variable &optional buffer*
This returns `t` if variable is buffer-local in buffer buffer (which defaults to the current buffer); otherwise, `nil`.
Function: **local-variable-if-set-p** *variable &optional buffer*
This returns `t` if variable either has a buffer-local value in buffer buffer, or is automatically buffer-local. Otherwise, it returns `nil`. If omitted or `nil`, buffer defaults to the current buffer.
Function: **buffer-local-value** *variable buffer*
This function returns the buffer-local binding of variable (a symbol) in buffer buffer. If variable does not have a buffer-local binding in buffer buffer, it returns the default value (see [Default Value](default-value)) of variable instead.
Function: **buffer-local-boundp** *variable buffer*
This returns non-`nil` if there’s either a buffer-local binding of variable (a symbol) in buffer buffer, or variable has a global binding.
Function: **buffer-local-variables** *&optional buffer*
This function returns a list describing the buffer-local variables in buffer buffer. (If buffer is omitted, the current buffer is used.) Normally, each list element has the form `(sym . val)`, where sym is a buffer-local variable (a symbol) and val is its buffer-local value. But when a variable’s buffer-local binding in buffer is void, its list element is just sym.
```
(make-local-variable 'foobar)
(makunbound 'foobar)
(make-local-variable 'bind-me)
(setq bind-me 69)
```
```
(setq lcl (buffer-local-variables))
;; First, built-in variables local in all buffers:
⇒ ((mark-active . nil)
(buffer-undo-list . nil)
(mode-name . "Fundamental")
…
```
```
;; Next, non-built-in buffer-local variables.
;; This one is buffer-local and void:
foobar
;; This one is buffer-local and nonvoid:
(bind-me . 69))
```
Note that storing new values into the CDRs of cons cells in this list does *not* change the buffer-local values of the variables.
Command: **kill-local-variable** *variable*
This function deletes the buffer-local binding (if any) for variable (a symbol) in the current buffer. As a result, the default binding of variable becomes visible in this buffer. This typically results in a change in the value of variable, since the default value is usually different from the buffer-local value just eliminated.
If you kill the buffer-local binding of a variable that automatically becomes buffer-local when set, this makes the default value visible in the current buffer. However, if you set the variable again, that will once again create a buffer-local binding for it.
`kill-local-variable` returns variable.
This function is a command because it is sometimes useful to kill one buffer-local variable interactively, just as it is useful to create buffer-local variables interactively.
Function: **kill-all-local-variables**
This function eliminates all the buffer-local variable bindings of the current buffer except for variables marked as permanent and local hook functions that have a non-`nil` `permanent-local-hook` property (see [Setting Hooks](setting-hooks)). As a result, the buffer will see the default values of most variables.
This function also resets certain other information pertaining to the buffer: it sets the local keymap to `nil`, the syntax table to the value of `(standard-syntax-table)`, the case table to `(standard-case-table)`, and the abbrev table to the value of `fundamental-mode-abbrev-table`.
The very first thing this function does is run the normal hook `change-major-mode-hook` (see below).
Every major mode command begins by calling this function, which has the effect of switching to Fundamental mode and erasing most of the effects of the previous major mode. To ensure that this does its job, the variables that major modes set should not be marked permanent.
`kill-all-local-variables` returns `nil`.
Variable: **change-major-mode-hook**
The function `kill-all-local-variables` runs this normal hook before it does anything else. This gives major modes a way to arrange for something special to be done if the user switches to a different major mode. It is also useful for buffer-specific minor modes that should be forgotten if the user changes the major mode.
For best results, make this variable buffer-local, so that it will disappear after doing its job and will not interfere with the subsequent major mode. See [Hooks](hooks).
A buffer-local variable is *permanent* if the variable name (a symbol) has a `permanent-local` property that is non-`nil`. Such variables are unaffected by `kill-all-local-variables`, and their local bindings are therefore not cleared by changing major modes. Permanent locals are appropriate for data pertaining to where the file came from or how to save it, rather than with how to edit the contents.
elisp None #### The rx Structured Regexp Notation
As an alternative to the string-based syntax, Emacs provides the structured `rx` notation based on Lisp S-expressions. This notation is usually easier to read, write and maintain than regexp strings, and can be indented and commented freely. It requires a conversion into string form since that is what regexp functions expect, but that conversion typically takes place during byte-compilation rather than when the Lisp code using the regexp is run.
Here is an `rx` regexp[22](#FOOT22) that matches a block comment in the C programming language:
```
(rx "/*" ; Initial /*
(zero-or-more
(or (not (any "*")) ; Either non-*,
(seq "*" ; or * followed by
(not (any "/"))))) ; non-/
(one-or-more "*") ; At least one star,
"/") ; and the final /
```
or, using shorter synonyms and written more compactly,
```
(rx "/*"
(* (| (not "*")
(: "*" (not "/"))))
(+ "*") "/")
```
In conventional string syntax, it would be written
```
"/\\*\\(?:[^*]\\|\\*[^/]\\)*\\*+/"
```
The `rx` notation is mainly useful in Lisp code; it cannot be used in most interactive situations where a regexp is requested, such as when running `query-replace-regexp` or in variable customization.
| | | |
| --- | --- | --- |
| • [Rx Constructs](rx-constructs) | | Constructs valid in rx forms. |
| • [Rx Functions](rx-functions) | | Functions and macros that use rx forms. |
| • [Extending Rx](extending-rx) | | How to define your own rx forms. |
| programming_docs |
elisp None #### Default Coding Systems
This section describes variables that specify the default coding system for certain files or when running certain subprograms, and the function that I/O operations use to access them.
The idea of these variables is that you set them once and for all to the defaults you want, and then do not change them again. To specify a particular coding system for a particular operation in a Lisp program, don’t change these variables; instead, override them using `coding-system-for-read` and `coding-system-for-write` (see [Specifying Coding Systems](specifying-coding-systems)).
User Option: **auto-coding-regexp-alist**
This variable is an alist of text patterns and corresponding coding systems. Each element has the form `(regexp
. coding-system)`; a file whose first few kilobytes match regexp is decoded with coding-system when its contents are read into a buffer. The settings in this alist take priority over `coding:` tags in the files and the contents of `file-coding-system-alist` (see below). The default value is set so that Emacs automatically recognizes mail files in Babyl format and reads them with no code conversions.
User Option: **file-coding-system-alist**
This variable is an alist that specifies the coding systems to use for reading and writing particular files. Each element has the form `(pattern . coding)`, where pattern is a regular expression that matches certain file names. The element applies to file names that match pattern.
The CDR of the element, coding, should be either a coding system, a cons cell containing two coding systems, or a function name (a symbol with a function definition). If coding is a coding system, that coding system is used for both reading the file and writing it. If coding is a cons cell containing two coding systems, its CAR specifies the coding system for decoding, and its CDR specifies the coding system for encoding.
If coding is a function name, the function should take one argument, a list of all arguments passed to `find-operation-coding-system`. It must return a coding system or a cons cell containing two coding systems. This value has the same meaning as described above.
If coding (or what returned by the above function) is `undecided`, the normal code-detection is performed.
User Option: **auto-coding-alist**
This variable is an alist that specifies the coding systems to use for reading and writing particular files. Its form is like that of `file-coding-system-alist`, but, unlike the latter, this variable takes priority over any `coding:` tags in the file.
Variable: **process-coding-system-alist**
This variable is an alist specifying which coding systems to use for a subprocess, depending on which program is running in the subprocess. It works like `file-coding-system-alist`, except that pattern is matched against the program name used to start the subprocess. The coding system or systems specified in this alist are used to initialize the coding systems used for I/O to the subprocess, but you can specify other coding systems later using `set-process-coding-system`.
**Warning:** Coding systems such as `undecided`, which determine the coding system from the data, do not work entirely reliably with asynchronous subprocess output. This is because Emacs handles asynchronous subprocess output in batches, as it arrives. If the coding system leaves the character code conversion unspecified, or leaves the end-of-line conversion unspecified, Emacs must try to detect the proper conversion from one batch at a time, and this does not always work.
Therefore, with an asynchronous subprocess, if at all possible, use a coding system which determines both the character code conversion and the end of line conversion—that is, one like `latin-1-unix`, rather than `undecided` or `latin-1`.
Variable: **network-coding-system-alist**
This variable is an alist that specifies the coding system to use for network streams. It works much like `file-coding-system-alist`, with the difference that the pattern in an element may be either a port number or a regular expression. If it is a regular expression, it is matched against the network service name used to open the network stream.
Variable: **default-process-coding-system**
This variable specifies the coding systems to use for subprocess (and network stream) input and output, when nothing else specifies what to do.
The value should be a cons cell of the form `(input-coding
. output-coding)`. Here input-coding applies to input from the subprocess, and output-coding applies to output to it.
User Option: **auto-coding-functions**
This variable holds a list of functions that try to determine a coding system for a file based on its undecoded contents.
Each function in this list should be written to look at text in the current buffer, but should not modify it in any way. The buffer will contain the text of parts of the file. Each function should take one argument, size, which tells it how many characters to look at, starting from point. If the function succeeds in determining a coding system for the file, it should return that coding system. Otherwise, it should return `nil`.
The functions in this list could be called either when the file is visited and Emacs wants to decode its contents, and/or when the file’s buffer is about to be saved and Emacs wants to determine how to encode its contents.
If a file has a ‘`coding:`’ tag, that takes precedence, so these functions won’t be called.
Function: **find-auto-coding** *filename size*
This function tries to determine a suitable coding system for filename. It examines the buffer visiting the named file, using the variables documented above in sequence, until it finds a match for one of the rules specified by these variables. It then returns a cons cell of the form `(coding . source)`, where coding is the coding system to use and source is a symbol, one of `auto-coding-alist`, `auto-coding-regexp-alist`, `:coding`, or `auto-coding-functions`, indicating which one supplied the matching rule. The value `:coding` means the coding system was specified by the `coding:` tag in the file (see [coding tag](https://www.gnu.org/software/emacs/manual/html_node/emacs/Specify-Coding.html#Specify-Coding) in The GNU Emacs Manual). The order of looking for a matching rule is `auto-coding-alist` first, then `auto-coding-regexp-alist`, then the `coding:` tag, and lastly `auto-coding-functions`. If no matching rule was found, the function returns `nil`.
The second argument size is the size of text, in characters, following point. The function examines text only within size characters after point. Normally, the buffer should be positioned at the beginning when this function is called, because one of the places for the `coding:` tag is the first one or two lines of the file; in that case, size should be the size of the buffer.
Function: **set-auto-coding** *filename size*
This function returns a suitable coding system for file filename. It uses `find-auto-coding` to find the coding system. If no coding system could be determined, the function returns `nil`. The meaning of the argument size is like in `find-auto-coding`.
Function: **find-operation-coding-system** *operation &rest arguments*
This function returns the coding system to use (by default) for performing operation with arguments. The value has this form:
```
(decoding-system . encoding-system)
```
The first element, decoding-system, is the coding system to use for decoding (in case operation does decoding), and encoding-system is the coding system for encoding (in case operation does encoding).
The argument operation is a symbol; it should be one of `write-region`, `start-process`, `call-process`, `call-process-region`, `insert-file-contents`, or `open-network-stream`. These are the names of the Emacs I/O primitives that can do character code and eol conversion.
The remaining arguments should be the same arguments that might be given to the corresponding I/O primitive. Depending on the primitive, one of those arguments is selected as the *target*. For example, if operation does file I/O, whichever argument specifies the file name is the target. For subprocess primitives, the process name is the target. For `open-network-stream`, the target is the service name or port number.
Depending on operation, this function looks up the target in `file-coding-system-alist`, `process-coding-system-alist`, or `network-coding-system-alist`. If the target is found in the alist, `find-operation-coding-system` returns its association in the alist; otherwise it returns `nil`.
If operation is `insert-file-contents`, the argument corresponding to the target may be a cons cell of the form `(filename . buffer)`. In that case, filename is a file name to look up in `file-coding-system-alist`, and buffer is a buffer that contains the file’s contents (not yet decoded). If `file-coding-system-alist` specifies a function to call for this file, and that function needs to examine the file’s contents (as it usually does), it should examine the contents of buffer instead of reading the file.
elisp None ### Common Item Keywords
The customization declarations that we will describe in the next few sections—`defcustom`, `defgroup`, etc.—all accept keyword arguments (see [Constant Variables](constant-variables)) for specifying various information. This section describes keywords that apply to all types of customization declarations.
All of these keywords, except `:tag`, can be used more than once in a given item. Each use of the keyword has an independent effect. The keyword `:tag` is an exception because any given item can only display one name.
`:tag label`
Use label, a string, instead of the item’s name, to label the item in customization menus and buffers. **Don’t use a tag which is substantially different from the item’s real name; that would cause confusion.**
`:group group`
Put this customization item in group group. If this keyword is missing from a customization item, it’ll be placed in the same group that was last defined (in the current file).
When you use `:group` in a `defgroup`, it makes the new group a subgroup of group.
If you use this keyword more than once, you can put a single item into more than one group. Displaying any of those groups will show this item. Please don’t overdo this, since the result would be annoying.
`:link link-data`
Include an external link after the documentation string for this item. This is a sentence containing a button that references some other documentation.
There are several alternatives you can use for link-data:
`(custom-manual info-node)`
Link to an Info node; info-node is a string which specifies the node name, as in `"(emacs)Top"`. The link appears as ‘`[Manual]`’ in the customization buffer and enters the built-in Info reader on info-node.
`(info-link info-node)`
Like `custom-manual` except that the link appears in the customization buffer with the Info node name.
`(url-link url)`
Link to a web page; url is a string which specifies the URL. The link appears in the customization buffer as url and invokes the WWW browser specified by `browse-url-browser-function`.
`(emacs-commentary-link library)`
Link to the commentary section of a library; library is a string which specifies the library name. See [Library Headers](https://www.gnu.org/software/emacs/manual/html_node/elisp/Library-Headers.html).
`(emacs-library-link library)`
Link to an Emacs Lisp library file; library is a string which specifies the library name.
`(file-link file)`
Link to a file; file is a string which specifies the name of the file to visit with `find-file` when the user invokes this link.
`(function-link function)`
Link to the documentation of a function; function is a string which specifies the name of the function to describe with `describe-function` when the user invokes this link.
`(variable-link variable)`
Link to the documentation of a variable; variable is a string which specifies the name of the variable to describe with `describe-variable` when the user invokes this link.
`(face-link face)`
Link to the documentation of a face; face is a string which specifies the name of the face to describe with `describe-face` when the user invokes this link.
`(custom-group-link group)` Link to another customization group. Invoking it creates a new customization buffer for group.
You can specify the text to use in the customization buffer by adding `:tag name` after the first element of the link-data; for example, `(info-link :tag "foo" "(emacs)Top")` makes a link to the Emacs manual which appears in the buffer as ‘`foo`’.
You can use this keyword more than once, to add multiple links.
`:load file`
Load file file (a string) before displaying this customization item (see [Loading](loading)). Loading is done with `load`, and only if the file is not already loaded.
`:require feature`
Execute `(require 'feature)` when your saved customizations set the value of this item. feature should be a symbol.
The most common reason to use `:require` is when a variable enables a feature such as a minor mode, and just setting the variable won’t have any effect unless the code which implements the mode is loaded.
`:version version`
This keyword specifies that the item was first introduced in Emacs version version, or that its default value was changed in that version. The value version must be a string.
`:package-version '(package . version)`
This keyword specifies that the item was first introduced in package version version, or that its meaning or default value was changed in that version. This keyword takes priority over `:version`.
package should be the official name of the package, as a symbol (e.g., `MH-E`). version should be a string. If the package package is released as part of Emacs, package and version should appear in the value of `customize-package-emacs-version-alist`.
Packages distributed as part of Emacs that use the `:package-version` keyword must also update the `customize-package-emacs-version-alist` variable.
Variable: **customize-package-emacs-version-alist**
This alist provides a mapping for the versions of Emacs that are associated with versions of a package listed in the `:package-version` keyword. Its elements are:
```
(package (pversion . eversion)…)
```
For each package, which is a symbol, there are one or more elements that contain a package version pversion with an associated Emacs version eversion. These versions are strings. For example, the MH-E package updates this alist with the following:
```
(add-to-list 'customize-package-emacs-version-alist
'(MH-E ("6.0" . "22.1") ("6.1" . "22.1") ("7.0" . "22.1")
("7.1" . "22.1") ("7.2" . "22.1") ("7.3" . "22.1")
("7.4" . "22.1") ("8.0" . "22.1")))
```
The value of package needs to be unique and it needs to match the package value appearing in the `:package-version` keyword. Since the user might see the value in an error message, a good choice is the official name of the package, such as MH-E or Gnus.
elisp None ### Changing File Names and Attributes
The functions in this section rename, copy, delete, link, and set the modes (permissions) of files. Typically, they signal a `file-error` error if they fail to perform their function, reporting the system-dependent error message that describes the reason for the failure. If they fail because a file is missing, they signal a `file-missing` error instead.
For performance, the operating system may cache or alias changes made by these functions instead of writing them immediately to secondary storage. See [Files and Storage](files-and-storage).
In the functions that have an argument newname, if this argument is a directory name it is treated as if the nondirectory part of the source name were appended. Typically, a directory name is one that ends in ‘`/`’ (see [Directory Names](directory-names)). For example, if the old name is `a/b/c`, the newname `d/e/f/` is treated as if it were `d/e/f/c`. This special treatment does not apply if newname is not a directory name but names a file that is a directory; for example, the newname `d/e/f` is left as-is even if `d/e/f` happens to be a directory.
In the functions that have an argument newname, if a file by the name of newname already exists, the actions taken depend on the value of the argument ok-if-already-exists:
* Signal a `file-already-exists` error if ok-if-already-exists is `nil`.
* Request confirmation if ok-if-already-exists is a number.
* Replace the old file without confirmation if ok-if-already-exists is any other value.
Command: **add-name-to-file** *oldname newname &optional ok-if-already-exists*
This function gives the file named oldname the additional name newname. This means that newname becomes a new hard link to oldname.
If newname is a symbolic link, its directory entry is replaced, not the directory entry it points to. If oldname is a symbolic link, this function might or might not follow the link; it does not follow the link on GNU platforms. If oldname is a directory, this function typically fails, although for the superuser on a few old-fashioned non-GNU platforms it can succeed and create a filesystem that is not tree-structured.
In the first part of the following example, we list two files, `foo` and `foo3`.
```
$ ls -li fo*
81908 -rw-rw-rw- 1 rms rms 29 Aug 18 20:32 foo
84302 -rw-rw-rw- 1 rms rms 24 Aug 18 20:31 foo3
```
Now we create a hard link, by calling `add-name-to-file`, then list the files again. This shows two names for one file, `foo` and `foo2`.
```
(add-name-to-file "foo" "foo2")
⇒ nil
```
```
$ ls -li fo*
81908 -rw-rw-rw- 2 rms rms 29 Aug 18 20:32 foo
81908 -rw-rw-rw- 2 rms rms 29 Aug 18 20:32 foo2
84302 -rw-rw-rw- 1 rms rms 24 Aug 18 20:31 foo3
```
Finally, we evaluate the following:
```
(add-name-to-file "foo" "foo3" t)
```
and list the files again. Now there are three names for one file: `foo`, `foo2`, and `foo3`. The old contents of `foo3` are lost.
```
(add-name-to-file "foo1" "foo3")
⇒ nil
```
```
$ ls -li fo*
81908 -rw-rw-rw- 3 rms rms 29 Aug 18 20:32 foo
81908 -rw-rw-rw- 3 rms rms 29 Aug 18 20:32 foo2
81908 -rw-rw-rw- 3 rms rms 29 Aug 18 20:32 foo3
```
This function is meaningless on operating systems where multiple names for one file are not allowed. Some systems implement multiple names by copying the file instead.
See also `file-nlinks` in [File Attributes](file-attributes).
Command: **rename-file** *filename newname &optional ok-if-already-exists*
This command renames the file filename as newname.
If filename has additional names aside from filename, it continues to have those names. In fact, adding the name newname with `add-name-to-file` and then deleting filename has the same effect as renaming, aside from momentary intermediate states and treatment of errors, directories and symbolic links.
This command does not follow symbolic links. If filename is a symbolic link, this command renames the symbolic link, not the file it points to. If newname is a symbolic link, its directory entry is replaced, not the directory entry it points to.
This command does nothing if filename and newname are the same directory entry, i.e., if they refer to the same parent directory and give the same name within that directory. Otherwise, if filename and newname name the same file, this command does nothing on POSIX-conforming systems, and removes filename on some non-POSIX systems.
If newname exists, then it must be an empty directory if oldname is a directory and a non-directory otherwise.
Command: **copy-file** *oldname newname &optional ok-if-already-exists time preserve-uid-gid preserve-extended-attributes*
This command copies the file oldname to newname. An error is signaled if oldname is not a regular file. If newname names a directory, it copies oldname into that directory, preserving its final name component.
This function follows symbolic links, except that it does not follow a dangling symbolic link to create newname.
If time is non-`nil`, then this function gives the new file the same last-modified time that the old one has. (This works on only some operating systems.) If setting the time gets an error, `copy-file` signals a `file-date-error` error. In an interactive call, a prefix argument specifies a non-`nil` value for time.
If argument preserve-uid-gid is `nil`, we let the operating system decide the user and group ownership of the new file (this is usually set to the user running Emacs). If preserve-uid-gid is non-`nil`, we attempt to copy the user and group ownership of the file. This works only on some operating systems, and only if you have the correct permissions to do so.
If the optional argument preserve-permissions is non-`nil`, this function copies the file modes (or “permissions”) of oldname to newname, as well as the Access Control List and SELinux context (if any). See [Information about Files](information-about-files).
Otherwise, the file modes of newname are left unchanged if it is an existing file, and set to those of oldname, masked by the default file permissions (see `set-default-file-modes` below), if newname is to be newly created. The Access Control List or SELinux context are not copied over in either case.
Command: **make-symbolic-link** *target linkname &optional ok-if-already-exists*
This command makes a symbolic link to target, named linkname. This is like the shell command ‘`ln -s target linkname`’. The target argument is treated only as a string; it need not name an existing file. If ok-if-already-exists is an integer, indicating interactive use, then leading ‘`~`’ is expanded and leading ‘`/:`’ is stripped in the target string.
If target is a relative file name, the resulting symbolic link is interpreted relative to the directory containing the symbolic link. See [Relative File Names](relative-file-names).
If both target and linkname have remote file name syntax, and if both remote identifications are equal, the symbolic link points to the local file name part of target.
This function is not available on systems that don’t support symbolic links.
Command: **delete-file** *filename &optional trash*
This command deletes the file filename. If the file has multiple names, it continues to exist under the other names. If filename is a symbolic link, `delete-file` deletes only the symbolic link and not its target.
A suitable kind of `file-error` error is signaled if the file does not exist, or is not deletable. (On GNU and other POSIX-like systems, a file is deletable if its directory is writable.)
If the optional argument trash is non-`nil` and the variable `delete-by-moving-to-trash` is non-`nil`, this command moves the file into the system Trash instead of deleting it. See [Miscellaneous File Operations](https://www.gnu.org/software/emacs/manual/html_node/emacs/Misc-File-Ops.html#Misc-File-Ops) in The GNU Emacs Manual. When called interactively, trash is `t` if no prefix argument is given, and `nil` otherwise.
See also `delete-directory` in [Create/Delete Dirs](create_002fdelete-dirs).
Command: **set-file-modes** *filename mode &optional flag*
This function sets the *file mode* (or *permissions*) of filename to mode.
By default this function follows symbolic links. However, if the optional argument flag is the symbol `nofollow`, this function does not follow filename if it is a symbolic link; this can help prevent inadvertently changing the mode bits of a file somewhere else. On platforms that do not support changing mode bits on a symbolic link, this function signals an error when filename is a symbolic link and flag is `nofollow`.
If called non-interactively, mode must be an integer. Only the lowest 12 bits of the integer are used; on most systems, only the lowest 9 bits are meaningful. You can use the Lisp construct for octal numbers to enter mode. For example,
```
(set-file-modes "myfile" #o644 'nofollow)
```
specifies that the file should be readable and writable for its owner, readable for group members, and readable for all other users. See [File permissions](https://www.gnu.org/software/coreutils/manual/html_node/File-permissions.html#File-permissions) in The GNU `Coreutils` Manual, for a description of mode bit specifications.
Interactively, mode is read from the minibuffer using `read-file-modes` (see below), which lets the user type in either an integer or a string representing the permissions symbolically.
See [Testing Accessibility](testing-accessibility), for the function `file-modes`, which returns the permissions of a file.
Function: **set-default-file-modes** *mode*
This function sets the default permissions for new files created by Emacs and its subprocesses. Every file created with Emacs initially has these permissions, or a subset of them (`write-region` will not grant execute permissions even if the default file permissions allow execution). On GNU and other POSIX-like systems, the default permissions are given by the bitwise complement of the ‘`umask`’ value, i.e. each bit that is set in the argument mode will be *reset* in the default permissions with which Emacs creates files.
The argument mode should be an integer which specifies the permissions, similar to `set-file-modes` above. Only the lowest 9 bits are meaningful.
The default file permissions have no effect when you save a modified version of an existing file; saving a file preserves its existing permissions.
Macro: **with-file-modes** *mode body…*
This macro evaluates the body forms with the default permissions for new files temporarily set to modes (whose value is as for `set-file-modes` above). When finished, it restores the original default file permissions, and returns the value of the last form in body.
This is useful for creating private files, for example.
Function: **default-file-modes**
This function returns the default file permissions, as an integer.
Function: **read-file-modes** *&optional prompt base-file*
This function reads a set of file mode bits from the minibuffer. The first optional argument prompt specifies a non-default prompt. Second second optional argument base-file is the name of a file on whose permissions to base the mode bits that this function returns, if what the user types specifies mode bits relative to permissions of an existing file.
If user input represents an octal number, this function returns that number. If it is a complete symbolic specification of mode bits, as in `"u=rwx"`, the function converts it to the equivalent numeric value using `file-modes-symbolic-to-number` and returns the result. If the specification is relative, as in `"o+g"`, then the permissions on which the specification is based are taken from the mode bits of base-file. If base-file is omitted or `nil`, the function uses `0` as the base mode bits. The complete and relative specifications can be combined, as in `"u+r,g+rx,o+r,g-w"`. See [File permissions](https://www.gnu.org/software/coreutils/manual/html_node/File-permissions.html#File-permissions) in The GNU `Coreutils` Manual, for a description of file mode specifications.
Function: **file-modes-symbolic-to-number** *modes &optional base-modes*
This function converts a symbolic file mode specification in modes into the equivalent integer. If the symbolic specification is based on an existing file, that file’s mode bits are taken from the optional argument base-modes; if that argument is omitted or `nil`, it defaults to 0, i.e., no access rights at all.
Function: **file-modes-number-to-symbolic** *modes*
This function converts a numeric file mode specification in modes into the equivalent symbolic form.
Function: **set-file-times** *filename &optional time flag*
This function sets the access and modification times of filename to time. The return value is `t` if the times are successfully set, otherwise it is `nil`. time defaults to the current time and must be a time value (see [Time of Day](time-of-day)).
By default this function follows symbolic links. However, if the optional argument flag is the symbol `nofollow`, this function does not follow filename if it is a symbolic link; this can help prevent inadvertently changing the times of a file somewhere else. On platforms that do not support changing times on a symbolic link, this function signals an error when filename is a symbolic link and flag is `nofollow`.
Function: **set-file-extended-attributes** *filename attribute-alist*
This function sets the Emacs-recognized extended file attributes for filename. The second argument attribute-alist should be an alist of the same form returned by `file-extended-attributes`. The return value is `t` if the attributes are successfully set, otherwise it is `nil`. See [Extended Attributes](extended-attributes).
Function: **set-file-selinux-context** *filename context*
This function sets the SELinux security context for filename to context. The context argument should be a list `(user role type range)`, where each element is a string. See [Extended Attributes](extended-attributes).
The function returns `t` if it succeeds in setting the SELinux context of filename. It returns `nil` if the context was not set (e.g., if SELinux is disabled, or if Emacs was compiled without SELinux support).
Function: **set-file-acl** *filename acl*
This function sets the Access Control List for filename to acl. The acl argument should have the same form returned by the function `file-acl`. See [Extended Attributes](extended-attributes).
The function returns `t` if it successfully sets the ACL of filename, `nil` otherwise.
| programming_docs |
elisp None #### Fontsets
A *fontset* is a list of fonts, each assigned to a range of character codes. An individual font cannot display the whole range of characters that Emacs supports, but a fontset can. Fontsets have names, just as fonts do, and you can use a fontset name in place of a font name when you specify the font for a frame or a face. Here is information about defining a fontset under Lisp program control.
Function: **create-fontset-from-fontset-spec** *fontset-spec &optional style-variant-p noerror*
This function defines a new fontset according to the specification string fontset-spec. The string should have this format:
```
fontpattern, [charset:font]…
```
Whitespace characters before and after the commas are ignored.
The first part of the string, fontpattern, should have the form of a standard X font name, except that the last two fields should be ‘`fontset-alias`’.
The new fontset has two names, one long and one short. The long name is fontpattern in its entirety. The short name is ‘`fontset-alias`’. You can refer to the fontset by either name. If a fontset with the same name already exists, an error is signaled, unless noerror is non-`nil`, in which case this function does nothing.
If optional argument style-variant-p is non-`nil`, that says to create bold, italic and bold-italic variants of the fontset as well. These variant fontsets do not have a short name, only a long one, which is made by altering fontpattern to indicate the bold and/or italic status.
The specification string also says which fonts to use in the fontset. See below for the details.
The construct ‘`charset:font`’ specifies which font to use (in this fontset) for one particular character set. Here, charset is the name of a character set, and font is the font to use for that character set. You can use this construct any number of times in the specification string.
For the remaining character sets, those that you don’t specify explicitly, Emacs chooses a font based on fontpattern: it replaces ‘`fontset-alias`’ with a value that names one character set. For the ASCII character set, ‘`fontset-alias`’ is replaced with ‘`ISO8859-1`’.
In addition, when several consecutive fields are wildcards, Emacs collapses them into a single wildcard. This is to prevent use of auto-scaled fonts. Fonts made by scaling larger fonts are not usable for editing, and scaling a smaller font is not useful because it is better to use the smaller font in its own size, which Emacs does.
Thus if fontpattern is this,
```
-*-fixed-medium-r-normal-*-24-*-*-*-*-*-fontset-24
```
the font specification for ASCII characters would be this:
```
-*-fixed-medium-r-normal-*-24-*-ISO8859-1
```
and the font specification for Chinese GB2312 characters would be this:
```
-*-fixed-medium-r-normal-*-24-*-gb2312*-*
```
You may not have any Chinese font matching the above font specification. Most X distributions include only Chinese fonts that have ‘`song ti`’ or ‘`fangsong ti`’ in the family field. In such a case, ‘`Fontset-n`’ can be specified as below:
```
Emacs.Fontset-0: -*-fixed-medium-r-normal-*-24-*-*-*-*-*-fontset-24,\
chinese-gb2312:-*-*-medium-r-normal-*-24-*-gb2312*-*
```
Then, the font specifications for all but Chinese GB2312 characters have ‘`fixed`’ in the family field, and the font specification for Chinese GB2312 characters has a wild card ‘`\*`’ in the family field.
Function: **set-fontset-font** *fontset characters font-spec &optional frame add*
This function modifies the existing fontset to use the font specified by font-spec for displaying the specified characters.
If fontset is `nil`, this function modifies the fontset of the selected frame or that of frame if frame is not `nil`.
If fontset is `t`, this function modifies the default fontset, whose short name as a string is ‘`fontset-default`’.
The characters argument can be a single character which should be displayed using font-spec. It can also be a cons cell `(from . to)`, where from and to are characters. In that case, use font-spec for all the characters in the range from and to (inclusive).
characters may be a charset symbol (see [Character Sets](character-sets)). In that case, use font-spec for all the characters in the charset.
characters may be a script symbol (see [char-script-table](character-properties)). In that case, use font-spec for all the characters belonging to the script.
characters may be `nil`, which means to use font-spec for any character in fontset for which no font-spec is specified.
font-spec may be a font-spec object created by the function `font-spec` (see [Low-Level Font](low_002dlevel-font)).
font-spec may be a cons cell `(family . registry)`, where family is a family name of a font (possibly including a foundry name at the head), and registry is a registry name of a font (possibly including an encoding name at the tail).
font-spec may be a font name, a string.
font-spec may be `nil`, which explicitly specifies that there’s no font for the specified characters. This is useful, for example, to avoid expensive system-wide search for fonts for characters that have no glyphs, like those from the Unicode Private Use Area (PUA).
The optional argument add, if non-`nil`, specifies how to add font-spec to the font specifications previously set for characters. If it is `prepend`, font-spec is prepended to the existing specs. If it is `append`, font-spec is appended. By default, font-spec overwrites the previously set font specs.
For instance, this changes the default fontset to use a font whose family name is ‘`Kochi Gothic`’ for all characters belonging to the charset `japanese-jisx0208`:
```
(set-fontset-font t 'japanese-jisx0208
(font-spec :family "Kochi Gothic"))
```
Function: **char-displayable-p** *char*
This function returns non-`nil` if Emacs ought to be able to display char. Or more precisely, if the selected frame’s fontset has a font to display the character set that char belongs to.
Fontsets can specify a font on a per-character basis; when the fontset does that, this function’s value may not be accurate.
This function may return non-`nil` even when there is no font available, since it also checks whether the coding system for the text terminal can encode the character (see [Terminal I/O Encoding](terminal-i_002fo-encoding)).
elisp None #### Frame Size
The canonical way to specify the *size of a frame* from within Emacs is by specifying its *text size*—a tuple of the width and height of the frame’s text area (see [Frame Layout](frame-layout)). It can be measured either in pixels or in terms of the frame’s canonical character size (see [Frame Font](frame-font)).
For frames with an internal menu or tool bar, the frame’s native height cannot be told exactly before the frame has been actually drawn. This means that in general you cannot use the native size to specify the initial size of a frame. As soon as you know the native size of a visible frame, you can calculate its outer size (see [Frame Layout](frame-layout)) by adding in the remaining components from the return value of `frame-geometry`. For invisible frames or for frames that have yet to be created, however, the outer size can only be estimated. This also means that calculating an exact initial position of a frame specified via offsets from the right or bottom edge of the screen (see [Frame Position](frame-position)) is impossible.
The text size of any frame can be set and retrieved with the help of the `height` and `width` frame parameters (see [Size Parameters](size-parameters)). The text size of the initial frame can be also set with the help of an X-style geometry specification. See [Command Line Arguments for Emacs Invocation](https://www.gnu.org/software/emacs/manual/html_node/emacs/Emacs-Invocation.html#Emacs-Invocation) in The GNU Emacs Manual. Below we list some functions to access and set the size of an existing, visible frame, by default the selected one.
Function: **frame-height** *&optional frame*
Function: **frame-width** *&optional frame*
These functions return the height and width of the text area of frame, measured in units of the default font height and width of frame (see [Frame Font](frame-font)). These functions are plain shorthands for writing `(frame-parameter frame 'height)` and `(frame-parameter frame 'width)`.
If the text area of frame measured in pixels is not a multiple of its default font size, the values returned by these functions are rounded down to the number of characters of the default font that fully fit into the text area.
The functions following next return the pixel widths and heights of the native, outer and inner frame and the text area (see [Frame Layout](frame-layout)) of a given frame. For a text terminal, the results are in characters rather than pixels.
Function: **frame-outer-width** *&optional frame*
Function: **frame-outer-height** *&optional frame*
These functions return the outer width and height of frame in pixels.
Function: **frame-native-height** *&optional frame*
Function: **frame-native-width** *&optional frame*
These functions return the native width and height of frame in pixels.
Function: **frame-inner-width** *&optional frame*
Function: **frame-inner-height** *&optional frame*
These functions return the inner width and height of frame in pixels.
Function: **frame-text-width** *&optional frame*
Function: **frame-text-height** *&optional frame*
These functions return the width and height of the text area of frame in pixels.
On window systems that support it, Emacs tries by default to make the text size of a frame measured in pixels a multiple of the frame’s character size. This, however, usually means that a frame can be resized only in character size increments when dragging its external borders. It also may break attempts to truly maximize the frame or making it “fullheight” or “fullwidth” (see [Size Parameters](size-parameters)) leaving some empty space below and/or on the right of the frame. The following option may help in that case.
User Option: **frame-resize-pixelwise**
If this option is `nil` (the default), a frame’s text pixel size is usually rounded to a multiple of the current values of that frame’s `frame-char-height` and `frame-char-width` whenever the frame is resized. If this is non-`nil`, no rounding occurs, hence frame sizes can increase/decrease by one pixel.
Setting this variable usually causes the next resize operation to pass the corresponding size hints to the window manager. This means that this variable should be set only in a user’s initial file; applications should never bind it temporarily.
The precise meaning of a value of `nil` for this option depends on the toolkit used. Dragging the external border with the mouse is done character-wise provided the window manager is willing to process the corresponding size hints. Calling `set-frame-size` (see below) with arguments that do not specify the frame size as an integer multiple of its character size, however, may: be ignored, cause a rounding (GTK+), or be accepted (Lucid, Motif, MS-Windows).
With some window managers you may have to set this to non-`nil` in order to make a frame appear truly maximized or full-screen.
Function: **set-frame-size** *frame width height &optional pixelwise*
This function sets the size of the text area of frame, measured in terms of the canonical height and width of a character on frame (see [Frame Font](frame-font)).
The optional argument pixelwise non-`nil` means to measure the new width and height in units of pixels instead. Note that if `frame-resize-pixelwise` is `nil`, some toolkits may refuse to truly honor the request if it does not increase/decrease the frame size to a multiple of its character size.
Function: **set-frame-height** *frame height &optional pretend pixelwise*
This function resizes the text area of frame to a height of height lines. The sizes of existing windows in frame are altered proportionally to fit.
If pretend is non-`nil`, then Emacs displays height lines of output in frame, but does not change its value for the actual height of the frame. This is only useful on text terminals. Using a smaller height than the terminal actually implements may be useful to reproduce behavior observed on a smaller screen, or if the terminal malfunctions when using its whole screen. Setting the frame height directly does not always work, because knowing the correct actual size may be necessary for correct cursor positioning on text terminals.
The optional fourth argument pixelwise non-`nil` means that frame should be height pixels high. Note that if `frame-resize-pixelwise` is `nil`, some window managers may refuse to truly honor the request if it does not increase/decrease the frame height to a multiple of its character height.
When used interactively, this command will ask the user for the number of lines to set the height of the currently selected frame. You can also provide this value with a numeric prefix.
Function: **set-frame-width** *frame width &optional pretend pixelwise*
This function sets the width of the text area of frame, measured in characters. The argument pretend has the same meaning as in `set-frame-height`.
The optional fourth argument pixelwise non-`nil` means that frame should be width pixels wide. Note that if `frame-resize-pixelwise` is `nil`, some window managers may refuse to fully honor the request if it does not increase/decrease the frame width to a multiple of its character width.
When used interactively, this command will ask the user for the number of columns to set the width of the currently selected frame. You can also provide this value with a numeric prefix.
None of these three functions will make a frame smaller than needed to display all of its windows together with their scroll bars, fringes, margins, dividers, mode and header lines. This contrasts with requests by the window manager triggered, for example, by dragging the external border of a frame with the mouse. Such requests are always honored by clipping, if necessary, portions that cannot be displayed at the right, bottom corner of the frame. The parameters `min-width` and `min-height` (see [Size Parameters](size-parameters)) can be used to obtain a similar behavior when changing the frame size from within Emacs.
The abnormal hook `window-size-change-functions` (see [Window Hooks](window-hooks)) tracks all changes of the inner size of a frame including those induced by request of the window-system or window manager. To rule out false positives that might occur when changing only the sizes of a frame’s windows without actually changing the size of the inner frame, use the following function.
Function: **frame-size-changed-p** *&optional frame*
This function returns non-`nil` when the inner width or height of frame has changed since `window-size-change-functions` was run the last time for frame. It always returns `nil` immediately after running `window-size-change-functions` for frame.
elisp None #### Reading File Names
The high-level completion functions `read-file-name`, `read-directory-name`, and `read-shell-command` are designed to read file names, directory names, and shell commands, respectively. They provide special features, including automatic insertion of the default directory.
Function: **read-file-name** *prompt &optional directory default require-match initial predicate*
This function reads a file name, prompting with prompt and providing completion.
As an exception, this function reads a file name using a graphical file dialog instead of the minibuffer, if all of the following are true:
1. It is invoked via a mouse command.
2. The selected frame is on a graphical display supporting such dialogs.
3. The variable `use-dialog-box` is non-`nil`. See [Dialog Boxes](https://www.gnu.org/software/emacs/manual/html_node/emacs/Dialog-Boxes.html#Dialog-Boxes) in The GNU Emacs Manual.
4. The directory argument, described below, does not specify a remote file. See [Remote Files](https://www.gnu.org/software/emacs/manual/html_node/emacs/Remote-Files.html#Remote-Files) in The GNU Emacs Manual.
The exact behavior when using a graphical file dialog is platform-dependent. Here, we simply document the behavior when using the minibuffer.
`read-file-name` does not automatically expand the returned file name. You can call `expand-file-name` yourself if an absolute file name is required.
The optional argument require-match has the same meaning as in `completing-read`. See [Minibuffer Completion](minibuffer-completion).
The argument directory specifies the directory to use for completing relative file names. It should be an absolute directory name. If the variable `insert-default-directory` is non-`nil`, directory is also inserted in the minibuffer as initial input. It defaults to the current buffer’s value of `default-directory`.
If you specify initial, that is an initial file name to insert in the buffer (after directory, if that is inserted). In this case, point goes at the beginning of initial. The default for initial is `nil`—don’t insert any file name. To see what initial does, try the command `C-x C-v` in a buffer visiting a file. **Please note:** we recommend using default rather than initial in most cases.
If default is non-`nil`, then the function returns default if the user exits the minibuffer with the same non-empty contents that `read-file-name` inserted initially. The initial minibuffer contents are always non-empty if `insert-default-directory` is non-`nil`, as it is by default. default is not checked for validity, regardless of the value of require-match. However, if require-match is non-`nil`, the initial minibuffer contents should be a valid file (or directory) name. Otherwise `read-file-name` attempts completion if the user exits without any editing, and does not return default. default is also available through the history commands.
If default is `nil`, `read-file-name` tries to find a substitute default to use in its place, which it treats in exactly the same way as if it had been specified explicitly. If default is `nil`, but initial is non-`nil`, then the default is the absolute file name obtained from directory and initial. If both default and initial are `nil` and the buffer is visiting a file, `read-file-name` uses the absolute file name of that file as default. If the buffer is not visiting a file, then there is no default. In that case, if the user types RET without any editing, `read-file-name` simply returns the pre-inserted contents of the minibuffer.
If the user types RET in an empty minibuffer, this function returns an empty string, regardless of the value of require-match. This is, for instance, how the user can make the current buffer visit no file using `M-x set-visited-file-name`.
If predicate is non-`nil`, it specifies a function of one argument that decides which file names are acceptable completion alternatives. A file name is an acceptable value if predicate returns non-`nil` for it.
Here is an example of using `read-file-name`:
```
(read-file-name "The file is ")
;; After evaluation of the preceding expression,
;; the following appears in the minibuffer:
```
```
---------- Buffer: Minibuffer ----------
The file is /gp/gnu/elisp/∗
---------- Buffer: Minibuffer ----------
```
Typing `manual TAB` results in the following:
```
---------- Buffer: Minibuffer ----------
The file is /gp/gnu/elisp/manual.texi∗
---------- Buffer: Minibuffer ----------
```
If the user types RET, `read-file-name` returns the file name as the string `"/gp/gnu/elisp/manual.texi"`.
Variable: **read-file-name-function**
If non-`nil`, this should be a function that accepts the same arguments as `read-file-name`. When `read-file-name` is called, it calls this function with the supplied arguments instead of doing its usual work.
User Option: **read-file-name-completion-ignore-case**
If this variable is non-`nil`, `read-file-name` ignores case when performing completion.
Function: **read-directory-name** *prompt &optional directory default require-match initial*
This function is like `read-file-name` but allows only directory names as completion alternatives.
If default is `nil` and initial is non-`nil`, `read-directory-name` constructs a substitute default by combining directory (or the current buffer’s default directory if directory is `nil`) and initial. If both default and initial are `nil`, this function uses directory as substitute default, or the current buffer’s default directory if directory is `nil`.
User Option: **insert-default-directory**
This variable is used by `read-file-name`, and thus, indirectly, by most commands reading file names. (This includes all commands that use the code letters ‘`f`’ or ‘`F`’ in their interactive form. See [Code Characters for interactive](interactive-codes).) Its value controls whether `read-file-name` starts by placing the name of the default directory in the minibuffer, plus the initial file name, if any. If the value of this variable is `nil`, then `read-file-name` does not place any initial input in the minibuffer (unless you specify initial input with the initial argument). In that case, the default directory is still used for completion of relative file names, but is not displayed.
If this variable is `nil` and the initial minibuffer contents are empty, the user may have to explicitly fetch the next history element to access a default value. If the variable is non-`nil`, the initial minibuffer contents are always non-empty and the user can always request a default value by immediately typing RET in an unedited minibuffer. (See above.)
For example:
```
;; Here the minibuffer starts out with the default directory.
(let ((insert-default-directory t))
(read-file-name "The file is "))
```
```
---------- Buffer: Minibuffer ----------
The file is ~lewis/manual/∗
---------- Buffer: Minibuffer ----------
```
```
;; Here the minibuffer is empty and only the prompt
;; appears on its line.
(let ((insert-default-directory nil))
(read-file-name "The file is "))
```
```
---------- Buffer: Minibuffer ----------
The file is ∗
---------- Buffer: Minibuffer ----------
```
Function: **read-shell-command** *prompt &optional initial history &rest args*
This function reads a shell command from the minibuffer, prompting with prompt and providing intelligent completion. It completes the first word of the command using candidates that are appropriate for command names, and the rest of the command words as file names.
This function uses `minibuffer-local-shell-command-map` as the keymap for minibuffer input. The history argument specifies the history list to use; if is omitted or `nil`, it defaults to `shell-command-history` (see [shell-command-history](minibuffer-history)). The optional argument initial specifies the initial content of the minibuffer (see [Initial Input](initial-input)). The rest of args, if present, are used as the default and inherit-input-method arguments in `read-from-minibuffer` (see [Text from Minibuffer](text-from-minibuffer)).
Variable: **minibuffer-local-shell-command-map**
This keymap is used by `read-shell-command` for completing command and file names that are part of a shell command. It uses `minibuffer-local-map` as its parent keymap, and binds TAB to `completion-at-point`.
| programming_docs |
elisp None ### Time Calculations
These functions perform calendrical computations using time values (see [Time of Day](time-of-day)). As with any time value, a value of `nil` for any of their time-value arguments stands for the current system time, and a single number stands for the number of seconds since the epoch.
Function: **time-less-p** *t1 t2*
This returns `t` if time value t1 is less than time value t2. The result is `nil` if either argument is a NaN.
Function: **time-equal-p** *t1 t2*
This returns `t` if t1 and t2 are equal time values. The result is `nil` if either argument is a NaN.
Function: **time-subtract** *t1 t2*
This returns the time difference t1 - t2 between two time values, as a Lisp time value. The result is exact and its clock resolution is no worse than the worse of its two arguments’ resolutions. The result is floating-point only if it is infinite or a NaN. If you need the difference in units of elapsed seconds, you can convert it with `time-convert` or `float-time`. See [Time Conversion](time-conversion).
Function: **time-add** *t1 t2*
This returns the sum of two time values, using the same conversion rules as `time-subtract`. One argument should represent a time difference rather than a point in time, as a time value that is often just a single number of elapsed seconds. Here is how to add a number of seconds to a time value:
```
(time-add time seconds)
```
Function: **time-to-days** *time-value*
This function returns the number of days between the beginning of year 1 and time-value, assuming the default time zone. The operating system limits the range of time and zone values.
Function: **time-to-day-in-year** *time-value*
This returns the day number within the year corresponding to time-value, assuming the default time zone. The operating system limits the range of time and zone values.
Function: **date-leap-year-p** *year*
This function returns `t` if year is a leap year.
Function: **date-days-in-month** *year month*
Return the number of days in month in year. For instance, February 2020 has 29 days.
Function: **date-ordinal-to-time** *year ordinal*
Return the date of ordinal in year as a decoded time structure. For instance, the 120th day in 2004 is April 29th.
elisp None #### Usual Display Conventions
Here are the conventions for displaying each character code (in the absence of a display table, which can override these conventions; see [Display Tables](display-tables)).
* The *printable ASCII characters*, character codes 32 through 126 (consisting of numerals, English letters, and symbols like ‘`#`’) are displayed literally.
* The tab character (character code 9) displays as whitespace stretching up to the next tab stop column. See [Text Display](https://www.gnu.org/software/emacs/manual/html_node/emacs/Text-Display.html#Text-Display) in The GNU Emacs Manual. The variable `tab-width` controls the number of spaces per tab stop (see below).
* The newline character (character code 10) has a special effect: it ends the preceding line and starts a new line.
* The non-printable *ASCII control characters*—character codes 0 through 31, as well as the DEL character (character code 127)—display in one of two ways according to the variable `ctl-arrow`. If this variable is non-`nil` (the default), these characters are displayed as sequences of two glyphs, where the first glyph is ‘`^`’ (a display table can specify a glyph to use instead of ‘`^`’); e.g., the DEL character is displayed as ‘`^?`’. If `ctl-arrow` is `nil`, these characters are displayed as octal escapes (see below).
This rule also applies to carriage return (character code 13), if that character appears in the buffer. But carriage returns usually do not appear in buffer text; they are eliminated as part of end-of-line conversion (see [Coding System Basics](coding-system-basics)).
* *Raw bytes* are non-ASCII characters with codes 128 through 255 (see [Text Representations](text-representations)). These characters display as *octal escapes*: sequences of four glyphs, where the first glyph is the ASCII code for ‘`\`’, and the others are digit characters representing the character code in octal. (A display table can specify a glyph to use instead of ‘`\`’.)
* Each non-ASCII character with code above 255 is displayed literally, if the terminal supports it. If the terminal does not support it, the character is said to be *glyphless*, and it is usually displayed using a placeholder glyph. For example, if a graphical terminal has no font for a character, Emacs usually displays a box containing the character code in hexadecimal. See [Glyphless Chars](glyphless-chars).
The above display conventions apply even when there is a display table, for any character whose entry in the active display table is `nil`. Thus, when you set up a display table, you need only specify the characters for which you want special display behavior.
The following variables affect how certain characters are displayed on the screen. Since they change the number of columns the characters occupy, they also affect the indentation functions. They also affect how the mode line is displayed; if you want to force redisplay of the mode line using the new values, call the function `force-mode-line-update` (see [Mode Line Format](mode-line-format)).
User Option: **ctl-arrow**
This buffer-local variable controls how control characters are displayed. If it is non-`nil`, they are displayed as a caret followed by the character: ‘`^A`’. If it is `nil`, they are displayed as octal escapes: a backslash followed by three octal digits, as in ‘`\001`’.
User Option: **tab-width**
The value of this buffer-local variable is the spacing between tab stops used for displaying tab characters in Emacs buffers. The value is in units of columns, and the default is 8. Note that this feature is completely independent of the user-settable tab stops used by the command `tab-to-tab-stop`. See [Indent Tabs](indent-tabs).
elisp None ### Input Functions
This section describes the Lisp functions and variables that pertain to reading.
In the functions below, stream stands for an input stream (see the previous section). If stream is `nil` or omitted, it defaults to the value of `standard-input`.
An `end-of-file` error is signaled if reading encounters an unterminated list, vector, or string.
Function: **read** *&optional stream*
This function reads one textual Lisp expression from stream, returning it as a Lisp object. This is the basic Lisp input function.
Function: **read-from-string** *string &optional start end*
This function reads the first textual Lisp expression from the text in string. It returns a cons cell whose CAR is that expression, and whose CDR is an integer giving the position of the next remaining character in the string (i.e., the first one not read).
If start is supplied, then reading begins at index start in the string (where the first character is at index 0). If you specify end, then reading is forced to stop just before that index, as if the rest of the string were not there.
For example:
```
(read-from-string "(setq x 55) (setq y 5)")
⇒ ((setq x 55) . 11)
```
```
(read-from-string "\"A short string\"")
⇒ ("A short string" . 16)
```
```
;; Read starting at the first character.
(read-from-string "(list 112)" 0)
⇒ ((list 112) . 10)
```
```
;; Read starting at the second character.
(read-from-string "(list 112)" 1)
⇒ (list . 5)
```
```
;; Read starting at the seventh character,
;; and stopping at the ninth.
(read-from-string "(list 112)" 6 8)
⇒ (11 . 8)
```
Variable: **standard-input**
This variable holds the default input stream—the stream that `read` uses when the stream argument is `nil`. The default is `t`, meaning use the minibuffer.
Variable: **read-circle**
If non-`nil`, this variable enables the reading of circular and shared structures. See [Circular Objects](circular-objects). Its default value is `t`.
When reading or writing from the standard input/output streams of the Emacs process in batch mode, it is sometimes required to make sure any arbitrary binary data will be read/written verbatim, and/or that no translation of newlines to or from CR-LF pairs is performed. This issue does not exist on POSIX hosts, only on MS-Windows and MS-DOS. The following function allows you to control the I/O mode of any standard stream of the Emacs process.
Function: **set-binary-mode** *stream mode*
Switch stream into binary or text I/O mode. If mode is non-`nil`, switch to binary mode, otherwise switch to text mode. The value of stream can be one of `stdin`, `stdout`, or `stderr`. This function flushes any pending output data of stream as a side effect, and returns the previous value of I/O mode for stream. On POSIX hosts, it always returns a non-`nil` value and does nothing except flushing pending output.
elisp None ### Declaring Functions Obsolete
You can mark a named function as *obsolete*, meaning that it may be removed at some point in the future. This causes Emacs to warn that the function is obsolete whenever it byte-compiles code containing that function, and whenever it displays the documentation for that function. In all other respects, an obsolete function behaves like any other function.
The easiest way to mark a function as obsolete is to put a `(declare (obsolete …))` form in the function’s `defun` definition. See [Declare Form](declare-form). Alternatively, you can use the `make-obsolete` function, described below.
A macro (see [Macros](macros)) can also be marked obsolete with `make-obsolete`; this has the same effects as for a function. An alias for a function or macro can also be marked as obsolete; this makes the alias itself obsolete, not the function or macro which it resolves to.
Function: **make-obsolete** *obsolete-name current-name when*
This function marks obsolete-name as obsolete. obsolete-name should be a symbol naming a function or macro, or an alias for a function or macro.
If current-name is a symbol, the warning message says to use current-name instead of obsolete-name. current-name does not need to be an alias for obsolete-name; it can be a different function with similar functionality. current-name can also be a string, which serves as the warning message. The message should begin in lower case, and end with a period. It can also be `nil`, in which case the warning message provides no additional details.
The argument when should be a string indicating when the function was first made obsolete—for example, a date or a release number.
Macro: **define-obsolete-function-alias** *obsolete-name current-name when &optional doc*
This convenience macro marks the function obsolete-name obsolete and also defines it as an alias for the function current-name. It is equivalent to the following:
```
(defalias obsolete-name current-name doc)
(make-obsolete obsolete-name current-name when)
```
In addition, you can mark a particular calling convention for a function as obsolete:
Function: **set-advertised-calling-convention** *function signature when*
This function specifies the argument list signature as the correct way to call function. This causes the Emacs byte compiler to issue a warning whenever it comes across an Emacs Lisp program that calls function any other way (however, it will still allow the code to be byte compiled). when should be a string indicating when the variable was first made obsolete (usually a version number string).
For instance, in old versions of Emacs the `sit-for` function accepted three arguments, like this
```
(sit-for seconds milliseconds nodisp)
```
However, calling `sit-for` this way is considered obsolete (see [Waiting](waiting)). The old calling convention is deprecated like this:
```
(set-advertised-calling-convention
'sit-for '(seconds &optional nodisp) "22.1")
```
elisp None #### Document Object Model
The DOM returned by `libxml-parse-html-region` (and the other XML parsing functions) is a tree structure where each node has a node name (called a *tag*), and optional key/value *attribute* list, and then a list of *child nodes*. The child nodes are either strings or DOM objects.
```
(body ((width . "101"))
(div ((class . "thing"))
"Foo"
(div nil
"Yes")))
```
Function: **dom-node** *tag &optional attributes &rest children*
This function creates a DOM node of type tag. If given, attributes should be a key/value pair list. If given, children should be DOM nodes.
The following functions can be used to work with this structure. Each function takes a DOM node, or a list of nodes. In the latter case, only the first node in the list is used.
Simple accessors:
`dom-tag node`
Return the *tag* (also called “node name”) of the node.
`dom-attr node attribute`
Return the value of attribute in the node. A common usage would be:
```
(dom-attr img 'href)
=> "https://fsf.org/logo.png"
```
`dom-children node`
Return all the children of the node.
`dom-non-text-children node`
Return all the non-string children of the node.
`dom-attributes node`
Return the key/value pair list of attributes of the node.
`dom-text node`
Return all the textual elements of the node as a concatenated string.
`dom-texts node`
Return all the textual elements of the node, as well as the textual elements of all the children of the node, recursively, as a concatenated string. This function also takes an optional separator to be inserted between the textual elements.
`dom-parent dom node`
Return the parent of node in dom.
`dom-remove dom node` Remove node from dom.
The following are functions for altering the DOM.
`dom-set-attribute node attribute value`
Set the attribute of the node to value.
`dom-remove-attribute node attribute`
Remove attribute from node.
`dom-append-child node child`
Append child as the last child of node.
`dom-add-child-before node child before`
Add child to node’s child list before the before node. If before is `nil`, make child the first child.
`dom-set-attributes node attributes` Replace all the attributes of the node with a new key/value list.
The following are functions for searching for elements in the DOM. They all return lists of matching nodes.
`dom-by-tag dom tag`
Return all nodes in dom that are of type tag. A typical use would be:
```
(dom-by-tag dom 'td)
=> '((td ...) (td ...) (td ...))
```
`dom-by-class dom match`
Return all nodes in dom that have class names that match match, which is a regular expression.
`dom-by-style dom style`
Return all nodes in dom that have styles that match match, which is a regular expression.
`dom-by-id dom style`
Return all nodes in dom that have IDs that match match, which is a regular expression.
`dom-search dom predicate`
Return all nodes in dom where predicate returns a non-`nil` value. predicate is called with the node to be tested as its parameter.
`dom-strings dom`
Return all strings in dom.
Utility functions:
`dom-pp dom &optional remove-empty`
Pretty-print dom at point. If remove-empty, don’t print textual nodes that just contain white-space.
`dom-print dom &optional pretty xml` Print dom at point. If xml is non-`nil`, print as XML; otherwise, print as HTML. If pretty is non-`nil`, indent the HTML/XML logically.
elisp None #### Getting Help about a Major Mode
The `describe-mode` function provides information about major modes. It is normally bound to `C-h m`. It uses the value of the variable `major-mode` (see [Major Modes](major-modes)), which is why every major mode command needs to set that variable.
Command: **describe-mode** *&optional buffer*
This command displays the documentation of the current buffer’s major mode and minor modes. It uses the `documentation` function to retrieve the documentation strings of the major and minor mode commands (see [Accessing Documentation](accessing-documentation)).
If called from Lisp with a non-`nil` buffer argument, this function displays the documentation for that buffer’s major and minor modes, rather than those of the current buffer.
elisp None ### Minibuffer Windows
These functions access and select minibuffer windows, test whether they are active and control how they get resized.
Function: **minibuffer-window** *&optional frame*
This function returns the minibuffer window used for frame frame. If frame is `nil`, that stands for the selected frame.
Note that the minibuffer window used by a frame need not be part of that frame—a frame that has no minibuffer of its own necessarily uses some other frame’s minibuffer window. The minibuffer window of a minibuffer-less frame can be changed by setting that frame’s `minibuffer` frame parameter (see [Buffer Parameters](buffer-parameters)).
Function: **set-minibuffer-window** *window*
This function specifies window as the minibuffer window to use. This affects where the minibuffer is displayed if you put text in it without invoking the usual minibuffer commands. It has no effect on the usual minibuffer input functions because they all start by choosing the minibuffer window according to the selected frame.
Function: **window-minibuffer-p** *&optional window*
This function returns `t` if window is a minibuffer window. window defaults to the selected window.
The following function returns the window showing the currently active minibuffer.
Function: **active-minibuffer-window**
This function returns the window of the currently active minibuffer, or `nil` if there is no active minibuffer.
It is not sufficient to determine whether a given window shows the currently active minibuffer by comparing it with the result of `(minibuffer-window)`, because there can be more than one minibuffer window if there is more than one frame.
Function: **minibuffer-window-active-p** *window*
This function returns non-`nil` if window shows the currently active minibuffer.
The following two options control whether minibuffer windows are resized automatically and how large they can get in the process.
User Option: **resize-mini-windows**
This option specifies whether minibuffer windows are resized automatically. The default value is `grow-only`, which means that a minibuffer window by default expands automatically to accommodate the text it displays and shrinks back to one line as soon as the minibuffer gets empty. If the value is `t`, Emacs will always try to fit the height of a minibuffer window to the text it displays (with a minimum of one line). If the value is `nil`, a minibuffer window never changes size automatically. In that case the window resizing commands (see [Resizing Windows](resizing-windows)) can be used to adjust its height.
User Option: **max-mini-window-height**
This option provides a maximum height for resizing minibuffer windows automatically. A floating-point number specifies the maximum height as a fraction of the frame’s height; an integer specifies the maximum height in units of the frame’s canonical character height (see [Frame Font](frame-font)). The default value is 0.25.
Note that the values of the above two variables take effect at display time, so let-binding them around code which produces echo-area messages will not work. If you want to prevent resizing of minibuffer windows when displaying long messages, bind the `message-truncate-lines` variable instead (see [Echo Area Customization](echo-area-customization)).
The option `resize-mini-windows` does not affect the behavior of minibuffer-only frames (see [Frame Layout](frame-layout)). The following option allows to automatically resize such frames as well.
User Option: **resize-mini-frames**
If this is `nil`, minibuffer-only frames are never resized automatically.
If this is a function, that function is called with the minibuffer-only frame to be resized as sole argument. At the time this function is called, the buffer of the minibuffer window of that frame is the buffer whose contents will be shown the next time that window is redisplayed. The function is expected to fit the frame to the buffer in some appropriate way.
Any other non-`nil` value means to resize minibuffer-only frames by calling `fit-mini-frame-to-buffer`, a function that behaves like `fit-frame-to-buffer` (see [Resizing Windows](resizing-windows)) but does not strip leading or trailing empty lines from the buffer text.
| programming_docs |
elisp None ### Defining Macros
A Lisp macro object is a list whose CAR is `macro`, and whose CDR is a function. Expansion of the macro works by applying the function (with `apply`) to the list of *unevaluated* arguments from the macro call.
It is possible to use an anonymous Lisp macro just like an anonymous function, but this is never done, because it does not make sense to pass an anonymous macro to functionals such as `mapcar`. In practice, all Lisp macros have names, and they are almost always defined with the `defmacro` macro.
Macro: **defmacro** *name args [doc] [declare] body…*
`defmacro` defines the symbol name (which should not be quoted) as a macro that looks like this:
```
(macro lambda args . body)
```
(Note that the CDR of this list is a lambda expression.) This macro object is stored in the function cell of name. The meaning of args is the same as in a function, and the keywords `&rest` and `&optional` may be used (see [Argument List](argument-list)). Neither name nor args should be quoted. The return value of `defmacro` is undefined.
doc, if present, should be a string specifying the macro’s documentation string. declare, if present, should be a `declare` form specifying metadata for the macro (see [Declare Form](declare-form)). Note that macros cannot have interactive declarations, since they cannot be called interactively.
Macros often need to construct large list structures from a mixture of constants and nonconstant parts. To make this easier, use the ‘```’ syntax (see [Backquote](backquote)). For example:
```
(defmacro t-becomes-nil (variable)
`(if (eq ,variable t)
(setq ,variable nil)))
```
```
(t-becomes-nil foo)
≡ (if (eq foo t) (setq foo nil))
```
elisp None #### Mutex Type
A *mutex* is an exclusive lock that threads can own and disown, in order to synchronize between them. See [Mutexes](mutexes).
Mutex objects have no read syntax. They print in hash notation, giving the name of the mutex (if it has been given a name) or its address in core:
```
(make-mutex "my-mutex")
⇒ #<mutex my-mutex>
(make-mutex)
⇒ #<mutex 01c7e4e0>
```
elisp None #### Lisp Macro Evaluation
If the first element of a list being evaluated is a macro object, then the list is a *macro call*. When a macro call is evaluated, the elements of the rest of the list are *not* initially evaluated. Instead, these elements themselves are used as the arguments of the macro. The macro definition computes a replacement form, called the *expansion* of the macro, to be evaluated in place of the original form. The expansion may be any sort of form: a self-evaluating constant, a symbol, or a list. If the expansion is itself a macro call, this process of expansion repeats until some other sort of form results.
Ordinary evaluation of a macro call finishes by evaluating the expansion. However, the macro expansion is not necessarily evaluated right away, or at all, because other programs also expand macro calls, and they may or may not evaluate the expansions.
Normally, the argument expressions are not evaluated as part of computing the macro expansion, but instead appear as part of the expansion, so they are computed when the expansion is evaluated.
For example, given a macro defined as follows:
```
(defmacro cadr (x)
(list 'car (list 'cdr x)))
```
an expression such as `(cadr (assq 'handler list))` is a macro call, and its expansion is:
```
(car (cdr (assq 'handler list)))
```
Note that the argument `(assq 'handler list)` appears in the expansion.
See [Macros](macros), for a complete description of Emacs Lisp macros.
elisp None ### Lambda Expressions
A lambda expression is a function object written in Lisp. Here is an example:
```
(lambda (x)
"Return the hyperbolic cosine of X."
(* 0.5 (+ (exp x) (exp (- x)))))
```
In Emacs Lisp, such a list is a valid expression which evaluates to a function object.
A lambda expression, by itself, has no name; it is an *anonymous function*. Although lambda expressions can be used this way (see [Anonymous Functions](anonymous-functions)), they are more commonly associated with symbols to make *named functions* (see [Function Names](function-names)). Before going into these details, the following subsections describe the components of a lambda expression and what they do.
| | | |
| --- | --- | --- |
| • [Lambda Components](lambda-components) | | The parts of a lambda expression. |
| • [Simple Lambda](simple-lambda) | | A simple example. |
| • [Argument List](argument-list) | | Details and special features of argument lists. |
| • [Function Documentation](function-documentation) | | How to put documentation in a function. |
elisp None ### Pointer Shape
You can specify the mouse pointer style for particular text or images using the `pointer` text property, and for images with the `:pointer` and `:map` image properties. The values you can use in these properties are in the table below. The actual shapes may vary between systems; the descriptions are examples.
`text` `nil`
The usual mouse pointer style used over text (an “I”-like shape).
`arrow` `vdrag` `modeline`
An arrow that points north-west.
`hand`
A hand that points upwards.
`hdrag`
A right-left arrow.
`nhdrag`
An up-down arrow.
`hourglass` A rotating ring.
Over void parts of the window (parts that do not correspond to any of the buffer contents), the mouse pointer usually uses the `arrow` style, but you can specify a different style (one of those above) by setting `void-text-area-pointer`.
User Option: **void-text-area-pointer**
This variable specifies the mouse pointer style for void text areas. These include the areas after the end of a line or below the last line in the buffer. The default is to use the `arrow` (non-text) pointer style.
When using X, you can specify what the `text` pointer style really looks like by setting the variable `x-pointer-shape`.
Variable: **x-pointer-shape**
This variable specifies the pointer shape to use ordinarily in the Emacs frame, for the `text` pointer style.
Variable: **x-sensitive-text-pointer-shape**
This variable specifies the pointer shape to use when the mouse is over mouse-sensitive text.
These variables affect newly created frames. They do not normally affect existing frames; however, if you set the mouse color of a frame, that also installs the current value of those two variables. See [Font and Color Parameters](font-and-color-parameters).
The values you can use, to specify either of these pointer shapes, are defined in the file `lisp/term/x-win.el`. Use `M-x apropos RET x-pointer RET` to see a list of them.
elisp None Reading and Printing Lisp Objects
---------------------------------
*Printing* and *reading* are the operations of converting Lisp objects to textual form and vice versa. They use the printed representations and read syntax described in [Lisp Data Types](lisp-data-types).
This chapter describes the Lisp functions for reading and printing. It also describes *streams*, which specify where to get the text (if reading) or where to put it (if printing).
| | | |
| --- | --- | --- |
| • [Streams Intro](streams-intro) | | Overview of streams, reading and printing. |
| • [Input Streams](input-streams) | | Various data types that can be used as input streams. |
| • [Input Functions](input-functions) | | Functions to read Lisp objects from text. |
| • [Output Streams](output-streams) | | Various data types that can be used as output streams. |
| • [Output Functions](output-functions) | | Functions to print Lisp objects as text. |
| • [Output Variables](output-variables) | | Variables that control what the printing functions do. |
elisp None ### Case Conversion in Lisp
The character case functions change the case of single characters or of the contents of strings. The functions normally convert only alphabetic characters (the letters ‘`A`’ through ‘`Z`’ and ‘`a`’ through ‘`z`’, as well as non-ASCII letters); other characters are not altered. You can specify a different case conversion mapping by specifying a case table (see [Case Tables](case-tables)).
These functions do not modify the strings that are passed to them as arguments.
The examples below use the characters ‘`X`’ and ‘`x`’ which have ASCII codes 88 and 120 respectively.
Function: **downcase** *string-or-char*
This function converts string-or-char, which should be either a character or a string, to lower case.
When string-or-char is a string, this function returns a new string in which each letter in the argument that is upper case is converted to lower case. When string-or-char is a character, this function returns the corresponding lower case character (an integer); if the original character is lower case, or is not a letter, the return value is equal to the original character.
```
(downcase "The cat in the hat")
⇒ "the cat in the hat"
(downcase ?X)
⇒ 120
```
Function: **upcase** *string-or-char*
This function converts string-or-char, which should be either a character or a string, to upper case.
When string-or-char is a string, this function returns a new string in which each letter in the argument that is lower case is converted to upper case. When string-or-char is a character, this function returns the corresponding upper case character (an integer); if the original character is upper case, or is not a letter, the return value is equal to the original character.
```
(upcase "The cat in the hat")
⇒ "THE CAT IN THE HAT"
(upcase ?x)
⇒ 88
```
Function: **capitalize** *string-or-char*
This function capitalizes strings or characters. If string-or-char is a string, the function returns a new string whose contents are a copy of string-or-char in which each word has been capitalized. This means that the first character of each word is converted to upper case, and the rest are converted to lower case.
The definition of a word is any sequence of consecutive characters that are assigned to the word constituent syntax class in the current syntax table (see [Syntax Class Table](syntax-class-table)).
When string-or-char is a character, this function does the same thing as `upcase`.
```
(capitalize "The cat in the hat")
⇒ "The Cat In The Hat"
```
```
(capitalize "THE 77TH-HATTED CAT")
⇒ "The 77th-Hatted Cat"
```
```
(capitalize ?x)
⇒ 88
```
Function: **upcase-initials** *string-or-char*
If string-or-char is a string, this function capitalizes the initials of the words in string-or-char, without altering any letters other than the initials. It returns a new string whose contents are a copy of string-or-char, in which each word has had its initial letter converted to upper case.
The definition of a word is any sequence of consecutive characters that are assigned to the word constituent syntax class in the current syntax table (see [Syntax Class Table](syntax-class-table)).
When the argument to `upcase-initials` is a character, `upcase-initials` has the same result as `upcase`.
```
(upcase-initials "The CAT in the hAt")
⇒ "The CAT In The HAt"
```
Note that case conversion is not a one-to-one mapping of codepoints and length of the result may differ from length of the argument. Furthermore, because passing a character forces return type to be a character, functions are unable to perform proper substitution and result may differ compared to treating a one-character string. For example:
```
(upcase "fi") ; note: single character, ligature "fi"
⇒ "FI"
```
```
(upcase ?fi)
⇒ 64257 ; i.e. ?fi
```
To avoid this, a character must first be converted into a string, using `string` function, before being passed to one of the casing functions. Of course, no assumptions on the length of the result may be made.
Mapping for such special cases are taken from `special-uppercase`, `special-lowercase` and `special-titlecase` See [Character Properties](character-properties).
See [Text Comparison](text-comparison), for functions that compare strings; some of them ignore case differences, or can optionally ignore case differences.
elisp None ### Categories
*Categories* provide an alternate way of classifying characters syntactically. You can define several categories as needed, then independently assign each character to one or more categories. Unlike syntax classes, categories are not mutually exclusive; it is normal for one character to belong to several categories.
Each buffer has a *category table* which records which categories are defined and also which characters belong to each category. Each category table defines its own categories, but normally these are initialized by copying from the standard categories table, so that the standard categories are available in all modes.
Each category has a name, which is an ASCII printing character in the range ‘’ to ‘`~`’. You specify the name of a category when you define it with `define-category`.
The category table is actually a char-table (see [Char-Tables](char_002dtables)). The element of the category table at index c is a *category set*—a bool-vector—that indicates which categories character c belongs to. In this category set, if the element at index cat is `t`, that means category cat is a member of the set, and that character c belongs to category cat.
For the next three functions, the optional argument table defaults to the current buffer’s category table.
Function: **define-category** *char docstring &optional table*
This function defines a new category, with name char and documentation docstring, for the category table table.
Here’s an example of defining a new category for characters that have strong right-to-left directionality (see [Bidirectional Display](bidirectional-display)) and using it in a special category table. To obtain the information about the directionality of characters, the example code uses the ‘`bidi-class`’ Unicode property (see [bidi-class](character-properties)).
```
(defvar special-category-table-for-bidi
;; Make an empty category-table.
(let ((category-table (make-category-table))
;; Create a char-table which gives the 'bidi-class' Unicode
;; property for each character.
(uniprop-table
(unicode-property-table-internal 'bidi-class)))
(define-category ?R "Characters of bidi-class R, AL, or RLO"
category-table)
;; Modify the category entry of each character whose
;; 'bidi-class' Unicode property is R, AL, or RLO --
;; these have a right-to-left directionality.
(map-char-table
(lambda (key val)
(if (memq val '(R AL RLO))
(modify-category-entry key ?R category-table)))
uniprop-table)
category-table))
```
Function: **category-docstring** *category &optional table*
This function returns the documentation string of category category in category table table.
```
(category-docstring ?a)
⇒ "ASCII"
(category-docstring ?l)
⇒ "Latin"
```
Function: **get-unused-category** *&optional table*
This function returns a category name (a character) which is not currently defined in table. If all possible categories are in use in table, it returns `nil`.
Function: **category-table**
This function returns the current buffer’s category table.
Function: **category-table-p** *object*
This function returns `t` if object is a category table, otherwise `nil`.
Function: **standard-category-table**
This function returns the standard category table.
Function: **copy-category-table** *&optional table*
This function constructs a copy of table and returns it. If table is not supplied (or is `nil`), it returns a copy of the standard category table. Otherwise, an error is signaled if table is not a category table.
Function: **set-category-table** *table*
This function makes table the category table for the current buffer. It returns table.
Function: **make-category-table**
This creates and returns an empty category table. In an empty category table, no categories have been allocated, and no characters belong to any categories.
Function: **make-category-set** *categories*
This function returns a new category set—a bool-vector—whose initial contents are the categories listed in the string categories. The elements of categories should be category names; the new category set has `t` for each of those categories, and `nil` for all other categories.
```
(make-category-set "al")
⇒ #&128"\0\0\0\0\0\0\0\0\0\0\0\0\2\20\0\0"
```
Function: **char-category-set** *char*
This function returns the category set for character char in the current buffer’s category table. This is the bool-vector which records which categories the character char belongs to. The function `char-category-set` does not allocate storage, because it returns the same bool-vector that exists in the category table.
```
(char-category-set ?a)
⇒ #&128"\0\0\0\0\0\0\0\0\0\0\0\0\2\20\0\0"
```
Function: **category-set-mnemonics** *category-set*
This function converts the category set category-set into a string containing the characters that designate the categories that are members of the set.
```
(category-set-mnemonics (char-category-set ?a))
⇒ "al"
```
Function: **modify-category-entry** *char category &optional table reset*
This function modifies the category set of char in category table table (which defaults to the current buffer’s category table). char can be a character, or a cons cell of the form `(min . max)`; in the latter case, the function modifies the category sets of all characters in the range between min and max, inclusive.
Normally, it modifies a category set by adding category to it. But if reset is non-`nil`, then it deletes category instead.
Command: **describe-categories** *&optional buffer-or-name*
This function describes the category specifications in the current category table. It inserts the descriptions in a buffer, and then displays that buffer. If buffer-or-name is non-`nil`, it describes the category table of that buffer instead.
elisp None ### Building Emacs
This section explains the steps involved in building the Emacs executable. You don’t have to know this material to build and install Emacs, since the makefiles do all these things automatically. This information is pertinent to Emacs developers.
Building Emacs requires GNU Make version 3.81 or later.
Compilation of the C source files in the `src` directory produces an executable file called `temacs`, also called a *bare impure Emacs*. It contains the Emacs Lisp interpreter and I/O routines, but not the editing commands.
The command `temacs -l loadup` would run `temacs` and direct it to load `loadup.el`. The `loadup` library loads additional Lisp libraries, which set up the normal Emacs editing environment. After this step, the Emacs executable is no longer *bare*.
Because it takes some time to load the standard Lisp files, the `temacs` executable usually isn’t run directly by users. Instead, one of the last steps of building Emacs runs the command ‘`temacs -batch -l loadup --temacs=dump-method`’. The special option `--temacs` tells `temacs` how to record all the standard preloaded Lisp functions and variables, so that when you subsequently run Emacs, it will start much faster. The `--temacs` option requires an argument dump-method, which can be one of the following:
‘`pdump`’
Record the preloaded Lisp data in a *dump file*. This method produces an additional data file which Emacs will load at startup. The produced dump file is usually called `emacs.pdmp`, and is installed in the Emacs `exec-directory` (see [Help Functions](help-functions)). This method is the most preferred one, as it does not require Emacs to employ any special techniques of memory allocation, which might get in the way of various memory-layout techniques used by modern systems to enhance security and privacy.
‘`pbootstrap`’
Like ‘`pdump`’, but used while *bootstrapping* Emacs, when no previous Emacs binary and no `\*.elc` byte-compiled Lisp files are available. The produced dump file is usually named `bootstrap-emacs.pdmp` in this case.
‘`dump`’
This method causes `temacs` to dump out an executable program, called `emacs`, which has all the standard Lisp files already preloaded into it. (The ‘`-batch`’ argument prevents `temacs` from trying to initialize any of its data on the terminal, so that the tables of terminal information are empty in the dumped Emacs.) This method is also known as *unexec*, because it produces a program file from a running process, and thus is in some sense the opposite of executing a program to start a process. Although this method was the way that Emacs traditionally saved its state, it is now deprecated.
‘`bootstrap`’ Like ‘`dump`’, but used when bootstrapping Emacs with the `unexec` method.
The dumped `emacs` executable (also called a *pure* Emacs) is the one which is installed. If the portable dumper was used to build Emacs, the `emacs` executable is actually an exact copy of `temacs`, and the corresponding `emacs.pdmp` file is installed as well. The variable `preloaded-file-list` stores a list of the preloaded Lisp files recorded in the dump file or in the dumped Emacs executable. If you port Emacs to a new operating system, and are not able to implement dumping of any kind, then Emacs must load `loadup.el` each time it starts.
By default the dumped `emacs` executable records details such as the build time and host name. Use the `--disable-build-details` option of `configure` to suppress these details, so that building and installing Emacs twice from the same sources is more likely to result in identical copies of Emacs.
You can specify additional files to preload by writing a library named `site-load.el` that loads them. You may need to rebuild Emacs with an added definition
```
#define SITELOAD_PURESIZE_EXTRA n
```
to make n added bytes of pure space to hold the additional files; see `src/puresize.h`. (Try adding increments of 20000 until it is big enough.) However, the advantage of preloading additional files decreases as machines get faster. On modern machines, it is usually not advisable.
After `loadup.el` reads `site-load.el`, it finds the documentation strings for primitive and preloaded functions (and variables) in the file `etc/DOC` where they are stored, by calling `Snarf-documentation` (see [Accessing Documentation](accessing-documentation#Definition-of-Snarf_002ddocumentation)).
You can specify other Lisp expressions to execute just before dumping by putting them in a library named `site-init.el`. This file is executed after the documentation strings are found.
If you want to preload function or variable definitions, there are three ways you can do this and make their documentation strings accessible when you subsequently run Emacs:
* Arrange to scan these files when producing the `etc/DOC` file, and load them with `site-load.el`.
* Load the files with `site-init.el`, then copy the files into the installation directory for Lisp files when you install Emacs.
* Specify a `nil` value for `byte-compile-dynamic-docstrings` as a local variable in each of these files, and load them with either `site-load.el` or `site-init.el`. (This method has the drawback that the documentation strings take up space in Emacs all the time.)
It is not advisable to put anything in `site-load.el` or `site-init.el` that would alter any of the features that users expect in an ordinary unmodified Emacs. If you feel you must override normal features for your site, do it with `default.el`, so that users can override your changes if they wish. See [Startup Summary](startup-summary). Note that if either `site-load.el` or `site-init.el` changes `load-path`, the changes will be lost after dumping. See [Library Search](library-search). To make a permanent change to `load-path`, use the `--enable-locallisppath` option of `configure`.
In a package that can be preloaded, it is sometimes necessary (or useful) to delay certain evaluations until Emacs subsequently starts up. The vast majority of such cases relate to the values of customizable variables. For example, `tutorial-directory` is a variable defined in `startup.el`, which is preloaded. The default value is set based on `data-directory`. The variable needs to access the value of `data-directory` when Emacs starts, not when it is dumped, because the Emacs executable has probably been installed in a different location since it was dumped.
Function: **custom-initialize-delay** *symbol value*
This function delays the initialization of symbol to the next Emacs start. You normally use this function by specifying it as the `:initialize` property of a customizable variable. (The argument value is unused, and is provided only for compatibility with the form Custom expects.)
In the unlikely event that you need a more general functionality than `custom-initialize-delay` provides, you can use `before-init-hook` (see [Startup Summary](startup-summary)).
Function: **dump-emacs-portable** *to-file &optional track-referrers*
This function dumps the current state of Emacs into a dump file to-file, using the `pdump` method. Normally, the dump file is called `emacs-name.dmp`, where emacs-name is the name of the Emacs executable file. The optional argument track-referrers, if non-`nil`, causes the portable dumper to keep additional information to help track down the provenance of object types that are not yet supported by the `pdump` method.
Although the portable dumper code can run on many platforms, the dump files that it produces are not portable—they can be loaded only by the Emacs executable that dumped them.
If you want to use this function in an Emacs that was already dumped, you must run Emacs with the ‘`-batch`’ option.
Function: **dump-emacs** *to-file from-file*
This function dumps the current state of Emacs into an executable file to-file, using the `unexec` method. It takes symbols from from-file (this is normally the executable file `temacs`).
This function cannot be used in an Emacs that was already dumped. This function is deprecated, and by default Emacs is built without `unexec` support so this function is not available.
Function: **pdumper-stats**
If the current Emacs session restored its state from a dump file, this function returns information about the dump file and the time it took to restore the Emacs state. The value is an alist `((dumped-with-pdumper . t) (load-time . time) (dump-file-name . file))`, where file is the name of the dump file, and time is the time in seconds it took to restore the state from the dump file. If the current session was not restored from a dump file, the value is nil.
| programming_docs |
elisp None ### Basic Thread Functions
Threads can be created and waited for. A thread cannot be exited directly, but the current thread can be exited implicitly, and other threads can be signaled.
Function: **make-thread** *function &optional name*
Create a new thread of execution which invokes function. When function returns, the thread exits.
The new thread is created with no local variable bindings in effect. The new thread’s current buffer is inherited from the current thread.
name can be supplied to give a name to the thread. The name is used for debugging and informational purposes only; it has no meaning to Emacs. If name is provided, it must be a string.
This function returns the new thread.
Function: **threadp** *object*
This function returns `t` if object represents an Emacs thread, `nil` otherwise.
Function: **thread-join** *thread*
Block until thread exits, or until the current thread is signaled. It returns the result of the thread function. If thread has already exited, this returns immediately.
Function: **thread-signal** *thread error-symbol data*
Like `signal` (see [Signaling Errors](signaling-errors)), but the signal is delivered in the thread thread. If thread is the current thread, then this just calls `signal` immediately. Otherwise, thread will receive the signal as soon as it becomes current. If thread was blocked by a call to `mutex-lock`, `condition-wait`, or `thread-join`; `thread-signal` will unblock it.
If thread is the main thread, the signal is not propagated there. Instead, it is shown as message in the main thread.
Function: **thread-yield**
Yield execution to the next runnable thread.
Function: **thread-name** *thread*
Return the name of thread, as specified to `make-thread`.
Function: **thread-live-p** *thread*
Return `t` if thread is alive, or `nil` if it is not. A thread is alive as long as its function is still executing.
Function: **thread--blocker** *thread*
Return the object that thread is waiting on. This function is primarily intended for debugging, and is given a “double hyphen” name to indicate that.
If thread is blocked in `thread-join`, this returns the thread for which it is waiting.
If thread is blocked in `mutex-lock`, this returns the mutex.
If thread is blocked in `condition-wait`, this returns the condition variable.
Otherwise, this returns `nil`.
Function: **current-thread**
Return the current thread.
Function: **all-threads**
Return a list of all the live thread objects. A new list is returned by each invocation.
Variable: **main-thread**
This variable keeps the main thread Emacs is running, or `nil` if Emacs is compiled without thread support.
When code run by a thread signals an error that is unhandled, the thread exits. Other threads can access the error form which caused the thread to exit using the following function.
Function: **thread-last-error** *&optional cleanup*
This function returns the last error form recorded when a thread exited due to an error. Each thread that exits abnormally overwrites the form stored by the previous thread’s error with a new value, so only the last one can be accessed. If cleanup is non-`nil`, the stored form is reset to `nil`.
elisp None #### Local Variables in Macro Expansions
In the previous section, the definition of `for` was fixed as follows to make the expansion evaluate the macro arguments the proper number of times:
```
(defmacro for (var from init to final do &rest body)
"Execute a simple for loop: (for i from 1 to 10 do (print i))."
```
```
`(let ((,var ,init)
(max ,final))
(while (<= ,var max)
,@body
(inc ,var))))
```
The new definition of `for` has a new problem: it introduces a local variable named `max` which the user does not expect. This causes trouble in examples such as the following:
```
(let ((max 0))
(for x from 0 to 10 do
(let ((this (frob x)))
(if (< max this)
(setq max this)))))
```
The references to `max` inside the body of the `for`, which are supposed to refer to the user’s binding of `max`, really access the binding made by `for`.
The way to correct this is to use an uninterned symbol instead of `max` (see [Creating Symbols](creating-symbols)). The uninterned symbol can be bound and referred to just like any other symbol, but since it is created by `for`, we know that it cannot already appear in the user’s program. Since it is not interned, there is no way the user can put it into the program later. It will never appear anywhere except where put by `for`. Here is a definition of `for` that works this way:
```
(defmacro for (var from init to final do &rest body)
"Execute a simple for loop: (for i from 1 to 10 do (print i))."
(let ((tempvar (make-symbol "max")))
`(let ((,var ,init)
(,tempvar ,final))
(while (<= ,var ,tempvar)
,@body
(inc ,var)))))
```
This creates an uninterned symbol named `max` and puts it in the expansion instead of the usual interned symbol `max` that appears in expressions ordinarily.
elisp None #### Menus and the Keyboard
When a prefix key ending with a keyboard event (a character or function key) has a definition that is a menu keymap, the keymap operates as a keyboard menu; the user specifies the next event by choosing a menu item with the keyboard.
Emacs displays the keyboard menu with the map’s overall prompt string, followed by the alternatives (the item strings of the map’s bindings), in the echo area. If the bindings don’t all fit at once, the user can type SPC to see the next line of alternatives. Successive uses of SPC eventually get to the end of the menu and then cycle around to the beginning. (The variable `menu-prompt-more-char` specifies which character is used for this; SPC is the default.)
When the user has found the desired alternative from the menu, he or she should type the corresponding character—the one whose binding is that alternative.
Variable: **menu-prompt-more-char**
This variable specifies the character to use to ask to see the next line of a menu. Its initial value is 32, the code for SPC.
elisp None ### Load Suffixes
We now describe some technical details about the exact suffixes that `load` tries.
Variable: **load-suffixes**
This is a list of suffixes indicating (compiled or source) Emacs Lisp files. It should not include the empty string. `load` uses these suffixes in order when it appends Lisp suffixes to the specified file name. The standard value is `(".elc" ".el")` which produces the behavior described in the previous section.
Variable: **load-file-rep-suffixes**
This is a list of suffixes that indicate representations of the same file. This list should normally start with the empty string. When `load` searches for a file it appends the suffixes in this list, in order, to the file name, before searching for another file.
Enabling Auto Compression mode appends the suffixes in `jka-compr-load-suffixes` to this list and disabling Auto Compression mode removes them again. The standard value of `load-file-rep-suffixes` if Auto Compression mode is disabled is `("")`. Given that the standard value of `jka-compr-load-suffixes` is `(".gz")`, the standard value of `load-file-rep-suffixes` if Auto Compression mode is enabled is `("" ".gz")`.
Function: **get-load-suffixes**
This function returns the list of all suffixes that `load` should try, in order, when its must-suffix argument is non-`nil`. This takes both `load-suffixes` and `load-file-rep-suffixes` into account. If `load-suffixes`, `jka-compr-load-suffixes` and `load-file-rep-suffixes` all have their standard values, this function returns `(".elc" ".elc.gz" ".el" ".el.gz")` if Auto Compression mode is enabled and `(".elc" ".el")` if Auto Compression mode is disabled.
To summarize, `load` normally first tries the suffixes in the value of `(get-load-suffixes)` and then those in `load-file-rep-suffixes`. If nosuffix is non-`nil`, it skips the former group, and if must-suffix is non-`nil`, it skips the latter group.
User Option: **load-prefer-newer**
If this option is non-`nil`, then rather than stopping at the first suffix that exists, `load` tests them all, and uses whichever file is the newest.
elisp None #### Font Lock Multiline
One way to ensure reliable rehighlighting of multiline Font Lock constructs is to put on them the text property `font-lock-multiline`. It should be present and non-`nil` for text that is part of a multiline construct.
When Font Lock is about to highlight a range of text, it first extends the boundaries of the range as necessary so that they do not fall within text marked with the `font-lock-multiline` property. Then it removes any `font-lock-multiline` properties from the range, and highlights it. The highlighting specification (mostly `font-lock-keywords`) must reinstall this property each time, whenever it is appropriate.
**Warning:** don’t use the `font-lock-multiline` property on large ranges of text, because that will make rehighlighting slow.
Variable: **font-lock-multiline**
If the `font-lock-multiline` variable is set to `t`, Font Lock will try to add the `font-lock-multiline` property automatically on multiline constructs. This is not a universal solution, however, since it slows down Font Lock somewhat. It can miss some multiline constructs, or make the property larger or smaller than necessary.
For elements whose matcher is a function, the function should ensure that submatch 0 covers the whole relevant multiline construct, even if only a small subpart will be highlighted. It is often just as easy to add the `font-lock-multiline` property by hand.
The `font-lock-multiline` property is meant to ensure proper refontification; it does not automatically identify new multiline constructs. Identifying them requires that Font Lock mode operate on large enough chunks at a time. This will happen by accident on many cases, which may give the impression that multiline constructs magically work. If you set the `font-lock-multiline` variable non-`nil`, this impression will be even stronger, since the highlighting of those constructs which are found will be properly updated from then on. But that does not work reliably.
To find multiline constructs reliably, you must either manually place the `font-lock-multiline` property on the text before Font Lock mode looks at it, or use `font-lock-fontify-region-function`.
elisp None #### Keymaps and Minor Modes
Each minor mode can have its own keymap, which is active when the mode is enabled. To set up a keymap for a minor mode, add an element to the alist `minor-mode-map-alist`. See [Definition of minor-mode-map-alist](controlling-active-maps#Definition-of-minor_002dmode_002dmap_002dalist).
One use of minor mode keymaps is to modify the behavior of certain self-inserting characters so that they do something else as well as self-insert. (Another way to customize `self-insert-command` is through `post-self-insert-hook`, see [Commands for Insertion](commands-for-insertion). Apart from this, the facilities for customizing `self-insert-command` are limited to special cases, designed for abbrevs and Auto Fill mode. Do not try substituting your own definition of `self-insert-command` for the standard one. The editor command loop handles this function specially.)
Minor modes may bind commands to key sequences consisting of `C-c` followed by a punctuation character. However, sequences consisting of `C-c` followed by one of `{}<>:;`, or a control character or digit, are reserved for major modes. Also, `C-c letter` is reserved for users. See [Key Binding Conventions](https://www.gnu.org/software/emacs/manual/html_node/elisp/Key-Binding-Conventions.html).
elisp None #### Choosing a Window for Displaying a Buffer
The command `display-buffer` flexibly chooses a window for display, and displays a specified buffer in that window. It can be called interactively, via the key binding `C-x 4 C-o`. It is also used as a subroutine by many functions and commands, including `switch-to-buffer` and `pop-to-buffer` (see [Switching Buffers](switching-buffers)).
This command performs several complex steps to find a window to display in. These steps are described by means of *display actions*, which have the form `(functions . alist)`. Here, functions is either a single function or a list of functions, referred to as “action functions” (see [Buffer Display Action Functions](buffer-display-action-functions)); and alist is an association list, referred to as “action alist” (see [Buffer Display Action Alists](buffer-display-action-alists)). See [The Zen of Buffer Display](the-zen-of-buffer-display), for samples of display actions.
An action function accepts two arguments: the buffer to display and an action alist. It attempts to display the buffer in some window, picking or creating a window according to its own criteria. If successful, it returns the window; otherwise, it returns `nil`.
`display-buffer` works by combining display actions from several sources, and calling the action functions in turn, until one of them manages to display the buffer and returns a non-`nil` value.
Command: **display-buffer** *buffer-or-name &optional action frame*
This command makes buffer-or-name appear in some window, without selecting the window or making the buffer current. The argument buffer-or-name must be a buffer or the name of an existing buffer. The return value is the window chosen to display the buffer, or `nil` if no suitable window was found.
The optional argument action, if non-`nil`, should normally be a display action (described above). `display-buffer` builds a list of action functions and an action alist, by consolidating display actions from the following sources (in order of their precedence, from highest to lowest):
* The variable `display-buffer-overriding-action`.
* The user option `display-buffer-alist`.
* The action argument.
* The user option `display-buffer-base-action`.
* The constant `display-buffer-fallback-action`.
In practice this means that `display-buffer` builds a list of all action functions specified by these display actions. The first element of this list is the first action function specified by `display-buffer-overriding-action`, if any. Its last element is `display-buffer-pop-up-frame`—the last action function specified by `display-buffer-fallback-action`. Duplicates are not removed from this list—hence one and the same action function may be called multiple times during one call of `display-buffer`.
`display-buffer` calls the action functions specified by this list in turn, passing the buffer as the first argument and the combined action alist as the second argument, until one of the functions returns non-`nil`. See [Precedence of Action Functions](precedence-of-action-functions), for examples how display actions specified by different sources are processed by `display-buffer`.
Note that the second argument is always the list of *all* action alist entries specified by the sources named above. Hence, the first element of that list is the first action alist entry specified by `display-buffer-overriding-action`, if any. Its last element is the last alist entry of `display-buffer-base-action`, if any (the action alist of `display-buffer-fallback-action` is empty).
Note also, that the combined action alist may contain duplicate entries and entries for the same key with different values. As a rule, action functions always use the first association of a key they find. Hence, the association an action function uses is not necessarily the association provided by the display action that specified that action function,
The argument action can also have a non-`nil`, non-list value. This has the special meaning that the buffer should be displayed in a window other than the selected one, even if the selected window is already displaying it. If called interactively with a prefix argument, action is `t`. Lisp programs should always supply a list value.
The optional argument frame, if non-`nil`, specifies which frames to check when deciding whether the buffer is already displayed. It is equivalent to adding an element `(reusable-frames . frame)` to the action alist of action (see [Buffer Display Action Alists](buffer-display-action-alists)). The frame argument is provided for compatibility reasons, Lisp programs should not use it.
Variable: **display-buffer-overriding-action**
The value of this variable should be a display action, which is treated with the highest priority by `display-buffer`. The default value is an empty display action, i.e., `(nil . nil)`.
User Option: **display-buffer-alist**
The value of this option is an alist mapping conditions to display actions. Each condition may be either a regular expression matching a buffer name or a function that takes two arguments: a buffer name and the action argument passed to `display-buffer`. If either the name of the buffer passed to `display-buffer` matches a regular expression in this alist, or the function specified by a condition returns non-`nil`, then `display-buffer` uses the corresponding display action to display the buffer.
User Option: **display-buffer-base-action**
The value of this option should be a display action. This option can be used to define a standard display action for calls to `display-buffer`.
Constant: **display-buffer-fallback-action**
This display action specifies the fallback behavior for `display-buffer` if no other display actions are given.
elisp None #### Miscellaneous System Events
A few other event types represent occurrences within the system.
`(delete-frame (frame))`
This kind of event indicates that the user gave the window manager a command to delete a particular window, which happens to be an Emacs frame.
The standard definition of the `delete-frame` event is to delete frame.
`(iconify-frame (frame))`
This kind of event indicates that the user iconified frame using the window manager. Its standard definition is `ignore`; since the frame has already been iconified, Emacs has no work to do. The purpose of this event type is so that you can keep track of such events if you want to.
`(make-frame-visible (frame))`
This kind of event indicates that the user deiconified frame using the window manager. Its standard definition is `ignore`; since the frame has already been made visible, Emacs has no work to do.
`(wheel-up position)` `(wheel-down position)`
These kinds of event are generated by moving a mouse wheel. The position element is a mouse position list (see [Click Events](click-events)), specifying the position of the mouse cursor when the event occurred.
This kind of event is generated only on some kinds of systems. On some systems, `mouse-4` and `mouse-5` are used instead. For portable code, use the variables `mouse-wheel-up-event` and `mouse-wheel-down-event` defined in `mwheel.el` to determine what event types to expect for the mouse wheel.
`(drag-n-drop position files)`
This kind of event is generated when a group of files is selected in an application outside of Emacs, and then dragged and dropped onto an Emacs frame.
The element position is a list describing the position of the event, in the same format as used in a mouse-click event (see [Click Events](click-events)), and files is the list of file names that were dragged and dropped. The usual way to handle this event is by visiting these files.
This kind of event is generated, at present, only on some kinds of systems.
`help-echo`
This kind of event is generated when a mouse pointer moves onto a portion of buffer text which has a `help-echo` text property. The generated event has this form:
```
(help-echo frame help window object pos)
```
The precise meaning of the event parameters and the way these parameters are used to display the help-echo text are described in [Text help-echo](special-properties#Text-help_002decho).
`sigusr1` `sigusr2`
These events are generated when the Emacs process receives the signals `SIGUSR1` and `SIGUSR2`. They contain no additional data because signals do not carry additional information. They can be useful for debugging (see [Error Debugging](error-debugging)).
To catch a user signal, bind the corresponding event to an interactive command in the `special-event-map` (see [Controlling Active Maps](controlling-active-maps)). The command is called with no arguments, and the specific signal event is available in `last-input-event` (see [Event Input Misc](event-input-misc). For example:
```
(defun sigusr-handler ()
(interactive)
(message "Caught signal %S" last-input-event))
(define-key special-event-map [sigusr1] 'sigusr-handler)
```
To test the signal handler, you can make Emacs send a signal to itself:
```
(signal-process (emacs-pid) 'sigusr1)
```
`language-change`
This kind of event is generated on MS-Windows when the input language has changed. This typically means that the keyboard keys will send to Emacs characters from a different language. The generated event has this form:
```
(language-change frame codepage language-id)
```
Here frame is the frame which was current when the input language changed; codepage is the new codepage number; and language-id is the numerical ID of the new input language. The coding-system (see [Coding Systems](coding-systems)) that corresponds to codepage is `cpcodepage` or `windows-codepage`. To convert language-id to a string (e.g., to use it for various language-dependent features, such as `set-language-environment`), use the `w32-get-locale-info` function, like this:
```
;; Get the abbreviated language name, such as "ENU" for English
(w32-get-locale-info language-id)
;; Get the full English name of the language,
;; such as "English (United States)"
(w32-get-locale-info language-id 4097)
;; Get the full localized name of the language
(w32-get-locale-info language-id t)
```
If one of these events arrives in the middle of a key sequence—that is, after a prefix key—then Emacs reorders the events so that this event comes either before or after the multi-event key sequence, not within it.
Some of these special events, such as `delete-frame`, invoke Emacs commands by default; others are not bound. If you want to arrange for a special event to invoke a command, you can do that via `special-event-map`. The command you bind to a function key in that map can then examine the full event which invoked it in `last-input-event`. See [Special Events](special-events).
| programming_docs |
elisp None #### Basic Char Syntax
Since characters are really integers, the printed representation of a character is a decimal number. This is also a possible read syntax for a character, but writing characters that way in Lisp programs is not clear programming. You should *always* use the special read syntax formats that Emacs Lisp provides for characters. These syntax formats start with a question mark.
The usual read syntax for alphanumeric characters is a question mark followed by the character; thus, ‘`?A`’ for the character `A`, ‘`?B`’ for the character `B`, and ‘`?a`’ for the character `a`.
For example:
```
?Q ⇒ 81 ?q ⇒ 113
```
You can use the same syntax for punctuation characters. However, if the punctuation character has a special syntactic meaning in Lisp, you must quote it with a ‘`\`’. For example, ‘`?\(`’ is the way to write the open-paren character. Likewise, if the character is ‘`\`’, you must use a second ‘`\`’ to quote it: ‘`?\\`’.
You can express the characters control-g, backspace, tab, newline, vertical tab, formfeed, space, return, del, and escape as ‘`?\a`’, ‘`?\b`’, ‘`?\t`’, ‘`?\n`’, ‘`?\v`’, ‘`?\f`’, ‘`?\s`’, ‘`?\r`’, ‘`?\d`’, and ‘`?\e`’, respectively. (‘`?\s`’ followed by a dash has a different meaning—it applies the Super modifier to the following character.) Thus,
```
?\a ⇒ 7 ; control-g, `C-g`
?\b ⇒ 8 ; backspace, BS, `C-h`
?\t ⇒ 9 ; tab, TAB, `C-i`
?\n ⇒ 10 ; newline, `C-j`
?\v ⇒ 11 ; vertical tab, `C-k`
?\f ⇒ 12 ; formfeed character, `C-l`
?\r ⇒ 13 ; carriage return, RET, `C-m`
?\e ⇒ 27 ; escape character, ESC, `C-[`
?\s ⇒ 32 ; space character, SPC
?\\ ⇒ 92 ; backslash character, `\`
?\d ⇒ 127 ; delete character, DEL
```
These sequences which start with backslash are also known as *escape sequences*, because backslash plays the role of an escape character; this has nothing to do with the character ESC. ‘`\s`’ is meant for use in character constants; in string constants, just write the space.
A backslash is allowed, and harmless, preceding any character without a special escape meaning; thus, ‘`?\+`’ is equivalent to ‘`?+`’. There is no reason to add a backslash before most characters. However, you must add a backslash before any of the characters ‘`()[]\;"`’, and you should add a backslash before any of the characters ‘`|'`#.,`’ to avoid confusing the Emacs commands for editing Lisp code. You should also add a backslash before Unicode characters which resemble the previously mentioned ASCII ones, to avoid confusing people reading your code. Emacs will highlight some non-escaped commonly confused characters such as ‘`‘`’ to encourage this. You can also add a backslash before whitespace characters such as space, tab, newline and formfeed. However, it is cleaner to use one of the easily readable escape sequences, such as ‘`\t`’ or ‘`\s`’, instead of an actual whitespace character such as a tab or a space. (If you do write backslash followed by a space, you should write an extra space after the character constant to separate it from the following text.)
elisp None #### Type Keywords
You can specify keyword-argument pairs in a customization type after the type name symbol. Here are the keywords you can use, and their meanings:
`:value default`
Provide a default value.
If `nil` is not a valid value for the alternative, then it is essential to specify a valid default with `:value`.
If you use this for a type that appears as an alternative inside of `choice`; it specifies the default value to use, at first, if and when the user selects this alternative with the menu in the customization buffer.
Of course, if the actual value of the option fits this alternative, it will appear showing the actual value, not default.
`:format format-string`
This string will be inserted in the buffer to represent the value corresponding to the type. The following ‘`%`’ escapes are available for use in format-string:
‘`%[button%]`’
Display the text button marked as a button. The `:action` attribute specifies what the button will do if the user invokes it; its value is a function which takes two arguments—the widget which the button appears in, and the event.
There is no way to specify two different buttons with different actions.
‘`%{sample%}`’
Show sample in a special face specified by `:sample-face`.
‘`%v`’
Substitute the item’s value. How the value is represented depends on the kind of item, and (for variables) on the customization type.
‘`%d`’
Substitute the item’s documentation string.
‘`%h`’
Like ‘`%d`’, but if the documentation string is more than one line, add a button to control whether to show all of it or just the first line.
‘`%t`’
Substitute the tag here. You specify the tag with the `:tag` keyword.
‘`%%`’ Display a literal ‘`%`’.
`:action action`
Perform action if the user clicks on a button.
`:button-face face`
Use the face face (a face name or a list of face names) for button text displayed with ‘`%[…%]`’.
`:button-prefix prefix` `:button-suffix suffix`
These specify the text to display before and after a button. Each can be:
`nil`
No text is inserted.
a string
The string is inserted literally.
a symbol The symbol’s value is used.
`:tag tag`
Use tag (a string) as the tag for the value (or part of the value) that corresponds to this type.
`:doc doc`
Use doc as the documentation string for this value (or part of the value) that corresponds to this type. In order for this to work, you must specify a value for `:format`, and use ‘`%d`’ or ‘`%h`’ in that value.
The usual reason to specify a documentation string for a type is to provide more information about the meanings of alternatives inside a `choice` type or the parts of some other composite type.
`:help-echo motion-doc`
When you move to this item with `widget-forward` or `widget-backward`, it will display the string motion-doc in the echo area. In addition, motion-doc is used as the mouse `help-echo` string and may actually be a function or form evaluated to yield a help string. If it is a function, it is called with one argument, the widget.
`:match function`
Specify how to decide whether a value matches the type. The corresponding value, function, should be a function that accepts two arguments, a widget and a value; it should return non-`nil` if the value is acceptable.
`:match-inline function`
Specify how to decide whether an inline value matches the type. The corresponding value, function, should be a function that accepts two arguments, a widget and an inline value; it should return non-`nil` if the value is acceptable. See [Splicing into Lists](splicing-into-lists) for more information about inline values.
`:validate function`
Specify a validation function for input. function takes a widget as an argument, and should return `nil` if the widget’s current value is valid for the widget. Otherwise, it should return the widget containing the invalid data, and set that widget’s `:error` property to a string explaining the error.
`:type-error string`
string should be a string that describes why a value doesn’t match the type, as determined by the `:match` function. When the `:match` function returns `nil`, the widget’s `:error` property will be set to string.
elisp None ### Symbol Properties
A symbol may possess any number of *symbol properties*, which can be used to record miscellaneous information about the symbol. For example, when a symbol has a `risky-local-variable` property with a non-`nil` value, that means the variable which the symbol names is a risky file-local variable (see [File Local Variables](file-local-variables)).
Each symbol’s properties and property values are stored in the symbol’s property list cell (see [Symbol Components](symbol-components)), in the form of a property list (see [Property Lists](property-lists)).
| | | |
| --- | --- | --- |
| • [Symbol Plists](symbol-plists) | | Accessing symbol properties. |
| • [Standard Properties](standard-properties) | | Standard meanings of symbol properties. |
elisp None #### Defining Faces
The usual way to define a face is through the `defface` macro. This macro associates a face name (a symbol) with a default *face spec*. A face spec is a construct which specifies what attributes a face should have on any given terminal; for example, a face spec might specify one foreground color on high-color terminals, and a different foreground color on low-color terminals.
People are sometimes tempted to create a variable whose value is a face name. In the vast majority of cases, this is not necessary; the usual procedure is to define a face with `defface`, and then use its name directly.
Note that once you have defined a face (usually with `defface`), you cannot later undefine this face safely, except by restarting Emacs.
Macro: **defface** *face spec doc [keyword value]…*
This macro declares face as a named face whose default face spec is given by spec. You should not quote the symbol face, and it should not end in ‘`-face`’ (that would be redundant). The argument doc is a documentation string for the face. The additional keyword arguments have the same meanings as in `defgroup` and `defcustom` (see [Common Keywords](common-keywords)).
If face already has a default face spec, this macro does nothing.
The default face spec determines face’s appearance when no customizations are in effect (see [Customization](customization)). If face has already been customized (via Custom themes or via customizations read from the init file), its appearance is determined by the custom face spec(s), which override the default face spec spec. However, if the customizations are subsequently removed, the appearance of face will again be determined by its default face spec.
As an exception, if you evaluate a `defface` form with `C-M-x` (`eval-defun`) or with `C-x C-e` (`eval-last-sexp`) in Emacs Lisp mode, a special feature of these commands overrides any custom face specs on the face, causing the face to reflect exactly what the `defface` says.
The spec argument is a *face spec*, which states how the face should appear on different kinds of terminals. It should be an alist whose elements each have the form
```
(display . plist)
```
display specifies a class of terminals (see below). plist is a property list of face attributes and their values, specifying how the face appears on such terminals. For backward compatibility, you can also write an element as `(display plist)`.
The display part of an element of spec determines which terminals the element matches. If more than one element of spec matches a given terminal, the first element that matches is the one used for that terminal. There are three possibilities for display:
`default`
This element of spec doesn’t match any terminal; instead, it specifies defaults that apply to all terminals. This element, if used, must be the first element of spec. Each of the following elements can override any or all of these defaults.
`t`
This element of spec matches all terminals. Therefore, any subsequent elements of spec are never used. Normally `t` is used in the last (or only) element of spec.
a list
If display is a list, each element should have the form `(characteristic value…)`. Here characteristic specifies a way of classifying terminals, and the values are possible classifications which display should apply to. Here are the possible values of characteristic:
`type`
The kind of window system the terminal uses—either `graphic` (any graphics-capable display), `x`, `pc` (for the MS-DOS console), `w32` (for MS Windows 9X/NT/2K/XP), or `tty` (a non-graphics-capable display). See [window-system](window-systems).
`class`
What kinds of colors the terminal supports—either `color`, `grayscale`, or `mono`.
`background`
The kind of background—either `light` or `dark`.
`min-colors`
An integer that represents the minimum number of colors the terminal should support. This matches a terminal if its `display-color-cells` value is at least the specified integer.
`supports` Whether or not the terminal can display the face attributes given in value… (see [Face Attributes](face-attributes)). See [Display Face Attribute Testing](display-feature-testing#Display-Face-Attribute-Testing), for more information on exactly how this testing is done.
If an element of display specifies more than one value for a given characteristic, any of those values is acceptable. If display has more than one element, each element should specify a different characteristic; then *each* characteristic of the terminal must match one of the values specified for it in display.
For example, here’s the definition of the standard face `highlight`:
```
(defface highlight
'((((class color) (min-colors 88) (background light))
:background "darkseagreen2")
(((class color) (min-colors 88) (background dark))
:background "darkolivegreen")
(((class color) (min-colors 16) (background light))
:background "darkseagreen2")
(((class color) (min-colors 16) (background dark))
:background "darkolivegreen")
(((class color) (min-colors 8))
:background "green" :foreground "black")
(t :inverse-video t))
"Basic face for highlighting."
:group 'basic-faces)
```
Internally, Emacs stores each face’s default spec in its `face-defface-spec` symbol property (see [Symbol Properties](symbol-properties)). The `saved-face` property stores any face spec saved by the user using the customization buffer; the `customized-face` property stores the face spec customized for the current session, but not saved; and the `theme-face` property stores an alist associating the active customization settings and Custom themes with the face specs for that face. The face’s documentation string is stored in the `face-documentation` property.
Normally, a face is declared just once, using `defface`, and any further changes to its appearance are applied using the Customize framework (e.g., via the Customize user interface or via the `custom-set-faces` function; see [Applying Customizations](applying-customizations)), or by face remapping (see [Face Remapping](face-remapping)). In the rare event that you need to change a face spec directly from Lisp, you can use the `face-spec-set` function.
Function: **face-spec-set** *face spec &optional spec-type*
This function applies spec as a face spec for `face`. spec should be a face spec, as described in the above documentation for `defface`.
This function also defines face as a valid face name if it is not already one, and (re)calculates its attributes on existing frames.
The optional argument spec-type determines which spec to set. If it is omitted or `nil` or `face-override-spec`, this function sets the *override spec*, which overrides face specs on face of all the other types mentioned below. This is useful when calling this function outside of Custom code. If spec-type is `customized-face` or `saved-face`, this function sets the customized spec or the saved custom spec, respectively. If it is `face-defface-spec`, this function sets the default face spec (the same one set by `defface`). If it is `reset`, this function clears out all customization specs and override specs from face (in this case, the value of spec is ignored). The effect of any other value of spec-type on the face specs is reserved for internal use, but the function will still define face itself and recalculate its attributes, as described above.
elisp None ### Auto-Saving
Emacs periodically saves all files that you are visiting; this is called *auto-saving*. Auto-saving prevents you from losing more than a limited amount of work if the system crashes. By default, auto-saves happen every 300 keystrokes, or after around 30 seconds of idle time. See [Auto-Saving: Protection Against Disasters](https://www.gnu.org/software/emacs/manual/html_node/emacs/Auto-Save.html#Auto-Save) in The GNU Emacs Manual, for information on auto-save for users. Here we describe the functions used to implement auto-saving and the variables that control them.
Variable: **buffer-auto-save-file-name**
This buffer-local variable is the name of the file used for auto-saving the current buffer. It is `nil` if the buffer should not be auto-saved.
```
buffer-auto-save-file-name
⇒ "/xcssun/users/rms/lewis/#backups.texi#"
```
Command: **auto-save-mode** *arg*
This is the mode command for Auto Save mode, a buffer-local minor mode. When Auto Save mode is enabled, auto-saving is enabled in the buffer. The calling convention is the same as for other minor mode commands (see [Minor Mode Conventions](minor-mode-conventions)).
Unlike most minor modes, there is no `auto-save-mode` variable. Auto Save mode is enabled if `buffer-auto-save-file-name` is non-`nil` and `buffer-saved-size` (see below) is non-zero.
Variable: **auto-save-file-name-transforms**
This variable lists transforms to apply to buffer’s file name before making the auto-save file name.
Each transform is a list of the form `(regexp replacement [uniquify])`. regexp is a regular expression to match against the file name; if it matches, `replace-match` is used to replace the matching part with replacement. If the optional element uniquify is non-nil, the auto-save file name is constructed by concatenating the directory part of the transformed file name with the buffer’s file name in which all directory separators were changed to ‘`!`’ to prevent clashes. (This will not work correctly if your filesystem truncates the resulting name.)
If uniquify is one of the members of `secure-hash-algorithms`, Emacs constructs the nondirectory part of the auto-save file name by applying that `secure-hash` to the buffer file name. This avoids any risk of excessively long file names.
All the transforms in the list are tried, in the order they are listed. When one transform applies, its result is final; no further transforms are tried.
The default value is set up to put the auto-save files of remote files into the temporary directory (see [Unique File Names](unique-file-names)).
On MS-DOS filesystems without long names this variable is always ignored.
Function: **auto-save-file-name-p** *filename*
This function returns a non-`nil` value if filename is a string that could be the name of an auto-save file. It assumes the usual naming convention for auto-save files: a name that begins and ends with hash marks (‘`#`’) is a possible auto-save file name. The argument filename should not contain a directory part.
```
(make-auto-save-file-name)
⇒ "/xcssun/users/rms/lewis/#backups.texi#"
```
```
(auto-save-file-name-p "#backups.texi#")
⇒ 0
```
```
(auto-save-file-name-p "backups.texi")
⇒ nil
```
Function: **make-auto-save-file-name**
This function returns the file name to use for auto-saving the current buffer. This is just the file name with hash marks (‘`#`’) prepended and appended to it. This function does not look at the variable `auto-save-visited-file-name` (described below); callers of this function should check that variable first.
```
(make-auto-save-file-name)
⇒ "/xcssun/users/rms/lewis/#backups.texi#"
```
User Option: **auto-save-visited-file-name**
If this variable is non-`nil`, Emacs auto-saves buffers in the files they are visiting. That is, the auto-save is done in the same file that you are editing. Normally, this variable is `nil`, so auto-save files have distinct names that are created by `make-auto-save-file-name`.
When you change the value of this variable, the new value does not take effect in an existing buffer until the next time auto-save mode is reenabled in it. If auto-save mode is already enabled, auto-saves continue to go in the same file name until `auto-save-mode` is called again.
Note that setting this variable to a non-`nil` value does not change the fact that auto-saving is different from saving the buffer; e.g., the hooks described in [Saving Buffers](saving-buffers) are *not* run when a buffer is auto-saved.
Function: **recent-auto-save-p**
This function returns `t` if the current buffer has been auto-saved since the last time it was read in or saved.
Function: **set-buffer-auto-saved**
This function marks the current buffer as auto-saved. The buffer will not be auto-saved again until the buffer text is changed again. The function returns `nil`.
User Option: **auto-save-interval**
The value of this variable specifies how often to do auto-saving, in terms of number of input events. Each time this many additional input events are read, Emacs does auto-saving for all buffers in which that is enabled. Setting this to zero disables autosaving based on the number of characters typed.
User Option: **auto-save-timeout**
The value of this variable is the number of seconds of idle time that should cause auto-saving. Each time the user pauses for this long, Emacs does auto-saving for all buffers in which that is enabled. (If the current buffer is large, the specified timeout is multiplied by a factor that increases as the size increases; for a million-byte buffer, the factor is almost 4.)
If the value is zero or `nil`, then auto-saving is not done as a result of idleness, only after a certain number of input events as specified by `auto-save-interval`.
Variable: **auto-save-hook**
This normal hook is run whenever an auto-save is about to happen.
User Option: **auto-save-default**
If this variable is non-`nil`, buffers that are visiting files have auto-saving enabled by default. Otherwise, they do not.
Command: **do-auto-save** *&optional no-message current-only*
This function auto-saves all buffers that need to be auto-saved. It saves all buffers for which auto-saving is enabled and that have been changed since the previous auto-save.
If any buffers are auto-saved, `do-auto-save` normally displays a message saying ‘`Auto-saving...`’ in the echo area while auto-saving is going on. However, if no-message is non-`nil`, the message is inhibited.
If current-only is non-`nil`, only the current buffer is auto-saved.
Function: **delete-auto-save-file-if-necessary** *&optional force*
This function deletes the current buffer’s auto-save file if `delete-auto-save-files` is non-`nil`. It is called every time a buffer is saved.
Unless force is non-`nil`, this function only deletes the file if it was written by the current Emacs session since the last true save.
User Option: **delete-auto-save-files**
This variable is used by the function `delete-auto-save-file-if-necessary`. If it is non-`nil`, Emacs deletes auto-save files when a true save is done (in the visited file). This saves disk space and unclutters your directory.
Function: **rename-auto-save-file**
This function adjusts the current buffer’s auto-save file name if the visited file name has changed. It also renames an existing auto-save file, if it was made in the current Emacs session. If the visited file name has not changed, this function does nothing.
Variable: **buffer-saved-size**
The value of this buffer-local variable is the length of the current buffer, when it was last read in, saved, or auto-saved. This is used to detect a substantial decrease in size, and turn off auto-saving in response.
If it is -1, that means auto-saving is temporarily shut off in this buffer due to a substantial decrease in size. Explicitly saving the buffer stores a positive value in this variable, thus reenabling auto-saving. Turning auto-save mode off or on also updates this variable, so that the substantial decrease in size is forgotten.
If it is -2, that means this buffer should disregard changes in buffer size; in particular, it should not shut off auto-saving temporarily due to changes in buffer size.
Variable: **auto-save-list-file-name**
This variable (if non-`nil`) specifies a file for recording the names of all the auto-save files. Each time Emacs does auto-saving, it writes two lines into this file for each buffer that has auto-saving enabled. The first line gives the name of the visited file (it’s empty if the buffer has none), and the second gives the name of the auto-save file.
When Emacs exits normally, it deletes this file; if Emacs crashes, you can look in the file to find all the auto-save files that might contain work that was otherwise lost. The `recover-session` command uses this file to find them.
The default name for this file specifies your home directory and starts with ‘`.saves-`’. It also contains the Emacs process ID and the host name.
User Option: **auto-save-list-file-prefix**
After Emacs reads your init file, it initializes `auto-save-list-file-name` (if you have not already set it non-`nil`) based on this prefix, adding the host name and process ID. If you set this to `nil` in your init file, then Emacs does not initialize `auto-save-list-file-name`.
| programming_docs |
elisp None #### Easy Menu
The following macro provides a convenient way to define pop-up menus and/or menu bar menus.
Macro: **easy-menu-define** *symbol maps doc menu*
This macro defines a pop-up menu and/or menu bar submenu, whose contents are given by menu.
If symbol is non-`nil`, it should be a symbol; then this macro defines symbol as a function for popping up the menu (see [Pop-Up Menus](pop_002dup-menus)), with doc as its documentation string. symbol should not be quoted.
Regardless of the value of symbol, if maps is a keymap, the menu is added to that keymap, as a top-level menu for the menu bar (see [Menu Bar](menu-bar)). It can also be a list of keymaps, in which case the menu is added separately to each of those keymaps.
The first element of menu must be a string, which serves as the menu label. It may be followed by any number of the following keyword-argument pairs:
`:filter function`
function must be a function which, if called with one argument—the list of the other menu items—returns the actual items to be displayed in the menu.
`:visible include`
include is an expression; if it evaluates to `nil`, the menu is made invisible. `:included` is an alias for `:visible`.
`:active enable` enable is an expression; if it evaluates to `nil`, the menu is not selectable. `:enable` is an alias for `:active`.
The remaining elements in menu are menu items.
A menu item can be a vector of three elements, `[name
callback enable]`. name is the menu item name (a string). callback is a command to run, or an expression to evaluate, when the item is chosen. enable is an expression; if it evaluates to `nil`, the item is disabled for selection.
Alternatively, a menu item may have the form:
```
[ name callback [ keyword arg ]... ]
```
where name and callback have the same meanings as above, and each optional keyword and arg pair should be one of the following:
`:keys keys`
keys is a string to display as keyboard equivalent to the menu item. This is normally not needed, as keyboard equivalents are computed automatically. keys is expanded with `substitute-command-keys` before it is displayed (see [Keys in Documentation](keys-in-documentation)).
`:key-sequence keys`
keys is a hint indicating which key sequence to display as keyboard equivalent, in case the command is bound to several key sequences. It has no effect if keys is not bound to same command as this menu item.
`:active enable`
enable is an expression; if it evaluates to `nil`, the item is made unselectable. `:enable` is an alias for `:active`.
`:visible include`
include is an expression; if it evaluates to `nil`, the item is made invisible. `:included` is an alias for `:visible`.
`:label form`
form is an expression that is evaluated to obtain a value which serves as the menu item’s label (the default is name).
`:suffix form`
form is an expression that is dynamically evaluated and whose value is concatenated with the menu entry’s label.
`:style style`
style is a symbol describing the type of menu item; it should be `toggle` (a checkbox), or `radio` (a radio button), or anything else (meaning an ordinary menu item).
`:selected selected`
selected is an expression; the checkbox or radio button is selected whenever the expression’s value is non-`nil`.
`:help help` help is a string describing the menu item.
Alternatively, a menu item can be a string. Then that string appears in the menu as unselectable text. A string consisting of dashes is displayed as a separator (see [Menu Separators](menu-separators)).
Alternatively, a menu item can be a list with the same format as menu. This is a submenu.
Here is an example of using `easy-menu-define` to define a menu similar to the one defined in the example in [Menu Bar](menu-bar):
```
(easy-menu-define words-menu global-map
"Menu for word navigation commands."
'("Words"
["Forward word" forward-word]
["Backward word" backward-word]))
```
elisp None #### Echo Area Customization
These variables control details of how the echo area works.
Variable: **cursor-in-echo-area**
This variable controls where the cursor appears when a message is displayed in the echo area. If it is non-`nil`, then the cursor appears at the end of the message. Otherwise, the cursor appears at point—not in the echo area at all.
The value is normally `nil`; Lisp programs bind it to `t` for brief periods of time.
Variable: **echo-area-clear-hook**
This normal hook is run whenever the echo area is cleared—either by `(message nil)` or for any other reason.
User Option: **echo-keystrokes**
This variable determines how much time should elapse before command characters echo. Its value must be a number, and specifies the number of seconds to wait before echoing. If the user types a prefix key (such as `C-x`) and then delays this many seconds before continuing, the prefix key is echoed in the echo area. (Once echoing begins in a key sequence, all subsequent characters in the same key sequence are echoed immediately.)
If the value is zero, then command input is not echoed.
Variable: **message-truncate-lines**
Normally, displaying a long message resizes the echo area to display the entire message, wrapping long line as needed. But if the variable `message-truncate-lines` is non-`nil`, long lines of echo-area message are instead truncated to fit the mini-window width.
The variable `max-mini-window-height`, which specifies the maximum height for resizing minibuffer windows, also applies to the echo area (which is really a special use of the minibuffer window; see [Minibuffer Windows](minibuffer-windows)).
elisp None ### Minibuffers and Frames
Normally, each frame has its own minibuffer window at the bottom, which is used whenever that frame is selected. You can get that window with the function `minibuffer-window` (see [Minibuffer Windows](minibuffer-windows)).
However, you can also create a frame without a minibuffer. Such a frame must use the minibuffer window of some other frame. That other frame will serve as *surrogate minibuffer frame* for this frame and cannot be deleted via `delete-frame` (see [Deleting Frames](deleting-frames)) as long as this frame is live.
When you create the frame, you can explicitly specify its minibuffer window (in some other frame) with the `minibuffer` frame parameter (see [Buffer Parameters](buffer-parameters)). If you don’t, then the minibuffer is found in the frame which is the value of the variable `default-minibuffer-frame`. Its value should be a frame that does have a minibuffer.
If you use a minibuffer-only frame, you might want that frame to raise when you enter the minibuffer. If so, set the variable `minibuffer-auto-raise` to `t`. See [Raising and Lowering](raising-and-lowering).
Variable: **default-minibuffer-frame**
This variable specifies the frame to use for the minibuffer window, by default. It does not affect existing frames. It is always local to the current terminal and cannot be buffer-local. See [Multiple Terminals](multiple-terminals).
elisp None #### Testing Availability of Network Features
To test for the availability of a given network feature, use `featurep` like this:
```
(featurep 'make-network-process '(keyword value))
```
The result of this form is `t` if it works to specify keyword with value value in `make-network-process`. Here are some of the keyword—value pairs you can test in this way.
`(:nowait t)` Non-`nil` if non-blocking connect is supported.
`(:type datagram)` Non-`nil` if datagrams are supported.
`(:family local)` Non-`nil` if local (a.k.a. “UNIX domain”) sockets are supported.
`(:family ipv6)` Non-`nil` if IPv6 is supported.
`(:service t)` Non-`nil` if the system can select the port for a server.
To test for the availability of a given network option, use `featurep` like this:
```
(featurep 'make-network-process 'keyword)
```
The accepted keyword values are `:bindtodevice`, etc. For the complete list, see [Network Options](network-options). This form returns non-`nil` if that particular network option is supported by `make-network-process` (or `set-network-process-option`).
koa Troubleshooting Koa Troubleshooting Koa
===================
* [Whenever I try to access my route, it sends back a 404](#whenever-i-try-to-access-my-route-it-sends-back-a-404)
* [My response or context changes have no effect](#my-response-or-context-changes-have-no-effect)
* [My middleware is not called](#my-middleware-is-not-called)
See also [debugging Koa](guide.md#debugging-koa).
If you encounter a problem and later learn how to fix it, and think others might also encounter that problem, please consider contributing to this documentation.
Whenever I try to access my route, it sends back a 404
------------------------------------------------------
This is a common but troublesome problem when working with Koa middleware. First, it is critical to understand when Koa generates a 404. Koa does not care which or how much middleware was run, in many cases a 200 and 404 trigger the same number of middleware. Instead, the default status for any response is 404. The most obvious way this is changed is through `ctx.status`. However, if `ctx.body` is set when the status has not been explicitly defined (through `ctx.status`), the status is set to 200. This explains why simply setting the body results in a 200. Once the middleware is done (when the middleware and any returned promises are complete), Koa sends out the response. After that, nothing can alter the response. If it was a 404 at the time, it will be a 404 at the end, even if `ctx.status` or `ctx.body` are set afterwords.
Even though we now understand the basis of a 404, it might not be as clear why a 404 is generated in a specific case. This can be especially troublesome when it seems that `ctx.status` or `ctx.body` are set.
The unexpected 404 is a specific symptom of one of these more general problems:
* [My response or context changes have no effect](#my-response-or-context-changes-have-no-effect)
* [My middleware is not called](#my-middleware-is-not-called)
My response or context changes have no effect
---------------------------------------------
This can be caused when the response is sent before the code making the change is executed. If the change is to the `ctx.body` or `ctx.status` setter, this can cause a 404 and is by far the most common cause of these problems.
### Problematic code
```
router.get('/fetch', function (ctx, next) {
models.Book.findById(parseInt(ctx.query.id)).then(function (book) {
ctx.body = book;
});
});
```
When used, this route will always send back a 404, even though `ctx.body` is set.
The same behavior would occur in this `async` version:
```
router.get('/fetch', async (ctx, next) => {
models.Book.findById(parseInt(ctx.query.id)).then(function (book) {
ctx.body = book;
});
});
```
### Cause
`ctx.body` is not set until *after* the response has been sent. The code doesn't tell Koa to wait for the database to return the record. Koa sends the response after the middleware has been run, but not after the callback inside the middleware has been run. In the gap there, `ctx.body` has not yet been set, so Koa responds with a 404.
### Identifying this as the issue
Adding another piece of middleware and some logging can be extremely helpful in identifying this issue.
```
router.use('/fetch', function (ctx, next) {
return next().then(function () {
console.log('Middleware done');
});
});
router.get('/fetch', function (ctx, next) {
models.Book.findById(parseInt(ctx.query.id)).then(function (book) {
ctx.body = book;
console.log('Body set');
});
});
```
If you see this in the logs:
```
Middleware done
Body set
```
It means that the body is being set after the middleware is done, and after the response has been sent. If you see only one or none of these logs, proceed to [My middleware is not called](#my-middleware-is-not-called). If they are in the right order, make sure you haven't explicitly set the status to 404, make sure that it actually is a 404, and if that fails feel free to ask for help.
### Solution
```
router.get('/fetch', function (ctx, next) {
return models.Book.findById(parseInt(ctx.query.id)).then(function (book) {
ctx.body = book;
});
});
```
Returning the promise given by the database interface tells Koa to wait for the promise to finish before responding. At that time, the body will have been set. This results in Koa sending back a 200 with a proper response.
The fix in the `async` version is to add an `await` statement:
```
router.get('/fetch', async (ctx, next) => {
await models.Book.findById(parseInt(ctx.query.id)).then(function (book) {
ctx.body = book;
});
});
```
My middleware is not called
---------------------------
This can be due to an interrupted chain of middleware calls. This can cause a 404 if the middleware that is skipped is responsible for the `ctx.body` or `ctx.status` setter. This is less common than [My response or context changes have no effect](#my-response-or-context-changes-have-no-effect), but it can be a much bigger pain to troubleshoot.
### Problematic code
```
router.use(function (ctx, next) {
// Don't Repeat Yourself! Let's parse the ID here for all our middleware
if (ctx.query.id) {
ctx.state.id = parseInt(ctx.query.id);
}
});
router.get('/fetch', function (ctx, next) {
return models.Book.findById(ctx.state.id).then(function (book) {
ctx.body = book;
});
});
```
### Cause
In the code above, the book is never fetched from the database, and in fact our route was never called. Look closely at our helper middleware. We forgot to `return next()`! This causes the middleware flow to never reach our route, ending our "helper" middleware.
### Identifying this as the issue
Identifying this problem is easier than most, add a log at the beginning of the route. If it doesn't trigger, your route was never reached in the middleware chain.
```
router.use(function (ctx, next) {
// Don't Repeat Yourself! Let's parse the ID here for all our middleware
if (ctx.query.id) {
ctx.state.id = parseInt(ctx.query.id);
}
});
router.get('/fetch', function (ctx, next) {
console.log('Route called'); // Never happens
return models.Book.findById(ctx.state.id).then(function (book) {
ctx.body = book;
});
});
```
To find the middleware causing the problem, try adding logging at various points in the middleware chain.
### Solution
The solution for this is rather easy, simply add `return next()` to the end of your helper middleware.
```
router.use(function (ctx, next) {
if (ctx.query.id) {
ctx.state.id = parseInt(ctx.query.id);
}
return next();
});
router.get('/fetch', function (ctx, next) {
return models.Book.findById(ctx.state.id).then(function (book) {
ctx.body = book;
});
});
```
koa Migrating from Koa v1.x to v2.x Migrating from Koa v1.x to v2.x
===============================
New middleware signature
------------------------
Koa v2 introduces a new signature for middleware.
**Old signature middleware (v1.x) support will be removed in v3**
The new middleware signature is:
```
// uses async arrow functions
app.use(async (ctx, next) => {
try {
await next() // next is now a function
} catch (err) {
ctx.body = { message: err.message }
ctx.status = err.status || 500
}
})
app.use(async ctx => {
const user = await User.getById(this.session.userid) // await instead of yield
ctx.body = user // ctx instead of this
})
```
You don't have to use asynchronous functions - you just have to pass a function that returns a promise. A regular function that returns a promise works too!
The signature has changed to pass `Context` via an explicit parameter, `ctx` above, instead of via `this`. The context passing change makes Koa more compatible with es6 arrow functions, which capture `this`.
Using v1.x Middleware in v2.x
-----------------------------
Koa v2.x will try to convert legacy signature, generator middleware on `app.use`, using [koa-convert](https://github.com/koajs/convert). It is however recommended that you choose to migrate all v1.x middleware as soon as possible.
```
// Koa will convert
app.use(function *(next) {
const start = Date.now();
yield next;
const ms = Date.now() - start;
console.log(`${this.method} ${this.url} - ${ms}ms`);
});
```
You could do it manually as well, in which case Koa will not convert.
```
const convert = require('koa-convert');
app.use(convert(function *(next) {
const start = Date.now();
yield next;
const ms = Date.now() - start;
console.log(`${this.method} ${this.url} - ${ms}ms`);
}));
```
Upgrading middleware
--------------------
You will have to convert your generators to async functions with the new middleware signature:
```
app.use(async (ctx, next) => {
const user = await Users.getById(this.session.user_id);
await next();
ctx.body = { message: 'some message' };
})
```
Upgrading your middleware may require some work. One migration path is to update them one-by-one.
1. Wrap all your current middleware in `koa-convert`
2. Test
3. `npm outdated` to see which Koa middleware is outdated
4. Update one outdated middleware, remove using `koa-convert`
5. Test
6. Repeat steps 3-5 until you're done
Updating your code
------------------
You should start refactoring your code now to ease migrating to Koa v2:
* Return promises everywhere!
* Do not use `yield*`
* Do not use `yield {}` or `yield []`.
+ Convert `yield []` into `yield Promise.all([])`
+ Convert `yield {}` into `yield Bluebird.props({})`
You could also refactor your logic outside of Koa middleware functions. Create functions like `function* someLogic(ctx) {}` and call it in your middleware as `const result = yield someLogic(this)`. Not using `this` will help migrations to the new middleware signature, which does not use `this`.
Application object constructor requires new
-------------------------------------------
In v1.x, the Application constructor function could be called directly, without `new` to instantiate an instance of an application. For example:
```
var koa = require('koa');
var app = module.exports = koa();
```
v2.x uses es6 classes which require the `new` keyword to be used.
```
var koa = require('koa');
var app = module.exports = new koa();
```
ENV specific logging behavior removed
-------------------------------------
An explicit check for the `test` environment was removed from error handling.
Dependency changes
------------------
* [co](https://github.com/tj/co) is no longer bundled with Koa. Require or import it directly.
* [composition](https://github.com/thenables/composition) is no longer used and deprecated.
v1.x support
------------
The v1.x branch is still supported but should not receive feature updates. Except for this migration guide, documentation will target the latest version.
Help out
--------
If you encounter migration related issues not covered by this migration guide, please consider submitting a documentation pull request.
koa Koa Koa
===
Introduction
------------
Expressive HTTP middleware framework for node.js to make web applications and APIs more enjoyable to write. Koa's middleware stack flows in a stack-like manner, allowing you to perform actions downstream then filter and manipulate the response upstream.
Only methods that are common to nearly all HTTP servers are integrated directly into Koa's small ~570 SLOC codebase. This includes things like content negotiation, normalization of node inconsistencies, redirection, and a few others.
Koa is not bundled with any middleware.
Installation
------------
Koa requires **node v7.6.0** or higher for ES2015 and async function support.
You can quickly install a supported version of node with your favorite version manager:
```
$ nvm install 7
$ npm i koa
$ node my-koa-app.js
```
Application
-----------
A Koa application is an object containing an array of middleware functions which are composed and executed in a stack-like manner upon request. Koa is similar to many other middleware systems that you may have encountered such as Ruby's Rack, Connect, and so on - however a key design decision was made to provide high level "sugar" at the otherwise low-level middleware layer. This improves interoperability, robustness, and makes writing middleware much more enjoyable.
This includes methods for common tasks like content-negotiation, cache freshness, proxy support, and redirection among others. Despite supplying a reasonably large number of helpful methods Koa maintains a small footprint, as no middleware are bundled.
The obligatory hello world application:
```
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
```
### Cascading
Koa middleware cascade in a more traditional way as you may be used to with similar tools - this was previously difficult to make user friendly with node's use of callbacks. However with async functions we can achieve "true" middleware. Contrasting Connect's implementation which simply passes control through series of functions until one returns, Koa invoke "downstream", then control flows back "upstream".
The following example responds with "Hello World", however first the request flows through the `x-response-time` and `logging` middleware to mark when the request started, then continue to yield control through the response middleware. When a middleware invokes `next()` the function suspends and passes control to the next middleware defined. After there are no more middleware to execute downstream, the stack will unwind and each middleware is resumed to perform its upstream behaviour.
```
const Koa = require('koa');
const app = new Koa();
// logger
app.use(async (ctx, next) => {
await next();
const rt = ctx.response.get('X-Response-Time');
console.log(`${ctx.method} ${ctx.url} - ${rt}`);
});
// x-response-time
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});
// response
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
```
### Settings
Application settings are properties on the `app` instance, currently the following are supported:
* `app.env` defaulting to the **NODE\_ENV** or "development"
* `app.keys` array of signed cookie keys
* `app.proxy` when true proxy header fields will be trusted
* `app.subdomainOffset` offset of `.subdomains` to ignore, default to 2
* `app.proxyIpHeader` proxy ip header, default to `X-Forwarded-For`
* `app.maxIpsCount` max ips read from proxy ip header, default to 0 (means infinity)
You can pass the settings to the constructor:
```
const Koa = require('koa');
const app = new Koa({ proxy: true });
```
or dynamically:
```
const Koa = require('koa');
const app = new Koa();
app.proxy = true;
```
### app.listen(...)
A Koa application is not a 1-to-1 representation of an HTTP server. One or more Koa applications may be mounted together to form larger applications with a single HTTP server.
Create and return an HTTP server, passing the given arguments to `Server#listen()`. These arguments are documented on [nodejs.org](http://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback). The following is a useless Koa application bound to port `3000`:
```
const Koa = require('koa');
const app = new Koa();
app.listen(3000);
```
The `app.listen(...)` method is simply sugar for the following:
```
const http = require('http');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);
```
This means you can spin up the same application as both HTTP and HTTPS or on multiple addresses:
```
const http = require('http');
const https = require('https');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);
https.createServer(app.callback()).listen(3001);
```
### app.callback()
Return a callback function suitable for the `http.createServer()` method to handle a request. You may also use this callback function to mount your Koa app in a Connect/Express app.
### app.use(function)
Add the given middleware function to this application. `app.use()` returns `this`, so is chainable.
```
app.use(someMiddleware)
app.use(someOtherMiddleware)
app.listen(3000)
```
Is the same as
```
app.use(someMiddleware)
.use(someOtherMiddleware)
.listen(3000)
```
See [Middleware](https://github.com/koajs/koa/wiki#middleware) for more information.
### app.keys=
Set signed cookie keys.
These are passed to [KeyGrip](https://github.com/crypto-utils/keygrip), however you may also pass your own `KeyGrip` instance. For example the following are acceptable:
```
app.keys = ['im a newer secret', 'i like turtle'];
app.keys = new KeyGrip(['im a newer secret', 'i like turtle'], 'sha256');
```
These keys may be rotated and are used when signing cookies with the `{ signed: true }` option:
```
ctx.cookies.set('name', 'tobi', { signed: true });
```
### app.context
`app.context` is the prototype from which `ctx` is created. You may add additional properties to `ctx` by editing `app.context`. This is useful for adding properties or methods to `ctx` to be used across your entire app, which may be more performant (no middleware) and/or easier (fewer `require()`s) at the expense of relying more on `ctx`, which could be considered an anti-pattern.
For example, to add a reference to your database from `ctx`:
```
app.context.db = db();
app.use(async ctx => {
console.log(ctx.db);
});
```
Note:
* Many properties on `ctx` are defined using getters, setters, and `Object.defineProperty()`. You can only edit these properties (not recommended) by using `Object.defineProperty()` on `app.context`. See <https://github.com/koajs/koa/issues/652>.
* Mounted apps currently use their parent's `ctx` and settings. Thus, mounted apps are really just groups of middleware.
### Error Handling
By default outputs all errors to stderr unless `app.silent` is `true`. The default error handler also won't output errors when `err.status` is `404` or `err.expose` is `true`. To perform custom error-handling logic such as centralized logging you can add an "error" event listener:
```
app.on('error', err => {
log.error('server error', err)
});
```
If an error is in the req/res cycle and it is *not* possible to respond to the client, the `Context` instance is also passed:
```
app.on('error', (err, ctx) => {
log.error('server error', err, ctx)
});
```
When an error occurs *and* it is still possible to respond to the client, aka no data has been written to the socket, Koa will respond appropriately with a 500 "Internal Server Error". In either case an app-level "error" is emitted for logging purposes.
| programming_docs |
koa Frequently Asked Questions Frequently Asked Questions
==========================
Does Koa replace Express?
-------------------------
It's more like Connect, but a lot of the Express goodies were moved to the middleware level in Koa to help form a stronger foundation. This makes middleware more enjoyable and less error-prone to write, for the entire stack, not just the end application code.
Typically many middleware would re-implement similar features, or even worse incorrectly implement them, when features like signed cookie secrets among others are typically application-specific, not middleware specific.
Does Koa replace Connect?
-------------------------
No, just a different take on similar functionality now that async functions allow us to write code with fewer callbacks. Connect is equally capable, and some may still prefer it, it's up to what you prefer.
Does Koa include routing?
-------------------------
No - out of the box Koa has no form of routing, however many routing middleware are available: <https://github.com/koajs/koa/wiki>
Why isn't Koa just Express 4.0?
-------------------------------
Koa is a pretty large departure from what people know about Express, the design is fundamentally much different, so the migration from Express 3.0 to this Express 4.0 would effectively mean rewriting the entire application, so we thought it would be more appropriate to create a new library.
What custom properties do the Koa objects have?
-----------------------------------------------
Koa uses its own custom objects: `ctx`, `ctx.request`, and `ctx.response`. These objects abstract node's `req` and `res` objects with convenience methods and getters/setters. Generally, properties added to these objects must obey the following rules:
* They must be either very commonly used and/or must do something useful
* If a property exists as a setter, then it will also exist as a getter, but not vice versa
Many of `ctx.request` and `ctx.response`'s properties are delegated to `ctx`. If it's a getter/setter, then both the getter and the setter will strictly correspond to either `ctx.request` or `ctx.response`.
Please think about these rules before suggesting additional properties.
koa Guide Guide
=====
This guide covers Koa topics that are not directly API related, such as best practices for writing middleware and application structure suggestions. In these examples we use async functions as middleware - you can also use commonFunction or generatorFunction which will be a little different.
Table of Contents
-----------------
* [Guide](#guide)
+ [Table of Contents](#table-of-contents)
+ [Writing Middleware](#writing-middleware)
+ [Middleware Best Practices](#middleware-best-practices)
- [Middleware options](#middleware-options)
- [Named middleware](#named-middleware)
- [Combining multiple middleware with koa-compose](#combining-multiple-middleware-with-koa-compose)
- [Response Middleware](#response-middleware)
+ [Async operations](#async-operations)
+ [Debugging Koa](#debugging-koa)
Writing Middleware
------------------
Koa middleware are simple functions which return a `MiddlewareFunction` with signature (ctx, next). When the middleware is run, it must manually invoke `next()` to run the "downstream" middleware.
For example if you wanted to track how long it takes for a request to propagate through Koa by adding an `X-Response-Time` header field the middleware would look like the following:
```
async function responseTime(ctx, next) {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
}
app.use(responseTime);
```
If you're a front-end developer you can think any code before `next();` as the "capture" phase, while any code after is the "bubble" phase. This crude gif illustrates how async function allow us to properly utilize stack flow to implement request and response flows:
1. Create a date to track response time
2. Await control to the next middleware
3. Create another date to track duration
4. Await control to the next middleware
5. Set the response body to "Hello World"
6. Calculate duration time
7. Output log line
8. Calculate response time
9. Set `X-Response-Time` header field
10. Hand off to Koa to handle the response
Next we'll look at the best practices for creating Koa middleware.
Middleware Best Practices
-------------------------
This section covers middleware authoring best practices, such as middleware accepting options, named middleware for debugging, among others.
### Middleware options
When creating a public middleware, it's useful to conform to the convention of wrapping the middleware in a function that accepts options, allowing users to extend functionality. Even if your middleware accepts *no* options, this is still a good idea to keep things uniform.
Here our contrived `logger` middleware accepts a `format` string for customization, and returns the middleware itself:
```
function logger(format) {
format = format || ':method ":url"';
return async function (ctx, next) {
const str = format
.replace(':method', ctx.method)
.replace(':url', ctx.url);
console.log(str);
await next();
};
}
app.use(logger());
app.use(logger(':method :url'));
```
### Named middleware
Naming middleware is optional, however it's useful for debugging purposes to assign a name.
```
function logger(format) {
return async function logger(ctx, next) {
};
}
```
### Combining multiple middleware with koa-compose
Sometimes you want to "compose" multiple middleware into a single middleware for easy re-use or exporting. You can use [koa-compose](https://github.com/koajs/compose)
```
const compose = require('koa-compose');
async function random(ctx, next) {
if ('/random' == ctx.path) {
ctx.body = Math.floor(Math.random() * 10);
} else {
await next();
}
};
async function backwards(ctx, next) {
if ('/backwards' == ctx.path) {
ctx.body = 'sdrawkcab';
} else {
await next();
}
}
async function pi(ctx, next) {
if ('/pi' == ctx.path) {
ctx.body = String(Math.PI);
} else {
await next();
}
}
const all = compose([random, backwards, pi]);
app.use(all);
```
### Response Middleware
Middleware that decide to respond to a request and wish to bypass downstream middleware may simply omit `next()`. Typically this will be in routing middleware, but this can be performed by any. For example the following will respond with "two", however all three are executed, giving the downstream "three" middleware a chance to manipulate the response.
```
app.use(async function (ctx, next) {
console.log('>> one');
await next();
console.log('<< one');
});
app.use(async function (ctx, next) {
console.log('>> two');
ctx.body = 'two';
await next();
console.log('<< two');
});
app.use(async function (ctx, next) {
console.log('>> three');
await next();
console.log('<< three');
});
```
The following configuration omits `next()` in the second middleware, and will still respond with "two", however the third (and any other downstream middleware) will be ignored:
```
app.use(async function (ctx, next) {
console.log('>> one');
await next();
console.log('<< one');
});
app.use(async function (ctx, next) {
console.log('>> two');
ctx.body = 'two';
console.log('<< two');
});
app.use(async function (ctx, next) {
console.log('>> three');
await next();
console.log('<< three');
});
```
When the furthest downstream middleware executes `next();`, it's really yielding to a noop function, allowing the middleware to compose correctly anywhere in the stack.
Async operations
----------------
Async function and promise forms Koa's foundation, allowing you to write non-blocking sequential code. For example this middleware reads the filenames from `./docs`, and then reads the contents of each markdown file in parallel before assigning the body to the joint result.
```
const fs = require('mz/fs');
app.use(async function (ctx, next) {
const paths = await fs.readdir('docs');
const files = await Promise.all(paths.map(path => fs.readFile(`docs/${path}`, 'utf8')));
ctx.type = 'markdown';
ctx.body = files.join('');
});
```
Debugging Koa
-------------
Koa along with many of the libraries it's built with support the **DEBUG** environment variable from [debug](https://github.com/visionmedia/debug) which provides simple conditional logging.
For example to see all Koa-specific debugging information just pass `DEBUG=koa*` and upon boot you'll see the list of middleware used, among other things.
```
$ DEBUG=koa* node --harmony examples/simple
koa:application use responseTime +0ms
koa:application use logger +4ms
koa:application use contentLength +0ms
koa:application use notfound +0ms
koa:application use response +0ms
koa:application listen +0ms
```
Since JavaScript does not allow defining function names at runtime, you can also set a middleware's name as `._name`. This is useful when you don't have control of a middleware's name. For example:
```
const path = require('path');
const serve = require('koa-static');
const publicFiles = serve(path.join(__dirname, 'public'));
publicFiles._name = 'static /public';
app.use(publicFiles);
```
Now, instead of just seeing "serve" when debugging, you will see:
```
koa:application use static /public +0ms
```
koa Koa vs Express Koa vs Express
==============
Philosophically, Koa aims to "fix and replace node", whereas Express "augments node". Koa uses promises and async functions to rid apps of callback hell and simplify error handling. It exposes its own `ctx.request` and `ctx.response` objects instead of node's `req` and `res` objects.
Express, on the other hand, augments node's `req` and `res` objects with additional properties and methods and includes many other "framework" features, such as routing and templating, which Koa does not.
Thus, Koa can be viewed as an abstraction of node.js's `http` modules, where as Express is an application framework for node.js.
| Feature | Koa | Express | Connect |
| --- | --- | --- | --- |
| Middleware Kernel | ✓ | ✓ | ✓ |
| Routing | | ✓ | |
| Templating | | ✓ | |
| Sending Files | | ✓ | |
| JSONP | | ✓ | |
Thus, if you'd like to be closer to node.js and traditional node.js-style coding, you probably want to stick to Connect/Express or similar frameworks. If you want to get rid of callbacks, use Koa.
As result of this different philosophy is that traditional node.js "middleware", i.e. functions of the form `(req, res, next)`, are incompatible with Koa. Your application will essentially have to be rewritten from the ground, up.
Does Koa replace Express?
-------------------------
It's more like Connect, but a lot of the Express goodies were moved to the middleware level in Koa to help form a stronger foundation. This makes middleware more enjoyable and less error-prone to write, for the entire stack, not just the end application code.
Typically many middleware would re-implement similar features, or even worse incorrectly implement them, when features like signed cookie secrets among others are typically application-specific, not middleware specific.
Does Koa replace Connect?
-------------------------
No, just a different take on similar functionality now that generators allow us to write code with less callbacks. Connect is equally capable, and some may still prefer it, it's up to what you prefer.
Why isn't Koa just Express 4.0?
-------------------------------
Koa is a pretty large departure from what people know about Express, the design is fundamentally much different, so the migration from Express 3.0 to this Express 4.0 would effectively mean rewriting the entire application, so we thought it would be more appropriate to create a new library.
How is Koa different than Connect/Express?
------------------------------------------
### Promises-based control flow
No callback hell.
Better error handling through try/catch.
No need for domains.
### Koa is barebones
Unlike both Connect and Express, Koa does not include any middleware.
Unlike Express, routing is not provided.
Unlike Express, many convenience utilities are not provided. For example, sending files.
Koa is more modular.
### Koa relies less on middleware
For example, instead of a "body parsing" middleware, you would instead use a body parsing function.
### Koa abstracts node's request/response
Less hackery.
Better user experience.
Proper stream handling.
### Koa routing (third party libraries support)
Since Express comes with its own routing, but Koa does not have any in-built routing, there are third party libraries available such as koa-router and koa-route. Similarly, just like we have helmet for security in Express, for Koa we have koa-helmet available and the list goes on for Koa available third party libraries.
koa Error Handling Error Handling
==============
Try-Catch
---------
Using async functions means that you can try-catch `next`. This example adds a `.status` to all errors:
```
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
err.status = err.statusCode || err.status || 500;
throw err;
}
});
```
### Default Error Handler
The default error handler is essentially a `try-catch` at the very beginning of the middleware chain. To use a different error handler, simply put another `try-catch` at the beginning of the middleware chain, and handle the error there. However, the default error handler is good enough for most use cases. It will use a status code of `err.status`, or by default 500. If `err.expose` is true, then `err.message` will be the reply. Otherwise, a message generated from the error code will be used (e.g. for the code 500 the message "Internal Server Error" will be used). All headers will be cleared from the request, but any headers in `err.headers` will then be set. You can use a `try-catch`, as specified above, to add a header to this list.
Here is an example of creating your own error handler:
```
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
// will only respond with JSON
ctx.status = err.statusCode || err.status || 500;
ctx.body = {
message: err.message
};
}
})
```
The Error Event
---------------
Error event listeners can be specified with `app.on('error')`. If no error listener is specified, a default error listener is used. Error listeners receive all errors that make their way back through the middleware chain, if an error is caught and not thrown again, it will not be passed to the error listener. If no error event listener is specified, then `app.onerror` will be used, which simply log the error unless `error.expose`is true or `app.silent` is true or `error.status` is 404.
koa Context Context
=======
A Koa Context encapsulates node's `request` and `response` objects into a single object which provides many helpful methods for writing web applications and APIs. These operations are used so frequently in HTTP server development that they are added at this level instead of a higher level framework, which would force middleware to re-implement this common functionality.
A `Context` is created *per* request, and is referenced in middleware as the receiver, or the `ctx` identifier, as shown in the following snippet:
```
app.use(async ctx => {
ctx; // is the Context
ctx.request; // is a Koa Request
ctx.response; // is a Koa Response
});
```
Many of the context's accessors and methods simply delegate to their `ctx.request` or `ctx.response` equivalents for convenience, and are otherwise identical. For example `ctx.type` and `ctx.length` delegate to the `response` object, and `ctx.path` and `ctx.method` delegate to the `request`.
API
---
`Context` specific methods and accessors.
### ctx.req
Node's `request` object.
### ctx.res
Node's `response` object.
Bypassing Koa's response handling is **not supported**. Avoid using the following node properties:
* `res.statusCode`
* `res.writeHead()`
* `res.write()`
* `res.end()`
### ctx.request
A Koa `Request` object.
### ctx.response
A Koa `Response` object.
### ctx.state
The recommended namespace for passing information through middleware and to your frontend views.
```
ctx.state.user = await User.find(id);
```
### ctx.app
Application instance reference.
### ctx.app.emit
Koa applications extend an internal [EventEmitter](https://nodejs.org/dist/latest-v11.x/docs/api/events.html). `ctx.app.emit` emits an event with a type, defined by the first argument. For each event you can hook up "listeners", which is a function that is called when the event is emitted. Consult the [error handling docs](../error-handling.md) for more information.
### ctx.cookies.get(name, [options])
Get cookie `name` with `options`:
* `signed` the cookie requested should be signed
Koa uses the [cookies](https://github.com/pillarjs/cookies) module where options are simply passed.
### ctx.cookies.set(name, value, [options])
Set cookie `name` to `value` with `options`:
* `maxAge`: a number representing the milliseconds from `Date.now()` for expiry.
* `expires`: a `Date` object indicating the cookie's expiration date (expires at the end of session by default).
* `path`: a string indicating the path of the cookie (`/` by default).
* `domain`: a string indicating the domain of the cookie (no default).
* `secure`: a boolean indicating whether the cookie is only to be sent over HTTPS (`false` by default for HTTP, `true` by default for HTTPS). [Read more about this option](https://github.com/pillarjs/cookies#secure-cookies).
* `httpOnly`: a boolean indicating whether the cookie is only to be sent over HTTP(S), and not made available to client JavaScript (`true` by default).
* `sameSite`: a boolean or string indicating whether the cookie is a "same site" cookie (`false` by default). This can be set to `'strict'`, `'lax'`, `'none'`, or `true` (which maps to `'strict'`).
* `signed`: a boolean indicating whether the cookie is to be signed (`false` by default). If this is true, another cookie of the same name with the `.sig` suffix appended will also be sent, with a 27-byte url-safe base64 SHA1 value representing the hash of *cookie-name*=*cookie-value* against the first [Keygrip](https://www.npmjs.com/package/keygrip) key. This signature key is used to detect tampering the next time a cookie is received.
* `overwrite`: a boolean indicating whether to overwrite previously set cookies of the same name (`false` by default). If this is true, all cookies set during the same request with the same name (regardless of path or domain) are filtered out of the Set-Cookie header when setting this cookie.
Koa uses the [cookies](https://github.com/pillarjs/cookies) module where options are simply passed.
### ctx.throw([status], [msg], [properties])
Helper method to throw an error with a `.status` property defaulting to `500` that will allow Koa to respond appropriately. The following combinations are allowed:
```
ctx.throw(400);
ctx.throw(400, 'name required');
ctx.throw(400, 'name required', { user: user });
```
For example `ctx.throw(400, 'name required')` is equivalent to:
```
const err = new Error('name required');
err.status = 400;
err.expose = true;
throw err;
```
Note that these are user-level errors and are flagged with `err.expose` meaning the messages are appropriate for client responses, which is typically not the case for error messages since you do not want to leak failure details.
You may optionally pass a `properties` object which is merged into the error as-is, useful for decorating machine-friendly errors which are reported to the requester upstream.
```
ctx.throw(401, 'access_denied', { user: user });
```
Koa uses [http-errors](https://github.com/jshttp/http-errors) to create errors. `status` should only be passed as the first parameter.
### ctx.assert(value, [status], [msg], [properties])
Helper method to throw an error similar to `.throw()` when `!value`. Similar to node's [assert()](http://nodejs.org/api/assert.html) method.
```
ctx.assert(ctx.state.user, 401, 'User not found. Please login!');
```
Koa uses [http-assert](https://github.com/jshttp/http-assert) for assertions.
### ctx.respond
To bypass Koa's built-in response handling, you may explicitly set `ctx.respond = false;`. Use this if you want to write to the raw `res` object instead of letting Koa handle the response for you.
Note that using this is **not** supported by Koa. This may break intended functionality of Koa middleware and Koa itself. Using this property is considered a hack and is only a convenience to those wishing to use traditional `fn(req, res)` functions and middleware within Koa.
Request aliases
---------------
The following accessors and alias [Request](request.md) equivalents:
* `ctx.header`
* `ctx.headers`
* `ctx.method`
* `ctx.method=`
* `ctx.url`
* `ctx.url=`
* `ctx.originalUrl`
* `ctx.origin`
* `ctx.href`
* `ctx.path`
* `ctx.path=`
* `ctx.query`
* `ctx.query=`
* `ctx.querystring`
* `ctx.querystring=`
* `ctx.host`
* `ctx.hostname`
* `ctx.fresh`
* `ctx.stale`
* `ctx.socket`
* `ctx.protocol`
* `ctx.secure`
* `ctx.ip`
* `ctx.ips`
* `ctx.subdomains`
* `ctx.is()`
* `ctx.accepts()`
* `ctx.acceptsEncodings()`
* `ctx.acceptsCharsets()`
* `ctx.acceptsLanguages()`
* `ctx.get()`
Response aliases
----------------
The following accessors and alias [Response](response.md) equivalents:
* `ctx.body`
* `ctx.body=`
* `ctx.status`
* `ctx.status=`
* `ctx.message`
* `ctx.message=`
* `ctx.length=`
* `ctx.length`
* `ctx.type=`
* `ctx.type`
* `ctx.headerSent`
* `ctx.redirect()`
* `ctx.attachment()`
* `ctx.set()`
* `ctx.append()`
* `ctx.remove()`
* `ctx.lastModified=`
* `ctx.etag=`
| programming_docs |
koa Request Request
=======
A Koa `Request` object is an abstraction on top of node's vanilla request object, providing additional functionality that is useful for every day HTTP server development.
API
---
### request.header
Request header object. This is the same as the [`headers`](https://nodejs.org/api/http.html#http_message_headers) field on node's [`http.IncomingMessage`](https://nodejs.org/api/http.html#http_class_http_incomingmessage).
### request.header=
Set request header object.
### request.headers
Request header object. Alias as `request.header`.
### request.headers=
Set request header object. Alias as `request.header=`.
### request.method
Request method.
### request.method=
Set request method, useful for implementing middleware such as `methodOverride()`.
### request.length
Return request Content-Length as a number when present, or `undefined`.
### request.url
Get request URL.
### request.url=
Set request URL, useful for url rewrites.
### request.originalUrl
Get request original URL.
### request.origin
Get origin of URL, include `protocol` and `host`.
```
ctx.request.origin
// => http://example.com
```
### request.href
Get full request URL, include `protocol`, `host` and `url`.
```
ctx.request.href;
// => http://example.com/foo/bar?q=1
```
### request.path
Get request pathname.
### request.path=
Set request pathname and retain query-string when present.
### request.querystring
Get raw query string void of `?`.
### request.querystring=
Set raw query string.
### request.search
Get raw query string with the `?`.
### request.search=
Set raw query string.
### request.host
Get host (hostname:port) when present. Supports `X-Forwarded-Host` when `app.proxy` is **true**, otherwise `Host` is used.
### request.hostname
Get hostname when present. Supports `X-Forwarded-Host` when `app.proxy` is **true**, otherwise `Host` is used.
If host is IPv6, Koa delegates parsing to [WHATWG URL API](https://nodejs.org/dist/latest-v8.x/docs/api/url.html#url_the_whatwg_url_api), *Note* This may impact performance.
### request.URL
Get WHATWG parsed URL object.
### request.type
Get request `Content-Type` void of parameters such as "charset".
```
const ct = ctx.request.type;
// => "image/png"
```
### request.charset
Get request charset when present, or `undefined`:
```
ctx.request.charset;
// => "utf-8"
```
### request.query
Get parsed query-string, returning an empty object when no query-string is present. Note that this getter does *not* support nested parsing.
For example "color=blue&size=small":
```
{
color: 'blue',
size: 'small'
}
```
### request.query=
Set query-string to the given object. Note that this setter does *not* support nested objects.
```
ctx.query = { next: '/login' };
```
### request.fresh
Check if a request cache is "fresh", aka the contents have not changed. This method is for cache negotiation between `If-None-Match` / `ETag`, and `If-Modified-Since` and `Last-Modified`. It should be referenced after setting one or more of these response headers.
```
// freshness check requires status 20x or 304
ctx.status = 200;
ctx.set('ETag', '123');
// cache is ok
if (ctx.fresh) {
ctx.status = 304;
return;
}
// cache is stale
// fetch new data
ctx.body = await db.find('something');
```
### request.stale
Inverse of `request.fresh`.
### request.protocol
Return request protocol, "https" or "http". Supports `X-Forwarded-Proto` when `app.proxy` is **true**.
### request.secure
Shorthand for `ctx.protocol == "https"` to check if a request was issued via TLS.
### request.ip
Request remote address. Supports `X-Forwarded-For` when `app.proxy` is **true**.
### request.ips
When `X-Forwarded-For` is present and `app.proxy` is enabled an array of these ips is returned, ordered from upstream -> downstream. When disabled an empty array is returned.
For example if the value were "client, proxy1, proxy2", you would receive the array `["client", "proxy1", "proxy2"]`.
Most of the reverse proxy(nginx) set x-forwarded-for via `proxy_add_x_forwarded_for`, which poses a certain security risk. A malicious attacker can forge a client's ip address by forging a `X-Forwarded-For`request header. The request sent by the client has an `X-Forwarded-For` request header for 'forged'. After being forwarded by the reverse proxy, `request.ips` will be ['forged', 'client', 'proxy1', 'proxy2'].
Koa offers two options to avoid being bypassed.
If you can control the reverse proxy, you can avoid bypassing by adjusting the configuration, or use the `app.proxyIpHeader` provided by koa to avoid reading `x-forwarded-for` to get ips.
```
const app = new Koa({
proxy: true,
proxyIpHeader: 'X-Real-IP',
});
```
If you know exactly how many reverse proxies are in front of the server, you can avoid reading the user's forged request header by configuring `app.maxIpsCount`:
```
const app = new Koa({
proxy: true,
maxIpsCount: 1, // only one proxy in front of the server
});
// request.header['X-Forwarded-For'] === [ '127.0.0.1', '127.0.0.2' ];
// ctx.ips === [ '127.0.0.2' ];
```
### request.subdomains
Return subdomains as an array.
Subdomains are the dot-separated parts of the host before the main domain of the app. By default, the domain of the app is assumed to be the last two parts of the host. This can be changed by setting `app.subdomainOffset`.
For example, if the domain is "tobi.ferrets.example.com": If `app.subdomainOffset` is not set, `ctx.subdomains` is `["ferrets", "tobi"]`. If `app.subdomainOffset` is 3, `ctx.subdomains` is `["tobi"]`.
### request.is(types...)
Check if the incoming request contains the "Content-Type" header field, and it contains any of the give mime `type`s. If there is no request body, `null` is returned. If there is no content type, or the match fails `false` is returned. Otherwise, it returns the matching content-type.
```
// With Content-Type: text/html; charset=utf-8
ctx.is('html'); // => 'html'
ctx.is('text/html'); // => 'text/html'
ctx.is('text/*', 'text/html'); // => 'text/html'
// When Content-Type is application/json
ctx.is('json', 'urlencoded'); // => 'json'
ctx.is('application/json'); // => 'application/json'
ctx.is('html', 'application/*'); // => 'application/json'
ctx.is('html'); // => false
```
For example if you want to ensure that only images are sent to a given route:
```
if (ctx.is('image/*')) {
// process
} else {
ctx.throw(415, 'images only!');
}
```
### Content Negotiation
Koa's `request` object includes helpful content negotiation utilities powered by [accepts](http://github.com/expressjs/accepts) and [negotiator](https://github.com/federomero/negotiator). These utilities are:
* `request.accepts(types)`
* `request.acceptsEncodings(types)`
* `request.acceptsCharsets(charsets)`
* `request.acceptsLanguages(langs)`
If no types are supplied, **all** acceptable types are returned.
If multiple types are supplied, the best match will be returned. If no matches are found, a `false` is returned, and you should send a `406 "Not Acceptable"` response to the client.
In the case of missing accept headers where any type is acceptable, the first type will be returned. Thus, the order of types you supply is important.
### request.accepts(types)
Check if the given `type(s)` is acceptable, returning the best match when true, otherwise `false`. The `type` value may be one or more mime type string such as "application/json", the extension name such as "json", or an array `["json", "html", "text/plain"]`.
```
// Accept: text/html
ctx.accepts('html');
// => "html"
// Accept: text/*, application/json
ctx.accepts('html');
// => "html"
ctx.accepts('text/html');
// => "text/html"
ctx.accepts('json', 'text');
// => "json"
ctx.accepts('application/json');
// => "application/json"
// Accept: text/*, application/json
ctx.accepts('image/png');
ctx.accepts('png');
// => false
// Accept: text/*;q=.5, application/json
ctx.accepts(['html', 'json']);
ctx.accepts('html', 'json');
// => "json"
// No Accept header
ctx.accepts('html', 'json');
// => "html"
ctx.accepts('json', 'html');
// => "json"
```
You may call `ctx.accepts()` as many times as you like, or use a switch:
```
switch (ctx.accepts('json', 'html', 'text')) {
case 'json': break;
case 'html': break;
case 'text': break;
default: ctx.throw(406, 'json, html, or text only');
}
```
### request.acceptsEncodings(encodings)
Check if `encodings` are acceptable, returning the best match when true, otherwise `false`. Note that you should include `identity` as one of the encodings!
```
// Accept-Encoding: gzip
ctx.acceptsEncodings('gzip', 'deflate', 'identity');
// => "gzip"
ctx.acceptsEncodings(['gzip', 'deflate', 'identity']);
// => "gzip"
```
When no arguments are given all accepted encodings are returned as an array:
```
// Accept-Encoding: gzip, deflate
ctx.acceptsEncodings();
// => ["gzip", "deflate", "identity"]
```
Note that the `identity` encoding (which means no encoding) could be unacceptable if the client explicitly sends `identity;q=0`. Although this is an edge case, you should still handle the case where this method returns `false`.
### request.acceptsCharsets(charsets)
Check if `charsets` are acceptable, returning the best match when true, otherwise `false`.
```
// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
ctx.acceptsCharsets('utf-8', 'utf-7');
// => "utf-8"
ctx.acceptsCharsets(['utf-7', 'utf-8']);
// => "utf-8"
```
When no arguments are given all accepted charsets are returned as an array:
```
// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
ctx.acceptsCharsets();
// => ["utf-8", "utf-7", "iso-8859-1"]
```
### request.acceptsLanguages(langs)
Check if `langs` are acceptable, returning the best match when true, otherwise `false`.
```
// Accept-Language: en;q=0.8, es, pt
ctx.acceptsLanguages('es', 'en');
// => "es"
ctx.acceptsLanguages(['en', 'es']);
// => "es"
```
When no arguments are given all accepted languages are returned as an array:
```
// Accept-Language: en;q=0.8, es, pt
ctx.acceptsLanguages();
// => ["es", "pt", "en"]
```
### request.idempotent
Check if the request is idempotent.
### request.socket
Return the request socket.
### request.get(field)
Return request header with case-insensitive `field`.
koa Response Response
========
A Koa `Response` object is an abstraction on top of node's vanilla response object, providing additional functionality that is useful for every day HTTP server development.
API
---
### response.header
Response header object.
### response.headers
Response header object. Alias as `response.header`.
### response.socket
Response socket. Points to net.Socket instance as `request.socket`.
### response.status
Get response status. By default, `response.status` is set to `404` unlike node's `res.statusCode` which defaults to `200`.
### response.status=
Set response status via numeric code:
* 100 "continue"
* 101 "switching protocols"
* 102 "processing"
* 200 "ok"
* 201 "created"
* 202 "accepted"
* 203 "non-authoritative information"
* 204 "no content"
* 205 "reset content"
* 206 "partial content"
* 207 "multi-status"
* 208 "already reported"
* 226 "im used"
* 300 "multiple choices"
* 301 "moved permanently"
* 302 "found"
* 303 "see other"
* 304 "not modified"
* 305 "use proxy"
* 307 "temporary redirect"
* 308 "permanent redirect"
* 400 "bad request"
* 401 "unauthorized"
* 402 "payment required"
* 403 "forbidden"
* 404 "not found"
* 405 "method not allowed"
* 406 "not acceptable"
* 407 "proxy authentication required"
* 408 "request timeout"
* 409 "conflict"
* 410 "gone"
* 411 "length required"
* 412 "precondition failed"
* 413 "payload too large"
* 414 "uri too long"
* 415 "unsupported media type"
* 416 "range not satisfiable"
* 417 "expectation failed"
* 418 "I'm a teapot"
* 422 "unprocessable entity"
* 423 "locked"
* 424 "failed dependency"
* 426 "upgrade required"
* 428 "precondition required"
* 429 "too many requests"
* 431 "request header fields too large"
* 500 "internal server error"
* 501 "not implemented"
* 502 "bad gateway"
* 503 "service unavailable"
* 504 "gateway timeout"
* 505 "http version not supported"
* 506 "variant also negotiates"
* 507 "insufficient storage"
* 508 "loop detected"
* 510 "not extended"
* 511 "network authentication required"
**NOTE**: don't worry too much about memorizing these strings, if you have a typo an error will be thrown, displaying this list so you can make a correction.
Since `response.status` default is set to `404`, to send a response without a body and with a different status is to be done like this:
```
ctx.response.status = 200;
// Or whatever other status
ctx.response.status = 204;
```
### response.message
Get response status message. By default, `response.message` is associated with `response.status`.
### response.message=
Set response status message to the given value.
### response.length=
Set response Content-Length to the given value.
### response.length
Return response Content-Length as a number when present, or deduce from `ctx.body` when possible, or `undefined`.
### response.body
Get response body.
### response.body=
Set response body to one of the following:
* `string` written
* `Buffer` written
* `Stream` piped
* `Object` || `Array` json-stringified
* `null` || `undefined` no content response
If `response.status` has not been set, Koa will automatically set the status to `200` or `204` depending on `response.body`. Specifically, if `response.body` has not been set or has been set as `null` or `undefined`, Koa will automatically set `response.status` to `204`. If you really want to send no content response with other status, you should override the `204` status as the following way:
```
// This must be always set first before status, since null | undefined
// body automatically sets the status to 204
ctx.body = null;
// Now we override the 204 status with the desired one
ctx.status = 200;
```
Koa doesn't guard against everything that could be put as a response body -- a function doesn't serialise meaningfully, returning a boolean may make sense based on your application, and while an error works, it may not work as intended as some properties of an error are not enumerable. We recommend adding middleware in your app that asserts body types per app. A sample middleware might be:
```
app.use(async (ctx, next) => {
await next()
ctx.assert.equal('object', typeof ctx.body, 500, 'some dev did something wrong')
})
```
#### String
The Content-Type is defaulted to text/html or text/plain, both with a default charset of utf-8. The Content-Length field is also set.
#### Buffer
The Content-Type is defaulted to application/octet-stream, and Content-Length is also set.
#### Stream
The Content-Type is defaulted to application/octet-stream.
Whenever a stream is set as the response body, `.onerror` is automatically added as a listener to the `error` event to catch any errors. In addition, whenever the request is closed (even prematurely), the stream is destroyed. If you do not want these two features, do not set the stream as the body directly. For example, you may not want this when setting the body as an HTTP stream in a proxy as it would destroy the underlying connection.
See: <https://github.com/koajs/koa/pull/612> for more information.
Here's an example of stream error handling without automatically destroying the stream:
```
const PassThrough = require('stream').PassThrough;
app.use(async ctx => {
ctx.body = someHTTPStream.on('error', (err) => ctx.onerror(err)).pipe(PassThrough());
});
```
#### Object
The Content-Type is defaulted to application/json. This includes plain objects `{ foo: 'bar' }` and arrays `['foo', 'bar']`.
### response.get(field)
Get a response header field value with case-insensitive `field`.
```
const etag = ctx.response.get('ETag');
```
### response.has(field)
Returns `true` if the header identified by name is currently set in the outgoing headers. The header name matching is case-insensitive.
```
const rateLimited = ctx.response.has('X-RateLimit-Limit');
```
### response.set(field, value)
Set response header `field` to `value`:
```
ctx.set('Cache-Control', 'no-cache');
```
### response.append(field, value)
Append additional header `field` with value `val`.
```
ctx.append('Link', '<http://127.0.0.1/>');
```
### response.set(fields)
Set several response header `fields` with an object:
```
ctx.set({
'Etag': '1234',
'Last-Modified': date
});
```
This delegates to [setHeader](https://nodejs.org/dist/latest/docs/api/http.html#http_request_setheader_name_value) which sets or updates headers by specified keys and doesn't reset the entire header.
### response.remove(field)
Remove header `field`.
### response.type
Get response `Content-Type` void of parameters such as "charset".
```
const ct = ctx.type;
// => "image/png"
```
### response.type=
Set response `Content-Type` via mime string or file extension.
```
ctx.type = 'text/plain; charset=utf-8';
ctx.type = 'image/png';
ctx.type = '.png';
ctx.type = 'png';
```
Note: when appropriate a `charset` is selected for you, for example `response.type = 'html'` will default to "utf-8". If you need to overwrite `charset`, use `ctx.set('Content-Type', 'text/html')` to set response header field to value directly.
### response.is(types...)
Very similar to `ctx.request.is()`. Check whether the response type is one of the supplied types. This is particularly useful for creating middleware that manipulate responses.
For example, this is a middleware that minifies all HTML responses except for streams.
```
const minify = require('html-minifier');
app.use(async (ctx, next) => {
await next();
if (!ctx.response.is('html')) return;
let body = ctx.body;
if (!body || body.pipe) return;
if (Buffer.isBuffer(body)) body = body.toString();
ctx.body = minify(body);
});
```
### response.redirect(url, [alt])
Perform a [302] redirect to `url`.
The string "back" is special-cased to provide Referrer support, when Referrer is not present `alt` or "/" is used.
```
ctx.redirect('back');
ctx.redirect('back', '/index.html');
ctx.redirect('/login');
ctx.redirect('http://google.com');
```
To alter the default status of `302`, simply assign the status before or after this call. To alter the body, assign it after this call:
```
ctx.status = 301;
ctx.redirect('/cart');
ctx.body = 'Redirecting to shopping cart';
```
### response.attachment([filename], [options])
Set `Content-Disposition` to "attachment" to signal the client to prompt for download. Optionally specify the `filename` of the download and some [options](https://github.com/jshttp/content-disposition#options).
### response.headerSent
Check if a response header has already been sent. Useful for seeing if the client may be notified on error.
### response.lastModified
Return the `Last-Modified` header as a `Date`, if it exists.
### response.lastModified=
Set the `Last-Modified` header as an appropriate UTC string. You can either set it as a `Date` or date string.
```
ctx.response.lastModified = new Date();
```
### response.etag=
Set the ETag of a response including the wrapped `"`s. Note that there is no corresponding `response.etag` getter.
```
ctx.response.etag = crypto.createHash('md5').update(ctx.body).digest('hex');
```
### response.vary(field)
Vary on `field`.
### response.flushHeaders()
Flush any set headers, and begin the body.
sass Syntax Syntax
=======
Sass supports two different syntaxes. Each one can load the other, so it's up to you and your team which one to choose.
SCSS
-----
The SCSS syntax uses the file extension `.scss`. With a few small exceptions, it’s a superset of CSS, which means essentially **all valid CSS is valid SCSS as well**. Because of its similarity to CSS, it’s the easiest syntax to get used to and the most popular.
SCSS looks like this:
```
@mixin button-base() {
@include typography(button);
@include ripple-surface;
@include ripple-radius-bounded;
display: inline-flex;
position: relative;
height: $button-height;
border: none;
vertical-align: middle;
&:hover { cursor: pointer; }
&:disabled {
color: $mdc-button-disabled-ink-color;
cursor: default;
pointer-events: none;
}
}
```
The Indented Syntax
--------------------
The indented syntax was Sass’s original syntax, and so it uses the file extension `.sass`. Because of this extension, it’s sometimes just called “Sass”. The indented syntax supports all the same features as SCSS, but it uses indentation instead of curly braces and semicolons to describe the format of the document.
In general, any time you’d write curly braces in CSS or SCSS, you can just indent one level deeper in the indented syntax. And any time a line ends, that counts as a semicolon. There are also a few additional differences in the indented syntax that are noted throughout the reference.
### ⚠️ Heads up!
The indented syntax currently doesn’t support expressions that wrap across multiple lines. See [issue #216](https://github.com/sass/sass/issues/216).
The indented syntax looks like this:
```
@mixin button-base()
@include typography(button)
@include ripple-surface
@include ripple-radius-bounded
display: inline-flex
position: relative
height: $button-height
border: none
vertical-align: middle
&:hover
cursor: pointer
&:disabled
color: $mdc-button-disabled-ink-color
cursor: default
pointer-events: none
```
| programming_docs |
sass Values Values
=======
Sass supports a number of value types, most of which come straight from CSS. Every [expression](syntax/structure#expressions) produces a value, <variables> hold values. Most value types come straight from CSS:
* [Numbers](values/numbers), which may or may not have units, like `12` or `100px`.
* [Strings](values/strings), which may or may not have quotes, like `"Helvetica Neue"` or `bold`.
* [Colors](values/colors), which can be referred to by their hex representation or by name, like `#c6538c` or `blue`, or returned from functions, like `rgb(107, 113, 127)` or `hsl(210, 100%, 20%)`.
* [Lists of values](values/lists), which may be separated by spaces or commas and which may be enclosed in square brackets or no brackets at all, like `1.5em 1em 0 2em`, `Helvetica, Arial, sans-serif`, or `[col1-start]`.
A few more are specific to Sass:
* The [boolean](values/booleans) values `true` and `false`.
* The singleton [`null`](values/null) value.
* [Maps](values/maps) that associate values with keys, like `("background": red, "foreground": pink)`.
* [Function references](values/functions) returned by [`get-function()`](modules/meta#get-function) and called with [`call()`](modules/meta#call).
sass Documentation Documentation
==============
Sass is a stylesheet language that’s compiled to CSS. It allows you to use <variables>, [nested rules](style-rules#nesting), [mixins](at-rules/mixin), [functions](modules), and more, all with a fully CSS-compatible syntax. Sass helps keep large stylesheets well-organized and makes it easy to share design within and across projects.
* If you’re looking for an introduction to Sass, check out [the tutorial](https://sass-lang.com/guide).
* If you want to look up a built-in Sass function, look no further than [the built-in module reference](modules).
* If you’re calling Sass from JavaScript, you may want the [JS API documentation](https://github.com/sass/node-sass#usage).
* Or the [Dart API documentation](https://pub.dartlang.org/documentation/sass/latest/sass/sass-library.html) if you’re calling it from Dart.
* Otherwise, use the table of contents for the language reference!
Older Versions
---------------
This documentation is written for the most recent version of the Sass language. If you’re using [Dart Sass](https://sass-lang.com/dart-sass) 1.56.1, you’ll have access to all the features described here. But if you’re using an older version of Dart Sass or a deprecated Sass implementation like [LibSass](https://sass-lang.com/libsass) or [Ruby Sass](https://sass-lang.com/ruby-sass), there may be some behavioral differences.
Anywhere behavior differs between versions or implementations, the documentation includes a compatibility indicator like this:
Compatibility (Feature Name):
Dart Sass ✓
LibSass since 3.6.0
Ruby Sass ✗ Implementations with a “✓” fully support the feature in question, and implementations with a “✗” don’t support it all. Implementations with a version number started supporting the feature in question at that version. Implementations can also be marked as “partial”:
Compatibility:
Dart Sass ✓
LibSass partial
Ruby Sass ✗ [▶](javascript:;) Additional details go here.
This indicates that the implementation only supports some aspects of the feature. These compatibility indicators (and many others) have a “▶” button, which can be clicked to show more details about exactly how the implementations differ and which versions support which aspects of the feature in question.
sass sass
The [`sass` package](https://www.npmjs.com/package/sass) on npm is a pure-JavaScript package built from the [Dart Sass](https://sass-lang.com/dart-sass) implementation. In addition to Dart Sass's [command-line interface](cli/dart-sass), it provides a JavaScript API that can be used to drive Sass compilations from JavaScript. It even allows an application to control [how stylesheets are loaded](js-api/interfaces/options#importers) and [define custom functions](js-api/interfaces/options#functions).
[Usage
-----](#usage) The JavaScript API provides two entrypoints for compiling Sass to CSS, each of which has a synchronous variant that returns a plain [CompileResult](js-api/interfaces/compileresult) and an asynchronous variant that returns a `Promise`. **The asynchronous variants are much slower,** but they allow custom importers and functions to run asynchronously.
* [compile](js-api/modules#compile) and [compileAsync](js-api/modules#compileAsync) take a path to a Sass file and return the result of compiling that file to CSS. These functions accept an additional [Options](js-api/interfaces/options) argument.
```
constsass = require('sass');
constresult = sass.compile("style.scss");
console.log(result.css);
constcompressed = sass.compile("style.scss", {style:"compressed"});
console.log(compressed.css);
```
* [compileString](js-api/modules#compileString) and [compileStringAsync](js-api/modules#compileStringAsync) take a string that represents the contents of a Sass file and return the result of compiling that file to CSS. These functions accept an additional [StringOptions](js-api/modules#StringOptions) argument.
```
constsass = require('sass');
constinput = `
h1 {
font-size: 40px;
code {
font-face: Roboto Mono;
}
}`;
constresult = sass.compileString(input);
console.log(result.css);
constcompressed = sass.compileString(input, {style:"compressed"});
console.log(compressed.css);
```
[Integrations
------------](#integrations) Most popular Node.js build systems have integrations available for the JS API:
* Webpack uses the [`sass-loader` package](https://www.npmjs.com/package/sass-loader).
* Gulp uses the [`gulp-sass` package](https://www.npmjs.com/package/gulp-sass).
* Broccoli uses the [`broccoli-sass-source-maps` package](https://www.npmjs.com/package/broccoli-sass-source-maps).
* Ember uses the [`ember-cli-sass` package](https://www.npmjs.com/package/ember-cli-sass).
* Grunt uses the [`grunt-sass` package](https://www.npmjs.com/package/grunt-sass).
[Legacy API
----------](#legacy-api) The `sass` package also supports an older API. Although this API is deprecated, it will continue to be supported until the release of version 2.0.0 of the `sass` package. The legacy API is also supported by the [`node-sass` package](https://www.npmjs.com/package/node-sass), which is a native extension wrapper for the deprecated [LibSass](https://sass-lang.com/libsass) implementation.
The legacy API has two entrypoints for compiling Sass to CSS. Each one can compile either a Sass file by passing in [LegacyFileOptions](js-api/interfaces/legacyfileoptions) or a string of Sass code by passing in a [LegacyStringOptions](js-api/interfaces/legacystringoptions).
* [renderSync](js-api/modules#renderSync) runs synchronously. It's **by far the fastest option** when using Dart Sass, but at the cost of only supporting synchronous [importer](js-api/modules#LegacyImporter) and [function](js-api/modules#LegacyFunction) plugins.
```
constsass = require('sass'); // or require('node-sass');
constresult = sass.renderSync({file:"style.scss"});
console.log(result.css.toString());
```
* [render](js-api/modules#render) runs asynchronously and calls a callback when it finishes. It's much slower when using Dart Sass, but it supports asynchronous [importer](js-api/modules#LegacyImporter) and [function](js-api/modules#LegacyFunction) plugins.
```
constsass = require('sass'); // or require('node-sass');
sass.render({
file:"style.scss"
}, function(err, result) {
if (err) {
// ...
} else {
console.log(result.css.toString());
}
});
```
sass Built-In Modules Built-In Modules
=================
Compatibility:
Dart Sass since 1.23.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass currently supports loading built-in modules with `@use`. Users of other implementations must call functions using their global names instead.
Sass provides many built-in modules which contain useful functions (and the occasional mixin). These modules can be loaded with the [`@use` rule](at-rules/use) like any user-defined stylesheet, and their functions can be called [like any other module member](at-rules/use#loading-members). All built-in module URLs begin with `sass:` to indicate that they're part of Sass itself.
### ⚠️ Heads up!
Before the Sass module system was introduced, all Sass functions were globally available at all times. Many functions still have global aliases (these are listed in their documentation). The Sass team discourages their use and will eventually deprecate them, but for now they remain available for compatibility with older Sass versions and with LibSass (which doesn’t support the module system yet).
[A few functions](#global-functions) are *only* available globally even in the new module system, either because they have special evaluation behavior ([`if()`](#if)) or because they add extra behavior on top of built-in CSS functions ([`rgb()`](#rgb) and [`hsl()`](#hsl)). These will not be deprecated and can be used freely.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
@use "sass:color";
.button {
$primary-color: #6b717f;
color: $primary-color;
border: 1px solid color.scale($primary-color, $lightness: 20%);
}
```
```
@use "sass:color"
.button
$primary-color: #6b717f
color: $primary-color
border: 1px solid color.scale($primary-color, $lightness: 20%)
```
```
.button {
color: #6b717f;
border: 1px solid #878d9a;
}
```
Sass provides the following built-in modules:
* The [`sass:math` module](modules/math) provides functions that operate on [numbers](values/numbers).
* The [`sass:string` module](modules/string) makes it easy to combine, search, or split apart [strings](values/strings).
* The [`sass:color` module](modules/color) generates new [colors](values/colors) based on existing ones, making it easy to build color themes.
* The [`sass:list` module](modules/list) lets you access and modify values in [lists](values/lists).
* The [`sass:map` module](modules/map) makes it possible to look up the value associated with a key in a [map](values/maps), and much more.
* The [`sass:selector` module](modules/selector) provides access to Sass’s powerful selector engine.
* The [`sass:meta` module](modules/meta) exposes the details of Sass’s inner workings.
Global Functions
-----------------
```
hsl($hue $saturation $lightness)
hsl($hue $saturation $lightness / $alpha)
hsl($hue, $saturation, $lightness, $alpha: 1)
hsla($hue $saturation $lightness)
hsla($hue $saturation $lightness / $alpha)
hsla($hue, $saturation, $lightness, $alpha: 1) //=> color
```
Compatibility (Level 4 Syntax):
Dart Sass since 1.15.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;)
LibSass and Ruby Sass only support the following signatures:
* `hsl($hue, $saturation, $lightness)`
* `hsla($hue, $saturation, $lightness, $alpha)`
Note that for these implementations, the `$alpha` argument is *required* if the function name `hsla()` is used, and *forbidden* if the function name `hsl()` is used.
Compatibility (Percent Alpha):
Dart Sass ✓
LibSass ✗
Ruby Sass since 3.7.0
[▶](javascript:;) LibSass and older versions of Ruby Sass don’t support alpha values specified as percentages.
Returns a color with the given [hue, saturation, and lightness](https://en.wikipedia.org/wiki/HSL_and_HSV) and the given alpha channel.
The hue is a number between `0deg` and `360deg` (inclusive) and may be unitless. The saturation and lightness are numbers between `0%` and `100%` (inclusive) and may *not* be unitless. The alpha channel can be specified as either a unitless number between 0 and 1 (inclusive), or a percentage between `0%` and `100%` (inclusive).
### 💡 Fun fact:
You can pass [special functions](syntax/special-functions) like `calc()` or `var()` in place of any argument to `hsl()`. You can even use `var()` in place of multiple arguments, since it might be replaced by multiple values! When a color function is called this way, it returns an unquoted string using the same signature it was called with.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
```
@debug hsl(210deg 100% 20% / var(--opacity)); // hsl(210deg 100% 20% / var(--opacity))
@debug hsla(var(--peach), 20%); // hsla(var(--peach), 20%)
```
```
@debug hsl(210deg 100% 20% / var(--opacity)) // hsl(210deg 100% 20% / var(--opacity))
@debug hsla(var(--peach), 20%) // hsla(var(--peach), 20%)
```
### ⚠️ Heads up!
Sass’s [special parsing rules](operators/numeric#slash-separated-values) for slash-separated values make it difficult to pass variables for `$lightness` or `$alpha` when using the `hsl($hue $saturation $lightness / $alpha)` signature. Consider using `hsl($hue, $saturation, $lightness, $alpha)` instead.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
@debug hsl(210deg 100% 20%); // #036
@debug hsl(34, 35%, 92%); // #f2ece4
@debug hsl(210deg 100% 20% / 50%); // rgba(0, 51, 102, 0.5)
@debug hsla(34, 35%, 92%, 0.2); // rgba(242, 236, 228, 0.2)
```
```
@debug hsl(210deg 100% 20%) // #036
@debug hsl(34, 35%, 92%) // #f2ece4
@debug hsl(210deg 100% 20% / 50%) // rgba(0, 51, 102, 0.5)
@debug hsla(34, 35%, 92%, 0.2) // rgba(242, 236, 228, 0.2)
```
```
if($condition, $if-true, $if-false)
```
Returns `$if-true` if `$condition` is [truthy](at-rules/control/if#truthiness-and-falsiness), and `$if-false` otherwise.
This function is special in that it doesn’t even evaluate the argument that isn’t returned, so it’s safe to call even if the unused argument would throw an error.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
```
@debug if(true, 10px, 15px); // 10px
@debug if(false, 10px, 15px); // 15px
@debug if(variable-defined($var), $var, null); // null
```
```
@debug if(true, 10px, 15px) // 10px
@debug if(false, 10px, 15px) // 15px
@debug if(variable-defined($var), $var, null) // null
```
```
rgb($red $green $blue)
rgb($red $green $blue / $alpha)
rgb($red, $green, $blue, $alpha: 1)
rgb($color, $alpha)
rgba($red $green $blue)
rgba($red $green $blue / $alpha)
rgba($red, $green, $blue, $alpha: 1)
rgba($color, $alpha) //=> color
```
Compatibility (Level 4 Syntax):
Dart Sass since 1.15.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;)
LibSass and Ruby Sass only support the following signatures:
* `rgb($red, $green, $blue)`
* `rgba($red, $green, $blue, $alpha)`
* `rgba($color, $alpha)`
Note that for these implementations, the `$alpha` argument is *required* if the function name `rgba()` is used, and *forbidden* if the function name `rgb()` is used.
Compatibility (Percent Alpha):
Dart Sass ✓
LibSass ✗
Ruby Sass since 3.7.0
[▶](javascript:;) LibSass and older versions of Ruby Sass don’t support alpha values specified as percentages.
If `$red`, `$green`, `$blue`, and optionally `$alpha` are passed, returns a color with the given red, green, blue, and alpha channels.
Each channel can be specified as either a [unitless](values/numbers#units) number between 0 and 255 (inclusive), or a percentage between `0%` and `100%` (inclusive). The alpha channel can be specified as either a unitless number between 0 and 1 (inclusive), or a percentage between `0%` and `100%` (inclusive).
### 💡 Fun fact:
You can pass [special functions](syntax/special-functions) like `calc()` or `var()` in place of any argument to `rgb()`. You can even use `var()` in place of multiple arguments, since it might be replaced by multiple values! When a color function is called this way, it returns an unquoted string using the same signature it was called with.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
```
@debug rgb(0 51 102 / var(--opacity)); // rgb(0 51 102 / var(--opacity))
@debug rgba(var(--peach), 0.2); // rgba(var(--peach), 0.2)
```
```
@debug rgb(0 51 102 / var(--opacity)) // rgb(0 51 102 / var(--opacity))
@debug rgba(var(--peach), 0.2) // rgba(var(--peach), 0.2)
```
### ⚠️ Heads up!
Sass’s [special parsing rules](operators/numeric#slash-separated-values) for slash-separated values make it difficult to pass variables for `$blue` or `$alpha` when using the `rgb($red $green $blue / $alpha)` signature. Consider using `rgb($red, $green, $blue, $alpha)` instead.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
```
@debug rgb(0 51 102); // #036
@debug rgb(95%, 92.5%, 89.5%); // #f2ece4
@debug rgb(0 51 102 / 50%); // rgba(0, 51, 102, 0.5)
@debug rgba(95%, 92.5%, 89.5%, 0.2); // rgba(242, 236, 228, 0.2)
```
```
@debug rgb(0 51 102) // #036
@debug rgb(95%, 92.5%, 89.5%) // #f2ece4
@debug rgb(0 51 102 / 50%) // rgba(0, 51, 102, 0.5)
@debug rgba(95%, 92.5%, 89.5%, 0.2) // rgba(242, 236, 228, 0.2)
```
---
If `$color` and `$alpha` are passed, this returns `$color` with the given `$alpha` channel instead of its original alpha channel.
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
```
@debug rgb(#f2ece4, 50%); // rgba(242, 236, 228, 0.5);
@debug rgba(rgba(0, 51, 102, 0.5), 1); // #003366
```
```
@debug rgb(#f2ece4, 50%) // rgba(242, 236, 228, 0.5)
@debug rgba(rgba(0, 51, 102, 0.5), 1) // #003366
```
sass Variables Variables
==========
Sass variables are simple: you assign a value to a name that begins with `$`, and then you can refer to that name instead of the value itself. But despite their simplicity, they're one of the most useful tools Sass brings to the table. Variables make it possible to reduce repetition, do complex math, configure libraries, and much more.
A variable declaration looks a lot like a [property declaration](style-rules/declarations): it’s written `<variable>: <expression>`. Unlike a property, which can only be declared in a style rule or at-rule, variables can be declared anywhere you want. To use a variable, just include it in a value.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
$base-color: #c6538c;
$border-dark: rgba($base-color, 0.88);
.alert {
border: 1px solid $border-dark;
}
```
```
$base-color: #c6538c
$border-dark: rgba($base-color, 0.88)
.alert
border: 1px solid $border-dark
```
```
.alert {
border: 1px solid rgba(198, 83, 140, 0.88);
}
```
### ⚠️ Heads up!
CSS has [variables of its own](style-rules/declarations#custom-properties), which are totally different than Sass variables. Know the differences!
* Sass variables are all compiled away by Sass. CSS variables are included in the CSS output.
* CSS variables can have different values for different elements, but Sass variables only have one value at a time.
* Sass variables are *imperative*, which means if you use a variable and then change its value, the earlier use will stay the same. CSS variables are *declarative*, which means if you change the value, it’ll affect both earlier uses and later uses.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
$variable: value 1;
.rule-1 {
value: $variable;
}
$variable: value 2;
.rule-2 {
value: $variable;
}
```
```
$variable: value 1
.rule-1
value: $variable
$variable: value 2
.rule-2
value: $variable
```
```
.rule-1 {
value: value 1;
}
.rule-2 {
value: value 2;
}
```
### 💡 Fun fact:
Sass variables, like all Sass identifiers, treat hyphens and underscores as identical. This means that `$font-size` and `$font_size` both refer to the same variable. This is a historical holdover from the very early days of Sass, when it *only* allowed underscores in identifier names. Once Sass added support for hyphens to match CSS’s syntax, the two were made equivalent to make migration easier.
Default Values
---------------
Normally when you assign a value to a variable, if that variable already had a value, its old value is overwritten. But if you’re writing a Sass library, you might want to allow your users to configure your library’s variables before you use them to generate CSS.
To make this possible, Sass provides the `!default` flag. This assigns a value to a variable *only if* that variable isn’t defined or its value is [`null`](values/null). Otherwise, the existing value will be used.
### Configuring Modules
Compatibility:
Dart Sass since 1.23.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass currently supports `@use`. Users of other implementations must use the [`@import` rule](at-rules/import) instead.
Variables defined with `!default` can be configured when loading a module with the [`@use` rule](at-rules/use). Sass libraries often use `!default` variables to allow their users to configure the library’s CSS.
To load a module with configuration, write `@use <url> with (<variable>: <value>, <variable>: <value>)`. The configured values will override the variables’ default values. Only variables written at the top level of the stylesheet with a `!default` flag can be configured.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
* [CSS](#example-3-css)
```
// _library.scss
$black: #000 !default;
$border-radius: 0.25rem !default;
$box-shadow: 0 0.5rem 1rem rgba($black, 0.15) !default;
code {
border-radius: $border-radius;
box-shadow: $box-shadow;
}
```
```
// style.scss
@use 'library' with (
$black: #222,
$border-radius: 0.1rem
);
```
```
// _library.sass
$black: #000 !default
$border-radius: 0.25rem !default
$box-shadow: 0 0.5rem 1rem rgba($black, 0.15) !default
code
border-radius: $border-radius
box-shadow: $box-shadow
```
```
// style.sass
@use 'library' with ($black: #222, $border-radius: 0.1rem)
```
```
code {
border-radius: 0.1rem;
box-shadow: 0 0.5rem 1rem rgba(34, 34, 34, 0.15);
}
```
Built-in Variables
-------------------
Variables that are defined by a [built-in module](modules) cannot be modified.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
```
@use "sass:math" as math;
// This assignment will fail.
math.$pi: 0;
```
```
@use "sass:math" as math
// This assignment will fail.
math.$pi: 0
```
Scope
------
Variables declared at the top level of a stylesheet are *global*. This means that they can be accessed anywhere in their module after they’ve been declared. But that’s not true for all variables. Those declared in blocks (curly braces in SCSS or indented code in Sass) are usually *local*, and can only be accessed within the block they were declared.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
* [CSS](#example-5-css)
```
$global-variable: global value;
.content {
$local-variable: local value;
global: $global-variable;
local: $local-variable;
}
.sidebar {
global: $global-variable;
// This would fail, because $local-variable isn't in scope:
// local: $local-variable;
}
```
```
$global-variable: global value
.content
$local-variable: local value
global: $global-variable
local: $local-variable
.sidebar
global: $global-variable
// This would fail, because $local-variable isn't in scope:
// local: $local-variable
```
```
.content {
global: global value;
local: local value;
}
.sidebar {
global: global value;
}
```
### Shadowing
Local variables can even be declared with the same name as a global variable. If this happens, there are actually two different variables with the same name: one local and one global. This helps ensure that an author writing a local variable doesn’t accidentally change the value of a global variable they aren’t even aware of.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
* [CSS](#example-6-css)
```
$variable: global value;
.content {
$variable: local value;
value: $variable;
}
.sidebar {
value: $variable;
}
```
```
$variable: global value
.content
$variable: local value
value: $variable
.sidebar
value: $variable
```
```
.content {
value: local value;
}
.sidebar {
value: global value;
}
```
If you need to set a global variable’s value from within a local scope (such as in a mixin), you can use the `!global` flag. A variable declaration flagged as `!global` will *always* assign to the global scope.
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
* [CSS](#example-7-css)
```
$variable: first global value;
.content {
$variable: second global value !global;
value: $variable;
}
.sidebar {
value: $variable;
}
```
```
$variable: first global value
.content
$variable: second global value !global
value: $variable
.sidebar
value: $variable
```
```
.content {
value: second global value;
}
.sidebar {
value: second global value;
}
```
### ⚠️ Heads up!
Compatibility:
Dart Sass since 2.0.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Older Sass versions allowed `!global` to be used for a variable that doesn’t exist yet. This behavior was deprecated to make sure each stylesheet declares the same variables no matter how it’s executed.
The `!global` flag may only be used to set a variable that has already been declared at the top level of a file. It *may not* be used to declare a new variable.
### Flow Control Scope
Variables declared in [flow control rules](at-rules/control) have special scoping rules: they don’t shadow variables at the same level as the flow control rule. Instead, they just assign to those variables. This makes it much easier to conditionally assign a value to a variable, or build up a value as part of a loop.
* [SCSS](#example-8-scss)
* [Sass](#example-8-sass)
* [CSS](#example-8-css)
```
$dark-theme: true !default;
$primary-color: #f8bbd0 !default;
$accent-color: #6a1b9a !default;
@if $dark-theme {
$primary-color: darken($primary-color, 60%);
$accent-color: lighten($accent-color, 60%);
}
.button {
background-color: $primary-color;
border: 1px solid $accent-color;
border-radius: 3px;
}
```
```
$dark-theme: true !default
$primary-color: #f8bbd0 !default
$accent-color: #6a1b9a !default
@if $dark-theme
$primary-color: darken($primary-color, 60%)
$accent-color: lighten($accent-color, 60%)
.button
background-color: $primary-color
border: 1px solid $accent-color
border-radius: 3px
```
```
.button {
background-color: #750c30;
border: 1px solid #f5ebfc;
border-radius: 3px;
}
```
### ⚠️ Heads up!
Variables in flow control scope can assign to existing variables in the outer scope, but they can’t declare new variables there. Make sure the variable is already declared before you assign to it, even if you need to declare it as `null`.
Advanced Variable Functions
----------------------------
The Sass core library provides a couple advanced functions for working with variables. The [`meta.variable-exists()` function](modules/meta#variable-exists) returns whether a variable with the given name exists in the current scope, and the [`meta.global-variable-exists()` function](modules/meta#global-variable-exists) does the same but only for the global scope.
### ⚠️ Heads up!
Users occasionally want to use interpolation to define a variable name based on another variable. Sass doesn’t allow this, because it makes it much harder to tell at a glance which variables are defined where. What you *can* do, though, is define a [map](values/maps) from names to values that you can then access using variables.
* [SCSS](#example-9-scss)
* [Sass](#example-9-sass)
* [CSS](#example-9-css)
```
@use "sass:map";
$theme-colors: (
"success": #28a745,
"info": #17a2b8,
"warning": #ffc107,
);
.alert {
// Instead of $theme-color-#{warning}
background-color: map.get($theme-colors, "warning");
}
```
```
@use "sass:map"
$theme-colors: ("success": #28a745, "info": #17a2b8, "warning": #ffc107)
.alert
// Instead of $theme-color-#{warning}
background-color: map.get($theme-colors, "warning")
```
```
.alert {
background-color: #ffc107;
}
```
| programming_docs |
sass Style Rules Style Rules
============
Style rules are the foundation of Sass, just like they are for CSS. And they work the same way: you choose which elements to style with a selector, and [declare properties](style-rules/declarations) that affect how those elements look.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
.button {
padding: 3px 10px;
font-size: 12px;
border-radius: 3px;
border: 1px solid #e1e4e8;
}
```
```
.button
padding: 3px 10px
font-size: 12px
border-radius: 3px
border: 1px solid #e1e4e8
```
```
.button {
padding: 3px 10px;
font-size: 12px;
border-radius: 3px;
border: 1px solid #e1e4e8;
}
```
Nesting
--------
But Sass wants to make your life easier. Rather than repeating the same selectors over and over again, you can write one style rules inside another. Sass will automatically combine the outer rule’s selector with the inner rule’s.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
nav {
ul {
margin: 0;
padding: 0;
list-style: none;
}
li { display: inline-block; }
a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
}
```
```
nav
ul
margin: 0
padding: 0
list-style: none
li
display: inline-block
a
display: block
padding: 6px 12px
text-decoration: none
```
```
nav ul {
margin: 0;
padding: 0;
list-style: none;
}
nav li {
display: inline-block;
}
nav a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
```
### ⚠️ Heads up!
Nested rules are super helpful, but they can also make it hard to visualize how much CSS you’re actually generating. The deeper you nest, the more bandwidth it takes to serve your CSS and the more work it takes the browser to render it. Keep those selectors shallow!
### Selector Lists
Nested rules are clever about handling selector lists (that is, comma-separated selectors). Each complex selector (the ones between the commas) is nested separately, and then they’re combined back into a selector list.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
* [CSS](#example-3-css)
```
.alert, .warning {
ul, p {
margin-right: 0;
margin-left: 0;
padding-bottom: 0;
}
}
```
```
.alert, .warning
ul, p
margin-right: 0
margin-left: 0
padding-bottom: 0
```
```
.alert ul, .alert p, .warning ul, .warning p {
margin-right: 0;
margin-left: 0;
padding-bottom: 0;
}
```
### Selector Combinators
You can nest selectors that use [combinators](#) as well. You can put the combinator at the end of the outer selector, at the beginning of the inner selector, or even all on its own in between the two.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
* [CSS](#example-4-css)
```
ul > {
li {
list-style-type: none;
}
}
h2 {
+ p {
border-top: 1px solid gray;
}
}
p {
~ {
span {
opacity: 0.8;
}
}
}
```
```
ul >
li
list-style-type: none
h2
+ p
border-top: 1px solid gray
p
~
span
opacity: 0.8
```
```
ul > li {
list-style-type: none;
}
h2 + p {
border-top: 1px solid gray;
}
p ~ span {
opacity: 0.8;
}
```
### Advanced Nesting
If you want to do more with your nested style rules than just combine them in order with the descendant combinator (that is, a plain space) separating them, Sass has your back. See the [parent selector documentation](style-rules/parent-selector) for more details.
Interpolation
--------------
You can use <interpolation> to inject values from [expressions](syntax/structure#expressions) like variables and function calls into your selectors. This is particularly useful when you’re writing [mixins](at-rules/mixin), since it allows you to create selectors from parameters your users pass in.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
* [CSS](#example-5-css)
```
@mixin define-emoji($name, $glyph) {
span.emoji-#{$name} {
font-family: IconFont;
font-variant: normal;
font-weight: normal;
content: $glyph;
}
}
@include define-emoji("women-holding-hands", "👭");
```
```
@mixin define-emoji($name, $glyph)
span.emoji-#{$name}
font-family: IconFont
font-variant: normal
font-weight: normal
content: $glyph
@include define-emoji("women-holding-hands", "👭")
```
```
@charset "UTF-8";
span.emoji-women-holding-hands {
font-family: IconFont;
font-variant: normal;
font-weight: normal;
content: "👭";
}
```
### 💡 Fun fact:
Sass only parses selectors *after* interpolation is resolved. This means you can safely use interpolation to generate any part of the selector without worrying that it won’t parse.
You can combine interpolation with the parent selector `&`, the [`@at-root` rule](at-rules/at-root), and [selector functions](modules/selector) to wield some serious power when dynamically generating selectors. For more information, see the [parent selector documentation](style-rules/parent-selector).
sass Interpolation Interpolation
==============
Interpolation can be used almost anywhere in a Sass stylesheet to embed the result of a [SassScript expression](syntax/structure#expressions) into a chunk of CSS. Just wrap an expression in `#{}` in any of the following places:
* [Selectors in style rules](style-rules#interpolation)
* [Property names in declarations](style-rules/declarations#interpolation)
* [Custom property values](style-rules/declarations#custom-properties)
* [CSS at-rules](at-rules/css)
* [`@extend`s](at-rules/extend)
* [Plain CSS `@import`s](at-rules/import#plain-css-imports)
* [Quoted or unquoted strings](values/strings)
* [Special functions](syntax/special-functions)
* [Plain CSS function names](at-rules/function#plain-css-functions)
* [Loud comments](syntax/comments)
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
@mixin corner-icon($name, $top-or-bottom, $left-or-right) {
.icon-#{$name} {
background-image: url("/icons/#{$name}.svg");
position: absolute;
#{$top-or-bottom}: 0;
#{$left-or-right}: 0;
}
}
@include corner-icon("mail", top, left);
```
```
@mixin corner-icon($name, $top-or-bottom, $left-or-right)
.icon-#{$name}
background-image: url("/icons/#{$name}.svg")
position: absolute
#{$top-or-bottom}: 0
#{$left-or-right}: 0
@include corner-icon("mail", top, left)
```
```
.icon-mail {
background-image: url("/icons/mail.svg");
position: absolute;
top: 0;
left: 0;
}
```
In SassScript
--------------
Compatibility (Modern Syntax):
Dart Sass ✓
LibSass ✗
Ruby Sass since 4.0.0 (unreleased) [▶](javascript:;) LibSass and Ruby Sass currently use an older syntax for parsing interpolation in SassScript. For most practical purposes it works the same, but it can behave strangely around <operators>. See [this document](https://github.com/sass/language/blob/master/accepted/free-interpolation.md#old-interpolation-rules) for details.
Interpolation can be used in SassScript to inject SassScript into [unquoted strings](values/strings#unquoted). This is particularly useful when dynamically generating names (for example for animations), or when using [slash-separated values](operators/numeric#slash-separated-values). Note that interpolation in SassScript always returns an unquoted string.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
@mixin inline-animation($duration) {
$name: inline-#{unique-id()};
@keyframes #{$name} {
@content;
}
animation-name: $name;
animation-duration: $duration;
animation-iteration-count: infinite;
}
.pulse {
@include inline-animation(2s) {
from { background-color: yellow }
to { background-color: red }
}
}
```
```
@mixin inline-animation($duration)
$name: inline-#{unique-id()}
@keyframes #{$name}
@content
animation-name: $name
animation-duration: $duration
animation-iteration-count: infinite
.pulse
@include inline-animation(2s)
from
background-color: yellow
to
background-color: red
```
```
.pulse {
animation-name: inline-u7rrmuo7b;
animation-duration: 2s;
animation-iteration-count: infinite;
}
@keyframes inline-u7rrmuo7b {
from {
background-color: yellow;
}
to {
background-color: red;
}
}
```
### 💡 Fun fact:
Interpolation is useful for injecting values into strings, but other than that it’s rarely necessary in SassScript expressions. You definitely *don’t* need it to just use a variable in a property value. Instead of writing `color: #{$accent}`, you can just write `color: $accent`!
### ⚠️ Heads up!
It’s almost always a bad idea to use interpolation with numbers. Interpolation returns unquoted strings that can’t be used for any further math, and it avoids Sass’s built-in safeguards to ensure that units are used correctly.
Sass has powerful [unit arithmetic](values/numbers#units) that you can use instead. For example, instead of writing `#{$width}px`, write `$width * 1px`—or better yet, declare the `$width` variable in terms of `px` to begin with. That way if `$width` already has units, you’ll get a nice error message instead of compiling bogus CSS.
Quoted Strings
---------------
In most cases, interpolation injects the exact same text that would be used if the expression were used as a [property value](style-rules/declarations). But there is one exception: the quotation marks around quoted strings are removed (even if those quoted strings are in lists). This makes it possible to write quoted strings that contain syntax that’s not allowed in SassScript (like selectors) and interpolate them into style rules.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
* [CSS](#example-3-css)
```
.example {
unquoted: #{"string"};
}
```
```
.example
unquoted: #{"string"}
```
```
.example {
unquoted: string;
}
```
### ⚠️ Heads up!
While it’s tempting to use this feature to convert quoted strings to unquoted strings, it’s a lot clearer to use the [`string.unquote()` function](modules/string#unquote). Instead of `#{$string}`, write `string.unquote($string)`!
sass Command-Line Interface Command-Line Interface
=======================
Different implementations of Sass have different interfaces when using them from the command line:
* [Dart Sass](cli/dart-sass) has the same command-line interface no matter how you [install it](https://sass-lang.com/dart-sass).
* [Ruby Sass](cli/ruby-sass) is [deprecated](https://sass-lang.com/ruby-sass), and we recommend you move to a different implementation.
sass At-Rules At-Rules
=========
Much of Sass’s extra functionality comes in the form of new [at-rules](https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule) it adds on top of CSS:
* [`@use`](at-rules/use) loads mixins, functions, and variables from other Sass stylesheets, and combines CSS from multiple stylesheets together.
* [`@forward`](at-rules/forward) loads a Sass stylesheet and makes its mixins, functions, and variables available when your stylesheet is loaded with the `@use` rule.
* [`@import`](at-rules/import) extends the CSS at-rule to load styles, mixins, functions, and variables from other stylesheets.
* [`@mixin` and `@include`](at-rules/mixin) makes it easy to re-use chunks of styles.
* [`@function`](at-rules/function) defines custom functions that can be used in [SassScript expressions](syntax/structure#expressions).
* [`@extend`](at-rules/extend) allows selectors to inherit styles from one another.
* [`@at-root`](at-rules/at-root) puts styles within it at the root of the CSS document.
* [`@error`](at-rules/error) causes compilation to fail with an error message.
* [`@warn`](at-rules/warn) prints a warning without stopping compilation entirely.
* [`@debug`](at-rules/debug) prints a message for debugging purposes.
* Flow control rules like [`@if`](at-rules/control/if), [`@each`](at-rules/control/each), [`@for`](at-rules/control/for), and [`@while`](at-rules/control/while) control whether or how many times styles are emitted.
Sass also has some special behavior for [plain CSS at-rules](at-rules/css): they can contain <interpolation>, and they can be nested in style rules. Some of them, like [`@media`](at-rules/css#media) and [`@supports`](at-rules/css#supports), also allow SassScript to be used directly in the rule itself without interpolation.
sass Operators Operators
==========
Sass supports a handful of useful `operators` for working with different values. These include the standard mathematical operators like `+` and `*`, as well as operators for various other types:
* [`==` and `!=`](operators/equality) are used to check if two values are the same.
* [`+`, `-`, `*`, `/`, and `%`](operators/numeric) have their usual mathematical meaning for numbers, with special behaviors for units that matches the use of units in scientific math.
* [`<`, `<=`, `>`, and `>=`](operators/relational) check whether two numbers are greater or less than one another.
* [`and`, `or`, and `not`](operators/boolean) have the usual boolean behavior. Sass considers every value “true” except for `false` and `null`.
* [`+`, `-`, and `/`](operators/string) can be used to concatenate strings.
### ⚠️ Heads up!
Early on in Sass’s history, it added support for mathematical operations on [colors](values/colors). These operations operated on each of the colors’ RGB channels separately, so adding two colors would produce a color with the sum of their red channels as its red channel and so on.
This behavior wasn’t very useful, since it channel-by-channel RGB arithmetic didn’t correspond well to how humans perceive color. [Color functions](modules/color) were added which are much more useful, and color operations were deprecated. They’re still supported in LibSass and Ruby Sass, but they’ll produce warnings and users are strongly encouraged to avoid them.
Order of Operations
--------------------
Sass has a pretty standard [order of operations](https://en.wikipedia.org/wiki/Order_of_operations#Programming_languages), from tightest to loosest:
1. The unary operators [`not`](operators/boolean), [`+`, `-`](operators/numeric#unary-operators), and [`/`](operators/string#unary-operators).
2. The [`*`, `/`, and `%` operators](operators/numeric).
3. The [`+` and `-` operators](operators/numeric).
4. The [`>`, `>=`, `<` and `<=` operators](operators/relational).
5. The [`==` and `!=` operators](operators/equality).
6. The [`and` operator](operators/boolean).
7. The [`or` operator](operators/boolean).
8. The [`=` operator](#single-equals), when it’s available.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@debug 1 + 2 * 3 == 1 + (2 * 3); // true
@debug true or false and false == true or (false and false); // true
```
```
@debug 1 + 2 * 3 == 1 + (2 * 3) // true
@debug true or false and false == true or (false and false) // true
```
### Parentheses
You can explicitly control the order of operations using parentheses. An operation inside parentheses is always evaluated before any operations outside of them. Parentheses can even be nested, in which case the innermost parentheses will be evaluated first.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
```
@debug (1 + 2) * 3; // 9
@debug ((1 + 2) * 3 + 4) * 5; // 65
```
```
@debug (1 + 2) * 3 // 9
@debug ((1 + 2) * 3 + 4) * 5 // 65
```
Single Equals
--------------
Sass supports a special `=` operator that’s only allowed in function arguments, which just creates an [unquoted string](values/strings#unquoted) with its two operands separated by `=`. This exists for backwards-compatibility with very old IE-only syntax.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
* [CSS](#example-3-css)
```
.transparent-blue {
filter: chroma(color=#0000ff);
}
```
```
.transparent-blue
filter: chroma(color=#0000ff)
```
```
.transparent-blue {
filter: chroma(color=#0000ff);
}
```
sass @mixin and @include @mixin and @include
====================
Mixins allow you to define styles that can be re-used throughout your stylesheet. They make it easy to avoid using non-semantic classes like `.float-left`, and to distribute collections of styles in libraries.
Mixins are defined using the `@mixin` at-rule, which is written `@mixin <name> { ... }` or `@mixin name(<arguments...>) { ... }`. A mixin’s name can be any Sass identifier, and it can contain any [statement](../syntax/structure#statements) other than [top-level statements](../syntax/structure#top-level-statements). They can be used to encapsulate styles that can be dropped into a single [style rule](../style-rules); they can contain style rules of their own that can be nested in other rules or included at the top level of the stylesheet; or they can just serve to modify variables.
Mixins are included into the current context using the `@include` at-rule, which is written `@include <name>` or `@include <name>(<arguments...>)`, with the name of the mixin being included.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
@mixin reset-list {
margin: 0;
padding: 0;
list-style: none;
}
@mixin horizontal-list {
@include reset-list;
li {
display: inline-block;
margin: {
left: -2px;
right: 2em;
}
}
}
nav ul {
@include horizontal-list;
}
```
```
@mixin reset-list
margin: 0
padding: 0
list-style: none
@mixin horizontal-list
@include reset-list
li
display: inline-block
margin:
left: -2px
right: 2em
nav ul
@include horizontal-list
```
```
nav ul {
margin: 0;
padding: 0;
list-style: none;
}
nav ul li {
display: inline-block;
margin-left: -2px;
margin-right: 2em;
}
```
### 💡 Fun fact:
Mixin names, like all Sass identifiers, treat hyphens and underscores as identical. This means that `reset-list` and `reset_list` both refer to the same mixin. This is a historical holdover from the very early days of Sass, when it *only* allowed underscores in identifier names. Once Sass added support for hyphens to match CSS’s syntax, the two were made equivalent to make migration easier.
Arguments
----------
Mixins can also take arguments, which allows their behavior to be customized each time they’re called. The arguments are specified in the `@mixin` rule after the mixin’s name, as a list of variable names surrounded by parentheses. The mixin must then be included with the same number of arguments in the form of [SassScript expressions](../syntax/structure#expressions). The values of these expression are available within the mixin’s body as the corresponding variables.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
@mixin rtl($property, $ltr-value, $rtl-value) {
#{$property}: $ltr-value;
[dir=rtl] & {
#{$property}: $rtl-value;
}
}
.sidebar {
@include rtl(float, left, right);
}
```
```
@mixin rtl($property, $ltr-value, $rtl-value)
#{$property}: $ltr-value
[dir=rtl] &
#{$property}: $rtl-value
.sidebar
@include rtl(float, left, right)
```
```
.sidebar {
float: left;
}
[dir=rtl] .sidebar {
float: right;
}
```
### 💡 Fun fact:
Argument lists can also have trailing commas! This makes it easier to avoid syntax errors when refactoring your stylesheets.
### Optional Arguments
Normally, every argument a mixin declares must be passed when that mixin is included. However, you can make an argument optional by defining a *default value* which will be used if that argument isn’t passed. Default values use the same syntax as [variable declarations](../variables): the variable name, followed by a colon and a [SassScript expression](../syntax/structure#expressions). This makes it easy to define flexible mixin APIs that can be used in simple or complex ways.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
* [CSS](#example-3-css)
```
@mixin replace-text($image, $x: 50%, $y: 50%) {
text-indent: -99999em;
overflow: hidden;
text-align: left;
background: {
image: $image;
repeat: no-repeat;
position: $x $y;
}
}
.mail-icon {
@include replace-text(url("/images/mail.svg"), 0);
}
```
```
@mixin replace-text($image, $x: 50%, $y: 50%)
text-indent: -99999em
overflow: hidden
text-align: left
background:
image: $image
repeat: no-repeat
position: $x $y
.mail-icon
@include replace-text(url("/images/mail.svg"), 0)
```
```
.mail-icon {
text-indent: -99999em;
overflow: hidden;
text-align: left;
background-image: url("/images/mail.svg");
background-repeat: no-repeat;
background-position: 0 50%;
}
```
### 💡 Fun fact:
Default values can be any SassScript expression, and they can even refer to earlier arguments!
### Keyword Arguments
When a mixin is included, arguments can be passed by name in addition to passing them by their position in the argument list. This is especially useful for mixins with multiple optional arguments, or with [boolean](../values/booleans) arguments whose meanings aren’t obvious without a name to go with them. Keyword arguments use the same syntax as [variable declarations](../variables) and [optional arguments](#optional-arguments).
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
* [CSS](#example-4-css)
```
@mixin square($size, $radius: 0) {
width: $size;
height: $size;
@if $radius != 0 {
border-radius: $radius;
}
}
.avatar {
@include square(100px, $radius: 4px);
}
```
```
@mixin square($size, $radius: 0)
width: $size
height: $size
@if $radius != 0
border-radius: $radius
.avatar
@include square(100px, $radius: 4px)
```
```
.avatar {
width: 100px;
height: 100px;
border-radius: 4px;
}
```
### ⚠️ Heads up!
Because *any* argument can be passed by name, be careful when renaming a mixin’s arguments… it might break your users! It can be helpful to keep the old name around as an [optional argument](#optional-arguments) for a while and printing a [warning](warn) if anyone passes it, so they know to migrate to the new argument.
### Taking Arbitrary Arguments
Sometimes it’s useful for a mixin to be able to take any number of arguments. If the last argument in a `@mixin` declaration ends in `...`, then all extra arguments to that mixin are passed to that argument as a [list](../values/lists). This argument is known as an [argument list](../values/lists#argument-lists).
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
* [CSS](#example-5-css)
```
@mixin order($height, $selectors...) {
@for $i from 0 to length($selectors) {
#{nth($selectors, $i + 1)} {
position: absolute;
height: $height;
margin-top: $i * $height;
}
}
}
@include order(150px, "input.name", "input.address", "input.zip");
```
```
@mixin order($height, $selectors...)
@for $i from 0 to length($selectors)
#{nth($selectors, $i + 1)}
position: absolute
height: $height
margin-top: $i * $height
@include order(150px, "input.name", "input.address", "input.zip")
```
```
input.name {
position: absolute;
height: 150px;
margin-top: 0px;
}
input.address {
position: absolute;
height: 150px;
margin-top: 150px;
}
input.zip {
position: absolute;
height: 150px;
margin-top: 300px;
}
```
#### Taking Arbitrary Keyword Arguments
Argument lists can also be used to take arbitrary keyword arguments. The [`meta.keywords()` function](../modules/meta#keywords) takes an argument list and returns any extra keywords that were passed to the mixin as a [map](../values/maps) from argument names (not including `$`) to those arguments’ values.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
* [CSS](#example-6-css)
```
@use "sass:meta";
@mixin syntax-colors($args...) {
@debug meta.keywords($args);
// (string: #080, comment: #800, variable: #60b)
@each $name, $color in meta.keywords($args) {
pre span.stx-#{$name} {
color: $color;
}
}
}
@include syntax-colors(
$string: #080,
$comment: #800,
$variable: #60b,
)
```
```
@use "sass:meta"
@mixin syntax-colors($args...)
@debug meta.keywords($args)
// (string: #080, comment: #800, variable: #60b)
@each $name, $color in meta.keywords($args)
pre span.stx-#{$name}
color: $color
@include syntax-colors($string: #080, $comment: #800, $variable: #60b)
```
```
pre span.stx-string {
color: #080;
}
pre span.stx-comment {
color: #800;
}
pre span.stx-variable {
color: #60b;
}
```
### 💡 Fun fact:
If you don’t ever pass an argument list to the [`meta.keywords()` function](../modules/meta#keywords), that argument list won’t allow extra keyword arguments. This helps callers of your mixin make sure they haven’t accidentally misspelled any argument names.
#### Passing Arbitrary Arguments
Just like argument lists allow mixins to take arbitrary positional or keyword arguments, the same syntax can be used to *pass* positional and keyword arguments to a mixin. If you pass a list followed by `...` as the last argument of an include, its elements will be treated as additional positional arguments. Similarly, a map followed by `...` will be treated as additional keyword arguments. You can even pass both at once!
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
```
$form-selectors: "input.name", "input.address", "input.zip" !default;
@include order(150px, $form-selectors...);
```
```
$form-selectors: "input.name", "input.address", "input.zip" !default
@include order(150px, $form-selectors...)
```
### 💡 Fun fact:
Because an [argument list](../values/lists#argument-lists) keeps track of both positional and keyword arguments, you use it to pass both at once to another mixin. That makes it super easy to define an alias for a mixin!
* [SCSS](#example-8-scss)
* [Sass](#example-8-sass)
```
@mixin btn($args...) {
@warn "The btn() mixin is deprecated. Include button() instead.";
@include button($args...);
}
```
```
@mixin btn($args...)
@warn "The btn() mixin is deprecated. Include button() instead."
@include button($args...)
```
Content Blocks
---------------
In addition to taking arguments, a mixin can take an entire block of styles, known as a *content block*. A mixin can declare that it takes a content block by including the `@content` at-rule in its body. The content block is passed in using curly braces like any other block in Sass, and it’s injected in place of the `@content` rule.
* [SCSS](#example-9-scss)
* [Sass](#example-9-sass)
* [CSS](#example-9-css)
```
@mixin hover {
&:not([disabled]):hover {
@content;
}
}
.button {
border: 1px solid black;
@include hover {
border-width: 2px;
}
}
```
```
@mixin hover
&:not([disabled]):hover
@content
.button
border: 1px solid black
@include hover
border-width: 2px
```
```
.button {
border: 1px solid black;
}
.button:not([disabled]):hover {
border-width: 2px;
}
```
### 💡 Fun fact:
A mixin can include multiple `@content` at-rules. If it does, the content block will be included separately for each `@content`.
### ⚠️ Heads up!
A content block is *lexically scoped*, which means it can only see [local variables](../variables#scope) in the scope where the mixin is included. It can’t see any variables that are defined in the mixin it’s passed to, even if they’re defined before the content block is invoked.
### Passing Arguments to Content Blocks
Compatibility:
Dart Sass since 1.15.0
LibSass ✗
Ruby Sass ✗ A mixin can pass arguments to its content block the same way it would pass arguments to another mixin by writing `@content(<arguments...>)`. The user writing the content block can accept arguments by writing `@include <name> using (<arguments...>)`. The argument list for a content block works just like a mixin’s argument list, and the arguments passed to it by `@content` work just like passing arguments to a mixin.
### ⚠️ Heads up!
If a mixin passes arguments to its content block, that content block *must* declare that it accepts those arguments. This means that it’s a good idea to only pass arguments by position (rather than by name), and it means that passing more arguments is a breaking change.
If you want to be flexible in what information you pass to a content block, consider passing it a [map](../values/maps) that contains information it may need!
* [SCSS](#example-10-scss)
* [Sass](#example-10-sass)
* [CSS](#example-10-css)
```
@mixin media($types...) {
@each $type in $types {
@media #{$type} {
@content($type);
}
}
}
@include media(screen, print) using ($type) {
h1 {
font-size: 40px;
@if $type == print {
font-family: Calluna;
}
}
}
```
```
@mixin media($types...)
@each $type in $types
@media #{$type}
@content($type)
@include media(screen, print) using ($type)
h1
font-size: 40px
@if $type == print
font-family: Calluna
```
```
@media screen {
h1 {
font-size: 40px;
}
}
@media print {
h1 {
font-size: 40px;
font-family: Calluna;
}
}
```
Indented Mixin Syntax
----------------------
The [indented syntax](../syntax#the-indented-syntax) has a special syntax for defining and using mixins, in addition to the standard `@mixin` and `@include`. Mixins are defined using the character `=`, and they’re included using `+`. Although this syntax is terser, it’s also harder to understand at a glance and users are encouraged to avoid it.
* [Sass](#example-11-sass)
* [CSS](#example-11-css)
```
=reset-list
margin: 0
padding: 0
list-style: none
=horizontal-list
+reset-list
li
display: inline-block
margin:
left: -2px
right: 2em
nav ul
+horizontal-list
```
```
nav ul {
margin: 0;
padding: 0;
list-style: none;
}
nav ul li {
display: inline-block;
margin-left: -2px;
margin-right: 2em;
}
```
| programming_docs |
sass @warn @warn
======
When writing [mixins](mixin) and [functions](function), you may want to discourage users from passing certain arguments or certain values. They may be passing legacy arguments that are now deprecated, or they may be calling your API in a way that’s not quite optimal.
The `@warn` rule is designed just for that. It’s written `@warn <expression>` and it prints the value of the [expression](../syntax/structure#expressions) (usually a string) for the user, along with a stack trace indicating how the current mixin or function was called. Unlike the [`@error` rule](error), though, it doesn’t stop Sass entirely.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
$known-prefixes: webkit, moz, ms, o;
@mixin prefix($property, $value, $prefixes) {
@each $prefix in $prefixes {
@if not index($known-prefixes, $prefix) {
@warn "Unknown prefix #{$prefix}.";
}
-#{$prefix}-#{$property}: $value;
}
#{$property}: $value;
}
.tilt {
// Oops, we typo'd "webkit" as "wekbit"!
@include prefix(transform, rotate(15deg), wekbit ms);
}
```
```
$known-prefixes: webkit, moz, ms, o
@mixin prefix($property, $value, $prefixes)
@each $prefix in $prefixes
@if not index($known-prefixes, $prefix)
@warn "Unknown prefix #{$prefix}."
-#{$prefix}-#{$property}: $value
#{$property}: $value
.tilt
// Oops, we typo'd "webkit" as "wekbit"!
@include prefix(transform, rotate(15deg), wekbit ms)
```
```
.tilt {
-wekbit-transform: rotate(15deg);
-ms-transform: rotate(15deg);
transform: rotate(15deg);
}
```
The exact format of the warning and stack trace varies from implementation to implementation. This is what it looks like in Dart Sass:
```
Warning: Unknown prefix wekbit.
example.scss 6:7 prefix()
example.scss 16:3 root stylesheet
```
sass Flow Control Rules Flow Control Rules
===================
Sass provides a number of at-rules that make it possible to control whether styles get emitted, or to emit them multiple times with small variations. They can also be used in [mixins](mixin) and [functions](function) to write small algorithms to make writing your Sass easier. Sass supports four flow control rules:
* [`@if`](control/if) controls whether or not a block is evaluated.
* [`@each`](control/each) evaluates a block for each element in a [list](../values/lists) or each pair in a [map](../values/maps).
* [`@for`](control/for) evaluates a block a certain number of times.
* [`@while`](control/while) evaluates a block until a certain condition is met.
sass CSS At-Rules CSS At-Rules
=============
Compatibility (Name Interpolation):
Dart Sass since 1.15.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) LibSass, Ruby Sass, and older versions of Dart Sass don’t support [interpolation](../interpolation) in at-rule names. They do support interpolation in values.
Sass supports all the at-rules that are part of CSS proper. To stay flexible and forwards-compatible with future versions of CSS, Sass has general support that covers almost all at-rules by default. A CSS at-rule is written `@<name> <value>`, `@<name> { ... }`, or `@<name> <value> { ... }`. The name must be an identifier, and the value (if one exists) can be pretty much anything. Both the name and the value can contain [interpolation](../interpolation).
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
@namespace svg url(http://www.w3.org/2000/svg);
@font-face {
font-family: "Open Sans";
src: url("/fonts/OpenSans-Regular-webfont.woff2") format("woff2");
}
@counter-style thumbs {
system: cyclic;
symbols: "\1F44D";
}
```
```
@namespace svg url(http://www.w3.org/2000/svg)
@font-face
font-family: "Open Sans"
src: url("/fonts/OpenSans-Regular-webfont.woff2") format("woff2")
@counter-style thumbs
system: cyclic
symbols: "\1F44D"
```
```
@namespace svg url(http://www.w3.org/2000/svg);
@font-face {
font-family: "Open Sans";
src: url("/fonts/OpenSans-Regular-webfont.woff2") format("woff2");
}
@counter-style thumbs {
system: cyclic;
symbols: "\1F44D";
}
```
If a CSS at-rule is nested within a style rule, the two automatically swap positions so that the at-rule is at the top level of the CSS output and the style rule is within it. This makes it easy to add conditional styling without having to rewrite the style rule’s selector.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
.print-only {
display: none;
@media print { display: block; }
}
```
```
.print-only
display: none
@media print
display: block
```
```
.print-only {
display: none;
}
@media print {
.print-only {
display: block;
}
}
```
`@media`
---------
Compatibility (Range Syntax):
Dart Sass since 1.11.0
LibSass ✗
Ruby Sass since 3.7.0
[▶](javascript:;)
LibSass and older versions of Dart Sass and Ruby Sass don’t support media queries with features written in a [range context](https://www.w3.org/TR/mediaqueries-4/#mq-range-context). They do support other standard media queries.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
* [CSS](#example-3-css)
```
@media (width <= 700px) {
body {
background: green;
}
}
```
```
@media (width <= 700px)
body
background: green
```
```
@media (width <= 700px) {
body {
background: green;
}
}
```
The [`@media` rule](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries) does all of the above and more. In addition to allowing interpolation, it allows [SassScript expressions](../syntax/structure#expressions) to be used directly in the [feature queries](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries#Targeting_media_features).
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
* [CSS](#example-4-css)
```
$layout-breakpoint-small: 960px;
@media (min-width: $layout-breakpoint-small) {
.hide-extra-small {
display: none;
}
}
```
```
$layout-breakpoint-small: 960px
@media (min-width: $layout-breakpoint-small)
.hide-extra-small
display: none
```
```
@media (min-width: 960px) {
.hide-extra-small {
display: none;
}
}
```
When possible, Sass will also merge media queries that are nested within one another to make it easier to support browsers that don’t yet natively support nested `@media` rules.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
* [CSS](#example-5-css)
```
@media (hover: hover) {
.button:hover {
border: 2px solid black;
@media (color) {
border-color: #036;
}
}
}
```
```
@media (hover: hover)
.button:hover
border: 2px solid black
@media (color)
border-color: #036
```
```
@media (hover: hover) {
.button:hover {
border: 2px solid black;
}
}
@media (hover: hover) and (color) {
.button:hover {
border-color: #036;
}
}
```
`@supports`
------------
The [`@supports` rule](https://developer.mozilla.org/en-US/docs/Web/CSS/@supports) also allows [SassScript expressions](../syntax/structure#expressions) to be used in the declaration queries.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
* [CSS](#example-6-css)
```
@mixin sticky-position {
position: fixed;
@supports (position: sticky) {
position: sticky;
}
}
.banner {
@include sticky-position;
}
```
```
@mixin sticky-position
position: fixed
@supports (position: sticky)
position: sticky
.banner
@include sticky-position
```
```
.banner {
position: fixed;
}
@supports (position: sticky) {
.banner {
position: sticky;
}
}
```
`@keyframes`
-------------
The [`@keyframes` rule](https://developer.mozilla.org/en-US/docs/Web/CSS/@keyframes) works just like a general at-rule, except that its child rules must be valid keyframe rules (`<number>%`, `from`, or `to`) rather than normal selectors.
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
* [CSS](#example-7-css)
```
@keyframes slide-in {
from {
margin-left: 100%;
width: 300%;
}
70% {
margin-left: 90%;
width: 150%;
}
to {
margin-left: 0%;
width: 100%;
}
}
```
```
@keyframes slide-in
from
margin-left: 100%
width: 300%
70%
margin-left: 90%
width: 150%
to
margin-left: 0%
width: 100%
```
```
@keyframes slide-in {
from {
margin-left: 100%;
width: 300%;
}
70% {
margin-left: 90%;
width: 150%;
}
to {
margin-left: 0%;
width: 100%;
}
}
```
sass @at-root @at-root
=========
The `@at-root` rule is usually written `@at-root <selector> { ... }` and causes everything within it to be emitted at the root of the document instead of using the normal nesting. It's most often used when doing [advanced nesting](../style-rules/parent-selector#advanced-nesting) with the [SassScript parent selector](../style-rules/parent-selector#in-sassscript) and [selector functions](../modules/selector).
For example, suppose you want to write a selector that matches the outer selector *and* an element selector. You could write a mixin like this one that uses the [`selector.unify()` function](../modules/selector#unify) to combine `&` with a user’s selector.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
@use "sass:selector";
@mixin unify-parent($child) {
@at-root #{selector.unify(&, $child)} {
@content;
}
}
.wrapper .field {
@include unify-parent("input") {
/* ... */
}
@include unify-parent("select") {
/* ... */
}
}
```
```
@use "sass:selector"
@mixin unify-parent($child)
@at-root #{selector.unify(&, $child)}
@content
.wrapper .field
@include unify-parent("input")
/* ... */
@include unify-parent("select")
/* ... */
```
```
.wrapper input.field {
/* ... */
}
.wrapper select.field {
/* ... */
}
```
The `@at-root` rule is necessary here because Sass doesn’t know what interpolation was used to generate a selector when it’s performing selector nesting. This means it will automatically add the outer selector to the inner selector *even if* you used `&` as a SassScript expression. The `@at-root` explicitly tells Sass not to include the outer selector.
### 💡 Fun fact:
The `@at-root` rule can also be written `@at-root { ... }` to put multiple style rules at the root of the document. In fact, `@at-root <selector> { ... }` is just a shorthand for `@at-root { <selector> { ... } }`!
Beyond Style Rules
-------------------
On its own, `@at-root` only gets rid of [style rules](../style-rules). Any at-rules like [`@media`](css#media) or [`@supports`](css#supports) will be left in. If this isn’t what you want, though, you can control exactly what it includes or excludes using syntax like [media query features](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries#Targeting_media_features), written `@at-root (with: <rules...>) { ... }` or `@at-root (without: <rules...>) { ... }`. The `(without: ...)` query tells Sass which rules should be excluded; the `(with: ...)` query excludes all rules *except* those that are listed.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
@media print {
.page {
width: 8in;
@at-root (without: media) {
color: #111;
}
@at-root (with: rule) {
font-size: 1.2em;
}
}
}
```
```
@media print
.page
width: 8in
@at-root (without: media)
color: #111
@at-root (with: rule)
font-size: 1.2em
```
```
@media print {
.page {
width: 8in;
}
}
.page {
color: #111;
}
.page {
font-size: 1.2em;
}
```
In addition to the names of at-rules, there are two special values that can be used in queries:
* `rule` refers to style rules. For example, `@at-root (with: rule)` excludes all at-rules but preserves style rules.
* `all` refers to all at-rules *and* style rules should be excluded.
sass @use @use
=====
Compatibility:
Dart Sass since 1.23.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass currently supports `@use`. Users of other implementations must use the [`@import` rule](import) instead.
The `@use` rule loads [mixins](mixin), [functions](function), and [variables](../variables) from other Sass stylesheets, and combines CSS from multiple stylesheets together. Stylesheets loaded by `@use` are called "modules". Sass also provides [built-in modules](../modules) full of useful functions.
The simplest `@use` rule is written `@use "<url>"`, which loads the module at the given URL. Any styles loaded this way will be included exactly once in the compiled CSS output, no matter how many times those styles are loaded.
### ⚠️ Heads up!
A stylesheet’s `@use` rules must come before any rules other than `@forward`, including [style rules](../style-rules). However, you can declare variables before `@use` rules to use when [configuring modules](#configuration).
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
// foundation/_code.scss
code {
padding: .25em;
line-height: 0;
}
```
```
// foundation/_lists.scss
ul, ol {
text-align: left;
& & {
padding: {
bottom: 0;
left: 0;
}
}
}
```
```
// style.scss
@use 'foundation/code';
@use 'foundation/lists';
```
```
// foundation/_code.sass
code
padding: .25em
line-height: 0
```
```
// foundation/_lists.sass
ul, ol
text-align: left
& &
padding:
bottom: 0
left: 0
```
```
// style.sass
@use 'foundation/code'
@use 'foundation/lists'
```
```
code {
padding: .25em;
line-height: 0;
}
ul, ol {
text-align: left;
}
ul ul, ol ol {
padding-bottom: 0;
padding-left: 0;
}
```
Loading Members
----------------
You can access variables, functions, and mixins from another module by writing `<namespace>.<variable>`, `<namespace>.<function>()`, or `@include <namespace>.<mixin>()`. By default, the namespace is just the last component of the module’s URL.
Members (variables, functions, and mixins) loaded with `@use` are only visible in the stylesheet that loads them. Other stylesheets will need to write their own `@use` rules if they also want to access them. This helps make it easy to figure out exactly where each member is coming from. If you want to load members from many files at once, you can use the [`@forward` rule](forward) to forward them all from one shared file.
### 💡 Fun fact:
Because `@use` adds namespaces to member names, it’s safe to choose very simple names like `$radius` or `$width` when writing a stylesheet. This is different from the old [`@import` rule](import), which encouraged that users write long names like `$mat-corner-radius` to avoid conflicts with other libraries, and it helps keep your stylesheets clear and easy to read!
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
// src/_corners.scss
$radius: 3px;
@mixin rounded {
border-radius: $radius;
}
```
```
// style.scss
@use "src/corners";
.button {
@include corners.rounded;
padding: 5px + corners.$radius;
}
```
```
// src/_corners.sass
$radius: 3px
@mixin rounded
border-radius: $radius
```
```
// style.sass
@use "src/corners"
.button
@include corners.rounded
padding: 5px + corners.$radius
```
```
.button {
border-radius: 3px;
padding: 8px;
}
```
### Choosing a Namespace
By default, a module’s namespace is just the last component of its URL without a file extension. However, sometimes you might want to choose a different namespace—you might want to use a shorter name for a module you refer to a lot, or you might be loading multiple modules with the same filename. You can do this by writing `@use "<url>" as <namespace>`.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
* [CSS](#example-3-css)
```
// src/_corners.scss
$radius: 3px;
@mixin rounded {
border-radius: $radius;
}
```
```
// style.scss
@use "src/corners" as c;
.button {
@include c.rounded;
padding: 5px + c.$radius;
}
```
```
// src/_corners.sass
$radius: 3px
@mixin rounded
border-radius: $radius
```
```
// style.sass
@use "src/corners" as c
.button
@include c.rounded
padding: 5px + c.$radius
```
```
.button {
border-radius: 3px;
padding: 8px;
}
```
You can even load a module *without* a namespace by writing `@use "<url>" as *`. We recommend you only do this for stylesheets written by you, though; otherwise, they may introduce new members that cause name conflicts!
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
* [CSS](#example-4-css)
```
// src/_corners.scss
$radius: 3px;
@mixin rounded {
border-radius: $radius;
}
```
```
// style.scss
@use "src/corners" as *;
.button {
@include rounded;
padding: 5px + $radius;
}
```
```
// src/_corners.sass
$radius: 3px
@mixin rounded
border-radius: $radius
```
```
// style.sass
@use "src/corners" as *
.button
@include rounded
padding: 5px + $radius
```
```
.button {
border-radius: 3px;
padding: 8px;
}
```
### Private Members
As a stylesheet author, you may not want all the members you define to be available outside your stylesheet. Sass makes it easy to define a private member by starting its name with either `-` or `_`. These members will work just like normal within the stylesheet that defines them, but they won’t be part of a module’s public API. That means stylesheets that load your module can’t see them!
### 💡 Fun fact:
If you want to make a member private to an entire *package* rather than just a single module, just don’t [forward its module](forward) from any of your package’s entrypoints (the stylesheets you tell your users to load to use your package). You can even [hide that member](forward#controlling-visibility) while forwarding the rest of its module!
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
```
// src/_corners.scss
$-radius: 3px;
@mixin rounded {
border-radius: $-radius;
}
```
```
// style.scss
@use "src/corners";
.button {
@include corners.rounded;
// This is an error! $-radius isn't visible outside of `_corners.scss`.
padding: 5px + corners.$-radius;
}
```
```
// src/_corners.sass
$-radius: 3px
@mixin rounded
border-radius: $-radius
```
```
// style.sass
@use "src/corners"
.button
@include corners.rounded
// This is an error! $-radius isn't visible outside of `_corners.scss`.
padding: 5px + corners.$-radius
```
Configuration
--------------
A stylesheet can define variables with the [`!default` flag](../variables#default-values) to make them configurable. To load a module with configuration, write `@use <url> with (<variable>: <value>, <variable>: <value>)`. The configured values will override the variables’ default values.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
* [CSS](#example-6-css)
```
// _library.scss
$black: #000 !default;
$border-radius: 0.25rem !default;
$box-shadow: 0 0.5rem 1rem rgba($black, 0.15) !default;
code {
border-radius: $border-radius;
box-shadow: $box-shadow;
}
```
```
// style.scss
@use 'library' with (
$black: #222,
$border-radius: 0.1rem
);
```
```
// _library.sass
$black: #000 !default
$border-radius: 0.25rem !default
$box-shadow: 0 0.5rem 1rem rgba($black, 0.15) !default
code
border-radius: $border-radius
box-shadow: $box-shadow
```
```
// style.sass
@use 'library' with ($black: #222, $border-radius: 0.1rem)
```
```
code {
border-radius: 0.1rem;
box-shadow: 0 0.5rem 1rem rgba(34, 34, 34, 0.15);
}
```
### With Mixins
Configuring modules with `@use ... with` can be very handy, especially when using libraries that were originally written to work with the [`@import` rule](import). But it’s not particularly flexible, and we don’t recommend it for more advanced use-cases. If you find yourself wanting to configure many variables at once, pass [maps](../values/maps) as configuration, or update the configuration after the module is loaded, consider writing a mixin to set your variables instead and another mixin to inject your styles.
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
* [CSS](#example-7-css)
```
// _library.scss
$-black: #000;
$-border-radius: 0.25rem;
$-box-shadow: null;
/// If the user has configured `$-box-shadow`, returns their configured value.
/// Otherwise returns a value derived from `$-black`.
@function -box-shadow() {
@return $-box-shadow or (0 0.5rem 1rem rgba($-black, 0.15));
}
@mixin configure($black: null, $border-radius: null, $box-shadow: null) {
@if $black {
$-black: $black !global;
}
@if $border-radius {
$-border-radius: $border-radius !global;
}
@if $box-shadow {
$-box-shadow: $box-shadow !global;
}
}
@mixin styles {
code {
border-radius: $-border-radius;
box-shadow: -box-shadow();
}
}
```
```
// style.scss
@use 'library';
@include library.configure(
$black: #222,
$border-radius: 0.1rem
);
@include library.styles;
```
```
// _library.sass
$-black: #000
$-border-radius: 0.25rem
$-box-shadow: null
/// If the user has configured `$-box-shadow`, returns their configured value.
/// Otherwise returns a value derived from `$-black`.
@function -box-shadow()
@return $-box-shadow or (0 0.5rem 1rem rgba($-black, 0.15))
@mixin configure($black: null, $border-radius: null, $box-shadow: null)
@if $black
$-black: $black !global
@if $border-radius
$-border-radius: $border-radius !global
@if $box-shadow
$-box-shadow: $box-shadow !global
@mixin styles
code
border-radius: $-border-radius
box-shadow: -box-shadow()
```
```
// style.sass
@use 'library'
@include library.configure($black: #222, $border-radius: 0.1rem)
@include library.styles
```
```
code {
border-radius: 0.1rem;
box-shadow: 0 0.5rem 1rem rgba(34, 34, 34, 0.15);
}
```
### Reassigning Variables
After loading a module, you can reassign its variables.
* [SCSS](#example-8-scss)
* [Sass](#example-8-sass)
```
// _library.scss
$color: red;
```
```
// _override.scss
@use 'library';
library.$color: blue;
```
```
// style.scss
@use 'library';
@use 'override';
@debug library.$color; //=> blue
```
```
// _library.sass
$color: red
```
```
// _override.sass
@use 'library'
library.$color: blue
```
```
// style.sass
@use 'library'
@use 'override'
@debug library.$color //=> blue
```
This even works if you import a module without a namespace using `as *`. Assigning to a variable name defined in that module will overwrite its value in that module.
### ⚠️ Heads up!
Built-in module variables (such as [`math.$pi`](../modules/math#%24pi)) cannot be reassigned.
Finding the Module
-------------------
It wouldn’t be any fun to write out absolute URLs for every stylesheet you load, so Sass’s algorithm for finding a module makes it a little easier. For starters, you don’t have to explicitly write out the extension of the file you want to load; `@use "variables"` will automatically load `variables.scss`, `variables.sass`, or `variables.css`.
### ⚠️ Heads up!
To ensure that stylesheets work on every operating system, Sass loads files by *URL*, not by *file path*. This means you need to use forward slashes, not backslashes, even on Windows.
### Load Paths
All Sass implementations allow users to provide *load paths*: paths on the filesystem that Sass will look in when locating modules. For example, if you pass `node_modules/susy/sass` as a load path, you can use `@use "susy"` to load `node_modules/susy/sass/susy.scss`.
Modules will always be loaded relative to the current file first, though. Load paths will only be used if no relative file exists that matches the module’s URL. This ensures that you can’t accidentally mess up your relative imports when you add a new library.
### 💡 Fun fact:
Unlike some other languages, Sass doesn’t require that you use `./` for relative imports. Relative imports are always available.
### Partials
As a convention, Sass files that are only meant to be loaded as modules, not compiled on their own, begin with `_` (as in `_code.scss`). These are called *partials*, and they tell Sass tools not to try to compile those files on their own. You can leave off the `_` when importing a partial.
### Index Files
If you write an `_index.scss` or `_index.sass` in a folder, the index file will be loaded automatically when you load the URL for the folder itself.
* [SCSS](#example-9-scss)
* [Sass](#example-9-sass)
* [CSS](#example-9-css)
```
// foundation/_code.scss
code {
padding: .25em;
line-height: 0;
}
```
```
// foundation/_lists.scss
ul, ol {
text-align: left;
& & {
padding: {
bottom: 0;
left: 0;
}
}
}
```
```
// foundation/_index.scss
@use 'code';
@use 'lists';
```
```
// style.scss
@use 'foundation';
```
```
// foundation/_code.sass
code
padding: .25em
line-height: 0
```
```
// foundation/_lists.sass
ul, ol
text-align: left
& &
padding:
bottom: 0
left: 0
```
```
// foundation/_index.sass
@use 'code'
@use 'lists'
```
```
// style.sass
@use 'foundation'
```
```
code {
padding: .25em;
line-height: 0;
}
ul, ol {
text-align: left;
}
ul ul, ol ol {
padding-bottom: 0;
padding-left: 0;
}
```
Loading CSS
------------
In addition to loading `.sass` and `.scss` files, Sass can load plain old `.css` files.
* [SCSS](#example-10-scss)
* [Sass](#example-10-sass)
* [CSS](#example-10-css)
```
// code.css
code {
padding: .25em;
line-height: 0;
}
```
```
// style.scss
@use 'code';
```
```
// code.css
code {
padding: .25em;
line-height: 0;
}
```
```
// style.sass
@use 'code'
```
```
code {
padding: .25em;
line-height: 0;
}
```
CSS files loaded as modules don’t allow any special Sass features and so can’t expose any Sass variables, functions, or mixins. In order to make sure authors don’t accidentally write Sass in their CSS, all Sass features that aren’t also valid CSS will produce errors. Otherwise, the CSS will be rendered as-is. It can even be [extended](extend)!
Differences From `@import`
---------------------------
The `@use` rule is intended to replace the old [`@import` rule](import), but it’s intentionally designed to work differently. Here are some major differences between the two:
* `@use` only makes variables, functions, and mixins available within the scope of the current file. It never adds them to the global scope. This makes it easy to figure out where each name your Sass file references comes from, and means you can use shorter names without any risk of collision.
* `@use` only ever loads each file once. This ensures you don’t end up accidentally duplicating your dependencies’ CSS many times over.
* `@use` must appear at the beginning your file, and cannot be nested in style rules.
* Each `@use` rule can only have one URL.
* `@use` requires quotes around its URL, even when using the [indented syntax](../syntax#the-indented-syntax).
| programming_docs |
sass @extend @extend
========
There are often cases when designing a page when one class should have all the styles of another class, as well as its own specific styles. For example, the [BEM methodology](http://getbem.com/naming/) encourages modifier classes that go on the same elements as block or element classes. But this can create cluttered HTML, it's prone to errors from forgetting to include both classes, and it can bring non-semantic style concerns into your markup.
```
<div class="error error--serious">
Oh no! You've been hacked!
</div>
```
```
.error {
border: 1px #f00;
background-color: #fdd;
}
.error--serious {
border-width: 3px;
}
```
Sass’s `@extend` rule solves this. It’s written `@extend <selector>`, and it tells Sass that one selector should inherit the styles of another.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
.error {
border: 1px #f00;
background-color: #fdd;
&--serious {
@extend .error;
border-width: 3px;
}
}
```
```
.error
border: 1px #f00
background-color: #fdd
&--serious
@extend .error
border-width: 3px
```
```
.error, .error--serious {
border: 1px #f00;
background-color: #fdd;
}
.error--serious {
border-width: 3px;
}
```
When one class extends another, Sass styles all elements that match the extender as though they also match the class being extended. When one class selector extends another, it works exactly as though you added the extended class to every element in your HTML that already had the extending class. You can just write `class="error--serious"`, and Sass will make sure it’s styled as though it had `class="error"` as well.
Of course, selectors aren’t just used on their own in style rules. Sass knows to extend *everywhere* the selector is used. This ensures that your elements are styled exactly as if they matched the extended selector.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
.error:hover {
background-color: #fee;
}
.error--serious {
@extend .error;
border-width: 3px;
}
```
```
.error:hover
background-color: #fee
.error--serious
@extend .error
border-width: 3px
```
```
.error:hover, .error--serious:hover {
background-color: #fee;
}
.error--serious {
border-width: 3px;
}
```
### ⚠️ Heads up!
Extends are resolved after the rest of your stylesheet is compiled. In particular, it happens after [parent selectors](../style-rules/parent-selector) are resolved. This means that if you `@extend .error`, it won’t affect the inner selector in `.error { &__icon { ... } }`. It also means that [parent selectors in SassScript](../style-rules/parent-selector#in-sassscript) can’t see the results of extend.
How It Works
-------------
Unlike [mixins](mixin), which copy styles into the current style rule, `@extend` updates style rules that contain the extended selector so that they contain the extending selector as well. When extending selectors, Sass does *intelligent unification*:
* It never generates selectors like `#main#footer` that can’t possibly match any elements.
* It ensures that complex selectors are interleaved so that they work no matter which order the HTML elements are nested.
* It trims redundant selectors as much as possible, while still ensuring that the specificity is greater than or equal to that of the extender.
* It knows when one selector matches everything another does, and can combine them together.
* It intelligently handles [combinators](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors#Combinators), [universal selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Universal_selectors), and [pseudo-classes that contain selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/:not).
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
* [CSS](#example-3-css)
```
.content nav.sidebar {
@extend .info;
}
// This won't be extended, because `p` is incompatible with `nav`.
p.info {
background-color: #dee9fc;
}
// There's no way to know whether `<div class="guide">` will be inside or
// outside `<div class="content">`, so Sass generates both to be safe.
.guide .info {
border: 1px solid rgba(#000, 0.8);
border-radius: 2px;
}
// Sass knows that every element matching "main.content" also matches ".content"
// and avoids generating unnecessary interleaved selectors.
main.content .info {
font-size: 0.8em;
}
```
```
.content nav.sidebar
@extend .info
// This won't be extended, because `p` is incompatible with `nav`.
p.info
background-color: #dee9fc
// There's no way to know whether `<div class="guide">` will be inside or
// outside `<div class="content">`, so Sass generates both to be safe.
.guide .info
border: 1px solid rgba(#000, 0.8)
border-radius: 2px
// Sass knows that every element matching "main.content" also matches ".content"
// and avoids generating unnecessary interleaved selectors.
main.content .info
font-size: 0.8em
```
```
p.info {
background-color: #dee9fc;
}
.guide .info, .guide .content nav.sidebar, .content .guide nav.sidebar {
border: 1px solid rgba(0, 0, 0, 0.8);
border-radius: 2px;
}
main.content .info, main.content nav.sidebar {
font-size: 0.8em;
}
```
### 💡 Fun fact:
You can directly access Sass’s intelligent unification using [selector functions](../modules/selector)! The [`selector.unify()` function](../modules/selector#unify) returns a selector that matches the intersection of two selectors, while the [`selector.extend()` function](../modules/selector#extend) works just like `@extend`, but on a single selector.
### ⚠️ Heads up!
Because `@extend` updates style rules that contain the extended selector, their styles have precedence in [the cascade](https://developer.mozilla.org/en-US/docs/Web/CSS/Cascade) based on where the extended selector’s style rules appear, *not* based on where the `@extend` appears. This can be confusing, but just remember: this is the same precedence those rules would have if you added the extended class to your HTML!
Placeholder Selectors
----------------------
Sometimes you want to write a style rule that’s *only* intended to be extended. In that case, you can use [placeholder selectors](../style-rules/placeholder-selectors), which look like class selectors that start with `%` instead of `.`. Any selectors that include placeholders aren’t included in the CSS output, but selectors that extend them are.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
* [CSS](#example-4-css)
```
.alert:hover, %strong-alert {
font-weight: bold;
}
%strong-alert:hover {
color: red;
}
```
```
.alert:hover, %strong-alert
font-weight: bold
%strong-alert:hover
color: red
```
```
.alert:hover {
font-weight: bold;
}
```
### Private Placeholders
Like [module members](use#private-members), a placeholder selector can be marked private by starting its name with either `-` or `_`. A private placeholder selector can only be extended within the stylesheet that defines it. To any other stylesheets, it will look as though that selector doesn’t exist.
Extension Scope
----------------
When one stylesheet extends a selector, that extension will only affect style rules written in *upstream* modules—that is, modules that are loaded by that stylesheet using the [`@use` rule](use) or the [`@forward` rule](forward), modules loaded by *those* modules, and so on. This helps make your `@extend` rules more predictable, ensuring that they affect only the styles you were aware of when you wrote them.
### ⚠️ Heads up!
Extensions aren’t scoped at all if you’re using the [`@import` rule](import). Not only will they affect every stylesheet you import, they’ll affect every stylesheet that imports your stylesheet, everything else those stylesheets import, and so on. Without `@use`, extensions are *global*.
Mandatory and Optional Extends
-------------------------------
Normally, if an `@extend` doesn’t match any selectors in the stylesheet, Sass will produce an error. This helps protect from typos or from renaming a selector without renaming the selectors that inherit from it. Extends that require that the extended selector exists are *mandatory*.
This may not always be what you want, though. If you want the `@extend` to do nothing if the extended selector doesn’t exist, just add `!optional` to the end.
Extends or Mixins?
-------------------
Extends and [mixins](mixin) are both ways of encapsulating and re-using styles in Sass, which naturally raises the question of when to use which one. Mixins are obviously necessary when you need to configure the styles using [arguments](mixin#arguments), but what if they’re just a chunk of styles?
As a rule of thumb, extends are the best option when you’re expressing a relationship between semantic classes (or other semantic selectors). Because an element with class `.error--serious` *is an* error, it makes sense for it to extend `.error`. But for non-semantic collections of styles, writing a mixin can avoid cascade headaches and make it easier to configure down the line.
### 💡 Fun fact:
Most web servers compress the CSS they serve using an algorithm that’s very good at handling repeated chunks of identical text. This means that, although mixins may produce more CSS than extends, they probably won’t substantially increase the amount your users need to download. So choose the feature that makes the most sense for your use-case, not the one that generates the least CSS!
Limitations
------------
### Disallowed Selectors
Compatibility (No Compound Extensions):
Dart Sass ✓
LibSass ✗
Ruby Sass ✗ [▶](javascript:;)
LibSass and Ruby Sass currently allow compound selectors like `.message.info` to be extended. However, this behavior doesn’t match the definition of `@extend`: instead of styling elements that match the extending selector as though it had `class="message info"`, which would be affected by style rules that included either `.message` *or* `.info`, it only styled them with rules that included both `.message` *and* `info`.
In order to keep the definition of `@extend` straightforward and understandable, and to keep the implementation clean and efficient, that behavior is now deprecated and will be removed from future versions.
See [the breaking change page](https://sass-lang.com/documentation/breaking-changes/extend-compound) for more details.
Only *simple selectors*—individual selectors like `.info` or `a`—can be extended. If `.message.info` could be extended, the definition of `@extend` says that elements matching the extender would be styled as though they matched `.message.info`. That’s just the same as matching both `.message` and `.info`, so there wouldn’t be any benefit in writing that instead of `@extend .message, .info`.
Similarly, if `.main .info` could be extended, it would do (almost) the same thing as extending `.info` on its own. The subtle differences aren’t worth the confusion of looking like it’s doing something substantially different, so this isn’t allowed either.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
```
.alert {
@extend .message.info;
// ^^^^^^^^^^^^^
// Error: Write @extend .message, .info instead.
@extend .main .info;
// ^^^^^^^^^^^
// Error: write @extend .info instead.
}
```
```
.alert
@extend .message.info
// ^^^^^^^^^^^^^
// Error: Write @extend .message, .info instead.
@extend .main .info
// ^^^^^^^^^^^
// Error: write @extend .info instead.
```
### HTML Heuristics
When `@extend` [interleaves complex selectors](#how-it-works), it doesn’t generate all possible combinations of ancestor selectors. Many of the selectors it could generate are unlikely to actually match real HTML, and generating them all would make stylesheets way too big for very little real value. Instead, it uses a [heuristic](https://en.wikipedia.org/wiki/Heuristic): it assumes that each selector’s ancestors will be self-contained, without being interleaved with any other selector’s ancestors.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
* [CSS](#example-6-css)
```
header .warning li {
font-weight: bold;
}
aside .notice dd {
// Sass doesn't generate CSS to match the <dd> in
//
// <header>
// <aside>
// <div class="warning">
// <div class="notice">
// <dd>...</dd>
// </div>
// </div>
// </aside>
// </header>
//
// because matching all elements like that would require us to generate nine
// new selectors instead of just two.
@extend li;
}
```
```
header .warning li
font-weight: bold
aside .notice dd
// Sass doesn't generate CSS to match the <dd> in
//
// <header>
// <aside>
// <div class="warning">
// <div class="notice">
// <dd>...</dd>
// </div>
// </div>
// </aside>
// </header>
//
// because matching all elements like that would require us to generate nine
// new selectors instead of just two.
@extend li
```
```
header .warning li, header .warning aside .notice dd, aside .notice header .warning dd {
font-weight: bold;
}
```
### Extend in `@media`
While `@extend` is allowed within [`@media` and other CSS at-rules](css), it’s not allowed to extend selectors that appear outside its at-rule. This is because the extending selector only applies within the given media context, and there’s no way to make sure that restriction is preserved in the generated selector without duplicating the entire style rule.
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
```
@media screen and (max-width: 600px) {
.error--serious {
@extend .error;
// ^^^^^^
// Error: ".error" was extended in @media, but used outside it.
}
}
.error {
border: 1px #f00;
background-color: #fdd;
}
```
```
@media screen and (max-width: 600px)
.error--serious
@extend .error
// ^^^^^^
// Error: ".error" was extended in @media, but used outside it.
.error
border: 1px #f00
background-color: #fdd
```
sass @forward @forward
=========
The `@forward` rule loads a Sass stylesheet and makes its [mixins](mixin), [functions](function), and [variables](../variables) available when your stylesheet is loaded with the [`@use` rule](use). It makes it possible to organize Sass libraries across many files, while allowing their users to load a single entrypoint file.
The rule is written `@forward "<url>"`. It loads the module at the given URL just like `@use`, but it makes the [public](use#private-members) members of the loaded module available to users of your module as though they were defined directly in your module. Those members aren’t available in your module, though—if you want that, you’ll need to write a `@use` rule as well. Don’t worry, it’ll only load the module once!
If you *do* write both a `@forward` and a `@use` for the same module in the same file, it’s always a good idea to write the `@forward` first. That way, if your users want to [configure the forwarded module](use#configuration), that configuration will be applied to the `@forward` before your `@use` loads it without any configuration.
### 💡 Fun fact:
The `@forward` rule acts just like `@use` when it comes to a module’s CSS. Styles from a forwarded module will be included in the compiled CSS output, and the module with the `@forward` can <extend> it, even if it isn’t also `@use`d.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
// src/_list.scss
@mixin list-reset {
margin: 0;
padding: 0;
list-style: none;
}
```
```
// bootstrap.scss
@forward "src/list";
```
```
// styles.scss
@use "bootstrap";
li {
@include bootstrap.list-reset;
}
```
```
// src/_list.sass
@mixin list-reset
margin: 0
padding: 0
list-style: none
```
```
// bootstrap.sass
@forward "src/list"
```
```
// styles.sass
@use "bootstrap"
li
@include bootstrap.list-reset
```
```
li {
margin: 0;
padding: 0;
list-style: none;
}
```
Adding a Prefix
----------------
Because module members are usually used with [a namespace](use#loading-members), short and simple names are usually the most readable option. But those names might not make sense outside the module they’re defined in, so `@forward` has the option of adding an extra prefix to all the members it forwards.
This is written `@forward "<url>" as <prefix>-*`, and it adds the given prefix to the beginning of every mixin, function, and variable name forwarded by the module. For example, if the module defines a member named `reset` and it’s forwarded `as list-*`, downstream stylesheets will refer to it as `list-reset`.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
// src/_list.scss
@mixin reset {
margin: 0;
padding: 0;
list-style: none;
}
```
```
// bootstrap.scss
@forward "src/list" as list-*;
```
```
// styles.scss
@use "bootstrap";
li {
@include bootstrap.list-reset;
}
```
```
// src/_list.sass
@mixin reset
margin: 0
padding: 0
list-style: none
```
```
// bootstrap.sass
@forward "src/list" as list-*
```
```
// styles.sass
@use "bootstrap"
li
@include bootstrap.list-reset
```
```
li {
margin: 0;
padding: 0;
list-style: none;
}
```
Controlling Visibility
-----------------------
Sometimes, you don’t want to forward *every* member from a module. You may want to keep some members private so that only your package can use them, or you may want to require your users to load some members a different way. You can control exactly which members get forwarded by writing `@forward "<url>" hide <members...>` or `@forward "<url>" show <members...>`.
The `hide` form means that the listed members shouldn’t be forwarded, but everything else should. The `show` form means that *only* the named members should be forwarded. In both forms, you list the names of mixins, functions, or variables (including the `$`).
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
// src/_list.scss
$horizontal-list-gap: 2em;
@mixin list-reset {
margin: 0;
padding: 0;
list-style: none;
}
@mixin list-horizontal {
@include list-reset;
li {
display: inline-block;
margin: {
left: -2px;
right: $horizontal-list-gap;
}
}
}
```
```
// bootstrap.scss
@forward "src/list" hide list-reset, $horizontal-list-gap;
```
```
// src/_list.sass
$horizontal-list-gap: 2em
@mixin list-reset
margin: 0
padding: 0
list-style: none
@mixin list-horizontal
@include list-rest
li
display: inline-block
margin:
left: -2px
right: $horizontal-list-gap
```
```
// bootstrap.sass
@forward "src/list" hide list-reset, $horizontal-list-gap
```
Configuring Modules
--------------------
Compatibility:
Dart Sass since 1.24.0
LibSass ✗
Ruby Sass ✗ The `@forward` rule can also load a module with [configuration](use#configuration). This mostly works the same as it does for `@use`, with one addition: a `@forward` rule’s configuration can use the `!default` flag in its configuration. This allows a module to change the defaults of an upstream stylesheet while still allowing downstream stylesheets to override them.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
* [CSS](#example-4-css)
```
// _library.scss
$black: #000 !default;
$border-radius: 0.25rem !default;
$box-shadow: 0 0.5rem 1rem rgba($black, 0.15) !default;
code {
border-radius: $border-radius;
box-shadow: $box-shadow;
}
```
```
// _opinionated.scss
@forward 'library' with (
$black: #222 !default,
$border-radius: 0.1rem !default
);
```
```
// style.scss
@use 'opinionated' with ($black: #333);
```
```
// _library.sass
$black: #000 !default
$border-radius: 0.25rem !default
$box-shadow: 0 0.5rem 1rem rgba($black, 0.15) !default
code
border-radius: $border-radius
box-shadow: $box-shadow
```
```
// _opinionated.sass
@forward 'library' with ($black: #222 !default, $border-radius: 0.1rem !default)
```
```
// style.sass
@use 'opinionated' with ($black: #333)
```
```
code {
border-radius: 0.1rem;
box-shadow: 0 0.5rem 1rem rgba(51, 51, 51, 0.15);
}
```
| programming_docs |
sass @import @import
========
Sass extends CSS's [`@import` rule](https://developer.mozilla.org/en-US/docs/Web/CSS/@import) with the ability to import Sass and CSS stylesheets, providing access to [mixins](mixin), [functions](function), and [variables](../variables) and combining multiple stylesheets' CSS together. Unlike plain CSS imports, which require the browser to make multiple HTTP requests as it renders your page, Sass imports are handled entirely during compilation.
Sass imports have the same syntax as CSS imports, except that they allow multiple imports to be separated by commas rather than requiring each one to have its own `@import`. Also, in the [indented syntax](../syntax#the-indented-syntax), imported URLs aren’t required to have quotes.
### ⚠️ Heads up!
The Sass team discourages the continued use of the `@import` rule. Sass will [gradually phase it out](https://github.com/sass/sass/blob/master/accepted/module-system.md#timeline) over the next few years, and eventually remove it from the language entirely. Prefer the [`@use` rule](use) instead. (Note that only Dart Sass currently supports `@use`. Users of other implementations must use the `@import` rule instead.)
#### What’s Wrong With `@import`?
The `@import` rule has a number of serious issues:
* `@import` makes all variables, mixins, and functions globally accessible. This makes it very difficult for people (or tools) to tell where anything is defined.
* Because everything’s global, libraries must prefix to all their members to avoid naming collisions.
* [`@extend` rules](extend) are also global, which makes it difficult to predict which style rules will be extended.
* Each stylesheet is executed and its CSS emitted *every time* it’s `@import`ed, which increases compilation time and produces bloated output.
* There was no way to define private members or placeholder selectors that were inaccessible to downstream stylesheets.
The new module system and the `@use` rule address all these problems.
#### How Do I Migrate?
We’ve written a [migration tool](../cli/migrator) that automatically converts most `@import`-based code to `@use`-based code in a flash. Just point it at your entrypoints and let it run!
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
// foundation/_code.scss
code {
padding: .25em;
line-height: 0;
}
```
```
// foundation/_lists.scss
ul, ol {
text-align: left;
& & {
padding: {
bottom: 0;
left: 0;
}
}
}
```
```
// style.scss
@import 'foundation/code', 'foundation/lists';
```
```
// foundation/_code.sass
code
padding: .25em
line-height: 0
```
```
// foundation/_lists.sass
ul, ol
text-align: left
& &
padding:
bottom: 0
left: 0
```
```
// style.sass
@import foundation/code, foundation/lists
```
```
code {
padding: .25em;
line-height: 0;
}
ul, ol {
text-align: left;
}
ul ul, ol ol {
padding-bottom: 0;
padding-left: 0;
}
```
When Sass imports a file, that file is evaluated as though its contents appeared directly in place of the `@import`. Any [mixins](mixin), [functions](function), and [variables](../variables) from the imported file are made available, and all its CSS is included at the exact point where the `@import` was written. What’s more, any mixins, functions, or variables that were defined before the `@import` (including from other `@import`s) are available in the imported stylesheet.
### ⚠️ Heads up!
If the same stylesheet is imported more than once, it will be evaluated again each time. If it just defines functions and mixins, this usually isn’t a big deal, but if it contains style rules they’ll be compiled to CSS more than once.
Finding the File
-----------------
It wouldn’t be any fun to write out absolute URLs for every stylesheet you import, so Sass’s algorithm for finding a file to import makes it a little easier. For starters, you don’t have to explicitly write out the extension of the file you want to import; `@import "variables"` will automatically load `variables.scss`, `variables.sass`, or `variables.css`.
### ⚠️ Heads up!
To ensure that stylesheets work on every operating system, Sass imports files by *URL*, not by *file path*. This means you need to use forward slashes, not backslashes, even when you’re on Windows.
### Load Paths
All Sass implementations allow users to provide *load paths*: paths on the filesystem that Sass will look in when resolving imports. For example, if you pass `node_modules/susy/sass` as a load path, you can use `@import "susy"` to load `node_modules/susy/sass/susy.scss`.
Imports will always be resolved relative to the current file first, though. Load paths will only be used if no relative file exists that matches the import. This ensures that you can’t accidentally mess up your relative imports when you add a new library.
### 💡 Fun fact:
Unlike some other languages, Sass doesn’t require that you use `./` for relative imports. Relative imports are always available.
### Partials
As a convention, Sass files that are only meant to be imported, not compiled on their own, begin with `_` (as in `_code.scss`). These are called *partials*, and they tell Sass tools not to try to compile those files on their own. You can leave off the `_` when importing a partial.
### Index Files
Compatibility:
Dart Sass ✓
LibSass since 3.6.0
Ruby Sass since 3.6.0
If you write an `_index.scss` or `_index.sass` in a folder, when the folder itself is imported that file will be loaded in its place.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
// foundation/_code.scss
code {
padding: .25em;
line-height: 0;
}
```
```
// foundation/_lists.scss
ul, ol {
text-align: left;
& & {
padding: {
bottom: 0;
left: 0;
}
}
}
```
```
// foundation/_index.scss
@import 'code', 'lists';
```
```
// style.scss
@import 'foundation';
```
```
// foundation/_code.sass
code
padding: .25em
line-height: 0
```
```
// foundation/_lists.sass
ul, ol
text-align: left
& &
padding:
bottom: 0
left: 0
```
```
// foundation/_index.sass
@import code, lists
```
```
// style.sass
@import foundation
```
```
code {
padding: .25em;
line-height: 0;
}
ul, ol {
text-align: left;
}
ul ul, ol ol {
padding-bottom: 0;
padding-left: 0;
}
```
### Custom Importers
All Sass implementations provide a way to define custom importers, which control how `@import`s locate stylesheets:
* [Node Sass](https://npmjs.com/package/node-sass) and [Dart Sass on npm](https://npmjs.com/package/sass) provide an [`importer` option](https://github.com/sass/node-sass#importer--v200---experimental) as part of their JS API.
* [Dart Sass on pub](https://pub.dartlang.org/packages/sass) provides an abstract [`Importer` class](https://pub.dartlang.org/documentation/sass/latest/sass/Importer-class.html) that can be extended by a custom importer.
* [Ruby Sass](https://sass-lang.com/ruby-sass) provides an abstract [`Importers::Base` class](https://www.rubydoc.info/gems/sass/Sass/Importers/Base) that can be extended by a custom importer.
Nesting
--------
Imports are usually written at the top level of a stylesheet, but they don’t have to be. They can nested within [style rules](../style-rules) or [plain CSS at-rules](css) as well. The imported CSS is nested in that context, which makes nested imports useful for scoping a chunk of CSS to a particular element or media query. Note that top-level [mixins](mixin), [functions](function), and [variables](../variables) defined in the nested import are still defined globally, though.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
* [CSS](#example-3-css)
```
// _theme.scss
pre, code {
font-family: 'Source Code Pro', Helvetica, Arial;
border-radius: 4px;
}
```
```
// style.scss
.theme-sample {
@import "theme";
}
```
```
// _theme.sass
pre, code
font-family: 'Source Code Pro', Helvetica, Arial
border-radius: 4px
```
```
// style.sass
.theme-sample
@import theme
```
```
.theme-sample pre, .theme-sample code {
font-family: 'Source Code Pro', Helvetica, Arial;
border-radius: 4px;
}
```
### 💡 Fun fact:
Nested imports are very useful for scoping third-party stylesheets, but if you’re the author of the stylesheet you’re importing, it’s usually a better idea to write your styles in a <mixin> and include that mixin in the nested context. A mixin can be used in more flexible ways, and it’s clearer when looking at the imported stylesheet how it’s intended to be used.
### ⚠️ Heads up!
The CSS in nested imports is evaluated like a mixin, which means that any [parent selectors](../style-rules/parent-selector) will refer to the selector in which the stylesheet is nested.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
* [CSS](#example-4-css)
```
// _theme.scss
ul li {
$padding: 16px;
padding-left: $padding;
[dir=rtl] & {
padding: {
left: 0;
right: $padding;
}
}
}
```
```
// style.scss
.theme-sample {
@import "theme";
}
```
```
// _theme.sass
ul li
$padding: 16px
padding-left: $padding
[dir=rtl] &
padding:
left: 0
right: $padding
```
```
// style.sass
.theme-sample
@import theme
```
```
.theme-sample ul li {
padding-left: 16px;
}
[dir=rtl] .theme-sample ul li {
padding-left: 0;
padding-right: 16px;
}
```
Importing CSS
--------------
Compatibility:
Dart Sass since 1.11.0
LibSass partial
Ruby Sass ✗ [▶](javascript:;) LibSass supports importing files with the extension `.css`, but contrary to the specification they’re treated as SCSS files rather than being parsed as CSS. This behavior has been deprecated, and an update is in the works to support the behavior described below.
In addition to importing `.sass` and `.scss` files, Sass can import plain old `.css` files. The only rule is that the import *must not* explicitly include the `.css` extension, because that’s used to indicate a [plain CSS `@import`](#plain-css-imports).
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
* [CSS](#example-5-css)
```
// code.css
code {
padding: .25em;
line-height: 0;
}
```
```
// style.scss
@import 'code';
```
```
// code.css
code {
padding: .25em;
line-height: 0;
}
```
```
// style.sass
@import code
```
```
code {
padding: .25em;
line-height: 0;
}
```
CSS files imported by Sass don’t allow any special Sass features. In order to make sure authors don’t accidentally write Sass in their CSS, all Sass features that aren’t also valid CSS will produce errors. Otherwise, the CSS will be rendered as-is. It can even be [extended](extend)!
Plain CSS `@import`s
---------------------
Compatibility:
Dart Sass ✓
LibSass partial
Ruby Sass ✓ [▶](javascript:;) By default, LibSass handles plain CSS imports correctly. However, any [custom importers](../js-api/interfaces/legacysharedoptions#importer) will incorrectly apply to plain-CSS `@import` rules, making it possible for those rules to load Sass files.
Because `@import` is also defined in CSS, Sass needs a way of compiling plain CSS `@import`s without trying to import the files at compile time. To accomplish this, and to ensure SCSS is as much of a superset of CSS as possible, Sass will compile any `@import`s with the following characteristics to plain CSS imports:
* Imports where the URL ends with `.css`.
* Imports where the URL begins `http://` or `https://`.
* Imports where the URL is written as a `url()`.
* Imports that have media queries.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
* [CSS](#example-6-css)
```
@import "theme.css";
@import "http://fonts.googleapis.com/css?family=Droid+Sans";
@import url(theme);
@import "landscape" screen and (orientation: landscape);
```
```
@import "theme.css"
@import "http://fonts.googleapis.com/css?family=Droid+Sans"
@import url(theme)
@import "landscape" screen and (orientation: landscape)
```
```
@import url(theme.css);
@import "http://fonts.googleapis.com/css?family=Droid+Sans";
@import url(theme);
@import "landscape" screen and (orientation: landscape);
```
### Interpolation
Although Sass imports can’t use [interpolation](../interpolation) (to make sure it’s always possible to tell where [mixins](mixin), [functions](function), and [variables](../variables) come from), plain CSS imports can. This makes it possible to dynamically generate imports, for example based on mixin parameters.
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
* [CSS](#example-7-css)
```
@mixin google-font($family) {
@import url("http://fonts.googleapis.com/css?family=#{$family}");
}
@include google-font("Droid Sans");
```
```
@mixin google-font($family)
@import url("http://fonts.googleapis.com/css?family=#{$family}")
@include google-font("Droid Sans")
```
```
@import url("http://fonts.googleapis.com/css?family=Droid Sans");
```
Import and Modules
-------------------
Compatibility:
Dart Sass since 1.23.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass currently supports `@use`. Users of other implementations must use the [`@import` rule](import) instead.
Sass’s [module system](use) integrates seamlessly with `@import`, whether you’re importing a file that contains `@use` rules or loading a file that contains imports as a module. We want to make the transition from `@import` to `@use` as smooth as possible.
### Importing a Module-System File
When you import a file that contains `@use` rules, the importing file has access to all members (even private members) defined directly in that file, but *not* any members from modules that file has loaded. However, if that file contains [`@forward` rules](forward), the importing file will have access to forwarded members. This means that you can import a library that was written to be used with the module system.
### ⚠️ Heads up!
When a file with `@use` rules is imported, all the CSS transitively loaded by those is included in the resulting stylesheet, even if it’s already been included by another import. If you’re not careful, this can result in bloated CSS output!
#### Import-Only Files
An API that makes sense for `@use` might not make sense for `@import`. For example, `@use` adds a namespace to all members by default so you can safely use short names, but `@import` doesn’t so you might need something longer. If you’re a library author, you may be concerned that if you update your library to use the new module system, your existing `@import`-based users will break.
To make this easier, Sass also supports *import-only files*. If you name a file `<name>.import.scss`, it will only be loaded for imports, not for `@use`s. This way, you can retain compatibility for `@import` users while still providing a nice API for users of the new module system.
* [SCSS](#example-8-scss)
* [Sass](#example-8-sass)
```
// _reset.scss
// Module system users write `@include reset.list()`.
@mixin list() {
ul {
margin: 0;
padding: 0;
list-style: none;
}
}
```
```
// _reset.import.scss
// Legacy import users can keep writing `@include reset-list()`.
@forward "reset" as reset-*;
```
```
// _reset.sass
// Module system users write `@include reset.list()`.
@mixin list()
ul
margin: 0
padding: 0
list-style: none
```
```
// _reset.import.sass
// Legacy import users can keep writing `@include reset-list()`.
@forward "reset" as reset-*
```
#### Configuring Modules Through Imports
Compatibility:
Dart Sass since 1.24.0
LibSass ✗
Ruby Sass ✗ You can [configure modules](use#configuration) that are loaded through an `@import` by defining global variables prior the `@import` that first loads that module.
* [SCSS](#example-9-scss)
* [Sass](#example-9-sass)
* [CSS](#example-9-css)
```
// _library.scss
$color: blue !default;
a {
color: $color;
}
```
```
// _library.import.scss
@forward 'library' as lib-*;
```
```
// style.sass
$lib-color: green;
@import "library";
```
```
$color: blue !default
a
color: $color
```
```
// _library.import.sass
@forward 'library' as lib-*
```
```
// style.sass
$lib-color: green
@import "library"
```
```
a {
color: green;
}
```
### ⚠️ Heads up!
Modules are only loaded once, so if you change the configuration after you `@import` a module for the first time (even indirectly), the change will be ignored if you `@import` the module again.
### Loading a Module That Contains Imports
When you use `@use` (or `@forward`) load a module that uses `@import`, that module will contain all the public members defined by the stylesheet you load *and* everything that stylesheet transitively imports. In other words, everything that’s imported is treated as though it were written in one big stylesheet.
This makes it easy to convert start using `@use` in a stylesheet even before all the libraries you depend on have converted to the new module system. Be aware, though, that if they do convert their APIs may well change!
sass @debug @debug
=======
Sometimes it’s useful to see the value of a [variable](../variables) or [expression](../syntax/structure#expressions) while you’re developing your stylesheet. That’s what the `@debug` rule is for: it’s written `@debug <expression>`, and it prints the value of that expression, along with the filename and line number.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@mixin inset-divider-offset($offset, $padding) {
$divider-offset: (2 * $padding) + $offset;
@debug "divider offset: #{$divider-offset}";
margin-left: $divider-offset;
width: calc(100% - #{$divider-offset});
}
```
```
@mixin inset-divider-offset($offset, $padding)
$divider-offset: (2 * $padding) + $offset
@debug "divider offset: #{$divider-offset}"
margin-left: $divider-offset
width: calc(100% - #{$divider-offset})
```
The exact format of the debug message varies from implementation to implementation. This is what it looks like in Dart Sass:
```
test.scss:3 Debug: divider offset: 132px
```
### 💡 Fun fact:
You can pass any value to `@debug`, not just a string! It prints the same representation of that value as the [`meta.inspect()` function](../modules/meta#inspect).
sass @error @error
=======
When writing [mixins](mixin) and [functions](function) that take arguments, you usually want to ensure that those arguments have the types and formats your API expects. If they aren't, the user needs to be notified and your mixin/function needs to stop running.
Sass makes this easy with the `@error` rule, which is written `@error <expression>`. It prints the value of the [expression](../syntax/structure#expressions) (usually a string) along with a stack trace indicating how the current mixin or function was called. Once the error is printed, Sass stops compiling the stylesheet and tells whatever system is running it that an error occurred.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@mixin reflexive-position($property, $value) {
@if $property != left and $property != right {
@error "Property #{$property} must be either left or right.";
}
$left-value: if($property == right, initial, $value);
$right-value: if($property == right, $value, initial);
left: $left-value;
right: $right-value;
[dir=rtl] & {
left: $right-value;
right: $left-value;
}
}
.sidebar {
@include reflexive-position(top, 12px);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Error: Property top must be either left or right.
}
```
```
@mixin reflexive-position($property, $value)
@if $property != left and $property != right
@error "Property #{$property} must be either left or right."
$left-value: if($property == right, initial, $value)
$right-value: if($property == right, $value, initial)
left: $left-value
right: $right-value
[dir=rtl] &
left: $right-value
right: $left-value
.sidebar
@include reflexive-position(top, 12px)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Error: Property top must be either left or right.
```
The exact format of the error and stack trace varies from implementation to implementation, and can also depend on your build system. This is what it looks like in Dart Sass when run from the command line:
```
Error: "Property top must be either left or right."
╷
3 │ @error "Property #{$property} must be either left or right.";
│ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
╵
example.scss 3:5 reflexive-position()
example.scss 19:3 root stylesheet
```
| programming_docs |
sass @function @function
==========
Functions allow you to define complex operations on [SassScript values](../values) that you can re-use throughout your stylesheet. They make it easy to abstract out common formulas and behaviors in a readable way.
Functions are defined using the `@function` at-rule, which is written `@function <name>(<arguments...>) { ... }`. A function’s name can be any Sass identifier. It can only contain [universal statements](../syntax/structure#universal-statements), as well as the [`@return` at-rule](#return) which indicates the value to use as the result of the function call. Functions are called using the normal CSS function syntax.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
@function pow($base, $exponent) {
$result: 1;
@for $_ from 1 through $exponent {
$result: $result * $base;
}
@return $result;
}
.sidebar {
float: left;
margin-left: pow(4, 3) * 1px;
}
```
```
@function pow($base, $exponent)
$result: 1
@for $_ from 1 through $exponent
$result: $result * $base
@return $result
.sidebar
float: left
margin-left: pow(4, 3) * 1px
```
```
.sidebar {
float: left;
margin-left: 64px;
}
```
### 💡 Fun fact:
Function names, like all Sass identifiers, treat hyphens and underscores as identical. This means that `scale-color` and `scale_color` both refer to the same function. This is a historical holdover from the very early days of Sass, when it *only* allowed underscores in identifier names. Once Sass added support for hyphens to match CSS’s syntax, the two were made equivalent to make migration easier.
### ⚠️ Heads up!
While it’s technically possible for functions to have side-effects like setting [global variables](../variables#scope), this is strongly discouraged. Use [mixins](mixin) for side-effects, and use functions just to compute values.
Arguments
----------
Arguments allow functions’ behavior to be customized each time they’re called. The arguments are specified in the `@function` rule after the function’s name, as a list of variable names surrounded by parentheses. The function must be called with the same number of arguments in the form of [SassScript expressions](../syntax/structure#expressions). The values of these expression are available within the function’s body as the corresponding variables.
### 💡 Fun fact:
Argument lists can also have trailing commas! This makes it easier to avoid syntax errors when refactoring your stylesheets.
### Optional Arguments
Normally, every argument a function declares must be passed when that function is included. However, you can make an argument optional by defining a *default value* which will be used if that arguments isn’t passed. Default values use the same syntax as [variable declarations](../variables): the variable name, followed by a colon and a [SassScript expression](../syntax/structure#expressions). This makes it easy to define flexible function APIs that can be used in simple or complex ways.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
@function invert($color, $amount: 100%) {
$inverse: change-color($color, $hue: hue($color) + 180);
@return mix($inverse, $color, $amount);
}
$primary-color: #036;
.header {
background-color: invert($primary-color, 80%);
}
```
```
@function invert($color, $amount: 100%)
$inverse: change-color($color, $hue: hue($color) + 180)
@return mix($inverse, $color, $amount)
$primary-color: #036
.header
background-color: invert($primary-color, 80%)
```
```
.header {
background-color: #523314;
}
```
### 💡 Fun fact:
Default values can be any SassScript expression, and they can even refer to earlier arguments!
### Keyword Arguments
When a function is called, arguments can be passed by name in addition to passing them by their position in the argument list. This is especially useful for functions with multiple optional arguments, or with [boolean](../values/booleans) arguments whose meanings aren’t obvious without a name to go with them. Keyword arguments use the same syntax as [variable declarations](../variables) and [optional arguments](#optional-arguments).
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
* [CSS](#example-3-css)
```
$primary-color: #036;
.banner {
background-color: $primary-color;
color: scale-color($primary-color, $lightness: +40%);
}
```
```
$primary-color: #036
.banner
background-color: $primary-color
color: scale-color($primary-color, $lightness: +40%)
```
```
.banner {
background-color: #036;
color: #0a85ff;
}
```
### ⚠️ Heads up!
Because *any* argument can be passed by name, be careful when renaming a function’s arguments… it might break your users! It can be helpful to keep the old name around as an [optional argument](#optional-arguments) for a while and printing a [warning](warn) if anyone passes it, so they know to migrate to the new argument.
### Taking Arbitrary Arguments
Sometimes it’s useful for a function to be able to take any number of arguments. If the last argument in a `@function` declaration ends in `...`, then all extra arguments to that function are passed to that argument as a [list](../values/lists). This argument is known as an [argument list](../values/lists#argument-lists).
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
* [CSS](#example-4-css)
```
@function sum($numbers...) {
$sum: 0;
@each $number in $numbers {
$sum: $sum + $number;
}
@return $sum;
}
.micro {
width: sum(50px, 30px, 100px);
}
```
```
@function sum($numbers...)
$sum: 0
@each $number in $numbers
$sum: $sum + $number
@return $sum
.micro
width: sum(50px, 30px, 100px)
```
```
.micro {
width: 180px;
}
```
#### Taking Arbitrary Keyword Arguments
Argument lists can also be used to take arbitrary keyword arguments. The [`meta.keywords()` function](../modules/meta#keywords) takes an argument list and returns any extra keywords that were passed to the function as a [map](../values/maps) from argument names (not including `$`) to those arguments’ values.
### 💡 Fun fact:
If you don’t ever pass an argument list to the [`meta.keywords()` function](../modules/meta#keywords), that argument list won’t allow extra keyword arguments. This helps callers of your function make sure they haven’t accidentally misspelled any argument names.
#### Passing Arbitrary Arguments
Just like argument lists allow functions to take arbitrary positional or keyword arguments, the same syntax can be used to *pass* positional and keyword arguments to a function. If you pass a list followed by `...` as the last argument of a function call, its elements will be treated as additional positional arguments. Similarly, a map followed by `...` will be treated as additional keyword arguments. You can even pass both at once!
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
* [CSS](#example-5-css)
```
$widths: 50px, 30px, 100px;
.micro {
width: min($widths...);
}
```
```
$widths: 50px, 30px, 100px
.micro
width: min($widths...)
```
```
.micro {
width: 30px;
}
```
### 💡 Fun fact:
Because an [argument list](../values/lists#argument-lists) keeps track of both positional and keyword arguments, you use it to pass both at once to another function. That makes it super easy to define an alias for a function!
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
```
@function fg($args...) {
@warn "The fg() function is deprecated. Call foreground() instead.";
@return foreground($args...);
}
```
```
@function fg($args...)
@warn "The fg() function is deprecated. Call foreground() instead."
@return foreground($args...)
```
`@return`
----------
The `@return` at-rule indicates the value to use as the result of calling a function. It’s only allowed within a `@function` body, and each `@function` must end with a `@return`.
When a `@return` is encountered, it immediately ends the function and returns its result. Returning early can be useful for handling edge-cases or cases where a more efficient algorithm is available without wrapping the entire function in an [`@else` block](control/if#else).
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
```
@use "sass:string";
@function str-insert($string, $insert, $index) {
// Avoid making new strings if we don't need to.
@if string.length($string) == 0 {
@return $insert;
}
$before: string.slice($string, 0, $index);
$after: string.slice($string, $index);
@return $before + $insert + $after;
}
```
```
@use "sass:string"
@function str-insert($string, $insert, $index)
// Avoid making new strings if we don't need to.
@if string.length($string) == 0
@return $insert
$before: string.slice($string, 0, $index)
$after: string.slice($string, $index)
@return $before + $insert + $after
```
Other Functions
----------------
In addition to user-defined function, Sass provides a substantial [core library](../modules) of built-in functions that are always available to use. Sass implementations also make it possible to define [custom functions](../js-api/interfaces/legacysharedoptions#functions) in the host language. And of course, you can always call [plain CSS functions](#plain-css-functions) (even ones with [weird syntax](../syntax/special-functions)).
### Plain CSS Functions
Any function call that’s not either a user-defined or [built-in](../modules) function is compiled to a plain CSS function (unless it uses [Sass argument syntax](function#arguments)). The arguments will be compiled to CSS and included as-is in the function call. This ensures that Sass supports all CSS functions without needing to release new versions every time a new one is added.
* [SCSS](#example-8-scss)
* [Sass](#example-8-sass)
```
@debug var(--main-bg-color); // var(--main-bg-color)
$primary: #f2ece4;
$accent: #e1d7d2;
@debug radial-gradient($primary, $accent); // radial-gradient(#f2ece4, #e1d7d2)
```
```
@debug var(--main-bg-color) // var(--main-bg-color)
$primary: #f2ece4
$accent: #e1d7d2
@debug radial-gradient($primary, $accent) // radial-gradient(#f2ece4, #e1d7d2)
```
### ⚠️ Heads up!
Because any unknown function will be compiled to CSS, it’s easy to miss when you typo a function name. Consider running a [CSS linter](https://stylelint.io/) on your stylesheet’s output to be notified when this happens!
### 💡 Fun fact:
Some CSS functions, like `calc()` and `element()` have unusual syntax. Sass [parses these functions specially](../syntax/special-functions) as [unquoted strings](../values/strings#unquoted).
sass @each @each
======
The `@each` rule makes it easy to emit styles or evaluate code for each element of a [list](../../values/lists) or each pair in a [map](../../values/maps). It’s great for repetitive styles that only have a few variations between them. It’s usually written `@each <variable> in <expression> { ... }`, where the [expression](../../syntax/structure#expressions) returns a list. The block is evaluated for each element of the list in turn, which is assigned to the given variable name.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
$sizes: 40px, 50px, 80px;
@each $size in $sizes {
.icon-#{$size} {
font-size: $size;
height: $size;
width: $size;
}
}
```
```
$sizes: 40px, 50px, 80px
@each $size in $sizes
.icon-#{$size}
font-size: $size
height: $size
width: $size
```
```
.icon-40px {
font-size: 40px;
height: 40px;
width: 40px;
}
.icon-50px {
font-size: 50px;
height: 50px;
width: 50px;
}
.icon-80px {
font-size: 80px;
height: 80px;
width: 80px;
}
```
With Maps
----------
You can also use `@each` to iterate over every key/value pair in a map by writing it `@each <variable>, <variable> in <expression> { ... }`. The key is assigned to the first variable name, and the element is assigned to the second.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
$icons: ("eye": "\f112", "start": "\f12e", "stop": "\f12f");
@each $name, $glyph in $icons {
.icon-#{$name}:before {
display: inline-block;
font-family: "Icon Font";
content: $glyph;
}
}
```
```
$icons: ("eye": "\f112", "start": "\f12e", "stop": "\f12f")
@each $name, $glyph in $icons
.icon-#{$name}:before
display: inline-block
font-family: "Icon Font"
content: $glyph
```
```
@charset "UTF-8";
.icon-eye:before {
display: inline-block;
font-family: "Icon Font";
content: "";
}
.icon-start:before {
display: inline-block;
font-family: "Icon Font";
content: "";
}
.icon-stop:before {
display: inline-block;
font-family: "Icon Font";
content: "";
}
```
Destructuring
--------------
If you have a list of lists, you can use `@each` to automatically assign variables to each of the values from the inner lists by writing it `@each <variable...> in <expression> { ... }`. This is known as *destructuring*, since the variables match the structure of the inner lists. Each variable name is assigned to the value at the corresponding position in the list, or [`null`](../../values/null) if the list doesn’t have enough values.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
* [CSS](#example-3-css)
```
$icons:
"eye" "\f112" 12px,
"start" "\f12e" 16px,
"stop" "\f12f" 10px;
@each $name, $glyph, $size in $icons {
.icon-#{$name}:before {
display: inline-block;
font-family: "Icon Font";
content: $glyph;
font-size: $size;
}
}
```
```
$icons: "eye" "\f112" 12px, "start" "\f12e" 16px, "stop" "\f12f" 10px
@each $name, $glyph, $size in $icons
.icon-#{$name}:before
display: inline-block
font-family: "Icon Font"
content: $glyph
font-size: $size
```
```
@charset "UTF-8";
.icon-eye:before {
display: inline-block;
font-family: "Icon Font";
content: "";
font-size: 12px;
}
.icon-start:before {
display: inline-block;
font-family: "Icon Font";
content: "";
font-size: 16px;
}
.icon-stop:before {
display: inline-block;
font-family: "Icon Font";
content: "";
font-size: 10px;
}
```
### 💡 Fun fact:
Because `@each` supports destructuring and [maps count as lists of lists](../../values/maps), `@each`‘s map support works without needing special support for maps in particular.
sass @while @while
=======
The `@while` rule, written `@while <expression> { ... }`, evaluates its block if its [expression](../../syntax/structure#expressions) returns `true`. Then, if its expression still returns `true`, it evaluates its block again. This continues until the expression finally returns `false`.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
@use "sass:math";
/// Divides `$value` by `$ratio` until it's below `$base`.
@function scale-below($value, $base, $ratio: 1.618) {
@while $value > $base {
$value: math.div($value, $ratio);
}
@return $value;
}
$normal-font-size: 16px;
sup {
font-size: scale-below(20px, 16px);
}
```
```
@use "sass:math"
/// Divides `$value` by `$ratio` until it's below `$base`.
@function scale-below($value, $base, $ratio: 1.618)
@while $value > $base
$value: math.div($value, $ratio)
@return $value
$normal-font-size: 16px
sup
font-size: scale-below(20px, 16px)
```
```
sup {
font-size: 12.36094px;
}
```
### ⚠️ Heads up!
Although `@while` is necessary for a few particularly complex stylesheets, you’re usually better of using either [`@each`](each) or [`@for`](for) if either of them will work. They’re clearer for the reader, and often faster to compile as well.
Truthiness and Falsiness
-------------------------
Anywhere `true` or `false` are allowed, you can use other values as well. The values `false` and [`null`](../../values/null) are *falsey*, which means Sass considers them to indicate falsehood and cause conditions to fail. Every other value is considered *truthy*, so Sass considers them to work like `true` and cause conditions to succeed.
For example, if you want to check if a string contains a space, you can just write `string.index($string, " ")`. The [`string.index()` function](../../modules/string#index) returns `null` if the string isn’t found and a number otherwise.
### ⚠️ Heads up!
Some languages consider more values falsey than just `false` and `null`. Sass isn’t one of those languages! Empty strings, empty lists, and the number `0` are all truthy in Sass.
sass @if and @else @if and @else
==============
The `@if` rule is written `@if <expression> { ... }`, and it controls whether or not its block gets evaluated (including emitting any styles as CSS). The [expression](../../syntax/structure#expressions) usually returns either [`true` or `false`](../../values/booleans)—if the expression returns `true`, the block is evaluated, and if the expression returns `false` it’s not.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
@mixin avatar($size, $circle: false) {
width: $size;
height: $size;
@if $circle {
border-radius: $size / 2;
}
}
.square-av {
@include avatar(100px, $circle: false);
}
.circle-av {
@include avatar(100px, $circle: true);
}
```
```
@mixin avatar($size, $circle: false)
width: $size
height: $size
@if $circle
border-radius: $size / 2
.square-av
@include avatar(100px, $circle: false)
.circle-av
@include avatar(100px, $circle: true)
```
```
.square-av {
width: 100px;
height: 100px;
}
.circle-av {
width: 100px;
height: 100px;
border-radius: 50px;
}
```
`@else`
--------
An `@if` rule can optionally be followed by an `@else` rule, written `@else { ... }`. This rule’s block is evaluated if the `@if` expression returns `false`.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
$light-background: #f2ece4;
$light-text: #036;
$dark-background: #6b717f;
$dark-text: #d2e1dd;
@mixin theme-colors($light-theme: true) {
@if $light-theme {
background-color: $light-background;
color: $light-text;
} @else {
background-color: $dark-background;
color: $dark-text;
}
}
.banner {
@include theme-colors($light-theme: true);
body.dark & {
@include theme-colors($light-theme: false);
}
}
```
```
$light-background: #f2ece4
$light-text: #036
$dark-background: #6b717f
$dark-text: #d2e1dd
@mixin theme-colors($light-theme: true)
@if $light-theme
background-color: $light-background
color: $light-text
@else
background-color: $dark-background
color: $dark-text
.banner
@include theme-colors($light-theme: true)
body.dark &
@include theme-colors($light-theme: false)
```
```
.banner {
background-color: #f2ece4;
color: #036;
}
body.dark .banner {
background-color: #6b717f;
color: #d2e1dd;
}
```
Conditional expressions may contain [boolean operators](../../operators/boolean) (`and`, `or`, `not`).
### `@else if`
You can also choose whether to evaluate an `@else` rule’s block by writing it `@else if <expression> { ... }`. If you do, the block is evaluated only if the preceding `@if`‘s expression returns `false` *and* the `@else if`’s expression returns `true`.
In fact, you can chain as many `@else if`s as you want after an `@if`. The first block in the chain whose expression returns `true` will be evaluated, and no others. If there’s a plain `@else` at the end of the chain, its block will be evaluated if every other block fails.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
* [CSS](#example-3-css)
```
@use "sass:math";
@mixin triangle($size, $color, $direction) {
height: 0;
width: 0;
border-color: transparent;
border-style: solid;
border-width: math.div($size, 2);
@if $direction == up {
border-bottom-color: $color;
} @else if $direction == right {
border-left-color: $color;
} @else if $direction == down {
border-top-color: $color;
} @else if $direction == left {
border-right-color: $color;
} @else {
@error "Unknown direction #{$direction}.";
}
}
.next {
@include triangle(5px, black, right);
}
```
```
@use "sass:math"
@mixin triangle($size, $color, $direction)
height: 0
width: 0
border-color: transparent
border-style: solid
border-width: math.div($size, 2)
@if $direction == up
border-bottom-color: $color
@else if $direction == right
border-left-color: $color
@else if $direction == down
border-top-color: $color
@else if $direction == left
border-right-color: $color
@else
@error "Unknown direction #{$direction}."
.next
@include triangle(5px, black, right)
```
```
.next {
height: 0;
width: 0;
border-color: transparent;
border-style: solid;
border-width: 2.5px;
border-left-color: black;
}
```
Truthiness and Falsiness
-------------------------
Anywhere `true` or `false` are allowed, you can use other values as well. The values `false` and [`null`](../../values/null) are *falsey*, which means Sass considers them to indicate falsehood and cause conditions to fail. Every other value is considered *truthy*, so Sass considers them to work like `true` and cause conditions to succeed.
For example, if you want to check if a string contains a space, you can just write `string.index($string, " ")`. The [`string.index()` function](../../modules/string#index) returns `null` if the string isn’t found and a number otherwise.
### ⚠️ Heads up!
Some languages consider more values falsey than just `false` and `null`. Sass isn’t one of those languages! Empty strings, empty lists, and the number `0` are all truthy in Sass.
| programming_docs |
sass @for @for
=====
The `@for` rule, written `@for <variable> from <expression> to <expression> { ... }` or `@for <variable> from <expression> through <expression> { ... }`, counts up or down from one number (the result of the first [expression](../../syntax/structure#expressions)) to another (the result of the second) and evaluates a block for each number in between. Each number along the way is assigned to the given variable name. If `to` is used, the final number is excluded; if `through` is used, it's included.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
$base-color: #036;
@for $i from 1 through 3 {
ul:nth-child(3n + #{$i}) {
background-color: lighten($base-color, $i * 5%);
}
}
```
```
$base-color: #036
@for $i from 1 through 3
ul:nth-child(3n + #{$i})
background-color: lighten($base-color, $i * 5%)
```
```
ul:nth-child(3n + 1) {
background-color: #004080;
}
ul:nth-child(3n + 2) {
background-color: #004d99;
}
ul:nth-child(3n + 3) {
background-color: #0059b3;
}
```
sass Numeric Operators Numeric Operators
==================
Sass supports the standard set of mathematical operators for [numbers](../values/numbers). They automatically convert between compatible units.
* `<expression> + <expression>` adds the first [expression](../syntax/structure#expressions)’s value to the second’s.
* `<expression> - <expression>` subtracts the first [expression](../syntax/structure#expressions)’s value from the second’s.
* `<expression> * <expression>` multiplies the first [expression](../syntax/structure#expressions)’s value by the second’s.
* `<expression> % <expression>` returns the remainder of the first [expression](../syntax/structure#expressions)’s value divided by the second’s. This is known as the [*modulo* operator](https://en.wikipedia.org/wiki/Modulo_operation).
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@debug 10s + 15s; // 25s
@debug 1in - 10px; // 0.8958333333in
@debug 5px * 3px; // 15px*px
@debug 1in % 9px; // 0.0625in
```
```
@debug 10s + 15s // 25s
@debug 1in - 10px // 0.8958333333in
@debug 5px * 3px // 15px*px
@debug 1in % 9px // 0.0625in
```
Unitless numbers can be used with numbers of any unit.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
```
@debug 100px + 50; // 150px
@debug 4s * 10; // 40s
```
```
@debug 100px + 50 // 150px
@debug 4s * 10 // 40s
```
Numbers with incompatible units can’t be used with addition, subtraction, or modulo.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
@debug 100px + 10s;
// ^^^^^^^^^^^
// Error: Incompatible units px and s.
```
```
@debug 100px + 10s
// ^^^^^^^^^^^
// Error: Incompatible units px and s.
```
Unary Operators
----------------
You can also write `+` and `-` as unary operators, which take only one value:
* `+<expression>` returns the expression’s value without changing it.
* `-<expression>` returns the negative version of the expression’s value.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
```
@debug +(5s + 7s); // 12s
@debug -(50px + 30px); // -80px
@debug -(10px - 15px); // 5px
```
```
@debug +(5s + 7s) // 12s
@debug -(50px + 30px) // -80px
@debug -(10px - 15px) // 5px
```
### ⚠️ Heads up!
Because `-` can refer to both subtraction and unary negation, it can be confusing which is which in a space-separated list. To be safe:
* Always write spaces on both sides of `-` when subtracting.
* Write a space before `-` but not after for a negative number or a unary negation.
* Wrap unary negation in parentheses if it’s in a space-separated list.
The different meanings of `-` in Sass take precedence in the following order:
1. `-` as part of an identifier. The only exception are units; Sass normally allows any valid identifier to be used as an identifier, but units may not contain a hyphen followed by a digit.
2. `-` between an expression and a literal number with no whitespace, which is parsed as subtraction.
3. `-` at the beginning of a literal number, which is parsed as a negative number.
4. `-` between two numbers regardless of whitespace, which is parsed as subtraction.
5. `-` before a value other than a literal number, which is parsed as unary negation.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
```
@debug a-1; // a-1
@debug 5px-3px; // 2px
@debug 5-3; // 2
@debug 1 -2 3; // 1 -2 3
$number: 2;
@debug 1 -$number 3; // -1 3
@debug 1 (-$number) 3; // 1 -2 3
```
```
@debug a-1 // a-1
@debug 5px-3px // 2px
@debug 5-3 // 2
@debug 1 -2 3 // 1 -2 3
$number: 2
@debug 1 -$number 3 // -1 3
@debug 1 (-$number) 3 // 1 -2 3
```
Division
---------
Compatibility (math.div()):
Dart Sass since 1.33.0
LibSass ✗
Ruby Sass ✗ Unlike other mathematical operations, division in Sass is done with the [`math.div()`](../modules/math#div) function. Although many programming languages use `/` as a division operator, in CSS `/` is used as a separator (as in `font: 15px/32px` or `hsl(120 100% 50% / 0.8)`). While Sass does support the use of `/` as a division operator, this is deprecated and [will be removed](https://sass-lang.com/documentation/breaking-changes/slash-div) in a future version.
### Slash-Separated Values
For the time being while Sass still supports `/` as a division operator, it has to have a way to disambiguate between `/` as a separator and `/` as division. In order to make this work, if two numbers are separated by `/`, Sass will print the result as slash-separated instead of divided unless one of these conditions is met:
* Either expression is anything other than a literal number.
* The result is stored in a variable or returned by a function.
* The operation is surrounded by parentheses, unless those parentheses are outside a list that contains the operation.
* The result is used as part of another operation (other than `/`).
You can use [`list.slash()`] to force `/` to be used as a separator.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
```
@use "sass:list";
@debug 15px / 30px; // 15px/30px
@debug (10px + 5px) / 30px; // 0.5
@debug list.slash(10px + 5px, 30px); // 15px/30px
$result: 15px / 30px;
@debug $result; // 0.5
@function fifteen-divided-by-thirty() {
@return 15px / 30px;
}
@debug fifteen-divided-by-thirty(); // 0.5
@debug (15px/30px); // 0.5
@debug (bold 15px/30px sans-serif); // bold 15px/30px sans-serif
@debug 15px/30px + 1; // 1.5
```
```
@use "sass:list";
@debug 15px / 30px // 15px/30px
@debug (10px + 5px) / 30px // 0.5
@debug list.slash(10px + 5px, 30px) // 15px/30px
$result: 15px / 30px
@debug $result // 0.5
@function fifteen-divided-by-thirty()
@return 15px / 30px
@debug fifteen-divided-by-thirty() // 0.5
@debug (15px/30px) // 0.5
@debug (bold 15px/30px sans-serif) // bold 15px/30px sans-serif
@debug 15px/30px + 1 // 1.5
```
Units
------
Sass has powerful support for manipulating units based on how [real-world unit calculations](https://en.wikipedia.org/wiki/Unit_of_measurement#Calculations_with_units_of_measurement) work. When two numbers are multiplied, their units are multiplied as well. When one number is divided by another, the result takes its numerator units from the first number and its denominator units from the second. A number can have any number of units in the numerator and/or denominator.
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
```
@debug 4px * 6px; // 24px*px (read "square pixels")
@debug math.div(5px, 2s); // 2.5px/s (read "pixels per second")
// 3.125px*deg/s*em (read "pixel-degrees per second-em")
@debug 5px * math.div(math.div(30deg, 2s), 24em);
$degrees-per-second: math.div(20deg, 1s);
@debug $degrees-per-second; // 20deg/s
@debug math.div(1, $degrees-per-second); // 0.05s/deg
```
```
@debug 4px * 6px // 24px*px (read "square pixels")
@debug math.div(5px, 2s) // 2.5px/s (read "pixels per second")
// 3.125px*deg/s*em (read "pixel-degrees per second-em")
@debug 5px * math.div(math.div(30deg, 2s), 24em)
$degrees-per-second: math.div(20deg, 1s)
@debug $degrees-per-second // 20deg/s
@debug math.div(1, $degrees-per-second) // 0.05s/deg
```
### ⚠️ Heads up!
Because CSS doesn’t support complex units like square pixels, using a number with complex units as a [property value](../style-rules/declarations) will produce an error. This is a feature in disguise, though; if you aren’t ending up with the right unit, it usually means that something’s wrong with your calculations! And remember, you can always use the [`@debug` rule](../at-rules/debug) to check out the units of any variable or [expression](../syntax/structure#expressions).
Sass will automatically convert between compatible units, although which unit it will choose for the result depends on which implementation of Sass you’re using.If you try to combine incompatible units, like `1in + 1em`, Sass will throw an error.
* [SCSS](#example-8-scss)
* [Sass](#example-8-sass)
```
// CSS defines one inch as 96 pixels.
@debug 1in + 6px; // 102px or 1.0625in
@debug 1in + 1s;
// ^^^^^^^^
// Error: Incompatible units s and in.
```
```
// CSS defines one inch as 96 pixels.
@debug 1in + 6px // 102px or 1.0625in
@debug 1in + 1s
// ^^^^^^^^
// Error: Incompatible units s and in.
```
As in real-world unit calculations, if the numerator contains units that are compatible with units in the denominator (like `math.div(96px, 1in)`), they’ll cancel out. This makes it easy to define a ratio that you can use for converting between units. In the example below, we set the desired speed to one second per 50 pixels, and then multiply that by the number of pixels the transition covers to get the time it should take.
* [SCSS](#example-9-scss)
* [Sass](#example-9-sass)
* [CSS](#example-9-css)
```
$transition-speed: math.div(1s, 50px);
@mixin move($left-start, $left-stop) {
position: absolute;
left: $left-start;
transition: left ($left-stop - $left-start) * $transition-speed;
&:hover {
left: $left-stop;
}
}
.slider {
@include move(10px, 120px);
}
```
```
$transition-speed: math.div(1s, 50px)
@mixin move($left-start, $left-stop)
position: absolute
left: $left-start
transition: left ($left-stop - $left-start) * $transition-speed
&:hover
left: $left-stop
.slider
@include move(10px, 120px)
```
```
.slider {
position: absolute;
left: 10px;
transition: left 2.2s;
}
.slider:hover {
left: 120px;
}
```
### ⚠️ Heads up!
If your arithmetic gives you the wrong unit, you probably need to check your math. You may be leaving off units for a quantity that should have them! Staying unit-clean allows Sass to give you helpful errors when something isn’t right.
You should especially avoid using interpolation like `#{$number}px`. This doesn’t actually create a number! It creates an [unquoted string](../values/strings#unquoted) that *looks* like a number, but won’t work with any [number operations](numeric) or [functions](../modules/math). Try to make your math unit-clean so that `$number` already has the unit `px`, or write `$number * 1px`.
### ⚠️ Heads up!
Percentages in Sass work just like every other unit. They are *not* interchangeable with decimals, because in CSS decimals and percentages mean different things. For example, `50%` is a number with `%` as its unit, and Sass considers it different than the number `0.5`.
You can convert between decimals and percentages using unit arithmetic. `math.div($percentage, 100%)` will return the corresponding decimal, and `$decimal * 100%` will return the corresponding percentage. You can also use the [`math.percentage()` function](../modules/math#percentage) as a more explicit way of writing `$decimal * 100%`.
sass Equality Operators Equality Operators
===================
Compatibility (Unitless Equality):
Dart Sass ✓
LibSass ✗
Ruby Sass since 4.0.0 (unreleased) [▶](javascript:;) LibSass and older versions of Ruby Sass consider numbers without units to be equal to the same numbers with any units. This behavior was deprecated and has been removed from more recently releases because it violates [transitivity](https://en.wikipedia.org/wiki/Transitive_relation).
The equality operators return whether or not two values are the same. They’re written `<expression> == <expression>`, which returns whether two [expressions](../syntax/structure#expressions) are equal, and `<expression> != <expression>`, which returns whether two expressions are *not* equal. Two values are considered equal if they’re the same type *and* the same value, which means different things for different types:
* [Numbers](../values/numbers) are equal if they have the same value *and* the same units, or if their values are equal when their units are converted between one another.
* [Strings](../values/strings) are unusual in that [unquoted](../values/strings#unquoted) and [quoted](../values/strings#quoted) strings with the same contents are considered equal.
* [Colors](../values/colors) are equal if they have the same red, green, blue, and alpha values.
* [Lists](../values/lists) are equal if their contents are equal. Comma-separated lists aren’t equal to space-separated lists, and bracketed lists aren’t equal to unbracketed lists.
* [Maps](../values/maps) are equal if their keys and values are both equal.
* [Calculations](../values/calculations) are equal if their names and arguments are all equal. Operation arguments are compared textually.
* [`true`, `false`](../values/booleans), and [`null`](../values/null) are only equal to themselves.
* [Functions](../values/functions) are equal to the same function. Functions are compared *by reference*, so even if two functions have the same name and definition they’re considered different if they aren’t defined in the same place.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@debug 1px == 1px; // true
@debug 1px != 1em; // true
@debug 1 != 1px; // true
@debug 96px == 1in; // true
@debug "Helvetica" == Helvetica; // true
@debug "Helvetica" != "Arial"; // true
@debug hsl(34, 35%, 92.1%) == #f2ece4; // true
@debug rgba(179, 115, 153, 0.5) != rgba(179, 115, 153, 0.8); // true
@debug (5px 7px 10px) == (5px 7px 10px); // true
@debug (5px 7px 10px) != (10px 14px 20px); // true
@debug (5px 7px 10px) != (5px, 7px, 10px); // true
@debug (5px 7px 10px) != [5px 7px 10px]; // true
$theme: ("venus": #998099, "nebula": #d2e1dd);
@debug $theme == ("venus": #998099, "nebula": #d2e1dd); // true
@debug $theme != ("venus": #998099, "iron": #dadbdf); // true
@debug true == true; // true
@debug true != false; // true
@debug null != false; // true
@debug get-function("rgba") == get-function("rgba"); // true
@debug get-function("rgba") != get-function("hsla"); // true
```
```
@debug 1px == 1px // true
@debug 1px != 1em // true
@debug 1 != 1px // true
@debug 96px == 1in // true
@debug "Helvetica" == Helvetica // true
@debug "Helvetica" != "Arial" // true
@debug hsl(34, 35%, 92.1%) == #f2ece4 // true
@debug rgba(179, 115, 153, 0.5) != rgba(179, 115, 153, 0.8) // true
@debug (5px 7px 10px) == (5px 7px 10px) // true
@debug (5px 7px 10px) != (10px 14px 20px) // true
@debug (5px 7px 10px) != (5px, 7px, 10px) // true
@debug (5px 7px 10px) != [5px 7px 10px] // true
$theme: ("venus": #998099, "nebula": #d2e1dd)
@debug $theme == ("venus": #998099, "nebula": #d2e1dd) // true
@debug $theme != ("venus": #998099, "iron": #dadbdf) // true
@debug calc(10px + 10%) == calc(10px + 10%) // true
@debug calc(10% + 10px) == calc(10px + 10%) // false
@debug true == true // true
@debug true != false // true
@debug null != false // true
@debug get-function("rgba") == get-function("rgba") // true
@debug get-function("rgba") != get-function("hsla") // true
```
sass String Operators String Operators
=================
Sass supports a few operators that generate [strings](../values/strings):
* `<expression> + <expression>` returns a string that contains both expressions’ values. If the either value is a [quoted string](../values/strings#quoted), the result will be quoted; otherwise, it will be unquoted.
* `<expression> - <expression>` returns an unquoted string that contains both expressions’ values, separated by `-`. This is a legacy operator, and [interpolation](../interpolation) should generally be used instead.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@debug "Helvetica" + " Neue"; // "Helvetica Neue"
@debug sans- + serif; // sans-serif
@debug sans - serif; // sans-serif
```
```
@debug "Helvetica" + " Neue" // "Helvetica Neue"
@debug sans- + serif // sans-serif
@debug sans - serif // sans-serif
```
These operators don’t just work for strings! They can be used with any values that can be written to CSS, with a few exceptions:
* Numbers can’t be used as the left-hand value, because they have [their own operators](numeric).
* Colors can’t be used as the left-hand value, because they used to have [their own operators](../operators).
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
```
@debug "Elapsed time: " + 10s; // "Elapsed time: 10s";
@debug true + " is a boolean value"; // "true is a boolean value";
```
```
@debug "Elapsed time: " + 10s // "Elapsed time: 10s";
@debug true + " is a boolean value" // "true is a boolean value";
```
### ⚠️ Heads up!
It’s often cleaner and clearer to use [interpolation](../interpolation) to create strings, rather than relying on this operators.
Unary Operators
----------------
For historical reasons, Sass also supports `/` and `-` as a unary operators which take only one value:
* `/<expression>` returns an unquoted string starting with `/` and followed by the expression’s value.
* `-<expression>` returns an unquoted string starting with `-` and followed by the expression’s value.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
@debug / 15px; // /15px
@debug - moz; // -moz
```
```
@debug / 15px // /15px
@debug - moz // -moz
```
sass Relational Operators Relational Operators
=====================
Relational operators determine whether [numbers](../values/numbers) are larger or smaller than one another. They automatically convert between compatible units.
* `<expression> < <expression>` returns whether the first [expression](../syntax/structure#expressions)’s value is less than the second’s.
* `<expression> <= <expression>` returns whether the first [expression](../syntax/structure#expressions)’s value is less than or equal to the second’s.
* `<expression> > <expression>` returns whether the first [expression](../syntax/structure#expressions)’s value is greater than to the second’s.
* `<expression> >= <expression>`, returns whether the first [expression](../syntax/structure#expressions)’s value is greater than or equal to the second’s.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@debug 100 > 50; // true
@debug 10px < 17px; // true
@debug 96px >= 1in; // true
@debug 1000ms <= 1s; // true
```
```
@debug 100 > 50 // true
@debug 10px < 17px // true
@debug 96px >= 1in // true
@debug 1000ms <= 1s // true
```
Unitless numbers can be compared with any number. They’re automatically converted to that number’s unit.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
```
@debug 100 > 50px; // true
@debug 10px < 17; // true
```
```
@debug 100 > 50px // true
@debug 10px < 17 // true
```
Numbers with incompatible units can’t be compared.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
@debug 100px > 10s;
// ^^^^^^^^^^^
// Error: Incompatible units px and s.
```
```
@debug 100px > 10s
// ^^^^^^^^^^^
// Error: Incompatible units px and s.
```
sass Boolean Operators Boolean Operators
==================
Unlike languages like JavaScript, Sass uses words rather than symbols for its [boolean](../values/booleans) operators.
* `not <expression>` returns the opposite of the expression’s value: it turns `true` into `false` and `false` into `true`.
* `<expression> and <expression>` returns `true` if *both* expressions’ values are `true`, and `false` if either is `false`.
* `<expression> or <expression>` returns `true` if *either* expression’s value is `true`, and `false` if both are `false`.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@debug not true; // false
@debug not false; // true
@debug true and true; // true
@debug true and false; // false
@debug true or false; // true
@debug false or false; // false
```
```
@debug not true // false
@debug not false // true
@debug true and true // true
@debug true and false // false
@debug true or false // true
@debug false or false // false
```
Truthiness and Falsiness
-------------------------
Anywhere `true` or `false` are allowed, you can use other values as well. The values `false` and [`null`](../values/null) are *falsey*, which means Sass considers them to indicate falsehood and cause conditions to fail. Every other value is considered *truthy*, so Sass considers them to work like `true` and cause conditions to succeed.
For example, if you want to check if a string contains a space, you can just write `string.index($string, " ")`. The [`string.index()` function](../modules/string#index) returns `null` if the string isn’t found and a number otherwise.
### ⚠️ Heads up!
Some languages consider more values falsey than just `false` and `null`. Sass isn’t one of those languages! Empty strings, empty lists, and the number `0` are all truthy in Sass.
| programming_docs |
sass sass Index
-----
### Compile
* [CompileResult](interfaces/compileresult)
* [compile](modules#compile)
* [compileAsync](modules#compileAsync)
* [compileString](modules#compileString)
* [compileStringAsync](modules#compileStringAsync)
### Options
* [Options](interfaces/options)
* [StringOptionsWithImporter](interfaces/stringoptionswithimporter)
* [StringOptionsWithoutImporter](interfaces/stringoptionswithoutimporter)
* [OutputStyle](modules#OutputStyle)
* [StringOptions](modules#StringOptions)
* [Syntax](modules#Syntax)
### Logger
* [Logger](modules/logger)
* [Logger](interfaces/logger)
* [SourceLocation](interfaces/sourcelocation)
* [SourceSpan](interfaces/sourcespan)
### Importer
* [FileImporter](interfaces/fileimporter)
* [Importer](interfaces/importer)
* [ImporterResult](interfaces/importerresult)
### Custom Function
* [SassArgumentList](classes/sassargumentlist)
* [SassBoolean](classes/sassboolean)
* [SassColor](classes/sasscolor)
* [SassFunction](classes/sassfunction)
* [SassList](classes/sasslist)
* [SassMap](classes/sassmap)
* [SassNumber](classes/sassnumber)
* [SassString](classes/sassstring)
* [Value](classes/value)
* [CustomFunction](modules#CustomFunction)
* [ListSeparator](modules#ListSeparator)
* [sassFalse](modules#sassFalse)
* [sassNull](modules#sassNull)
* [sassTrue](modules#sassTrue)
### Other
* [Exception](classes/exception)
* [LegacyFileOptions](interfaces/legacyfileoptions)
* [PromiseOr](modules#PromiseOr)
* [info](modules#info)
### Legacy
* [types](modules/types)
* [LegacyException](interfaces/legacyexception)
* [LegacyImporterThis](interfaces/legacyimporterthis)
* [LegacyPluginThis](interfaces/legacypluginthis)
* [LegacyResult](interfaces/legacyresult)
* [LegacySharedOptions](interfaces/legacysharedoptions)
* [LegacyStringOptions](interfaces/legacystringoptions)
* [LegacyAsyncFunction](modules#LegacyAsyncFunction)
* [LegacyAsyncFunctionDone](modules#LegacyAsyncFunctionDone)
* [LegacyAsyncImporter](modules#LegacyAsyncImporter)
* [LegacyFunction](modules#LegacyFunction)
* [LegacyImporter](modules#LegacyImporter)
* [LegacyImporterResult](modules#LegacyImporterResult)
* [LegacyOptions](modules#LegacyOptions)
* [LegacySyncFunction](modules#LegacySyncFunction)
* [LegacySyncImporter](modules#LegacySyncImporter)
* [LegacyValue](modules#LegacyValue)
* [FALSE](modules#FALSE)
* [NULL](modules#NULL)
* [TRUE](modules#TRUE)
* [render](modules#render)
* [renderSync](modules#renderSync)
Compile
-------
### compile
* compile(path: string, options?: [Options](interfaces/options)<"sync">): [CompileResult](interfaces/compileresult)
* Compatibility:
Dart Sass since 1.45.0
Node Sass ✗ Synchronously compiles the Sass file at `path` to CSS. If it succeeds it returns a [CompileResult](interfaces/compileresult), and if it fails it throws an [Exception](classes/exception).
This only allows synchronous [Importer](interfaces/importer)s and [CustomFunction](modules#CustomFunction)s.
example
```
constsass = require('sass');
constresult = sass.compile("style.scss");
console.log(result.css);
```
#### Parameters
+ ##### path: string
+ #####
Optional options: [Options](interfaces/options)<"sync">#### Returns [CompileResult](interfaces/compileresult)
### compileAsync
* compileAsync(path: string, options?: [Options](interfaces/options)<"async">): Promise<[CompileResult](interfaces/compileresult)>
* Compatibility:
Dart Sass since 1.45.0
Node Sass ✗ Asynchronously compiles the Sass file at `path` to CSS. Returns a promise that resolves with a [CompileResult](interfaces/compileresult) if it succeeds and rejects with an [Exception](classes/exception) if it fails.
This only allows synchronous or asynchronous [Importer](interfaces/importer)s and [CustomFunction](modules#CustomFunction)s.
### ⚠️ Heads up!
When using Dart Sass, **[compile](modules#compile) is almost twice as fast as [compileAsync](modules#compileAsync)**, due to the overhead of making the entire evaluation process asynchronous.
example
```
constsass = require('sass');
constresult = awaitsass.compileAsync("style.scss");
console.log(result.css);
```
#### Parameters
+ ##### path: string
+ #####
Optional options: [Options](interfaces/options)<"async">#### Returns Promise<[CompileResult](interfaces/compileresult)>
### compileString
* compileString(source: string, options?: [StringOptions](modules#StringOptions)<"sync">): [CompileResult](interfaces/compileresult)
* Compatibility:
Dart Sass since 1.45.0
Node Sass ✗ Synchronously compiles a stylesheet whose contents is `source` to CSS. If it succeeds it returns a [CompileResult](interfaces/compileresult), and if it fails it throws an [Exception](classes/exception).
This only allows synchronous [Importer](interfaces/importer)s and [CustomFunction](modules#CustomFunction)s.
example
```
constsass = require('sass');
constresult = sass.compileString(`
h1 {
font-size: 40px;
code {
font-face: Roboto Mono;
}
}`);
console.log(result.css);
```
#### Parameters
+ ##### source: string
+ #####
Optional options: [StringOptions](modules#StringOptions)<"sync">#### Returns [CompileResult](interfaces/compileresult)
### compileStringAsync
* compileStringAsync(source: string, options?: [StringOptions](modules#StringOptions)<"async">): Promise<[CompileResult](interfaces/compileresult)>
* Compatibility:
Dart Sass since 1.45.0
Node Sass ✗ Asynchronously compiles a stylesheet whose contents is `source` to CSS. Returns a promise that resolves with a [CompileResult](interfaces/compileresult) if it succeeds and rejects with an [Exception](classes/exception) if it fails.
This only allows synchronous or asynchronous [Importer](interfaces/importer)s and [CustomFunction](modules#CustomFunction)s.
### ⚠️ Heads up!
When using Dart Sass, **[compile](modules#compile) is almost twice as fast as [compileAsync](modules#compileAsync)**, due to the overhead of making the entire evaluation process asynchronous.
example
```
constsass = require('sass');
constresult = awaitsass.compileStringAsync(`
h1 {
font-size: 40px;
code {
font-face: Roboto Mono;
}
}`);
console.log(result.css);
```
#### Parameters
+ ##### source: string
+ #####
Optional options: [StringOptions](modules#StringOptions)<"async">#### Returns Promise<[CompileResult](interfaces/compileresult)>
Options
-------
### OutputStyle
OutputStyle: "expanded" | "compressed"
Possible output styles for the compiled CSS:
* `"expanded"` (the default for Dart Sass) writes each selector and declaration on its own line.
* `"compressed"` removes as many extra characters as possible, and writes the entire stylesheet on a single line.
### StringOptions
StringOptions<sync>: [StringOptionsWithImporter](interfaces/stringoptionswithimporter)<sync> | [StringOptionsWithoutImporter](interfaces/stringoptionswithoutimporter)<sync>
Options that can be passed to [compileString](modules#compileString) or [compileStringAsync](modules#compileStringAsync).
This is a [StringOptionsWithImporter](interfaces/stringoptionswithimporter) if it has a [StringOptionsWithImporter.importer](interfaces/stringoptionswithimporter#importer) field, and a [StringOptionsWithoutImporter](interfaces/stringoptionswithoutimporter) otherwise.
#### Type parameters
* #### sync: "sync" | "async"
This lets the TypeScript checker verify that asynchronous [Importer](interfaces/importer)s, [FileImporter](interfaces/fileimporter)s, and [CustomFunction](modules#CustomFunction)s aren't passed to [compile](modules#compile) or [compileString](modules#compileString).
### Syntax
Syntax: "scss" | "indented" | "css"
Syntaxes supported by Sass:
* `'scss'` is the [SCSS syntax](../syntax#scss).
* `'indented'` is the [indented syntax](../syntax#the-indented-syntax)
* `'css'` is plain CSS, which is parsed like SCSS but forbids the use of any special Sass features.
Custom Function
---------------
### CustomFunction
CustomFunction<sync>: (args: [Value](classes/value)[]) => [PromiseOr](modules#PromiseOr)<[Value](classes/value), sync>
#### Type parameters
* #### sync: "sync" | "async"
A `CustomFunction<'sync'>` must return synchronously, but in return it can be passed to [compile](modules#compile) and [compileString](modules#compileString) in addition to [compileAsync](modules#compileAsync) and [compileStringAsync](modules#compileStringAsync).
A `CustomFunction<'async'>` may either return synchronously or asynchronously, but it can only be used with [compileAsync](modules#compileAsync) and [compileStringAsync](modules#compileStringAsync).
#### Type declaration
* + (args: [Value](classes/value)[]): [PromiseOr](modules#PromiseOr)<[Value](classes/value), sync>
+ A callback that implements a custom Sass function. This can be passed to [Options.functions](interfaces/options#functions).
```
constresult = sass.compile('style.scss', {
functions: {
"sum($arg1, $arg2)": (args) => {
constarg1 = args[0].assertNumber('arg1');
constvalue1 = arg1.value;
constvalue2 = args[1].assertNumber('arg2')
.convertValueToMatch(arg1, 'arg2', 'arg1');
returnnewsass.SassNumber(value1 + value2).coerceToMatch(arg1);
}
}
});
```
throws
any - This function may throw an error, which the Sass compiler will treat as the function call failing. If the exception object has a `message` property, it will be used as the wrapped exception's message; otherwise, the exception object's `toString()` will be used. This means it's safe for custom functions to throw plain strings.
#### Parameters
- ##### args: [Value](classes/value)[]
An array of arguments passed by the function's caller. If the function takes [arbitrary arguments](../at-rules/function#taking-arbitrary-arguments), the last element will be a [SassArgumentList](classes/sassargumentlist).#### Returns [PromiseOr](modules#PromiseOr)<[Value](classes/value), sync>
The function's result. This may be in the form of a `Promise`, but if it is the function may only be passed to [compileAsync](modules#compileAsync) and [compileStringAsync](modules#compileStringAsync), not [compile](modules#compile) or [compileString](modules#compileString).
### ListSeparator
ListSeparator: "," | "/" | " " | null
Possible separators used by Sass lists. The special separator `null` is only used for lists with fewer than two elements, and indicates that the separator has not yet been decided for this list.
### sassFalse
sassFalse: [SassBoolean](classes/sassboolean)
Sass's [`false` value](../values/booleans).
### sassNull
sassNull: [Value](classes/value)
Sass's [`null` value](../values/null).
### sassTrue
sassTrue: [SassBoolean](classes/sassboolean)
Sass's [`true` value](../values/booleans).
Other
-----
### PromiseOr
PromiseOr<T, sync>: sync extends "async" ? T | Promise<T> : T
A utility type for choosing between synchronous and asynchronous return values.
This is used as the return value for plugins like [CustomFunction](modules#CustomFunction), [Importer](interfaces/importer), and [FileImporter](interfaces/fileimporter) so that TypeScript enforces that asynchronous plugins are only passed to [compileAsync](modules#compileAsync) and [compileStringAsync](modules#compileStringAsync), not [compile](modules#compile) or [compileString](modules#compileString).
#### Type parameters
* #### T
* #### sync: "sync" | "async"
If this is `'sync'`, this can only be a `T`. If it's `'async'`, this can be either a `T` or a `Promise<T>`.
### info
info: string
Information about the Sass implementation. This always begins with a unique identifier for the Sass implementation, followed by U+0009 TAB, followed by its npm package version. Some implementations include additional information as well, but not in any standardized format.
* For Dart Sass, the implementation name is `dart-sass`.
* For Node Sass, the implementation name is `node-sass`.
* For the embedded host, the implementation name is `sass-embedded`.
Legacy
------
### LegacyAsyncFunction
LegacyAsyncFunction: ((this: [LegacyPluginThis](interfaces/legacypluginthis), done: (result: [LegacyValue](modules#LegacyValue)) => void) => void) | ((this: [LegacyPluginThis](interfaces/legacypluginthis), arg1: [LegacyValue](modules#LegacyValue), done: [LegacyAsyncFunctionDone](modules#LegacyAsyncFunctionDone)) => void) | ((this: [LegacyPluginThis](interfaces/legacypluginthis), arg1: [LegacyValue](modules#LegacyValue), arg2: [LegacyValue](modules#LegacyValue), done: [LegacyAsyncFunctionDone](modules#LegacyAsyncFunctionDone)) => void) | ((this: [LegacyPluginThis](interfaces/legacypluginthis), arg1: [LegacyValue](modules#LegacyValue), arg2: [LegacyValue](modules#LegacyValue), arg3: [LegacyValue](modules#LegacyValue), done: [LegacyAsyncFunctionDone](modules#LegacyAsyncFunctionDone)) => void) | ((this: [LegacyPluginThis](interfaces/legacypluginthis), arg1: [LegacyValue](modules#LegacyValue), arg2: [LegacyValue](modules#LegacyValue), arg3: [LegacyValue](modules#LegacyValue), arg4: [LegacyValue](modules#LegacyValue), done: [LegacyAsyncFunctionDone](modules#LegacyAsyncFunctionDone)) => void) | ((this: [LegacyPluginThis](interfaces/legacypluginthis), arg1: [LegacyValue](modules#LegacyValue), arg2: [LegacyValue](modules#LegacyValue), arg3: [LegacyValue](modules#LegacyValue), arg4: [LegacyValue](modules#LegacyValue), arg5: [LegacyValue](modules#LegacyValue), done: [LegacyAsyncFunctionDone](modules#LegacyAsyncFunctionDone)) => void) | ((this: [LegacyPluginThis](interfaces/legacypluginthis), arg1: [LegacyValue](modules#LegacyValue), arg2: [LegacyValue](modules#LegacyValue), arg3: [LegacyValue](modules#LegacyValue), arg4: [LegacyValue](modules#LegacyValue), arg5: [LegacyValue](modules#LegacyValue), arg6: [LegacyValue](modules#LegacyValue), done: [LegacyAsyncFunctionDone](modules#LegacyAsyncFunctionDone)) => void) | ((this: [LegacyPluginThis](interfaces/legacypluginthis), …args: […[LegacyValue](modules#LegacyValue)[], [LegacyAsyncFunctionDone](modules#LegacyAsyncFunctionDone)]) => void)
An asynchronous callback that implements a custom Sass function. This can be passed to [LegacySharedOptions.functions](interfaces/legacysharedoptions#functions), but only for [render](modules#render).
An asynchronous function must return `undefined`. Its final argument will always be a callback, which it should call with the result of the function once it's done running.
If this throws an error, Sass will treat that as the function failing with that error message.
```
sass.render({
file:'style.scss',
functions: {
"sum($arg1, $arg2)": (arg1, arg2, done) => {
if (!(arg1instanceofsass.types.Number)) {
thrownewError("$arg1: Expected a number");
} elseif (!(arg2instanceofsass.types.Number)) {
thrownewError("$arg2: Expected a number");
}
done(newsass.types.Number(arg1.getValue() + arg2.getValue()));
}
}
}, (result, error) => {
// ...
});
```
This is passed one argument for each argument that's declared in the signature that's passed to [LegacySharedOptions.functions](interfaces/legacysharedoptions#functions). If the signature [takes arbitrary arguments](../at-rules/function#taking-arbitrary-arguments), they're passed as a single argument list in the last argument before the callback.
deprecated
This only works with the legacy [render](modules#render) and [renderSync](modules#renderSync) APIs. Use [CustomFunction](modules#CustomFunction) with [compile](modules#compile), [compileString](modules#compileString), [compileAsync](modules#compileAsync), and [compileStringAsync](modules#compileStringAsync) instead.
### LegacyAsyncFunctionDone
LegacyAsyncFunctionDone: (result: [LegacyValue](modules#LegacyValue) | [Error](classes/types.error)) => void
#### Type declaration
* + (result: [LegacyValue](modules#LegacyValue) | [Error](classes/types.error)): void
+ The function called by a [LegacyAsyncFunction](modules#LegacyAsyncFunction) to indicate that it's finished.
deprecated
This only works with the legacy [render](modules#render) and [renderSync](modules#renderSync) APIs. Use [CustomFunction](modules#CustomFunction) with [compile](modules#compile), [compileString](modules#compileString), [compileAsync](modules#compileAsync), and [compileStringAsync](modules#compileStringAsync) instead.
#### Parameters
- ##### result: [LegacyValue](modules#LegacyValue) | [Error](classes/types.error)
If this is a [LegacyValue](modules#LegacyValue), that indicates that the function call completed successfully. If it's a [types.Error](classes/types.error), that indicates that the function call failed.#### Returns void
### LegacyAsyncImporter
LegacyAsyncImporter: (this: [LegacyImporterThis](interfaces/legacyimporterthis), url: string, prev: string, done: (result: [LegacyImporterResult](modules#LegacyImporterResult)) => void) => void
#### Type declaration
* + (this: [LegacyImporterThis](interfaces/legacyimporterthis), url: string, prev: string, done: (result: [LegacyImporterResult](modules#LegacyImporterResult)) => void): void
+ An asynchronous callback that implements custom Sass loading logic for [`@import` rules](../at-rules/import) and [`@use` rules](../at-rules/use). This can be passed to [LegacySharedOptions.importer](interfaces/legacysharedoptions#importer) for either [render](modules#render) or [renderSync](modules#renderSync).
An asynchronous importer must return `undefined`, and then call `done` with the result of its [LegacyImporterResult](modules#LegacyImporterResult) once it's done running.
See [LegacySharedOptions.importer](interfaces/legacysharedoptions#importer) for more detailed documentation.
```
sass.render({
file:"style.scss",
importer: [
function(url, prev, done) {
if (url != "big-headers") done(null);
done({
contents:'h1 { font-size: 40px; }'
});
}
]
});
```
deprecated
This only works with the legacy [render](modules#render) and [renderSync](modules#renderSync) APIs. Use [Importer](interfaces/importer) with [compile](modules#compile), [compileString](modules#compileString), [compileAsync](modules#compileAsync), and [compileStringAsync](modules#compileStringAsync) instead.
#### Parameters
- ##### this: [LegacyImporterThis](interfaces/legacyimporterthis)
- ##### url: string
The `@use` or `@import` rule’s URL as a string, exactly as it appears in the stylesheet.
- ##### prev: string
A string identifying the stylesheet that contained the `@use` or `@import`. This string’s format depends on how that stylesheet was loaded:
* If the stylesheet was loaded from the filesystem, it’s the absolute path of its file.
* If the stylesheet was loaded from an importer that returned its contents, it’s the URL of the `@use` or `@import` rule that loaded it.
* If the stylesheet came from the data option, it’s the string "stdin".
- ##### done: (result: [LegacyImporterResult](modules#LegacyImporterResult)) => void
The callback to call once the importer has finished running.
* + (result: [LegacyImporterResult](modules#LegacyImporterResult)): void
+ #### Parameters
- ##### result: [LegacyImporterResult](modules#LegacyImporterResult)#### Returns void#### Returns void
### LegacyFunction
LegacyFunction<sync>: sync extends "async" ? [LegacySyncFunction](modules#LegacySyncFunction) | [LegacyAsyncFunction](modules#LegacyAsyncFunction) : [LegacySyncFunction](modules#LegacySyncFunction)
A callback that implements a custom Sass function. For [renderSync](modules#renderSync), this must be a [LegacySyncFunction](modules#LegacySyncFunction) which returns its result directly; for [render](modules#render), it may be either a [LegacySyncFunction](modules#LegacySyncFunction) or a [LegacyAsyncFunction](modules#LegacyAsyncFunction) which calls a callback with its result.
See [LegacySharedOptions.functions](interfaces/legacysharedoptions#functions) for more details.
deprecated
This only works with the legacy [render](modules#render) and [renderSync](modules#renderSync) APIs. Use [CustomFunction](modules#CustomFunction) with [compile](modules#compile), [compileString](modules#compileString), [compileAsync](modules#compileAsync), and [compileStringAsync](modules#compileStringAsync) instead.
#### Type parameters
* #### sync: "sync" | "async"
### LegacyImporter
LegacyImporter<sync>: sync extends "async" ? [LegacySyncImporter](modules#LegacySyncImporter) | [LegacyAsyncImporter](modules#LegacyAsyncImporter) : [LegacySyncImporter](modules#LegacySyncImporter)
A callback that implements custom Sass loading logic for [`@import` rules](../at-rules/import) and [`@use` rules](../at-rules/use). For [renderSync](modules#renderSync), this must be a [LegacySyncImporter](modules#LegacySyncImporter) which returns its result directly; for [render](modules#render), it may be either a [LegacySyncImporter](modules#LegacySyncImporter) or a [LegacyAsyncImporter](modules#LegacyAsyncImporter) which calls a callback with its result.
See [LegacySharedOptions.importer](interfaces/legacysharedoptions#importer) for more details.
deprecated
This only works with the legacy [render](modules#render) and [renderSync](modules#renderSync) APIs. Use [Importer](interfaces/importer) with [compile](modules#compile), [compileString](modules#compileString), [compileAsync](modules#compileAsync), and [compileStringAsync](modules#compileStringAsync) instead.
#### Type parameters
* #### sync = "sync" | "async"
### LegacyImporterResult
LegacyImporterResult: { file: string } | { contents: string } | Error | null
The result of running a [LegacyImporter](modules#LegacyImporter). It must be one of the following types:
* An object with the key `contents` whose value is the contents of a stylesheet (in SCSS syntax). This causes Sass to load that stylesheet’s contents.
* An object with the key `file` whose value is a path on disk. This causes Sass to load that file as though it had been imported directly.
* `null`, which indicates that it doesn’t recognize the URL and another importer should be tried instead.
* An [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, indicating that importing failed.
deprecated
This only works with the legacy [render](modules#render) and [renderSync](modules#renderSync) APIs. Use [ImporterResult](interfaces/importerresult) with [compile](modules#compile), [compileString](modules#compileString), [compileAsync](modules#compileAsync), and [compileStringAsync](modules#compileStringAsync) instead.
### LegacyOptions
LegacyOptions<sync>: [LegacyFileOptions](interfaces/legacyfileoptions)<sync> | [LegacyStringOptions](interfaces/legacystringoptions)<sync>
Options for [render](modules#render) and [renderSync](modules#renderSync). This can either be [LegacyFileOptions](interfaces/legacyfileoptions) to load a file from disk, or [LegacyStringOptions](interfaces/legacystringoptions) to compile a string of Sass code.
See [LegacySharedOptions](interfaces/legacysharedoptions) for options that are shared across both file and string inputs.
deprecated
This only works with the legacy [render](modules#render) and [renderSync](modules#renderSync) APIs. Use [Options](interfaces/options) with [compile](modules#compile), [compileString](modules#compileString), [compileAsync](modules#compileAsync), and [compileStringAsync](modules#compileStringAsync) instead.
#### Type parameters
* #### sync: "sync" | "async"
### LegacySyncFunction
LegacySyncFunction: (this: [LegacyPluginThis](interfaces/legacypluginthis), …args: [LegacyValue](modules#LegacyValue)[]) => [LegacyValue](modules#LegacyValue)
#### Type declaration
* + (this: [LegacyPluginThis](interfaces/legacypluginthis), …args: [LegacyValue](modules#LegacyValue)[]): [LegacyValue](modules#LegacyValue)
+ A synchronous callback that implements a custom Sass function. This can be passed to [LegacySharedOptions.functions](interfaces/legacysharedoptions#functions) for either [render](modules#render) or [renderSync](modules#renderSync).
If this throws an error, Sass will treat that as the function failing with that error message.
```
constresult = sass.renderSync({
file:'style.scss',
functions: {
"sum($arg1, $arg2)": (arg1, arg2) => {
if (!(arg1instanceofsass.types.Number)) {
thrownewError("$arg1: Expected a number");
} elseif (!(arg2instanceofsass.types.Number)) {
thrownewError("$arg2: Expected a number");
}
returnnewsass.types.Number(arg1.getValue() + arg2.getValue());
}
}
});
```
deprecated
This only works with the legacy [render](modules#render) and [renderSync](modules#renderSync) APIs. Use [CustomFunction](modules#CustomFunction) with [compile](modules#compile), [compileString](modules#compileString), [compileAsync](modules#compileAsync), and [compileStringAsync](modules#compileStringAsync) instead.
#### Parameters
- ##### this: [LegacyPluginThis](interfaces/legacypluginthis)
- #####
Rest …args: [LegacyValue](modules#LegacyValue)[]
One argument for each argument that's declared in the signature that's passed to [LegacySharedOptions.functions](interfaces/legacysharedoptions#functions). If the signature [takes arbitrary arguments](../at-rules/function#taking-arbitrary-arguments), they're passed as a single argument list in the last argument.#### Returns [LegacyValue](modules#LegacyValue)
### LegacySyncImporter
LegacySyncImporter: (this: [LegacyImporterThis](interfaces/legacyimporterthis), url: string, prev: string) => [LegacyImporterResult](modules#LegacyImporterResult)
#### Type declaration
* + (this: [LegacyImporterThis](interfaces/legacyimporterthis), url: string, prev: string): [LegacyImporterResult](modules#LegacyImporterResult)
+ A synchronous callback that implements custom Sass loading logic for [`@import` rules](../at-rules/import) and [`@use` rules](../at-rules/use). This can be passed to [LegacySharedOptions.importer](interfaces/legacysharedoptions#importer) for either [render](modules#render) or [renderSync](modules#renderSync).
See [LegacySharedOptions.importer](interfaces/legacysharedoptions#importer) for more detailed documentation.
```
sass.renderSync({
file:"style.scss",
importer: [
function(url, prev) {
if (url != "big-headers") returnnull;
return {
contents:'h1 { font-size: 40px; }'
};
}
]
});
```
deprecated
This only works with the legacy [render](modules#render) and [renderSync](modules#renderSync) APIs. Use [Importer](interfaces/importer) with [compile](modules#compile), [compileString](modules#compileString), [compileAsync](modules#compileAsync), and [compileStringAsync](modules#compileStringAsync) instead.
#### Parameters
- ##### this: [LegacyImporterThis](interfaces/legacyimporterthis)
- ##### url: string
The `@use` or `@import` rule’s URL as a string, exactly as it appears in the stylesheet.
- ##### prev: string
A string identifying the stylesheet that contained the `@use` or `@import`. This string’s format depends on how that stylesheet was loaded:
* If the stylesheet was loaded from the filesystem, it’s the absolute path of its file.
* If the stylesheet was loaded from an importer that returned its contents, it’s the URL of the `@use` or `@import` rule that loaded it.
* If the stylesheet came from the data option, it’s the string "stdin".#### Returns [LegacyImporterResult](modules#LegacyImporterResult)
### LegacyValue
LegacyValue: [Null](classes/types.null) | [Number](classes/types.number) | [String](classes/types.string) | [Boolean](classes/types.boolean) | [Color](classes/types.color) | [List](classes/types.list) | [Map](classes/types.map)
A type representing all the possible values that may be passed to or returned from a [LegacyFunction](modules#LegacyFunction).
deprecated
This only works with the legacy [render](modules#render) and [renderSync](modules#renderSync) APIs. Use [Value](classes/value) with [compile](modules#compile), [compileString](modules#compileString), [compileAsync](modules#compileAsync), and [compileStringAsync](modules#compileStringAsync) instead.
### FALSE
FALSE: [Boolean](classes/types.boolean)<false>
A shorthand for `sass.types.Boolean.FALSE`.
deprecated
This only works with the legacy [render](modules#render) and [renderSync](modules#renderSync) APIs. Use [sassFalse](modules#sassFalse) with [compile](modules#compile), [compileString](modules#compileString), [compileAsync](modules#compileAsync), and [compileStringAsync](modules#compileStringAsync) instead.
### NULL
NULL: [Null](classes/types.null)
A shorthand for `sass.types.Null.NULL`.
deprecated
This only works with the legacy [render](modules#render) and [renderSync](modules#renderSync) APIs. Use [sassNull](modules#sassNull) with [compile](modules#compile), [compileString](modules#compileString), [compileAsync](modules#compileAsync), and [compileStringAsync](modules#compileStringAsync) instead.
### TRUE
TRUE: [Boolean](classes/types.boolean)<true>
A shorthand for `sass.types.Boolean.TRUE`.
deprecated
This only works with the legacy [render](modules#render) and [renderSync](modules#renderSync) APIs. Use [sassTrue](modules#sassTrue) with [compile](modules#compile), [compileString](modules#compileString), [compileAsync](modules#compileAsync), and [compileStringAsync](modules#compileStringAsync) instead.
### render
* render(options: [LegacyOptions](modules#LegacyOptions)<"async">, callback: (exception?: [LegacyException](interfaces/legacyexception), result?: [LegacyResult](interfaces/legacyresult)) => void): void
* This function asynchronously compiles a Sass file to CSS, and calls `callback` with a [LegacyResult](interfaces/legacyresult) if compilation succeeds or [LegacyException](interfaces/legacyexception) if it fails.
### ⚠️ Heads up!
When using Dart Sass, **[renderSync](modules#renderSync) is almost twice as fast as [render](modules#render)** by default, due to the overhead of making the entire evaluation process asynchronous.
```
constsass = require('sass'); // or require('node-sass');
sass.render({
file:"style.scss"
}, function(err, result) {
// ...
});
```
deprecated
Use [compileAsync](modules#compileAsync) or [compileStringAsync](modules#compileStringAsync) instead.
#### Parameters
+ ##### options: [LegacyOptions](modules#LegacyOptions)<"async">
+ ##### callback: (exception?: [LegacyException](interfaces/legacyexception), result?: [LegacyResult](interfaces/legacyresult)) => void
- * (exception?: [LegacyException](interfaces/legacyexception), result?: [LegacyResult](interfaces/legacyresult)): void
* #### Parameters
+ #####
Optional exception: [LegacyException](interfaces/legacyexception)
+ #####
Optional result: [LegacyResult](interfaces/legacyresult)#### Returns void#### Returns void
### renderSync
* renderSync(options: [LegacyOptions](modules#LegacyOptions)<"sync">): [LegacyResult](interfaces/legacyresult)
* This function synchronously compiles a Sass file to CSS. If it succeeds, it returns the result, and if it fails it throws an error.
example
```
constsass = require('sass'); // or require('node-sass');
constresult = sass.renderSync({file:"style.scss"});
// ...
```
deprecated
Use [compile](modules#compile) or [compileString](modules#compileString) instead.
#### Parameters
+ ##### options: [LegacyOptions](modules#LegacyOptions)<"sync">#### Returns [LegacyResult](interfaces/legacyresult)
| programming_docs |
sass Class Boolean<T>
Sass's [boolean type](../../values/booleans).
Custom functions should respect Sass’s notion of [truthiness](../../at-rules/control/if#truthiness-and-falsiness) by treating `false` and `null` as falsey and everything else as truthy.
### ⚠️ Heads up!
Boolean values can't be constructed, they can only be accessed through the [TRUE](types.boolean#TRUE) and [FALSE](types.boolean#FALSE) constants.
### Type parameters
* #### T: boolean = boolean
### Hierarchy
* Boolean
Index
-----
### Constructors
* [constructor](types.boolean#constructor)
### Properties
* [FALSE](types.boolean#FALSE)
* [TRUE](types.boolean#TRUE)
### Methods
* [getValue](types.boolean#getValue)
Constructors
------------
### constructor
* new Boolean<T>(): [Boolean](types.boolean)<T>
* #### Type parameters
+ #### T: boolean = boolean#### Returns [Boolean](types.boolean)<T>
Properties
----------
###
Static Readonly FALSE
FALSE: [Boolean](types.boolean)<false>
Sass's `false` value.
###
Static Readonly TRUE
TRUE: [Boolean](types.boolean)<true>
Sass's `true` value.
Methods
-------
### getValue
* getValue(): T
* Returns `true` if this is Sass's `true` value and `false` if this is Sass's `false` value.
example
```
// boolean is `true`.
boolean.getValue(); // true
boolean === sass.types.Boolean.TRUE; // true
// boolean is `false`.
boolean.getValue(); // false
boolean === sass.types.Boolean.FALSE; // true
```
#### Returns T
sass Class SassArgumentList
Sass's [argument list type](../../values/lists#argument-lists).
An argument list comes from a rest argument. It's distinct from a normal [SassList](sasslist) in that it may contain a keyword map as well as the positional arguments.
### Hierarchy
* [SassList](sasslist)
+ SassArgumentList
Index
-----
### Constructors
* [constructor](sassargumentlist#constructor)
### Accessors
* [asList](sassargumentlist#asList)
* [hasBrackets](sassargumentlist#hasBrackets)
* [isTruthy](sassargumentlist#isTruthy)
* [keywords](sassargumentlist#keywords)
* [realNull](sassargumentlist#realNull)
### Methods
* [assertBoolean](sassargumentlist#assertBoolean)
* [assertColor](sassargumentlist#assertColor)
* [assertFunction](sassargumentlist#assertFunction)
* [assertMap](sassargumentlist#assertMap)
* [assertNumber](sassargumentlist#assertNumber)
* [assertString](sassargumentlist#assertString)
* [equals](sassargumentlist#equals)
* [get](sassargumentlist#get)
* [hashCode](sassargumentlist#hashCode)
* [sassIndexToListIndex](sassargumentlist#sassIndexToListIndex)
* [tryMap](sassargumentlist#tryMap)
Constructors
------------
### constructor
* new SassArgumentList(contents: [Value](value)[] | List<[Value](value)>, keywords: Record<string, [Value](value)> | OrderedMap<string, [Value](value)>, separator?: [ListSeparator](../modules#ListSeparator)): [SassArgumentList](sassargumentlist)
* Creates a new argument list.
#### Parameters
+ ##### contents: [Value](value)[] | List<[Value](value)>
The positional arguments that make up the primary contents of the list. This may be either a plain JavaScript array or an immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
+ ##### keywords: Record<string, [Value](value)> | OrderedMap<string, [Value](value)>
The keyword arguments attached to this argument list, whose names should exclude `$`. This can be either a plain JavaScript object with argument names as fields, or an immutable [[OrderedMap]] from the [`immutable` package](https://immutable-js.com/)
+ #####
Optional separator: [ListSeparator](../modules#ListSeparator)
The separator for this list. Defaults to `','`.#### Returns [SassArgumentList](sassargumentlist)
Accessors
---------
### asList
* get asList(): List<[Value](value)>
* This value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns List<[Value](value)>
An immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
### hasBrackets
* get hasBrackets(): boolean
* Whether this value as a list has brackets.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns boolean
### isTruthy
* get isTruthy(): boolean
* Whether the value counts as `true` in an `@if` statement and other contexts.
#### Returns boolean
### keywords
* get keywords(): OrderedMap<string, [Value](value)>
* The keyword arguments attached to this argument list.
The argument names don't include `$`.
#### Returns OrderedMap<string, [Value](value)>
An immutable [[OrderedMap]] from the [`immutable` package](https://immutable-js.com/).
### realNull
* get realNull(): null | [Value](value)
* Returns JavaScript's `null` value if this is [sassNull](../modules#sassNull), and returns `this` otherwise.
#### Returns null | [Value](value)
Methods
-------
### assertBoolean
* assertBoolean(name?: string): [SassBoolean](sassboolean)
* Throws if `this` isn't a [SassBoolean](sassboolean).
### ⚠️ Heads up!
Functions should generally use [isTruthy](sassargumentlist#isTruthy) rather than requiring a literal boolean.
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassBoolean](sassboolean)
### assertColor
* assertColor(name?: string): [SassColor](sasscolor)
* Throws if `this` isn't a [SassColor](sasscolor).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassColor](sasscolor)
### assertFunction
* assertFunction(name?: string): [SassFunction](sassfunction)
* Throws if `this` isn't a [SassFunction](sassfunction).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassFunction](sassfunction)
### assertMap
* assertMap(name?: string): [SassMap](sassmap)
* Throws if `this` isn't a [SassMap](sassmap).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassMap](sassmap)
### assertNumber
* assertNumber(name?: string): [SassNumber](sassnumber)
* Throws if `this` isn't a [SassNumber](sassnumber).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassNumber](sassnumber)
### assertString
* assertString(name?: string): [SassString](sassstring)
* Throws if `this` isn't a [SassString](sassstring).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassString](sassstring)
### equals
* equals(other: [Value](value)): boolean
* Returns whether `this` represents the same value as `other`.
#### Parameters
+ ##### other: [Value](value)#### Returns boolean
### get
* get(index: number): undefined | [Value](value)
* Returns the value at index `index` in this value as a list, or `undefined` if `index` isn't valid for this list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
This is a shorthand for `this.asList.get(index)`, although it may be more efficient in some cases.
### ⚠️ Heads up!
This method uses the same indexing conventions as the `immutable` package: unlike Sass the index of the first element is 0, but like Sass negative numbers index from the end of the list.
#### Parameters
+ ##### index: number#### Returns undefined | [Value](value)
### hashCode
* hashCode(): number
* Returns a hash code that can be used to store `this` in a hash map.
#### Returns number
### sassIndexToListIndex
* sassIndexToListIndex(sassIndex: [Value](value), name?: string): number
* Converts `sassIndex` into a JavaScript-style index into the list returned by [asList](sassargumentlist#asList).
Sass indexes are one-based, while JavaScript indexes are zero-based. Sass indexes may also be negative in order to index from the end of the list.
throws
`Error` If `sassIndex` isn't a number, if that number isn't an integer, or if that integer isn't a valid index for [asList](sassargumentlist#asList).
#### Parameters
+ ##### sassIndex: [Value](value)
The Sass-style index into this as a list.
+ #####
Optional name: string
The name of the function argument `sassIndex` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns number
### tryMap
* tryMap(): null | [SassMap](sassmap)
* Returns `this` as a map if it counts as one (empty lists count as empty maps) or `null` if it doesn't.
#### Returns null | [SassMap](sassmap)
sass Class String
Sass's [string type](../../values/strings).
### ⚠️ Heads up!
This API currently provides no way of distinguishing between a [quoted](../../values/strings#quoted) and [unquoted](../../values/strings#unquoted) string.
### Hierarchy
* String
Index
-----
### Constructors
* [constructor](types.string#constructor)
### Methods
* [getValue](types.string#getValue)
* [setValue](types.string#setValue)
Constructors
------------
### constructor
* new String(value: string): [String](types.string)
* Creates an unquoted string with the given contents.
### ⚠️ Heads up!
This API currently provides no way of creating a [quoted](../../values/strings#quoted) string.
#### Parameters
+ ##### value: string#### Returns [String](types.string)
Methods
-------
### getValue
* getValue(): string
* Returns the contents of the string. If the string contains escapes, those escapes are included literally if it’s [unquoted](../../values/strings#unquoted), while the values of the escapes are included if it’s [quoted](../../values/strings#quoted).
example
```
// string is `Arial`.
string.getValue(); // "Arial"
// string is `"Helvetica Neue"`.
string.getValue(); // "Helvetica Neue"
// string is `\1F46D`.
string.getValue(); // "\\1F46D"
// string is `"\1F46D"`.
string.getValue(); // "👭"
```
#### Returns string
### setValue
* setValue(value: string): void
* Destructively modifies this string by setting its numeric value to `value`.
### ⚠️ Heads up!
Even if the string was originally quoted, this will cause it to become unquoted.
deprecated
Use [constructor](types.string#constructor) instead.
#### Parameters
+ ##### value: string#### Returns void
sass Class Map
Sass's [map type](../../values/maps).
### ⚠️ Heads up!
This map type is represented as a list of key-value pairs rather than a mapping from keys to values. The only way to find the value associated with a given key is to iterate through the map checking for that key. Maps created through this API are still forbidden from having duplicate keys.
### Hierarchy
* Map
Index
-----
### Constructors
* [constructor](types.map#constructor)
### Methods
* [getKey](types.map#getKey)
* [getLength](types.map#getLength)
* [getValue](types.map#getValue)
* [setKey](types.map#setKey)
* [setValue](types.map#setValue)
Constructors
------------
### constructor
* new Map(length: number): [Map](types.map)
* Creates a new Sass map.
### ⚠️ Heads up!
The initial keys and values of the map are undefined. They must be set using [setKey](types.map#setKey) and [setValue](types.map#setValue) before accessing them or passing the map back to Sass.
example
```
constmap = newsass.types.Map(2);
map.setKey(0, newsass.types.String("width"));
map.setValue(0, newsass.types.Number(300, "px"));
map.setKey(1, newsass.types.String("height"));
map.setValue(1, newsass.types.Number(100, "px"));
map; // (width: 300px, height: 100px)
```
#### Parameters
+ ##### length: number
The number of (initially undefined) key/value pairs in the map.#### Returns [Map](types.map)
Methods
-------
### getKey
* getKey(index: number): [LegacyValue](../modules#LegacyValue)
* Returns the key in the key/value pair at `index`.
example
```
// map is `(width: 300px, height: 100px)`
map.getKey(0); // width
map.getKey(1); // height
```
throws
`Error` if `index` is less than 0 or greater than or equal to the number of pairs in this map.
#### Parameters
+ ##### index: number
A (0-based) index of a key/value pair in this map.#### Returns [LegacyValue](../modules#LegacyValue)
### getLength
* getLength(): number
* Returns the number of key/value pairs in this map.
example
```
// map is `("light": 200, "medium": 400, "bold": 600)`
map.getLength(); // 3
// map is `(width: 300px, height: 100px)`
map.getLength(); // 2
```
#### Returns number
### getValue
* getValue(index: number): [LegacyValue](../modules#LegacyValue)
* Returns the value in the key/value pair at `index`.
example
```
// map is `(width: 300px, height: 100px)`
map.getValue(0); // 300px
map.getValue(1); // 100px
```
throws
`Error` if `index` is less than 0 or greater than or equal to the number of pairs in this map.
#### Parameters
+ ##### index: number
A (0-based) index of a key/value pair in this map.#### Returns [LegacyValue](../modules#LegacyValue)
### setKey
* setKey(index: number, key: [LegacyValue](../modules#LegacyValue)): void
* Sets the value in the key/value pair at `index` to `value`.
example
```
// map is `("light": 200, "medium": 400, "bold": 600)`
map.setValue(1, newsass.types.String("lighter"));
map; // ("lighter": 200, "medium": 300, "bold": 600)
```
throws
`Error` if `index` is less than 0 or greater than or equal to the number of pairs in this map.
#### Parameters
+ ##### index: number
A (0-based) index of a key/value pair in this map.
+ ##### key: [LegacyValue](../modules#LegacyValue)#### Returns void
### setValue
* setValue(index: number, value: [LegacyValue](../modules#LegacyValue)): void
* Sets the value in the key/value pair at `index` to `value`.
example
```
// map is `("light": 200, "medium": 400, "bold": 600)`
map.setValue(1, newsass.types.Number(300));
map; // ("light": 200, "medium": 300, "bold": 600)
```
throws
`Error` if `index` is less than 0 or greater than or equal to the number of pairs in this map.
#### Parameters
+ ##### index: number
A (0-based) index of a key/value pair in this map.
+ ##### value: [LegacyValue](../modules#LegacyValue)#### Returns void
sass Class Exception An exception thrown because a Sass compilation failed.
### Hierarchy
* Error
+ Exception
Index
-----
### Properties
* [message](exception#message)
* [name](exception#name)
* [sassMessage](exception#sassMessage)
* [sassStack](exception#sassStack)
* [span](exception#span)
* [stack](exception#stack)
* [prepareStackTrace](exception#prepareStackTrace)
* [stackTraceLimit](exception#stackTraceLimit)
### Methods
* [toString](exception#toString)
* [captureStackTrace](exception#captureStackTrace)
Properties
----------
### message
message: string
A human-friendly representation of the exception.
Because many tools simply print `Error.message` directly, this includes not only the textual description of what went wrong (the [sassMessage](exception#sassMessage)) but also an indication of where in the Sass stylesheet the error occurred (the [span](exception#span)) and the Sass stack trace at the point of error (the [sassStack](exception#sassStack)).
### name
name: string
###
Readonly sassMessage
sassMessage: string
A textual description of what went wrong.
Unlike [message](exception#message), this does *not* include representations of [span](exception#span) or [sassStack](exception#sassStack).
###
Readonly sassStack
sassStack: string
A human-friendly representation of the Sass stack trace at the point of error.
###
Readonly span
span: [SourceSpan](../interfaces/sourcespan)
The location the error occurred in the Sass file that triggered it.
###
Optional stack
stack?: string
###
Static Optional prepareStackTrace
prepareStackTrace?: (err: Error, stackTraces: CallSite[]) => any
#### Type declaration
* + (err: Error, stackTraces: CallSite[]): any
+ Optional override for formatting stack traces
see
<https://v8.dev/docs/stack-trace-api#customizing-stack-traces>
#### Parameters
- ##### err: Error
- ##### stackTraces: CallSite[]#### Returns any
###
Static stackTraceLimit
stackTraceLimit: number
Methods
-------
### toString
* toString(): string
* Returns the same string as [message](exception#message).
#### Returns string
###
Static captureStackTrace
* captureStackTrace(targetObject: object, constructorOpt?: Function): void
* Create .stack property on a target object
#### Parameters
+ ##### targetObject: object
+ #####
Optional constructorOpt: Function#### Returns void
sass Class SassNumber Sass's [number type](../../values/numbers).
### Hierarchy
* [Value](value)
+ SassNumber
Index
-----
### Constructors
* [constructor](sassnumber#constructor)
### Accessors
* [asInt](sassnumber#asInt)
* [asList](sassnumber#asList)
* [denominatorUnits](sassnumber#denominatorUnits)
* [hasBrackets](sassnumber#hasBrackets)
* [hasUnits](sassnumber#hasUnits)
* [isInt](sassnumber#isInt)
* [isTruthy](sassnumber#isTruthy)
* [numeratorUnits](sassnumber#numeratorUnits)
* [realNull](sassnumber#realNull)
* [separator](sassnumber#separator)
* [value](sassnumber#value)
### Methods
* [assertBoolean](sassnumber#assertBoolean)
* [assertColor](sassnumber#assertColor)
* [assertFunction](sassnumber#assertFunction)
* [assertInRange](sassnumber#assertInRange)
* [assertInt](sassnumber#assertInt)
* [assertMap](sassnumber#assertMap)
* [assertNoUnits](sassnumber#assertNoUnits)
* [assertNumber](sassnumber#assertNumber)
* [assertString](sassnumber#assertString)
* [assertUnit](sassnumber#assertUnit)
* [coerce](sassnumber#coerce)
* [coerceToMatch](sassnumber#coerceToMatch)
* [coerceValue](sassnumber#coerceValue)
* [coerceValueToMatch](sassnumber#coerceValueToMatch)
* [compatibleWithUnit](sassnumber#compatibleWithUnit)
* [convert](sassnumber#convert)
* [convertToMatch](sassnumber#convertToMatch)
* [convertValue](sassnumber#convertValue)
* [convertValueToMatch](sassnumber#convertValueToMatch)
* [equals](sassnumber#equals)
* [get](sassnumber#get)
* [hasUnit](sassnumber#hasUnit)
* [hashCode](sassnumber#hashCode)
* [sassIndexToListIndex](sassnumber#sassIndexToListIndex)
* [tryMap](sassnumber#tryMap)
Constructors
------------
### constructor
* new SassNumber(value: number, unit?: string | { denominatorUnits?: string[] | List<string>; numeratorUnits?: string[] | List<string> }): [SassNumber](sassnumber)
* Creates a new number with more complex units than just a single numerator.
Upon construction, any compatible numerator and denominator units are simplified away according to the conversion factor between them.
#### Parameters
+ ##### value: number
The number's numeric value.
+ #####
Optional unit: string | { denominatorUnits?: string[] | List<string>; numeratorUnits?: string[] | List<string> }
If this is a string, it's used as the single numerator unit for the number.#### Returns [SassNumber](sassnumber)
Accessors
---------
### asInt
* get asInt(): null | number
* If [value](sassnumber#value) is an integer according to [isInt](sassnumber#isInt), returns [value](sassnumber#value) rounded to that integer. If it's not an integer, returns `null`.
#### Returns null | number
### asList
* get asList(): List<[Value](value)>
* This value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns List<[Value](value)>
An immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
### denominatorUnits
* get denominatorUnits(): List<string>
* This number's denominator units as an immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
#### Returns List<string>
### hasBrackets
* get hasBrackets(): boolean
* Whether this value as a list has brackets.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns boolean
### hasUnits
* get hasUnits(): boolean
* Whether this number has any numerator or denominator units.
#### Returns boolean
### isInt
* get isInt(): boolean
* Whether [value](sassnumber#value) is an integer according to Sass's equality logic.
#### Returns boolean
### isTruthy
* get isTruthy(): boolean
* Whether the value counts as `true` in an `@if` statement and other contexts.
#### Returns boolean
### numeratorUnits
* get numeratorUnits(): List<string>
* This number's numerator units as an immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
#### Returns List<string>
### realNull
* get realNull(): null | [Value](value)
* Returns JavaScript's `null` value if this is [sassNull](../modules#sassNull), and returns `this` otherwise.
#### Returns null | [Value](value)
### separator
* get separator(): [ListSeparator](../modules#ListSeparator)
* The separator for this value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns [ListSeparator](../modules#ListSeparator)
### value
* get value(): number
* This number's numeric value.
#### Returns number
Methods
-------
### assertBoolean
* assertBoolean(name?: string): [SassBoolean](sassboolean)
* Throws if `this` isn't a [SassBoolean](sassboolean).
### ⚠️ Heads up!
Functions should generally use [isTruthy](sassnumber#isTruthy) rather than requiring a literal boolean.
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassBoolean](sassboolean)
### assertColor
* assertColor(name?: string): [SassColor](sasscolor)
* Throws if `this` isn't a [SassColor](sasscolor).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassColor](sasscolor)
### assertFunction
* assertFunction(name?: string): [SassFunction](sassfunction)
* Throws if `this` isn't a [SassFunction](sassfunction).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassFunction](sassfunction)
### assertInRange
* assertInRange(min: number, max: number, name?: string): number
* Returns [value](sassnumber#value) if it's within `min` and `max`. If [value](sassnumber#value) is equal to `min` or `max` according to Sass's equality, returns `min` or `max` respectively. Otherwise, throws an error.
#### Parameters
+ ##### min: number
+ ##### max: number
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns number
### assertInt
* assertInt(name?: string): number
* If [value](sassnumber#value) is an integer according to [isInt](sassnumber#isInt), returns it rounded to that integer. Otherwise, throws an error.
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns number
### assertMap
* assertMap(name?: string): [SassMap](sassmap)
* Throws if `this` isn't a [SassMap](sassmap).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassMap](sassmap)
### assertNoUnits
* assertNoUnits(name?: string): [SassNumber](sassnumber)
* If this number has no units, returns it. Otherwise, throws an error.
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassNumber](sassnumber)
### assertNumber
* assertNumber(name?: string): [SassNumber](sassnumber)
* Throws if `this` isn't a [SassNumber](sassnumber).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassNumber](sassnumber)
### assertString
* assertString(name?: string): [SassString](sassstring)
* Throws if `this` isn't a [SassString](sassstring).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassString](sassstring)
### assertUnit
* assertUnit(unit: string, name?: string): [SassNumber](sassnumber)
* If this number has `unit` as its only unit (and as a numerator), returns this number. Otherwise, throws an error.
#### Parameters
+ ##### unit: string
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassNumber](sassnumber)
### coerce
* coerce(newNumerators: string[] | List<string>, newDenominators: string[] | List<string>, name?: string): [SassNumber](sassnumber)
* Returns a copy of this number, converted to the units represented by `newNumerators` and `newDenominators`.
Unlike [convert](sassnumber#convert) this does *not* throw an error if this number is unitless and either `newNumerators` or `newDenominators` are not empty, or vice-versa. Instead, it treats all unitless numbers as convertible to and from all units without changing the value.
throws
`Error` if this number's units are incompatible with `newNumerators` and `newDenominators`.
#### Parameters
+ ##### newNumerators: string[] | List<string>
The numerator units to convert this number to. This may be either a plain JavaScript array or an immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
+ ##### newDenominators: string[] | List<string>
The denominator units to convert this number to. This may be either a plain JavaScript array or an immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassNumber](sassnumber)
### coerceToMatch
* coerceToMatch(other: [SassNumber](sassnumber), name?: string, otherName?: string): [SassNumber](sassnumber)
* Returns a copy of this number, converted to the units represented by `newNumerators` and `newDenominators`.
Unlike [convertToMatch](sassnumber#convertToMatch) this does *not* throw an error if this number is unitless and either `newNumerators` or `newDenominators` are not empty, or vice-versa. Instead, it treats all unitless numbers as convertible to and from all units without changing the value.
throws
`Error` if this number's units are incompatible with `other`'s units.
#### Parameters
+ ##### other: [SassNumber](sassnumber)
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.
+ #####
Optional otherName: string
The name of the function argument `other` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassNumber](sassnumber)
### coerceValue
* coerceValue(newNumerators: string[] | List<string>, newDenominators: string[] | List<string>, name?: string): number
* Returns [value](sassnumber#value), converted to the units represented by `newNumerators` and `newDenominators`.
Unlike [convertValue](sassnumber#convertValue) this does *not* throw an error if this number is unitless and either `newNumerators` or `newDenominators` are not empty, or vice-versa. Instead, it treats all unitless numbers as convertible to and from all units without changing the value.
throws
`Error` if this number's units are incompatible with `newNumerators` and `newDenominators`.
#### Parameters
+ ##### newNumerators: string[] | List<string>
The numerator units to convert [value](sassnumber#value) to. This may be either a plain JavaScript array or an immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
+ ##### newDenominators: string[] | List<string>
The denominator units to convert [value](sassnumber#value) to. This may be either a plain JavaScript array or an immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns number
### coerceValueToMatch
* coerceValueToMatch(other: [SassNumber](sassnumber), name?: string, otherName?: string): number
* Returns [value](sassnumber#value), converted to the units represented by `newNumerators` and `newDenominators`.
Unlike [convertValueToMatch](sassnumber#convertValueToMatch) this does *not* throw an error if this number is unitless and either `newNumerators` or `newDenominators` are not empty, or vice-versa. Instead, it treats all unitless numbers as convertible to and from all units without changing the value.
throws
`Error` if this number's units are incompatible with `other`'s units.
#### Parameters
+ ##### other: [SassNumber](sassnumber)
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.
+ #####
Optional otherName: string
The name of the function argument `other` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns number
### compatibleWithUnit
* compatibleWithUnit(unit: string): boolean
* Whether this has exactly one numerator unit, and that unit is compatible with `unit`.
#### Parameters
+ ##### unit: string#### Returns boolean
### convert
* convert(newNumerators: string[] | List<string>, newDenominators: string[] | List<string>, name?: string): [SassNumber](sassnumber)
* Returns a copy of this number, converted to the units represented by `newNumerators` and `newDenominators`.
throws
`Error` if this number's units are incompatible with `newNumerators` and `newDenominators`; or if this number is unitless and either `newNumerators` or `newDenominators` are not empty, or vice-versa.
#### Parameters
+ ##### newNumerators: string[] | List<string>
The numerator units to convert this number to. This may be either a plain JavaScript array or an immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
+ ##### newDenominators: string[] | List<string>
The denominator units to convert this number to. This may be either a plain JavaScript array or an immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassNumber](sassnumber)
### convertToMatch
* convertToMatch(other: [SassNumber](sassnumber), name?: string, otherName?: string): [SassNumber](sassnumber)
* Returns a copy of this number, converted to the same units as `other`.
throws
`Error` if this number's units are incompatible with `other`'s units, or if either number is unitless but the other is not.
#### Parameters
+ ##### other: [SassNumber](sassnumber)
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.
+ #####
Optional otherName: string
The name of the function argument `other` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassNumber](sassnumber)
### convertValue
* convertValue(newNumerators: string[] | List<string>, newDenominators: string[] | List<string>, name?: string): number
* Returns [value](sassnumber#value), converted to the units represented by `newNumerators` and `newDenominators`.
throws
`Error` if this number's units are incompatible with `newNumerators` and `newDenominators`; or if this number is unitless and either `newNumerators` or `newDenominators` are not empty, or vice-versa.
#### Parameters
+ ##### newNumerators: string[] | List<string>
The numerator units to convert [value](sassnumber#value) to. This may be either a plain JavaScript array or an immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
+ ##### newDenominators: string[] | List<string>
The denominator units to convert [value](sassnumber#value) to. This may be either a plain JavaScript array or an immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns number
### convertValueToMatch
* convertValueToMatch(other: [SassNumber](sassnumber), name?: string, otherName?: string): number
* Returns [value](sassnumber#value), converted to the same units as `other`.
throws
`Error` if this number's units are incompatible with `other`'s units, or if either number is unitless but the other is not.
#### Parameters
+ ##### other: [SassNumber](sassnumber)
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.
+ #####
Optional otherName: string
The name of the function argument `other` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns number
### equals
* equals(other: [Value](value)): boolean
* Returns whether `this` represents the same value as `other`.
#### Parameters
+ ##### other: [Value](value)#### Returns boolean
### get
* get(index: number): undefined | [Value](value)
* Returns the value at index `index` in this value as a list, or `undefined` if `index` isn't valid for this list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
This is a shorthand for `this.asList.get(index)`, although it may be more efficient in some cases.
### ⚠️ Heads up!
This method uses the same indexing conventions as the `immutable` package: unlike Sass the index of the first element is 0, but like Sass negative numbers index from the end of the list.
#### Parameters
+ ##### index: number#### Returns undefined | [Value](value)
### hasUnit
* hasUnit(unit: string): boolean
* Whether this number has `unit` as its only unit (and as a numerator).
#### Parameters
+ ##### unit: string#### Returns boolean
### hashCode
* hashCode(): number
* Returns a hash code that can be used to store `this` in a hash map.
#### Returns number
### sassIndexToListIndex
* sassIndexToListIndex(sassIndex: [Value](value), name?: string): number
* Converts `sassIndex` into a JavaScript-style index into the list returned by [asList](sassnumber#asList).
Sass indexes are one-based, while JavaScript indexes are zero-based. Sass indexes may also be negative in order to index from the end of the list.
throws
`Error` If `sassIndex` isn't a number, if that number isn't an integer, or if that integer isn't a valid index for [asList](sassnumber#asList).
#### Parameters
+ ##### sassIndex: [Value](value)
The Sass-style index into this as a list.
+ #####
Optional name: string
The name of the function argument `sassIndex` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns number
### tryMap
* tryMap(): null | [SassMap](sassmap)
* Returns `this` as a map if it counts as one (empty lists count as empty maps) or `null` if it doesn't.
#### Returns null | [SassMap](sassmap)
| programming_docs |
sass Class SassBoolean Sass's [boolean type](../../values/booleans).
### Hierarchy
* [Value](value)
+ SassBoolean
Index
-----
### Accessors
* [asList](sassboolean#asList)
* [hasBrackets](sassboolean#hasBrackets)
* [isTruthy](sassboolean#isTruthy)
* [realNull](sassboolean#realNull)
* [separator](sassboolean#separator)
* [value](sassboolean#value)
### Methods
* [assertBoolean](sassboolean#assertBoolean)
* [assertColor](sassboolean#assertColor)
* [assertFunction](sassboolean#assertFunction)
* [assertMap](sassboolean#assertMap)
* [assertNumber](sassboolean#assertNumber)
* [assertString](sassboolean#assertString)
* [equals](sassboolean#equals)
* [get](sassboolean#get)
* [hashCode](sassboolean#hashCode)
* [sassIndexToListIndex](sassboolean#sassIndexToListIndex)
* [tryMap](sassboolean#tryMap)
Accessors
---------
### asList
* get asList(): List<[Value](value)>
* This value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns List<[Value](value)>
An immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
### hasBrackets
* get hasBrackets(): boolean
* Whether this value as a list has brackets.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns boolean
### isTruthy
* get isTruthy(): boolean
* Whether the value counts as `true` in an `@if` statement and other contexts.
#### Returns boolean
### realNull
* get realNull(): null | [Value](value)
* Returns JavaScript's `null` value if this is [sassNull](../modules#sassNull), and returns `this` otherwise.
#### Returns null | [Value](value)
### separator
* get separator(): [ListSeparator](../modules#ListSeparator)
* The separator for this value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns [ListSeparator](../modules#ListSeparator)
### value
* get value(): boolean
* Whether this value is `true` or `false`.
#### Returns boolean
Methods
-------
### assertBoolean
* assertBoolean(name?: string): [SassBoolean](sassboolean)
* Throws if `this` isn't a [SassBoolean](sassboolean).
### ⚠️ Heads up!
Functions should generally use [isTruthy](sassboolean#isTruthy) rather than requiring a literal boolean.
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassBoolean](sassboolean)
### assertColor
* assertColor(name?: string): [SassColor](sasscolor)
* Throws if `this` isn't a [SassColor](sasscolor).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassColor](sasscolor)
### assertFunction
* assertFunction(name?: string): [SassFunction](sassfunction)
* Throws if `this` isn't a [SassFunction](sassfunction).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassFunction](sassfunction)
### assertMap
* assertMap(name?: string): [SassMap](sassmap)
* Throws if `this` isn't a [SassMap](sassmap).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassMap](sassmap)
### assertNumber
* assertNumber(name?: string): [SassNumber](sassnumber)
* Throws if `this` isn't a [SassNumber](sassnumber).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassNumber](sassnumber)
### assertString
* assertString(name?: string): [SassString](sassstring)
* Throws if `this` isn't a [SassString](sassstring).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassString](sassstring)
### equals
* equals(other: [Value](value)): boolean
* Returns whether `this` represents the same value as `other`.
#### Parameters
+ ##### other: [Value](value)#### Returns boolean
### get
* get(index: number): undefined | [Value](value)
* Returns the value at index `index` in this value as a list, or `undefined` if `index` isn't valid for this list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
This is a shorthand for `this.asList.get(index)`, although it may be more efficient in some cases.
### ⚠️ Heads up!
This method uses the same indexing conventions as the `immutable` package: unlike Sass the index of the first element is 0, but like Sass negative numbers index from the end of the list.
#### Parameters
+ ##### index: number#### Returns undefined | [Value](value)
### hashCode
* hashCode(): number
* Returns a hash code that can be used to store `this` in a hash map.
#### Returns number
### sassIndexToListIndex
* sassIndexToListIndex(sassIndex: [Value](value), name?: string): number
* Converts `sassIndex` into a JavaScript-style index into the list returned by [asList](sassboolean#asList).
Sass indexes are one-based, while JavaScript indexes are zero-based. Sass indexes may also be negative in order to index from the end of the list.
throws
`Error` If `sassIndex` isn't a number, if that number isn't an integer, or if that integer isn't a valid index for [asList](sassboolean#asList).
#### Parameters
+ ##### sassIndex: [Value](value)
The Sass-style index into this as a list.
+ #####
Optional name: string
The name of the function argument `sassIndex` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns number
### tryMap
* tryMap(): null | [SassMap](sassmap)
* Returns `this` as a map if it counts as one (empty lists count as empty maps) or `null` if it doesn't.
#### Returns null | [SassMap](sassmap)
sass Class Null The class for Sass's singleton [`null` value](../../values/null). The value itself can be accessed through the [NULL](types.null#NULL) field.
### Hierarchy
* Null
Index
-----
### Constructors
* [constructor](types.null#constructor)
### Properties
* [NULL](types.null#NULL)
Constructors
------------
### constructor
* new Null(): [Null](types.null)
* #### Returns [Null](types.null)
Properties
----------
###
Static Readonly NULL
NULL: [Null](types.null)
Sass's singleton `null` value.
sass Class SassFunction
Sass's [function type](../../values/functions).
### ⚠️ Heads up!
Although first-class Sass functions can be processed by custom functions, there's no way to invoke them outside of a Sass stylesheet.
### Hierarchy
* [Value](value)
+ SassFunction
Index
-----
### Constructors
* [constructor](sassfunction#constructor)
### Accessors
* [asList](sassfunction#asList)
* [hasBrackets](sassfunction#hasBrackets)
* [isTruthy](sassfunction#isTruthy)
* [realNull](sassfunction#realNull)
* [separator](sassfunction#separator)
### Methods
* [assertBoolean](sassfunction#assertBoolean)
* [assertColor](sassfunction#assertColor)
* [assertFunction](sassfunction#assertFunction)
* [assertMap](sassfunction#assertMap)
* [assertNumber](sassfunction#assertNumber)
* [assertString](sassfunction#assertString)
* [equals](sassfunction#equals)
* [get](sassfunction#get)
* [hashCode](sassfunction#hashCode)
* [sassIndexToListIndex](sassfunction#sassIndexToListIndex)
* [tryMap](sassfunction#tryMap)
Constructors
------------
### constructor
* new SassFunction(signature: string, callback: (args: [Value](value)[]) => [Value](value)): [SassFunction](sassfunction)
* Creates a new first-class function that can be invoked using [`meta.call()`](../../modules/meta#call).
#### Parameters
+ ##### signature: string
The function signature, like you'd write for the [`@function rule`](../../at-rules/function).
+ ##### callback: (args: [Value](value)[]) => [Value](value)
The callback that's invoked when this function is called, just like for a [CustomFunction](../modules#CustomFunction).
- * (args: [Value](value)[]): [Value](value)
* #### Parameters
+ ##### args: [Value](value)[]#### Returns [Value](value)#### Returns [SassFunction](sassfunction)
Accessors
---------
### asList
* get asList(): List<[Value](value)>
* This value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns List<[Value](value)>
An immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
### hasBrackets
* get hasBrackets(): boolean
* Whether this value as a list has brackets.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns boolean
### isTruthy
* get isTruthy(): boolean
* Whether the value counts as `true` in an `@if` statement and other contexts.
#### Returns boolean
### realNull
* get realNull(): null | [Value](value)
* Returns JavaScript's `null` value if this is [sassNull](../modules#sassNull), and returns `this` otherwise.
#### Returns null | [Value](value)
### separator
* get separator(): [ListSeparator](../modules#ListSeparator)
* The separator for this value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns [ListSeparator](../modules#ListSeparator)
Methods
-------
### assertBoolean
* assertBoolean(name?: string): [SassBoolean](sassboolean)
* Throws if `this` isn't a [SassBoolean](sassboolean).
### ⚠️ Heads up!
Functions should generally use [isTruthy](sassfunction#isTruthy) rather than requiring a literal boolean.
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassBoolean](sassboolean)
### assertColor
* assertColor(name?: string): [SassColor](sasscolor)
* Throws if `this` isn't a [SassColor](sasscolor).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassColor](sasscolor)
### assertFunction
* assertFunction(name?: string): [SassFunction](sassfunction)
* Throws if `this` isn't a [SassFunction](sassfunction).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassFunction](sassfunction)
### assertMap
* assertMap(name?: string): [SassMap](sassmap)
* Throws if `this` isn't a [SassMap](sassmap).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassMap](sassmap)
### assertNumber
* assertNumber(name?: string): [SassNumber](sassnumber)
* Throws if `this` isn't a [SassNumber](sassnumber).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassNumber](sassnumber)
### assertString
* assertString(name?: string): [SassString](sassstring)
* Throws if `this` isn't a [SassString](sassstring).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassString](sassstring)
### equals
* equals(other: [Value](value)): boolean
* Returns whether `this` represents the same value as `other`.
#### Parameters
+ ##### other: [Value](value)#### Returns boolean
### get
* get(index: number): undefined | [Value](value)
* Returns the value at index `index` in this value as a list, or `undefined` if `index` isn't valid for this list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
This is a shorthand for `this.asList.get(index)`, although it may be more efficient in some cases.
### ⚠️ Heads up!
This method uses the same indexing conventions as the `immutable` package: unlike Sass the index of the first element is 0, but like Sass negative numbers index from the end of the list.
#### Parameters
+ ##### index: number#### Returns undefined | [Value](value)
### hashCode
* hashCode(): number
* Returns a hash code that can be used to store `this` in a hash map.
#### Returns number
### sassIndexToListIndex
* sassIndexToListIndex(sassIndex: [Value](value), name?: string): number
* Converts `sassIndex` into a JavaScript-style index into the list returned by [asList](sassfunction#asList).
Sass indexes are one-based, while JavaScript indexes are zero-based. Sass indexes may also be negative in order to index from the end of the list.
throws
`Error` If `sassIndex` isn't a number, if that number isn't an integer, or if that integer isn't a valid index for [asList](sassfunction#asList).
#### Parameters
+ ##### sassIndex: [Value](value)
The Sass-style index into this as a list.
+ #####
Optional name: string
The name of the function argument `sassIndex` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns number
### tryMap
* tryMap(): null | [SassMap](sassmap)
* Returns `this` as a map if it counts as one (empty lists count as empty maps) or `null` if it doesn't.
#### Returns null | [SassMap](sassmap)
sass Class SassColor
Sass's [color type](../../values/colors).
No matter what representation was originally used to create this color, all of its channels are accessible.
### Hierarchy
* [Value](value)
+ SassColor
Index
-----
### Constructors
* [constructor](sasscolor#constructor)
### Accessors
* [alpha](sasscolor#alpha)
* [asList](sasscolor#asList)
* [blackness](sasscolor#blackness)
* [blue](sasscolor#blue)
* [green](sasscolor#green)
* [hasBrackets](sasscolor#hasBrackets)
* [hue](sasscolor#hue)
* [isTruthy](sasscolor#isTruthy)
* [lightness](sasscolor#lightness)
* [realNull](sasscolor#realNull)
* [red](sasscolor#red)
* [saturation](sasscolor#saturation)
* [separator](sasscolor#separator)
* [whiteness](sasscolor#whiteness)
### Methods
* [assertBoolean](sasscolor#assertBoolean)
* [assertColor](sasscolor#assertColor)
* [assertFunction](sasscolor#assertFunction)
* [assertMap](sasscolor#assertMap)
* [assertNumber](sasscolor#assertNumber)
* [assertString](sasscolor#assertString)
* [change](sasscolor#change)
* [equals](sasscolor#equals)
* [get](sasscolor#get)
* [hashCode](sasscolor#hashCode)
* [sassIndexToListIndex](sasscolor#sassIndexToListIndex)
* [tryMap](sasscolor#tryMap)
Constructors
------------
### constructor
* new SassColor(options: { alpha?: number; blue: number; green: number; red: number }): [SassColor](sasscolor)
* Creates an RGB color.
throws
`Error` if `red`, `green`, and `blue` aren't between `0` and `255`, or if `alpha` isn't between `0` and `1`.
#### Parameters
+ ##### options: { alpha?: number; blue: number; green: number; red: number }
- #####
Optional alpha?: number
- ##### blue: number
- ##### green: number
- ##### red: number#### Returns [SassColor](sasscolor)
### constructor
* new SassColor(options: { alpha?: number; hue: number; lightness: number; saturation: number }): [SassColor](sasscolor)
* Creates an HSL color.
throws
`Error` if `saturation` or `lightness` aren't between `0` and `100`, or if `alpha` isn't between `0` and `1`.
#### Parameters
+ ##### options: { alpha?: number; hue: number; lightness: number; saturation: number }
- #####
Optional alpha?: number
- ##### hue: number
- ##### lightness: number
- ##### saturation: number#### Returns [SassColor](sasscolor)
### constructor
* new SassColor(options: { alpha?: number; blackness: number; hue: number; whiteness: number }): [SassColor](sasscolor)
* Creates an HWB color.
throws
`Error` if `whiteness` or `blackness` aren't between `0` and `100`, or if `alpha` isn't between `0` and `1`.
#### Parameters
+ ##### options: { alpha?: number; blackness: number; hue: number; whiteness: number }
- #####
Optional alpha?: number
- ##### blackness: number
- ##### hue: number
- ##### whiteness: number#### Returns [SassColor](sasscolor)
Accessors
---------
### alpha
* get alpha(): number
* This color's alpha channel, between `0` and `1`.
#### Returns number
### asList
* get asList(): List<[Value](value)>
* This value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns List<[Value](value)>
An immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
### blackness
* get blackness(): number
* This color's blackness, between `0` and `100`.
#### Returns number
### blue
* get blue(): number
* This color's blue channel, between `0` and `255`.
#### Returns number
### green
* get green(): number
* This color's green channel, between `0` and `255`.
#### Returns number
### hasBrackets
* get hasBrackets(): boolean
* Whether this value as a list has brackets.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns boolean
### hue
* get hue(): number
* This color's hue, between `0` and `360`.
#### Returns number
### isTruthy
* get isTruthy(): boolean
* Whether the value counts as `true` in an `@if` statement and other contexts.
#### Returns boolean
### lightness
* get lightness(): number
* This color's lightness, between `0` and `100`.
#### Returns number
### realNull
* get realNull(): null | [Value](value)
* Returns JavaScript's `null` value if this is [sassNull](../modules#sassNull), and returns `this` otherwise.
#### Returns null | [Value](value)
### red
* get red(): number
* This color's red channel, between `0` and `255`.
#### Returns number
### saturation
* get saturation(): number
* This color's saturation, between `0` and `100`.
#### Returns number
### separator
* get separator(): [ListSeparator](../modules#ListSeparator)
* The separator for this value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns [ListSeparator](../modules#ListSeparator)
### whiteness
* get whiteness(): number
* This color's whiteness, between `0` and `100`.
#### Returns number
Methods
-------
### assertBoolean
* assertBoolean(name?: string): [SassBoolean](sassboolean)
* Throws if `this` isn't a [SassBoolean](sassboolean).
### ⚠️ Heads up!
Functions should generally use [isTruthy](sasscolor#isTruthy) rather than requiring a literal boolean.
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassBoolean](sassboolean)
### assertColor
* assertColor(name?: string): [SassColor](sasscolor)
* Throws if `this` isn't a [SassColor](sasscolor).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassColor](sasscolor)
### assertFunction
* assertFunction(name?: string): [SassFunction](sassfunction)
* Throws if `this` isn't a [SassFunction](sassfunction).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassFunction](sassfunction)
### assertMap
* assertMap(name?: string): [SassMap](sassmap)
* Throws if `this` isn't a [SassMap](sassmap).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassMap](sassmap)
### assertNumber
* assertNumber(name?: string): [SassNumber](sassnumber)
* Throws if `this` isn't a [SassNumber](sassnumber).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassNumber](sassnumber)
### assertString
* assertString(name?: string): [SassString](sassstring)
* Throws if `this` isn't a [SassString](sassstring).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassString](sassstring)
### change
* change(options: { alpha?: number; blue?: number; green?: number; red?: number }): [SassColor](sasscolor)
* Changes one or more of this color's RGB channels and returns the result.
#### Parameters
+ ##### options: { alpha?: number; blue?: number; green?: number; red?: number }
- #####
Optional alpha?: number
- #####
Optional blue?: number
- #####
Optional green?: number
- #####
Optional red?: number#### Returns [SassColor](sasscolor)
### change
* change(options: { alpha?: number; hue?: number; lightness?: number; saturation?: number }): [SassColor](sasscolor)
* Changes one or more of this color's HSL channels and returns the result.
#### Parameters
+ ##### options: { alpha?: number; hue?: number; lightness?: number; saturation?: number }
- #####
Optional alpha?: number
- #####
Optional hue?: number
- #####
Optional lightness?: number
- #####
Optional saturation?: number#### Returns [SassColor](sasscolor)
### change
* change(options: { alpha?: number; blackness?: number; hue?: number; whiteness?: number }): [SassColor](sasscolor)
* Changes one or more of this color's HWB channels and returns the result.
#### Parameters
+ ##### options: { alpha?: number; blackness?: number; hue?: number; whiteness?: number }
- #####
Optional alpha?: number
- #####
Optional blackness?: number
- #####
Optional hue?: number
- #####
Optional whiteness?: number#### Returns [SassColor](sasscolor)
### equals
* equals(other: [Value](value)): boolean
* Returns whether `this` represents the same value as `other`.
#### Parameters
+ ##### other: [Value](value)#### Returns boolean
### get
* get(index: number): undefined | [Value](value)
* Returns the value at index `index` in this value as a list, or `undefined` if `index` isn't valid for this list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
This is a shorthand for `this.asList.get(index)`, although it may be more efficient in some cases.
### ⚠️ Heads up!
This method uses the same indexing conventions as the `immutable` package: unlike Sass the index of the first element is 0, but like Sass negative numbers index from the end of the list.
#### Parameters
+ ##### index: number#### Returns undefined | [Value](value)
### hashCode
* hashCode(): number
* Returns a hash code that can be used to store `this` in a hash map.
#### Returns number
### sassIndexToListIndex
* sassIndexToListIndex(sassIndex: [Value](value), name?: string): number
* Converts `sassIndex` into a JavaScript-style index into the list returned by [asList](sasscolor#asList).
Sass indexes are one-based, while JavaScript indexes are zero-based. Sass indexes may also be negative in order to index from the end of the list.
throws
`Error` If `sassIndex` isn't a number, if that number isn't an integer, or if that integer isn't a valid index for [asList](sasscolor#asList).
#### Parameters
+ ##### sassIndex: [Value](value)
The Sass-style index into this as a list.
+ #####
Optional name: string
The name of the function argument `sassIndex` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns number
### tryMap
* tryMap(): null | [SassMap](sassmap)
* Returns `this` as a map if it counts as one (empty lists count as empty maps) or `null` if it doesn't.
#### Returns null | [SassMap](sassmap)
| programming_docs |
sass Class List
Sass's [list type](../../values/lists).
### ⚠️ Heads up!
This list type’s methods use 0-based indexing, even though within Sass lists use 1-based indexing. These methods also don’t support using negative numbers to index backwards from the end of the list.
### Hierarchy
* List
Index
-----
### Constructors
* [constructor](types.list#constructor)
### Methods
* [getLength](types.list#getLength)
* [getSeparator](types.list#getSeparator)
* [getValue](types.list#getValue)
* [setSeparator](types.list#setSeparator)
* [setValue](types.list#setValue)
Constructors
------------
### constructor
* new List(length: number, commaSeparator?: boolean): [List](types.list)
* Creates a new Sass list.
### ⚠️ Heads up!
The initial values of the list elements are undefined. These elements must be set using [setValue](types.list#setValue) before accessing them or passing the list back to Sass.
example
```
constlist = newsass.types.List(3);
list.setValue(0, newsass.types.Number(10, "px"));
list.setValue(1, newsass.types.Number(15, "px"));
list.setValue(2, newsass.types.Number(32, "px"));
list; // 10px, 15px, 32px
```
#### Parameters
+ ##### length: number
The number of (initially undefined) elements in the list.
+ #####
Optional commaSeparator: boolean
If `true`, the list is comma-separated; otherwise, it's space-separated. Defaults to `true`.#### Returns [List](types.list)
Methods
-------
### getLength
* getLength(): number
* Returns the number of elements in the list.
example
```
// list is `10px, 15px, 32px`
list.getLength(); // 3
// list is `1px solid`
list.getLength(); // 2
```
#### Returns number
### getSeparator
* getSeparator(): boolean
* Returns `true` if this list is comma-separated and `false` otherwise.
example
```
// list is `10px, 15px, 32px`
list.getSeparator(); // true
// list is `1px solid`
list.getSeparator(); // false
```
#### Returns boolean
### getValue
* getValue(index: number): undefined | [LegacyValue](../modules#LegacyValue)
* Returns the element at `index`, or `undefined` if that value hasn't yet been set.
example
```
// list is `10px, 15px, 32px`
list.getValue(0); // 10px
list.getValue(2); // 32px
```
throws
`Error` if `index` is less than 0 or greater than or equal to the number of elements in this list.
#### Parameters
+ ##### index: number
A (0-based) index into this list.#### Returns undefined | [LegacyValue](../modules#LegacyValue)
### setSeparator
* setSeparator(isComma: boolean): void
* Sets whether the list is comma-separated.
#### Parameters
+ ##### isComma: boolean
`true` to make the list comma-separated, `false` otherwise.#### Returns void
### setValue
* setValue(index: number, value: [LegacyValue](../modules#LegacyValue)): void
* Sets the element at `index` to `value`.
example
```
// list is `10px, 15px, 32px`
list.setValue(1, newsass.types.Number(18, "px"));
list; // 10px, 18px, 32px
```
throws
`Error` if `index` is less than 0 or greater than or equal to the number of elements in this list.
#### Parameters
+ ##### index: number
A (0-based) index into this list.
+ ##### value: [LegacyValue](../modules#LegacyValue)#### Returns void
sass Class SassMap Sass's [map type](../../values/maps).
### Hierarchy
* [Value](value)
+ SassMap
Index
-----
### Constructors
* [constructor](sassmap#constructor)
### Accessors
* [asList](sassmap#asList)
* [contents](sassmap#contents)
* [hasBrackets](sassmap#hasBrackets)
* [isTruthy](sassmap#isTruthy)
* [realNull](sassmap#realNull)
* [separator](sassmap#separator)
### Methods
* [assertBoolean](sassmap#assertBoolean)
* [assertColor](sassmap#assertColor)
* [assertFunction](sassmap#assertFunction)
* [assertMap](sassmap#assertMap)
* [assertNumber](sassmap#assertNumber)
* [assertString](sassmap#assertString)
* [equals](sassmap#equals)
* [get](sassmap#get)
* [hashCode](sassmap#hashCode)
* [sassIndexToListIndex](sassmap#sassIndexToListIndex)
Constructors
------------
### constructor
* new SassMap(contents?: OrderedMap<[Value](value), [Value](value)>): [SassMap](sassmap)
* Creates a new map.
#### Parameters
+ #####
Optional contents: OrderedMap<[Value](value), [Value](value)>
The contents of the map. This is an immutable [[OrderedMap]] from the [`immutable` package](https://immutable-js.com/). Defaults to an empty map.#### Returns [SassMap](sassmap)
Accessors
---------
### asList
* get asList(): List<[Value](value)>
* This value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns List<[Value](value)>
An immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
### contents
* get contents(): OrderedMap<[Value](value), [Value](value)>
* Returns the contents of this map as an immutable [[OrderedMap]] from the [`immutable` package](https://immutable-js.com/).
#### Returns OrderedMap<[Value](value), [Value](value)>
### hasBrackets
* get hasBrackets(): boolean
* Whether this value as a list has brackets.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns boolean
### isTruthy
* get isTruthy(): boolean
* Whether the value counts as `true` in an `@if` statement and other contexts.
#### Returns boolean
### realNull
* get realNull(): null | [Value](value)
* Returns JavaScript's `null` value if this is [sassNull](../modules#sassNull), and returns `this` otherwise.
#### Returns null | [Value](value)
### separator
* get separator(): [ListSeparator](../modules#ListSeparator)
* The separator for this value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns [ListSeparator](../modules#ListSeparator)
Methods
-------
### assertBoolean
* assertBoolean(name?: string): [SassBoolean](sassboolean)
* Throws if `this` isn't a [SassBoolean](sassboolean).
### ⚠️ Heads up!
Functions should generally use [isTruthy](sassmap#isTruthy) rather than requiring a literal boolean.
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassBoolean](sassboolean)
### assertColor
* assertColor(name?: string): [SassColor](sasscolor)
* Throws if `this` isn't a [SassColor](sasscolor).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassColor](sasscolor)
### assertFunction
* assertFunction(name?: string): [SassFunction](sassfunction)
* Throws if `this` isn't a [SassFunction](sassfunction).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassFunction](sassfunction)
### assertMap
* assertMap(name?: string): [SassMap](sassmap)
* Throws if `this` isn't a [SassMap](sassmap).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassMap](sassmap)
### assertNumber
* assertNumber(name?: string): [SassNumber](sassnumber)
* Throws if `this` isn't a [SassNumber](sassnumber).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassNumber](sassnumber)
### assertString
* assertString(name?: string): [SassString](sassstring)
* Throws if `this` isn't a [SassString](sassstring).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassString](sassstring)
### equals
* equals(other: [Value](value)): boolean
* Returns whether `this` represents the same value as `other`.
#### Parameters
+ ##### other: [Value](value)#### Returns boolean
### get
* get(key: [Value](value)): undefined | [Value](value)
* Returns the value associated with `key` in this map, or `undefined` if `key` isn't in the map.
This is a shorthand for `this.contents.get(key)`, although it may be more efficient in some cases.
#### Parameters
+ ##### key: [Value](value)#### Returns undefined | [Value](value)
### get
* get(index: number): undefined | [SassList](sasslist)
* Inherited from [Value.get](value#get).
#### Parameters
+ ##### index: number#### Returns undefined | [SassList](sasslist)
### hashCode
* hashCode(): number
* Returns a hash code that can be used to store `this` in a hash map.
#### Returns number
### sassIndexToListIndex
* sassIndexToListIndex(sassIndex: [Value](value), name?: string): number
* Converts `sassIndex` into a JavaScript-style index into the list returned by [asList](sassmap#asList).
Sass indexes are one-based, while JavaScript indexes are zero-based. Sass indexes may also be negative in order to index from the end of the list.
throws
`Error` If `sassIndex` isn't a number, if that number isn't an integer, or if that integer isn't a valid index for [asList](sassmap#asList).
#### Parameters
+ ##### sassIndex: [Value](value)
The Sass-style index into this as a list.
+ #####
Optional name: string
The name of the function argument `sassIndex` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns number
sass Class SassList Sass's [list type](../../values/lists).
### Hierarchy
* [Value](value)
+ SassList
- [SassArgumentList](sassargumentlist)
Index
-----
### Constructors
* [constructor](sasslist#constructor)
### Accessors
* [asList](sasslist#asList)
* [hasBrackets](sasslist#hasBrackets)
* [isTruthy](sasslist#isTruthy)
* [realNull](sasslist#realNull)
### Methods
* [assertBoolean](sasslist#assertBoolean)
* [assertColor](sasslist#assertColor)
* [assertFunction](sasslist#assertFunction)
* [assertMap](sasslist#assertMap)
* [assertNumber](sasslist#assertNumber)
* [assertString](sasslist#assertString)
* [equals](sasslist#equals)
* [get](sasslist#get)
* [hashCode](sasslist#hashCode)
* [sassIndexToListIndex](sasslist#sassIndexToListIndex)
* [tryMap](sasslist#tryMap)
Constructors
------------
### constructor
* new SassList(contents: [Value](value)[] | List<[Value](value)>, options?: { brackets?: boolean; separator?: [ListSeparator](../modules#ListSeparator) }): [SassList](sasslist)
* Creates a new list.
#### Parameters
+ ##### contents: [Value](value)[] | List<[Value](value)>
The contents of the list. This may be either a plain JavaScript array or an immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
+ #####
Optional options: { brackets?: boolean; separator?: [ListSeparator](../modules#ListSeparator) }
- #####
Optional brackets?: boolean
Whether the list has square brackets. Defaults to `false`.
- #####
Optional separator?: [ListSeparator](../modules#ListSeparator)
The separator to use between elements of this list. Defaults to `','`.#### Returns [SassList](sasslist)
### constructor
* new SassList(options?: { brackets?: boolean; separator?: [ListSeparator](../modules#ListSeparator) }): [SassList](sasslist)
* Creates an empty list.
#### Parameters
+ #####
Optional options: { brackets?: boolean; separator?: [ListSeparator](../modules#ListSeparator) }
- #####
Optional brackets?: boolean
Whether the list has square brackets. Defaults to `false`.
- #####
Optional separator?: [ListSeparator](../modules#ListSeparator)
The separator to use between elements of this list. Defaults to `','`.#### Returns [SassList](sasslist)
Accessors
---------
### asList
* get asList(): List<[Value](value)>
* This value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns List<[Value](value)>
An immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
### hasBrackets
* get hasBrackets(): boolean
* Whether this value as a list has brackets.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns boolean
### isTruthy
* get isTruthy(): boolean
* Whether the value counts as `true` in an `@if` statement and other contexts.
#### Returns boolean
### realNull
* get realNull(): null | [Value](value)
* Returns JavaScript's `null` value if this is [sassNull](../modules#sassNull), and returns `this` otherwise.
#### Returns null | [Value](value)
Methods
-------
### assertBoolean
* assertBoolean(name?: string): [SassBoolean](sassboolean)
* Throws if `this` isn't a [SassBoolean](sassboolean).
### ⚠️ Heads up!
Functions should generally use [isTruthy](sasslist#isTruthy) rather than requiring a literal boolean.
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassBoolean](sassboolean)
### assertColor
* assertColor(name?: string): [SassColor](sasscolor)
* Throws if `this` isn't a [SassColor](sasscolor).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassColor](sasscolor)
### assertFunction
* assertFunction(name?: string): [SassFunction](sassfunction)
* Throws if `this` isn't a [SassFunction](sassfunction).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassFunction](sassfunction)
### assertMap
* assertMap(name?: string): [SassMap](sassmap)
* Throws if `this` isn't a [SassMap](sassmap).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassMap](sassmap)
### assertNumber
* assertNumber(name?: string): [SassNumber](sassnumber)
* Throws if `this` isn't a [SassNumber](sassnumber).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassNumber](sassnumber)
### assertString
* assertString(name?: string): [SassString](sassstring)
* Throws if `this` isn't a [SassString](sassstring).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassString](sassstring)
### equals
* equals(other: [Value](value)): boolean
* Returns whether `this` represents the same value as `other`.
#### Parameters
+ ##### other: [Value](value)#### Returns boolean
### get
* get(index: number): undefined | [Value](value)
* Returns the value at index `index` in this value as a list, or `undefined` if `index` isn't valid for this list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
This is a shorthand for `this.asList.get(index)`, although it may be more efficient in some cases.
### ⚠️ Heads up!
This method uses the same indexing conventions as the `immutable` package: unlike Sass the index of the first element is 0, but like Sass negative numbers index from the end of the list.
#### Parameters
+ ##### index: number#### Returns undefined | [Value](value)
### hashCode
* hashCode(): number
* Returns a hash code that can be used to store `this` in a hash map.
#### Returns number
### sassIndexToListIndex
* sassIndexToListIndex(sassIndex: [Value](value), name?: string): number
* Converts `sassIndex` into a JavaScript-style index into the list returned by [asList](sasslist#asList).
Sass indexes are one-based, while JavaScript indexes are zero-based. Sass indexes may also be negative in order to index from the end of the list.
throws
`Error` If `sassIndex` isn't a number, if that number isn't an integer, or if that integer isn't a valid index for [asList](sasslist#asList).
#### Parameters
+ ##### sassIndex: [Value](value)
The Sass-style index into this as a list.
+ #####
Optional name: string
The name of the function argument `sassIndex` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns number
### tryMap
* tryMap(): null | [SassMap](sassmap)
* Returns `this` as a map if it counts as one (empty lists count as empty maps) or `null` if it doesn't.
#### Returns null | [SassMap](sassmap)
sass Class Value
The abstract base class of Sass's value types.
This is passed to and returned by [CustomFunction](../modules#CustomFunction)s, which are passed into the Sass implementation using [Options.functions](../interfaces/options#functions).
### Hierarchy
* Value
+ [SassBoolean](sassboolean)
+ [SassColor](sasscolor)
+ [SassFunction](sassfunction)
+ [SassList](sasslist)
+ [SassMap](sassmap)
+ [SassNumber](sassnumber)
+ [SassString](sassstring)
### Implements
* ValueObject
Index
-----
### Accessors
* [asList](value#asList)
* [hasBrackets](value#hasBrackets)
* [isTruthy](value#isTruthy)
* [realNull](value#realNull)
* [separator](value#separator)
### Methods
* [assertBoolean](value#assertBoolean)
* [assertColor](value#assertColor)
* [assertFunction](value#assertFunction)
* [assertMap](value#assertMap)
* [assertNumber](value#assertNumber)
* [assertString](value#assertString)
* [equals](value#equals)
* [get](value#get)
* [hashCode](value#hashCode)
* [sassIndexToListIndex](value#sassIndexToListIndex)
* [tryMap](value#tryMap)
Accessors
---------
### asList
* get asList(): List<[Value](value)>
* This value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns List<[Value](value)>
An immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
### hasBrackets
* get hasBrackets(): boolean
* Whether this value as a list has brackets.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns boolean
### isTruthy
* get isTruthy(): boolean
* Whether the value counts as `true` in an `@if` statement and other contexts.
#### Returns boolean
### realNull
* get realNull(): null | [Value](value)
* Returns JavaScript's `null` value if this is [sassNull](../modules#sassNull), and returns `this` otherwise.
#### Returns null | [Value](value)
### separator
* get separator(): [ListSeparator](../modules#ListSeparator)
* The separator for this value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns [ListSeparator](../modules#ListSeparator)
Methods
-------
### assertBoolean
* assertBoolean(name?: string): [SassBoolean](sassboolean)
* Throws if `this` isn't a [SassBoolean](sassboolean).
### ⚠️ Heads up!
Functions should generally use [isTruthy](value#isTruthy) rather than requiring a literal boolean.
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassBoolean](sassboolean)
### assertColor
* assertColor(name?: string): [SassColor](sasscolor)
* Throws if `this` isn't a [SassColor](sasscolor).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassColor](sasscolor)
### assertFunction
* assertFunction(name?: string): [SassFunction](sassfunction)
* Throws if `this` isn't a [SassFunction](sassfunction).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassFunction](sassfunction)
### assertMap
* assertMap(name?: string): [SassMap](sassmap)
* Throws if `this` isn't a [SassMap](sassmap).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassMap](sassmap)
### assertNumber
* assertNumber(name?: string): [SassNumber](sassnumber)
* Throws if `this` isn't a [SassNumber](sassnumber).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassNumber](sassnumber)
### assertString
* assertString(name?: string): [SassString](sassstring)
* Throws if `this` isn't a [SassString](sassstring).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassString](sassstring)
### equals
* equals(other: [Value](value)): boolean
* Returns whether `this` represents the same value as `other`.
#### Parameters
+ ##### other: [Value](value)#### Returns boolean
### get
* get(index: number): undefined | [Value](value)
* Returns the value at index `index` in this value as a list, or `undefined` if `index` isn't valid for this list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
This is a shorthand for `this.asList.get(index)`, although it may be more efficient in some cases.
### ⚠️ Heads up!
This method uses the same indexing conventions as the `immutable` package: unlike Sass the index of the first element is 0, but like Sass negative numbers index from the end of the list.
#### Parameters
+ ##### index: number#### Returns undefined | [Value](value)
### hashCode
* hashCode(): number
* Returns a hash code that can be used to store `this` in a hash map.
#### Returns number
### sassIndexToListIndex
* sassIndexToListIndex(sassIndex: [Value](value), name?: string): number
* Converts `sassIndex` into a JavaScript-style index into the list returned by [asList](value#asList).
Sass indexes are one-based, while JavaScript indexes are zero-based. Sass indexes may also be negative in order to index from the end of the list.
throws
`Error` If `sassIndex` isn't a number, if that number isn't an integer, or if that integer isn't a valid index for [asList](value#asList).
#### Parameters
+ ##### sassIndex: [Value](value)
The Sass-style index into this as a list.
+ #####
Optional name: string
The name of the function argument `sassIndex` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns number
### tryMap
* tryMap(): null | [SassMap](sassmap)
* Returns `this` as a map if it counts as one (empty lists count as empty maps) or `null` if it doesn't.
#### Returns null | [SassMap](sassmap)
| programming_docs |
sass Class SassString Sass's [string type](../../values/strings).
### Hierarchy
* [Value](value)
+ SassString
Index
-----
### Constructors
* [constructor](sassstring#constructor)
### Accessors
* [asList](sassstring#asList)
* [hasBrackets](sassstring#hasBrackets)
* [hasQuotes](sassstring#hasQuotes)
* [isTruthy](sassstring#isTruthy)
* [realNull](sassstring#realNull)
* [sassLength](sassstring#sassLength)
* [separator](sassstring#separator)
* [text](sassstring#text)
### Methods
* [assertBoolean](sassstring#assertBoolean)
* [assertColor](sassstring#assertColor)
* [assertFunction](sassstring#assertFunction)
* [assertMap](sassstring#assertMap)
* [assertNumber](sassstring#assertNumber)
* [assertString](sassstring#assertString)
* [equals](sassstring#equals)
* [get](sassstring#get)
* [hashCode](sassstring#hashCode)
* [sassIndexToListIndex](sassstring#sassIndexToListIndex)
* [sassIndexToStringIndex](sassstring#sassIndexToStringIndex)
* [tryMap](sassstring#tryMap)
Constructors
------------
### constructor
* new SassString(text: string, options?: { quotes?: boolean }): [SassString](sassstring)
* Creates a new string.
#### Parameters
+ ##### text: string
The contents of the string. For quoted strings, this is the semantic content—any escape sequences that were been written in the source text are resolved to their Unicode values. For unquoted strings, though, escape sequences are preserved as literal backslashes.
+ #####
Optional options: { quotes?: boolean }
- #####
Optional quotes?: boolean
Whether the string is quoted. Defaults to `true`.#### Returns [SassString](sassstring)
### constructor
* new SassString(options?: { quotes?: boolean }): [SassString](sassstring)
* Creates an empty string.
#### Parameters
+ #####
Optional options: { quotes?: boolean }
- #####
Optional quotes?: boolean
Whether the string is quoted. Defaults to `true`.#### Returns [SassString](sassstring)
Accessors
---------
### asList
* get asList(): List<[Value](value)>
* This value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns List<[Value](value)>
An immutable [List](types.list) from the [`immutable` package](https://immutable-js.com/).
### hasBrackets
* get hasBrackets(): boolean
* Whether this value as a list has brackets.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns boolean
### hasQuotes
* get hasQuotes(): boolean
* Whether this string has quotes.
#### Returns boolean
### isTruthy
* get isTruthy(): boolean
* Whether the value counts as `true` in an `@if` statement and other contexts.
#### Returns boolean
### realNull
* get realNull(): null | [Value](value)
* Returns JavaScript's `null` value if this is [sassNull](../modules#sassNull), and returns `this` otherwise.
#### Returns null | [Value](value)
### sassLength
* get sassLength(): number
* Sass's notion of this string's length.
Sass treats strings as a series of Unicode code points while JavaScript treats them as a series of UTF-16 code units. For example, the character U+1F60A SMILING FACE WITH SMILING EYES is a single Unicode code point but is represented in UTF-16 as two code units (`0xD83D` and `0xDE0A`). So in JavaScript, `"n😊b".length` returns `4`, whereas in Sass `string.length("n😊b")` returns `3`.
#### Returns number
### separator
* get separator(): [ListSeparator](../modules#ListSeparator)
* The separator for this value as a list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
#### Returns [ListSeparator](../modules#ListSeparator)
### text
* get text(): string
* The contents of the string.
For quoted strings, this is the semantic content—any escape sequences that were been written in the source text are resolved to their Unicode values. For unquoted strings, though, escape sequences are preserved as literal backslashes.
This difference allows us to distinguish between identifiers with escapes, such as `url\u28 http://example.com\u29`, and unquoted strings that contain characters that aren't valid in identifiers, such as `url(http://example.com)`. Unfortunately, it also means that we don't consider `foo` and `f\6F\6F` the same string.
#### Returns string
Methods
-------
### assertBoolean
* assertBoolean(name?: string): [SassBoolean](sassboolean)
* Throws if `this` isn't a [SassBoolean](sassboolean).
### ⚠️ Heads up!
Functions should generally use [isTruthy](sassstring#isTruthy) rather than requiring a literal boolean.
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassBoolean](sassboolean)
### assertColor
* assertColor(name?: string): [SassColor](sasscolor)
* Throws if `this` isn't a [SassColor](sasscolor).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassColor](sasscolor)
### assertFunction
* assertFunction(name?: string): [SassFunction](sassfunction)
* Throws if `this` isn't a [SassFunction](sassfunction).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassFunction](sassfunction)
### assertMap
* assertMap(name?: string): [SassMap](sassmap)
* Throws if `this` isn't a [SassMap](sassmap).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassMap](sassmap)
### assertNumber
* assertNumber(name?: string): [SassNumber](sassnumber)
* Throws if `this` isn't a [SassNumber](sassnumber).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassNumber](sassnumber)
### assertString
* assertString(name?: string): [SassString](sassstring)
* Throws if `this` isn't a [SassString](sassstring).
#### Parameters
+ #####
Optional name: string
The name of the function argument `this` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns [SassString](sassstring)
### equals
* equals(other: [Value](value)): boolean
* Returns whether `this` represents the same value as `other`.
#### Parameters
+ ##### other: [Value](value)#### Returns boolean
### get
* get(index: number): undefined | [Value](value)
* Returns the value at index `index` in this value as a list, or `undefined` if `index` isn't valid for this list.
All SassScript values can be used as lists. Maps count as lists of pairs, and all other values count as single-value lists.
This is a shorthand for `this.asList.get(index)`, although it may be more efficient in some cases.
### ⚠️ Heads up!
This method uses the same indexing conventions as the `immutable` package: unlike Sass the index of the first element is 0, but like Sass negative numbers index from the end of the list.
#### Parameters
+ ##### index: number#### Returns undefined | [Value](value)
### hashCode
* hashCode(): number
* Returns a hash code that can be used to store `this` in a hash map.
#### Returns number
### sassIndexToListIndex
* sassIndexToListIndex(sassIndex: [Value](value), name?: string): number
* Converts `sassIndex` into a JavaScript-style index into the list returned by [asList](sassstring#asList).
Sass indexes are one-based, while JavaScript indexes are zero-based. Sass indexes may also be negative in order to index from the end of the list.
throws
`Error` If `sassIndex` isn't a number, if that number isn't an integer, or if that integer isn't a valid index for [asList](sassstring#asList).
#### Parameters
+ ##### sassIndex: [Value](value)
The Sass-style index into this as a list.
+ #####
Optional name: string
The name of the function argument `sassIndex` came from (without the `$`) if it came from an argument. Used for error reporting.#### Returns number
### sassIndexToStringIndex
* sassIndexToStringIndex(sassIndex: [Value](value), name?: string): number
* Converts `sassIndex` to a JavaScript index into [text](sassstring#text).
Sass indices are one-based, while JavaScript indices are zero-based. Sass indices may also be negative in order to index from the end of the string.
In addition, Sass indices refer to Unicode code points while JavaScript string indices refer to UTF-16 code units. For example, the character U+1F60A SMILING FACE WITH SMILING EYES is a single Unicode code point but is represented in UTF-16 as two code units (`0xD83D` and `0xDE0A`). So in JavaScript, `"n😊b".charCodeAt(1)` returns `0xD83D`, whereas in Sass `string.slice("n😊b", 1, 1)` returns `"😊"`.
This function converts Sass's code point indices to JavaScript's code unit indices. This means it's O(n) in the length of `text`.
throws
`Error` - If `sassIndex` isn't a number, if that number isn't an integer, or if that integer isn't a valid index for this string.
#### Parameters
+ ##### sassIndex: [Value](value)
+ #####
Optional name: string#### Returns number
### tryMap
* tryMap(): null | [SassMap](sassmap)
* Returns `this` as a map if it counts as one (empty lists count as empty maps) or `null` if it doesn't.
#### Returns null | [SassMap](sassmap)
sass Class Number Sass's [number type](../../values/numbers).
### Hierarchy
* Number
Index
-----
### Constructors
* [constructor](types.number#constructor)
### Methods
* [getUnit](types.number#getUnit)
* [getValue](types.number#getValue)
* [setUnit](types.number#setUnit)
* [setValue](types.number#setValue)
Constructors
------------
### constructor
* new Number(value: number, unit?: string): [Number](types.number)
* example
```
new sass.types.Number(0.5); // == 0.5
new sass.types.Number(10, "px"); // == 10px
new sass.types.Number(10, "px\*px"); // == 10px \* 1px
new sass.types.Number(10, "px/s"); // == math.div(10px, 1s)
new sass.types.Number(10, "px\*px/s\*s"); // == 10px \* math.div(math.div(1px, 1s), 1s)
```
#### Parameters
+ ##### value: number
The numeric value of the number.
+ #####
Optional unit: string
If passed, the number's unit.
Complex units can be represented as `<unit>*<unit>*.../<unit>*<unit>*...`, with numerator units on the left-hand side of the `/` and denominator units on the right. A number with only numerator units may omit the `/` and the units after it, and a number with only denominator units may be represented with no units before the `/`.#### Returns [Number](types.number)
Methods
-------
### getUnit
* getUnit(): string
* Returns a string representation of this number's units. Complex units are returned in the same format that [constructor](types.number#constructor) accepts them.
example
```
// number is `10px`.
number.getUnit(); // "px"
// number is `math.div(10px, 1s)`.
number.getUnit(); // "px/s"
```
#### Returns string
### getValue
* getValue(): number
* Returns the value of the number, ignoring units.
### ⚠️ Heads up!
This means that `96px` and `1in` will return different values, even though they represent the same length.
example
```
constnumber = newsass.types.Number(10, "px");
number.getValue(); // 10
```
#### Returns number
### setUnit
* setUnit(unit: string): void
* Destructively modifies this number by setting its units to `unit`, independent of its numeric value. Complex units are specified in the same format as [constructor](types.number#constructor).
deprecated
Use [constructor](types.number#constructor) instead.
#### Parameters
+ ##### unit: string#### Returns void
### setValue
* setValue(value: number): void
* Destructively modifies this number by setting its numeric value to `value`, independent of its units.
deprecated
Use [constructor](types.number#constructor) instead.
#### Parameters
+ ##### value: number#### Returns void
sass Class Error An error that can be returned from a Sass function to signal that it encountered an error. This is the only way to signal an error asynchronously from a [LegacyAsyncFunction](../modules#LegacyAsyncFunction).
### Hierarchy
* Error
Index
-----
### Constructors
* [constructor](types.error#constructor)
Constructors
------------
### constructor
* new Error(message: string): [Error](types.error)
* #### Parameters
+ ##### message: string#### Returns [Error](types.error)
sass Class Color Sass's [color type](../../values/colors).
### Hierarchy
* Color
Index
-----
### Constructors
* [constructor](types.color#constructor)
### Methods
* [getA](types.color#getA)
* [getB](types.color#getB)
* [getG](types.color#getG)
* [getR](types.color#getR)
* [setA](types.color#setA)
* [setB](types.color#setB)
* [setG](types.color#setG)
* [setR](types.color#setR)
Constructors
------------
### constructor
* new Color(r: number, g: number, b: number, a?: number): [Color](types.color)
* Creates a new Sass color with the given red, green, blue, and alpha channels. The red, green, and blue channels must be integers between 0 and 255 (inclusive), and alpha must be between 0 and 1 (inclusive).
example
```
newsass.types.Color(107, 113, 127); // #6b717f
newsass.types.Color(0, 0, 0, 0); // rgba(0, 0, 0, 0)
```
#### Parameters
+ ##### r: number
+ ##### g: number
+ ##### b: number
+ #####
Optional a: number#### Returns [Color](types.color)
### constructor
* new Color(argb: number): [Color](types.color)
* Creates a new Sass color with alpha, red, green, and blue channels taken from respective two-byte chunks of a hexidecimal number.
example
```
newsass.types.Color(0xff6b717f); // #6b717f
newsass.types.Color(0x00000000); // rgba(0, 0, 0, 0)
```
#### Parameters
+ ##### argb: number#### Returns [Color](types.color)
Methods
-------
### getA
* getA(): number
* Returns the alpha channel of the color as a number from 0 to 1.
example
```
// color is `#6b717f`.
color.getA(); // 1
// color is `transparent`.
color.getA(); // 0
```
#### Returns number
### getB
* getB(): number
* Returns the blue channel of the color as an integer from 0 to 255.
example
```
// color is `#6b717f`.
color.getB(); // 127
// color is `#b37399`.
color.getB(); // 153
```
#### Returns number
### getG
* getG(): number
* Returns the green channel of the color as an integer from 0 to 255.
example
```
// color is `#6b717f`.
color.getG(); // 113
// color is `#b37399`.
color.getG(); // 115
```
#### Returns number
### getR
* getR(): number
* Returns the red channel of the color as an integer from 0 to 255.
example
```
// color is `#6b717f`.
color.getR(); // 107
// color is `#b37399`.
color.getR(); // 179
```
#### Returns number
### setA
* setA(value: number): void
* Sets the alpha channel of the color. The value must be between 0 and 1 (inclusive).
deprecated
Use [constructor](types.color#constructor) instead.
#### Parameters
+ ##### value: number#### Returns void
### setB
* setB(value: number): void
* Sets the blue channel of the color. The value must be an integer between 0 and 255 (inclusive).
deprecated
Use [constructor](types.color#constructor) instead.
#### Parameters
+ ##### value: number#### Returns void
### setG
* setG(value: number): void
* Sets the green channel of the color. The value must be an integer between 0 and 255 (inclusive).
deprecated
Use [constructor](types.color#constructor) instead.
#### Parameters
+ ##### value: number#### Returns void
### setR
* setR(value: number): void
* Sets the red channel of the color. The value must be an integer between 0 and 255 (inclusive).
deprecated
Use [constructor](types.color#constructor) instead.
#### Parameters
+ ##### value: number#### Returns void
sass Namespace Logger
Compatibility:
Dart Sass since 1.43.0
Node Sass ✗ A namespace for built-in [Logger](../interfaces/logger)s.
Index
-----
### Variables
* [silent](logger#silent)
Variables
---------
### silent
silent: [Logger](../interfaces/logger)
A [Logger](../interfaces/logger) that silently ignores all warnings and debug messages.
example
```
constsass = require('sass');
constresult = sass.renderSync({
file:'input.scss',
logger:sass.Logger.silent,
});
```
sass Namespace types
The namespace for value types used in the legacy function API.
deprecated
This only works with the legacy [render](../modules#render) and [renderSync](../modules#renderSync) APIs. Use [Value](../classes/value) with [compile](../modules#compile), [compileString](../modules#compileString), [compileAsync](../modules#compileAsync), and [compileStringAsync](../modules#compileStringAsync) instead.
Index
-----
### Classes
* [Boolean](../classes/types.boolean)
* [Color](../classes/types.color)
* [Error](../classes/types.error)
* [List](../classes/types.list)
* [Map](../classes/types.map)
* [Null](../classes/types.null)
* [Number](../classes/types.number)
* [String](../classes/types.string)
sass Interface Importer<sync>
An object that implements custom Sass loading logic for [`@use` rules](../../at-rules/use) and [`@import` rules](../../at-rules/import). It can be passed to [Options.importers](options#importers) or [StringOptionsWithImporter.importer](stringoptionswithimporter#importer).
Importers that simply redirect to files on disk are encouraged to use the [FileImporter](fileimporter) interface instead.
See [Options.importers](options#importers) for more details on the way loads are resolved.
example
Resolving a Load
This is the process of resolving a load using a custom importer:
* The compiler encounters `@use "db:foo/bar/baz"`.
* It calls [canonicalize](importer#canonicalize) with `"db:foo/bar/baz"`.
* [canonicalize](importer#canonicalize) returns `new URL("db:foo/bar/baz/_index.scss")`.
* If the compiler has already loaded a stylesheet with this canonical URL, it re-uses the existing module.
* Otherwise, it calls [load](importer#load) with `new URL("db:foo/bar/baz/_index.scss")`.
* [load](importer#load) returns an [ImporterResult](importerresult) that the compiler uses as the contents of the module.
example
Code Sample
```
sass.compile('style.scss', {
// An importer for URLs like `bgcolor:orange` that generates a
// stylesheet with the given background color.
importers: [{
canonicalize(url) {
if (!url.startsWith('bgcolor:')) returnnull;
returnnewURL(url);
},
load(canonicalUrl) {
return {
contents:`body {background-color: ${canonicalUrl.pathname}}`,
syntax:'scss'
};
}
}]
});
```
### Type parameters
* #### sync: "sync" | "async" = "sync" | "async"
An `Importer<'sync'>`'s [canonicalize](importer#canonicalize) and [load](importer#load) must return synchronously, but in return it can be passed to [compile](../modules#compile) and [compileString](../modules#compileString) in addition to [compileAsync](../modules#compileAsync) and [compileStringAsync](../modules#compileStringAsync).
An `Importer<'async'>`'s [canonicalize](importer#canonicalize) and [load](importer#load) may either return synchronously or asynchronously, but it can only be used with [compileAsync](../modules#compileAsync) and [compileStringAsync](../modules#compileStringAsync).
### Hierarchy
* Importer
Index
-----
### Methods
* [canonicalize](importer#canonicalize)
* [load](importer#load)
Methods
-------
### canonicalize
* canonicalize(url: string, options: { fromImport: boolean }): [PromiseOr](../modules#PromiseOr)<null | [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL), sync>
* If `url` is recognized by this importer, returns its canonical format.
If Sass has already loaded a stylesheet with the returned canonical URL, it re-uses the existing parse tree (and the loaded module for `@use`). This means that importers **must ensure** that the same canonical URL always refers to the same stylesheet, *even across different importers*. As such, importers are encouraged to use unique URL schemes to disambiguate between one another.
As much as possible, custom importers should canonicalize URLs the same way as the built-in filesystem importer:
+ The importer should look for stylesheets by adding the prefix `_` to the URL's basename, and by adding the extensions `.sass` and `.scss` if the URL doesn't already have one of those extensions. For example, if the URL was `foo/bar/baz`, the importer would look for:
- `foo/bar/baz.sass`
- `foo/bar/baz.scss`
- `foo/bar/_baz.sass`
- `foo/bar/_baz.scss`If the URL was `foo/bar/baz.scss`, the importer would just look for:
- `foo/bar/baz.scss`
- `foo/bar/_baz.scss`If the importer finds a stylesheet at more than one of these URLs, it should throw an exception indicating that the URL is ambiguous. Note that if the extension is explicitly specified, a stylesheet with the opposite extension is allowed to exist.
+ If none of the possible paths is valid, the importer should perform the same resolution on the URL followed by `/index`. In the example above, it would look for:
- `foo/bar/baz/index.sass`
- `foo/bar/baz/index.scss`
- `foo/bar/baz/_index.sass`
- `foo/bar/baz/_index.scss`As above, if the importer finds a stylesheet at more than one of these URLs, it should throw an exception indicating that the import is ambiguous. If no stylesheets are found, the importer should return `null`.
Calling [canonicalize](importer#canonicalize) multiple times with the same URL must return the same result. Calling [canonicalize](importer#canonicalize) with a URL returned by a previous call to [canonicalize](importer#canonicalize) must return that URL.
Relative loads in stylesheets loaded from an importer are handled by resolving the loaded URL relative to the canonical URL of the stylesheet that contains it, and passing that URL back to the importer's [canonicalize](importer#canonicalize) method. For example, suppose the "Resolving a Load" example [above](importer) returned a stylesheet that contained `@use "mixins"`:
+ The compiler resolves the URL `mixins` relative to the current stylesheet's canonical URL `db:foo/bar/baz/_index.scss` to get `db:foo/bar/baz/mixins`.
+ It calls [canonicalize](importer#canonicalize) with `"db:foo/bar/baz/mixins"`.
+ [canonicalize](importer#canonicalize) returns `new URL("db:foo/bar/baz/_mixins.scss")`. Because of this, [canonicalize](importer#canonicalize) must return a meaningful result when called with a URL relative to one returned by an earlier call to [canonicalize](importer#canonicalize).
throws
any - If this importer recognizes `url` but determines that it's invalid, it may throw an exception that will be wrapped by Sass. If the exception object has a `message` property, it will be used as the wrapped exception's message; otherwise, the exception object's `toString()` will be used. This means it's safe for importers to throw plain strings.
#### Parameters
+ ##### url: string
The loaded URL. Since this might be relative, it's represented as a string rather than a [[URL]] object.
+ ##### options: { fromImport: boolean }
- ##### fromImport: boolean
Whether this is being invoked because of a Sass `@import` rule, as opposed to a `@use` or `@forward` rule.
This should *only* be used for determining whether or not to load [import-only files](../../at-rules/import#import-only-files).#### Returns [PromiseOr](../modules#PromiseOr)<null | [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL), sync>
An absolute URL if this importer recognizes the `url`, or `null` if it doesn't. If this returns `null`, other importers or [load paths](options#loadPaths) may handle the load.
This may also return a `Promise`, but if it does the importer may only be passed to [compileAsync](../modules#compileAsync) and [compileStringAsync](../modules#compileStringAsync), not [compile](../modules#compile) or [compileString](../modules#compileString).
### load
* load(canonicalUrl: [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL)): [PromiseOr](../modules#PromiseOr)<null | [ImporterResult](importerresult), sync>
* Loads the Sass text for the given `canonicalUrl`, or returns `null` if this importer can't find the stylesheet it refers to.
throws
any - If this importer finds a stylesheet at `url` but it fails to load for some reason, or if `url` is uniquely associated with this importer but doesn't refer to a real stylesheet, the importer may throw an exception that will be wrapped by Sass. If the exception object has a `message` property, it will be used as the wrapped exception's message; otherwise, the exception object's `toString()` will be used. This means it's safe for importers to throw plain strings.
#### Parameters
+ ##### canonicalUrl: [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL)
The canonical URL of the stylesheet to load. This is guaranteed to come from a call to [canonicalize](importer#canonicalize), although not every call to [canonicalize](importer#canonicalize) will result in a call to [load](importer#load).#### Returns [PromiseOr](../modules#PromiseOr)<null | [ImporterResult](importerresult), sync>
The contents of the stylesheet at `canonicalUrl` if it can be loaded, or `null` if it can't.
This may also return a `Promise`, but if it does the importer may only be passed to [compileAsync](../modules#compileAsync) and [compileStringAsync](../modules#compileStringAsync), not [compile](../modules#compile) or [compileString](../modules#compileString).
| programming_docs |
sass Interface SourceLocation
A specific location within a source file.
This is always associated with a [SourceSpan](sourcespan) which indicates *which* file it refers to.
### Hierarchy
* SourceLocation
Index
-----
### Properties
* [column](sourcelocation#column)
* [line](sourcelocation#line)
* [offset](sourcelocation#offset)
Properties
----------
### column
column: number
The 0-based column number of this location.
### line
line: number
The 0-based line number of this location.
### offset
offset: number
The 0-based index of this location within its source file, in terms of UTF-16 code units.
sass Interface SourceSpan A span of text within a source file.
### Hierarchy
* SourceSpan
Index
-----
### Properties
* [context](sourcespan#context)
* [end](sourcespan#end)
* [start](sourcespan#start)
* [text](sourcespan#text)
* [url](sourcespan#url)
Properties
----------
###
Optional context
context?: string
Text surrounding the span.
If this is set, it must include only whole lines, and it must include at least all line(s) which are partially covered by this span.
### end
end: [SourceLocation](sourcelocation)
The end of this span, exclusive.
If [start](sourcespan#start) and [end](sourcespan#end) refer to the same location, the span has zero length and refers to the point immediately after [start](sourcespan#start) and before the next character.
### start
start: [SourceLocation](sourcelocation)
The beginning of this span, inclusive.
### text
text: string
The text covered by the span.
###
Optional url
url?: [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL)
The canonical URL of the file this span refers to.
sass Interface LegacyResult
The object returned by [render](../modules#render) and [renderSync](../modules#renderSync) after a successful compilation.
deprecated
This is only used by the legacy [render](../modules#render) and [renderSync](../modules#renderSync) APIs. Use [compile](../modules#compile), [compileString](../modules#compileString), [compileAsync](../modules#compileAsync), and [compileStringAsync](../modules#compileStringAsync) instead.
### Hierarchy
* LegacyResult
Index
-----
### Properties
* [css](legacyresult#css)
* [map](legacyresult#map)
* [stats](legacyresult#stats)
Properties
----------
### css
css: [Buffer](https://nodejs.org/api/buffer.html)
The compiled CSS. This can be converted to a string by calling [Buffer.toString](https://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end).
example
```
constresult = sass.renderSync({file:"style.scss"});
console.log(result.css.toString());
```
###
Optional map
map?: [Buffer](https://nodejs.org/api/buffer.html)
The source map that maps the compiled CSS to the source files from which it was generated. This can be converted to a string by calling [Buffer.toString](https://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end).
This is `undefined` unless either
* [LegacySharedOptions.sourceMap](legacysharedoptions#sourceMap) is a string; or
* [LegacySharedOptions.sourceMap](legacysharedoptions#sourceMap) is `true` and [LegacySharedOptions.outFile](legacysharedoptions#outFile) is set.
The source map uses absolute [`file:` URLs](https://en.wikipedia.org/wiki/File_URI_scheme) to link to the Sass source files, except if the source file comes from [LegacyStringOptions.data](legacystringoptions#data) in which case it lists its URL as `"stdin"`.
example
```
constresult = sass.renderSync({
file:"style.scss",
sourceMap:true,
outFile:"style.css"
})
console.log(result.map.toString());
```
### stats
stats: { duration: number; end: number; entry: string; includedFiles: string[]; start: number }
Additional information about the compilation.
#### Type declaration
* ##### duration: number
The number of milliseconds it took to compile the Sass file. This is always equal to `start` minus `end`.
* ##### end: number
The number of milliseconds between 1 January 1970 at 00:00:00 UTC and the time at which Sass compilation ended.
* ##### entry: string
The absolute path of [LegacyFileOptions.file](legacyfileoptions#file) or [LegacyStringOptions.file](legacystringoptions#file), or `"data"` if [LegacyStringOptions.file](legacystringoptions#file) wasn't set.
* ##### includedFiles: string[]
An array of the absolute paths of all Sass files loaded during compilation. If a stylesheet was loaded from a [LegacyImporter](../modules#LegacyImporter) that returned the stylesheet’s contents, the raw string of the `@use` or `@import` that loaded that stylesheet included in this array.
* ##### start: number
The number of milliseconds between 1 January 1970 at 00:00:00 UTC and the time at which Sass compilation began.
sass Interface FileImporter<sync>
A special type of importer that redirects all loads to existing files on disk. Although this is less powerful than a full [Importer](importer), it automatically takes care of Sass features like resolving partials and file extensions and of loading the file from disk.
Like all importers, this implements custom Sass loading logic for [`@use` rules](../../at-rules/use) and [`@import` rules](../../at-rules/import). It can be passed to [Options.importers](options#importers) or [StringOptionsWithImporter.importer](stringoptionswithimporter#importer).
example
```
const {pathToFileURL} = require('url');
sass.compile('style.scss', {
importers: [{
// An importer that redirects relative URLs starting with "~" to
// `node\_modules`.
findFileUrl(url) {
if (!url.startsWith('~')) returnnull;
returnnewURL(url.substring(1), pathToFileURL('node\_modules'));
}
}]
});
```
### Type parameters
* #### sync: "sync" | "async" = "sync" | "async"
A `FileImporter<'sync'>`'s [findFileUrl](fileimporter#findFileUrl) must return synchronously, but in return it can be passed to [compile](../modules#compile) and [compileString](../modules#compileString) in addition to [compileAsync](../modules#compileAsync) and [compileStringAsync](../modules#compileStringAsync).
A `FileImporter<'async'>`'s [findFileUrl](fileimporter#findFileUrl) may either return synchronously or asynchronously, but it can only be used with [compileAsync](../modules#compileAsync) and [compileStringAsync](../modules#compileStringAsync).
### Hierarchy
* FileImporter
Index
-----
### Methods
* [findFileUrl](fileimporter#findFileUrl)
Methods
-------
### findFileUrl
* findFileUrl(url: string, options: { fromImport: boolean }): [PromiseOr](../modules#PromiseOr)<null | [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL), sync>
* A callback that's called to partially resolve a load (such as [`@use`](../../at-rules/use) or [`@import`](../../at-rules/import)) to a file on disk.
Unlike an [Importer](importer), the compiler will automatically handle relative loads for a [FileImporter](fileimporter). See [Options.importers](options#importers) for more details on the way loads are resolved.
throws
any - If this importer recognizes `url` but determines that it's invalid, it may throw an exception that will be wrapped by Sass. If the exception object has a `message` property, it will be used as the wrapped exception's message; otherwise, the exception object's `toString()` will be used. This means it's safe for importers to throw plain strings.
#### Parameters
+ ##### url: string
The loaded URL. Since this might be relative, it's represented as a string rather than a [[URL]] object.
+ ##### options: { fromImport: boolean }
- ##### fromImport: boolean
Whether this is being invoked because of a Sass `@import` rule, as opposed to a `@use` or `@forward` rule.
This should *only* be used for determining whether or not to load [import-only files](../../at-rules/import#import-only-files).#### Returns [PromiseOr](../modules#PromiseOr)<null | [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL), sync>
An absolute `file:` URL if this importer recognizes the `url`. This may be only partially resolved: the compiler will automatically look for [partials](../../at-rules/use#partials), [index files](../../at-rules/use#index-files), and file extensions based on the returned URL. An importer may also return a fully resolved URL if it so chooses.
If this importer doesn't recognize the URL, it should return `null` instead to allow other importers or [load paths](options#loadPaths) to handle it.
This may also return a `Promise`, but if it does the importer may only be passed to [compileAsync](../modules#compileAsync) and [compileStringAsync](../modules#compileStringAsync), not [compile](../modules#compile) or [compileString](../modules#compileString).
sass Interface Logger
An object that can be passed to [LegacySharedOptions.logger](legacysharedoptions#logger) to control how Sass emits warnings and debug messages.
example
```
constfs = require('fs');
constsass = require('sass');
letlog = "";
sass.renderSync({
file:'input.scss',
logger: {
warn(message, options) {
if (options.span) {
log += `${span.url}:${span.start.line}:${span.start.column}: ` +
`${message}\n`;
} else {
log += `::: ${message}\n`;
}
}
}
});
fs.writeFileSync('log.txt', log);
```
### Hierarchy
* Logger
Index
-----
### Methods
* [debug](logger#debug)
* [warn](logger#warn)
Methods
-------
###
Optional debug
* debug(message: string, options: { span: [SourceSpan](sourcespan) }): void
* This method is called when Sass emits a debug message due to a [`@debug` rule](../../at-rules/debug).
If this is `undefined`, Sass will print debug messages to standard error.
#### Parameters
+ ##### message: string
The debug message.
+ ##### options: { span: [SourceSpan](sourcespan) }
- ##### span: [SourceSpan](sourcespan)
The location in the Sass source code that generated this debug message.#### Returns void
###
Optional warn
* warn(message: string, options: { deprecation: boolean; span?: [SourceSpan](sourcespan); stack?: string }): void
* This method is called when Sass emits a warning, whether due to a [`@warn` rule](../../at-rules/warn) or a warning generated by the Sass compiler.
If this is `undefined`, Sass will print warnings to standard error.
#### Parameters
+ ##### message: string
The warning message.
+ ##### options: { deprecation: boolean; span?: [SourceSpan](sourcespan); stack?: string }
- ##### deprecation: boolean
Whether this is a deprecation warning.
- #####
Optional span?: [SourceSpan](sourcespan)
The location in the Sass source code that generated this warning.
- #####
Optional stack?: string
The Sass stack trace at the point the warning was issued.#### Returns void
sass Interface LegacyImporterThis
The value of `this` in the context of a [LegacyImporter](../modules#LegacyImporter) function.
deprecated
This is only used by the legacy [render](../modules#render) and [renderSync](../modules#renderSync) APIs. Use [Importer](importer) with [compile](../modules#compile), [compileString](../modules#compileString), [compileAsync](../modules#compileAsync), and [compileStringAsync](../modules#compileStringAsync) instead.
### Hierarchy
* [LegacyPluginThis](legacypluginthis)
+ LegacyImporterThis
Index
-----
### Properties
* [fromImport](legacyimporterthis#fromImport)
* [options](legacyimporterthis#options)
Properties
----------
### fromImport
fromImport: boolean
Compatibility:
Dart Sass since 1.33.0
Node Sass ✗ Whether the importer is being invoked because of a Sass `@import` rule, as opposed to a `@use` or `@forward` rule.
This should *only* be used for determining whether or not to load [import-only files](../../at-rules/import#import-only-files).
### options
options: { context: [LegacyPluginThis](legacypluginthis); data?: string; file?: string; includePaths: string; indentType: 0 | 1; indentWidth: number; linefeed: "\r" | "\r\n" | "\n" | "\n\r"; precision: 10; result: { stats: { entry: string; start: number } }; style: 1 }
A partial representation of the options passed to [render](../modules#render) or [renderSync](../modules#renderSync).
#### Type declaration
* ##### context: [LegacyPluginThis](legacypluginthis)
The same [LegacyPluginThis](legacypluginthis) instance that contains this object.
* #####
Optional data?: string
The value passed to [LegacyStringOptions.data](legacystringoptions#data).
* #####
Optional file?: string
The value passed to [LegacyFileOptions.file](legacyfileoptions#file) or [LegacyStringOptions.file](legacystringoptions#file).
* ##### includePaths: string
The value passed to [LegacySharedOptions.includePaths](legacysharedoptions#includePaths) separated by `";"` on Windows or `":"` on other operating systems. This always includes the current working directory as the first entry.
* ##### indentType: 0 | 1
1 if [LegacySharedOptions.indentType](legacysharedoptions#indentType) was `"tab"`, 0 otherwise.
* ##### indentWidth: number
The value passed to [LegacySharedOptions.indentWidth](legacysharedoptions#indentWidth), or `2` otherwise.
* ##### linefeed: "\r" | "\r\n" | "\n" | "\n\r"
The value passed to [LegacySharedOptions.linefeed](legacysharedoptions#linefeed), or `"\n"` otherwise.
* ##### precision: 10
Always the number 10.
* ##### result: { stats: { entry: string; start: number } }
A partially-constructed [LegacyResult](legacyresult) object.
+ ##### stats: { entry: string; start: number }
Partial information about the compilation in progress.
- ##### entry: string
[LegacyFileOptions.file](legacyfileoptions#file) if it was passed, otherwise the string `"data"`.
- ##### start: number
The number of milliseconds between 1 January 1970 at 00:00:00 UTC and the time at which Sass compilation began.
* ##### style: 1
Always the number 1.
sass Interface StringOptionsWithoutImporter<sync>
Options that can be passed to [compileString](../modules#compileString) or [compileStringAsync](../modules#compileStringAsync).
If the [StringOptionsWithImporter.importer](stringoptionswithimporter#importer) field isn't passed, the entrypoint file can load files relative to itself if a `file://` URL is passed to the [url](stringoptionswithoutimporter#url) field.
### Type parameters
* #### sync: "sync" | "async"
This lets the TypeScript checker verify that asynchronous [Importer](importer)s, [FileImporter](fileimporter)s, and [CustomFunction](../modules#CustomFunction)s aren't passed to [compile](../modules#compile) or [compileString](../modules#compileString).
### Hierarchy
* [Options](options)<sync>
+ StringOptionsWithoutImporter
- [StringOptionsWithImporter](stringoptionswithimporter)
Index
-----
### Input
* [loadPaths](stringoptionswithoutimporter#loadPaths)
* [syntax](stringoptionswithoutimporter#syntax)
* [url](stringoptionswithoutimporter#url)
### Output
* [charset](stringoptionswithoutimporter#charset)
* [sourceMap](stringoptionswithoutimporter#sourceMap)
* [sourceMapIncludeSources](stringoptionswithoutimporter#sourceMapIncludeSources)
* [style](stringoptionswithoutimporter#style)
### Plugins
* [functions](stringoptionswithoutimporter#functions)
* [importers](stringoptionswithoutimporter#importers)
### Messages
* [alertAscii](stringoptionswithoutimporter#alertAscii)
* [alertColor](stringoptionswithoutimporter#alertColor)
* [logger](stringoptionswithoutimporter#logger)
* [quietDeps](stringoptionswithoutimporter#quietDeps)
* [verbose](stringoptionswithoutimporter#verbose)
Input
-----
###
Optional loadPaths
loadPaths?: string[]
Paths in which to look for stylesheets loaded by rules like [`@use`](../../at-rules/use) and [`@import`](../../at-rules/import).
A load path `loadPath` is equivalent to the following [FileImporter](fileimporter):
```
{
findFileUrl(url) {
// Load paths only support relative URLs.
if (/^[a-z]+:/i.test(url)) returnnull;
returnnewURL(url, pathToFileURL(loadPath));
}
}
```
###
Optional syntax
syntax?: [Syntax](../modules#Syntax)
The [Syntax](../modules#Syntax) to use to parse the entrypoint stylesheet.
default
`'scss'`
###
Optional url
url?: [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL)
The canonical URL of the entrypoint stylesheet.
A relative load's URL is first resolved relative to [url](stringoptionswithoutimporter#url), then resolved to a file on disk if it's a `file://` URL. If it can't be resolved to a file on disk, it's then passed to [importers](stringoptionswithoutimporter#importers) and [loadPaths](stringoptionswithoutimporter#loadPaths).
Output
------
###
Optional charset
charset?: boolean
Compatibility:
Dart Sass since 1.54.0
Node Sass ✗ If `true`, the compiler may prepend `@charset "UTF-8";` or U+FEFF (byte-order marker) if it outputs non-ASCII CSS.
If `false`, the compiler never emits these byte sequences. This is ideal when concatenating or embedding in HTML `<style>` tags. (The output will still be UTF-8.)
defaultvalue
`true`
###
Optional sourceMap
sourceMap?: boolean
Whether or not Sass should generate a source map. If it does, the source map will be available as [CompileResult.sourceMap](compileresult#sourceMap).
### ⚠️ Heads up!
Sass doesn't automatically add a `sourceMappingURL` comment to the generated CSS. It's up to callers to do that, since callers have full knowledge of where the CSS and the source map will exist in relation to one another and how they'll be served to the browser.
defaultvalue
`false`
###
Optional sourceMapIncludeSources
sourceMapIncludeSources?: boolean
Whether Sass should include the sources in the generated source map.
This option has no effect if [sourceMap](stringoptionswithoutimporter#sourceMap) is `false`.
defaultvalue
`false`
###
Optional style
style?: [OutputStyle](../modules#OutputStyle)
The [OutputStyle](../modules#OutputStyle) of the compiled CSS.
example
```
constsource = `
h1 {
font-size: 40px;
code {
font-face: Roboto Mono;
}
}`;
letresult = sass.compileString(source, {style:"expanded"});
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
// h1 code {
// font-face: Roboto Mono;
// }
result = sass.compileString(source, {style:"compressed"})
console.log(result.css.toString());
// h1{font-size:40px}h1 code{font-face:Roboto Mono}
```
Plugins
-------
###
Optional functions
functions?: Record<string, [CustomFunction](../modules#CustomFunction)<sync>>
Additional built-in Sass functions that are available in all stylesheets. This option takes an object whose keys are Sass function signatures like you'd write for the [`@function rule`](../../at-rules/function) and whose values are [CustomFunction](../modules#CustomFunction)s.
Functions are passed JavaScript representations of [Sass value types](../../js-api#value-types), and must return the same.
When writing custom functions, it's important to make them as user-friendly and as close to the standards set by Sass's core functions as possible. Some good guidelines to follow include:
* Use `Value.assert*` methods, like [Value.assertString](../classes/value#assertString), to cast untyped `Value` objects to more specific types. For values that were passed directly as arguments, pass in the argument name as well. This ensures that the user gets good error messages when they pass in the wrong type to your function.
* Individual classes may have more specific `assert*` methods, like [SassNumber.assertInt](../classes/sassnumber#assertInt), which should be used when possible.
* In Sass, every value counts as a list. Rather than trying to detect the [SassList](../classes/sasslist) type, you should use [Value.asList](../classes/value#asList) to treat all values as lists.
* When manipulating values like lists, strings, and numbers that have metadata (comma versus space separated, bracketed versus unbracketed, quoted versus unquoted, units), the output metadata should match the input metadata.
* When in doubt, lists should default to comma-separated, strings should default to quoted, and numbers should default to unitless.
* In Sass, lists and strings use one-based indexing and use negative indices to index from the end of value. Functions should follow these conventions. [Value.sassIndexToListIndex](../classes/value#sassIndexToListIndex) and [SassString.sassIndexToStringIndex](../classes/sassstring#sassIndexToStringIndex) can be used to do this automatically.
* String indexes in Sass refer to Unicode code points while JavaScript string indices refer to UTF-16 code units. For example, the character U+1F60A SMILING FACE WITH SMILING EYES is a single Unicode code point but is represented in UTF-16 as two code units (`0xD83D` and `0xDE0A`). So in JavaScript, `"a😊b".charCodeAt(1)` returns `0xD83D`, whereas in Sass `str-slice("a😊b", 1, 1)` returns `"😊"`. Functions should follow Sass's convention. [SassString.sassIndexToStringIndex](../classes/sassstring#sassIndexToStringIndex) can be used to do this automatically, and the [SassString.sassLength](../classes/sassstring#sassLength) getter can be used to access a string's length in code points.
example
```
sass.compileString(`
h1 {
font-size: pow(2, 5) \* 1px;
}`, {
functions: {
// Note: in real code, you should use `math.pow()` from the built-in
// `sass:math` module.
'pow($base, $exponent)':function(args) {
constbase = args[0].assertNumber('base').assertNoUnits('base');
constexponent =
args[1].assertNumber('exponent').assertNoUnits('exponent');
returnnewsass.SassNumber(Math.pow(base.value, exponent.value));
}
}
});
```
###
Optional importers
importers?: ([Importer](importer)<sync> | [FileImporter](fileimporter)<sync>)[]
Custom importers that control how Sass resolves loads from rules like [`@use`](../../at-rules/use) and [`@import`](../../at-rules/import).
Loads are resolved by trying, in order:
* The importer that was used to load the current stylesheet, with the loaded URL resolved relative to the current stylesheet's canonical URL.
* Each [Importer](importer) or [FileImporter](fileimporter) in [importers](stringoptionswithoutimporter#importers), in order.
* Each load path in [loadPaths](stringoptionswithoutimporter#loadPaths), in order.
If none of these return a Sass file, the load fails and Sass throws an error.
Messages
--------
###
Optional alertAscii
alertAscii?: boolean
If this is `true`, the compiler will exclusively use ASCII characters in its error and warning messages. Otherwise, it may use non-ASCII Unicode characters as well.
defaultvalue
`false`
###
Optional alertColor
alertColor?: boolean
If this is `true`, the compiler will use ANSI color escape codes in its error and warning messages. If it's `false`, it won't use these. If it's undefined, the compiler will determine whether or not to use colors depending on whether the user is using an interactive terminal.
###
Optional logger
logger?: [Logger](logger)
An object to use to handle warnings and/or debug messages from Sass.
By default, Sass emits warnings and debug messages to standard error, but if [Logger.warn](logger#warn) or [Logger.debug](logger#debug) is set, this will invoke them instead.
The special value [Logger.silent](../modules/logger#silent) can be used to easily silence all messages.
###
Optional quietDeps
quietDeps?: boolean
If this option is set to `true`, Sass won’t print warnings that are caused by dependencies. A “dependency” is defined as any file that’s loaded through [loadPaths](stringoptionswithoutimporter#loadPaths) or [importer](stringoptionswithimporter#importer). Stylesheets that are imported relative to the entrypoint are not considered dependencies.
This is useful for silencing deprecation warnings that you can’t fix on your own. However, please *also* notify your dependencies of the deprecations so that they can get fixed as soon as possible!
### ⚠️ Heads up!
If [compileString](../modules#compileString) or [compileStringAsync](../modules#compileStringAsync) is called without [[StringWithoutImporter.url]], *all* stylesheets it loads will be considered dependencies. Since it doesn’t have a path of its own, everything it loads is coming from a load path rather than a relative import.
defaultvalue
`false`
###
Optional verbose
verbose?: boolean
By default, Dart Sass will print only five instances of the same deprecation warning per compilation to avoid deluging users in console noise. If you set `verbose` to `true`, it will instead print every deprecation warning it encounters.
defaultvalue
`false`
| programming_docs |
sass Interface LegacyFileOptions<sync> If [file](legacyfileoptions#file) is passed without [data](legacyfileoptions#data), Sass will load the stylesheet at [file](legacyfileoptions#file) and compile it to CSS.
### Type parameters
* #### sync: "sync" | "async"
This lets the TypeScript checker verify that [LegacyAsyncImporter](../modules#LegacyAsyncImporter)s and [LegacyAsyncFunction](../modules#LegacyAsyncFunction)s aren't passed to [renderSync](../modules#renderSync).
### Hierarchy
* [LegacySharedOptions](legacysharedoptions)<sync>
+ LegacyFileOptions
Index
-----
### Input
* [data](legacyfileoptions#data)
* [file](legacyfileoptions#file)
* [includePaths](legacyfileoptions#includePaths)
### Output
* [charset](legacyfileoptions#charset)
* [indentType](legacyfileoptions#indentType)
* [indentWidth](legacyfileoptions#indentWidth)
* [linefeed](legacyfileoptions#linefeed)
* [outputStyle](legacyfileoptions#outputStyle)
### Plugins
* [functions](legacyfileoptions#functions)
* [importer](legacyfileoptions#importer)
### Messages
* [logger](legacyfileoptions#logger)
* [quietDeps](legacyfileoptions#quietDeps)
* [verbose](legacyfileoptions#verbose)
### Source Maps
* [omitSourceMapUrl](legacyfileoptions#omitSourceMapUrl)
* [outFile](legacyfileoptions#outFile)
* [sourceMap](legacyfileoptions#sourceMap)
* [sourceMapContents](legacyfileoptions#sourceMapContents)
* [sourceMapEmbed](legacyfileoptions#sourceMapEmbed)
* [sourceMapRoot](legacyfileoptions#sourceMapRoot)
Input
-----
###
Optional data
data?: undefined
See [LegacyStringOptions.file](legacystringoptions#file) for documentation of passing [file](legacyfileoptions#file) along with [data](legacyfileoptions#data).
### file
file: string
Compatibility (Plain CSS files):
Dart Sass since 1.11.0
Node Sass since partial [▶](javascript:;)
Node Sass and older versions of Dart Sass support loading files with the extension `.css`, but contrary to the specification they’re treated as SCSS files rather than being parsed as CSS. This behavior has been deprecated and should not be relied on. Any files that use Sass features should use the `.scss` extension.
All versions of Node Sass and Dart Sass otherwise support the file option as described below.
The path to the file for Sass to load and compile. If the file’s extension is `.scss`, it will be parsed as SCSS; if it’s `.sass`, it will be parsed as the indented syntax; and if it’s `.css`, it will be parsed as plain CSS. If it has no extension, it will be parsed as SCSS.
example
```
sass.renderSync({file:"style.scss"});
```
###
Optional includePaths
includePaths?: string[]
Compatibility (SASS\_PATH):
Dart Sass since 1.15.0
Node Sass since 3.9.0
[▶](javascript:;) Earlier versions of Dart Sass and Node Sass didn’t support the `SASS_PATH` environment variable.
This array of strings option provides [load paths](../../at-rules/import#load-paths) for Sass to look for stylesheets. Earlier load paths will take precedence over later ones.
```
sass.renderSync({
file:"style.scss",
includePaths: ["node\_modules/bootstrap/dist/css"]
});
```
Load paths are also loaded from the `SASS_PATH` environment variable, if it’s set. This variable should be a list of paths separated by `;` (on Windows) or `:` (on other operating systems). Load paths from the `includePaths` option take precedence over load paths from `SASS_PATH`.
```
$ SASS\_PATH=node\_modules/bootstrap/dist/css sass style.scss style.css
```
Output
------
###
Optional charset
charset?: boolean
Compatibility:
Dart Sass since 1.39.0
Node Sass ✗ By default, if the CSS document contains non-ASCII characters, Sass adds a `@charset` declaration (in expanded output mode) or a byte-order mark (in compressed mode) to indicate its encoding to browsers or other consumers. If `charset` is `false`, these annotations are omitted.
###
Optional indentType
indentType?: "space" | "tab"
Compatibility:
Dart Sass ✓
Node Sass since 3.0.0
Whether the generated CSS should use spaces or tabs for indentation.
```
constresult = sass.renderSync({
file:"style.scss",
indentType:"tab",
indentWidth:1
});
result.css.toString();
// "h1 {\n\tfont-size: 40px;\n}\n"
```
defaultvalue
`'space'`
###
Optional indentWidth
indentWidth?: number
Compatibility:
Dart Sass ✓
Node Sass since 3.0.0
How many spaces or tabs (depending on [indentType](legacyfileoptions#indentType)) should be used per indentation level in the generated CSS. It must be between 0 and 10 (inclusive).
defaultvalue
`2`
###
Optional linefeed
linefeed?: "cr" | "crlf" | "lf" | "lfcr"
Compatibility:
Dart Sass ✓
Node Sass since 3.0.0
Which character sequence to use at the end of each line in the generated CSS. It can have the following values:
* `'lf'` uses U+000A LINE FEED.
* `'lfcr'` uses U+000A LINE FEED followed by U+000D CARRIAGE RETURN.
* `'cr'` uses U+000D CARRIAGE RETURN.
* `'crlf'` uses U+000D CARRIAGE RETURN followed by U+000A LINE FEED.
defaultvalue
`'lf'`
###
Optional outputStyle
outputStyle?: "expanded" | "compressed" | "nested" | "compact"
The output style of the compiled CSS. There are four possible output styles:
* `"expanded"` (the default for Dart Sass) writes each selector and declaration on its own line.
* `"compressed"` removes as many extra characters as possible, and writes the entire stylesheet on a single line.
* `"nested"` (the default for Node Sass, not supported by Dart Sass) indents CSS rules to match the nesting of the Sass source.
* `"compact"` (not supported by Dart Sass) puts each CSS rule on its own single line.
example
```
constsource = `
h1 {
font-size: 40px;
code {
font-face: Roboto Mono;
}
}`;
letresult = sass.renderSync({
data:source,
outputStyle:"expanded"
});
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
// h1 code {
// font-face: Roboto Mono;
// }
result = sass.renderSync({
data:source,
outputStyle:"compressed"
});
console.log(result.css.toString());
// h1{font-size:40px}h1 code{font-face:Roboto Mono}
result = sass.renderSync({
data:source,
outputStyle:"nested"
});
console.log(result.css.toString());
// h1 {
// font-size: 40px; }
// h1 code {
// font-face: Roboto Mono; }
result = sass.renderSync({
data:source,
outputStyle:"compact"
});
console.log(result.css.toString());
// h1 { font-size: 40px; }
// h1 code { font-face: Roboto Mono; }
```
Plugins
-------
###
Optional functions
functions?: {}
Additional built-in Sass functions that are available in all stylesheets. This option takes an object whose keys are Sass function signatures and whose values are [LegacyFunction](../modules#LegacyFunction)s. Each function should take the same arguments as its signature.
Functions are passed JavaScript representations of [Sass value types](../../js-api#value-types), and must return the same.
### ⚠️ Heads up!
When writing custom functions, it’s important to ensure that all the arguments are the types you expect. Otherwise, users’ stylesheets could crash in hard-to-debug ways or, worse, compile to meaningless CSS.
example
```
sass.render({
data:`
h1 {
font-size: pow(2, 5) \* 1px;
}`,
functions: {
// This function uses the synchronous API, and can be passed to either
// renderSync() or render().
'pow($base, $exponent)':function(base, exponent) {
if (!(baseinstanceofsass.types.Number)) {
throw"$base: Expected a number.";
} elseif (base.getUnit()) {
throw"$base: Expected a unitless number.";
}
if (!(exponentinstanceofsass.types.Number)) {
throw"$exponent: Expected a number.";
} elseif (exponent.getUnit()) {
throw"$exponent: Expected a unitless number.";
}
returnnewsass.types.Number(
Math.pow(base.getValue(), exponent.getValue()));
},
// This function uses the asynchronous API, and can only be passed to
// render().
'sqrt($number)':function(number, done) {
if (!(numberinstanceofsass.types.Number)) {
throw"$number: Expected a number.";
} elseif (number.getUnit()) {
throw"$number: Expected a unitless number.";
}
done(newsass.types.Number(Math.sqrt(number.getValue())));
}
}
}, function(err, result) {
console.log(result.css.toString());
// h1 {
// font-size: 32px;
// }
});
```
#### Type declaration
* #####
[key: string]: [LegacyFunction](../modules#LegacyFunction)<sync>
###
Optional importer
importer?: [LegacyImporter](../modules#LegacyImporter)<sync> | [LegacyImporter](../modules#LegacyImporter)<sync>[]
Compatibility:
Dart Sass ✓
Node Sass since 3.0.0
[▶](javascript:;)
Versions of Node Sass before 3.0.0 don’t support arrays of importers, nor do they support importers that return `Error` objects.
Versions of Node Sass before 2.0.0 don’t support the `importer` option at all.
Compatibility (Import order):
Dart Sass since 1.20.2
Node Sass ✗ [▶](javascript:;)
Versions of Dart Sass before 1.20.2 preferred resolving imports using [includePaths](legacyfileoptions#includePaths) before resolving them using custom importers.
All versions of Node Sass currently pass imports to importers before loading them relative to the file in which the `@import` appears. This behavior is considered incorrect and should not be relied on because it violates the principle of *locality*, which says that it should be possible to reason about a stylesheet without knowing everything about how the entire system is set up. If a user tries to import a stylesheet relative to another stylesheet, that import should *always* work. It shouldn’t be possible for some configuration somewhere else to break it.
Additional handler(s) for loading files when a [`@use` rule](../../at-rules/use) or an [`@import` rule](../../at-rules/import) is encountered. It can either be a single [LegacyImporter](../modules#LegacyImporter) function, or an array of [LegacyImporter](../modules#LegacyImporter)s.
Importers take the URL of the `@import` or `@use` rule and return a [LegacyImporterResult](../modules#LegacyImporterResult) indicating how to handle that rule. For more details, see [LegacySyncImporter](../modules#LegacySyncImporter) and [LegacyAsyncImporter](../modules#LegacyAsyncImporter).
Loads are resolved by trying, in order:
* Loading a file from disk relative to the file in which the `@use` or `@import` appeared.
* Each custom importer.
* Loading a file relative to the current working directory.
* Each load path in [includePaths](legacyfileoptions#includePaths).
* Each load path specified in the `SASS_PATH` environment variable, which should be semicolon-separated on Windows and colon-separated elsewhere.
example
```
sass.render({
file:"style.scss",
importer: [
// This importer uses the synchronous API, and can be passed to either
// renderSync() or render().
function(url, prev) {
// This generates a stylesheet from scratch for `@use "big-headers"`.
if (url != "big-headers") returnnull;
return {
contents:`
h1 {
font-size: 40px;
}`
};
},
// This importer uses the asynchronous API, and can only be passed to
// render().
function(url, prev, done) {
// Convert `@use "foo/bar"` to "node\_modules/foo/sass/bar".
constcomponents = url.split('/');
constinnerPath = components.slice(1).join('/');
done({
file:`node\_modules/${components.first}/sass/${innerPath}`
});
}
]
}, function(err, result) {
// ...
});
```
Messages
--------
###
Optional logger
logger?: [Logger](logger)
Compatibility:
Dart Sass since 1.43.0
Node Sass ✗ An object to use to handle warnings and/or debug messages from Sass.
By default, Sass emits warnings and debug messages to standard error, but if [Logger.warn](logger#warn) or [Logger.debug](logger#debug) is set, this will invoke them instead.
The special value [Logger.silent](../modules/logger#silent) can be used to easily silence all messages.
###
Optional quietDeps
quietDeps?: boolean
Compatibility:
Dart Sass since 1.35.0
Node Sass ✗ If this option is set to `true`, Sass won’t print warnings that are caused by dependencies. A “dependency” is defined as any file that’s loaded through [loadPaths](options#loadPaths) or [importer](legacyfileoptions#importer). Stylesheets that are imported relative to the entrypoint are not considered dependencies.
This is useful for silencing deprecation warnings that you can’t fix on your own. However, please *also* notify your dependencies of the deprecations so that they can get fixed as soon as possible!
### ⚠️ Heads up!
If [render](../modules#render) or [renderSync](../modules#renderSync) is called without [LegacyFileOptions.file](legacyfileoptions#file) or [LegacyStringOptions.file](legacystringoptions#file), *all* stylesheets it loads will be considered dependencies. Since it doesn’t have a path of its own, everything it loads is coming from a load path rather than a relative import.
defaultvalue
`false`
###
Optional verbose
verbose?: boolean
Compatibility:
Dart Sass since 1.35.0
Node Sass ✗ By default, Dart Sass will print only five instances of the same deprecation warning per compilation to avoid deluging users in console noise. If you set `verbose` to `true`, it will instead print every deprecation warning it encounters.
defaultvalue
`false`
Source Maps
-----------
###
Optional omitSourceMapUrl
omitSourceMapUrl?: boolean
If `true`, Sass won't add a link from the generated CSS to the source map.
```
constresult = sass.renderSync({
file:"style.scss",
sourceMap:"out.map",
omitSourceMapUrl:true
})
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
```
defaultvalue
`false`
###
Optional outFile
outFile?: string
The location that Sass expects the generated CSS to be saved to. It’s used to determine the URL used to link from the generated CSS to the source map, and from the source map to the Sass source files.
### ⚠️ Heads up!
Despite the name, Sass does *not* write the CSS output to this file. The caller must do that themselves.
```
result = sass.renderSync({
file:"style.scss",
sourceMap:true,
outFile:"out.css"
})
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
// /\*# sourceMappingURL=out.css.map \* /
```
###
Optional sourceMap
sourceMap?: string | boolean
Whether or not Sass should generate a source map. If it does, the source map will be available as [LegacyResult.map](legacyresult#map) (unless [sourceMapEmbed](legacyfileoptions#sourceMapEmbed) is `true`).
If this option is a string, it’s the path that the source map is expected to be written to, which is used to link to the source map from the generated CSS and to link *from* the source map to the Sass source files. Note that if `sourceMap` is a string and [outFile](legacyfileoptions#outFile) isn’t passed, Sass assumes that the CSS will be written to the same directory as the file option if it’s passed.
If this option is `true`, the path is assumed to be [outFile](legacyfileoptions#outFile) with `.map` added to the end. If it’s `true` and [outFile](legacyfileoptions#outFile) isn’t passed, it has no effect.
example
```
letresult = sass.renderSync({
file:"style.scss",
sourceMap:"out.map"
})
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
// /\*# sourceMappingURL=out.map \* /
result = sass.renderSync({
file:"style.scss",
sourceMap:true,
outFile:"out.css"
})
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
// /\*# sourceMappingURL=out.css.map \* /
```
defaultvalue
`false`
###
Optional sourceMapContents
sourceMapContents?: boolean
Whether to embed the entire contents of the Sass files that contributed to the generated CSS in the source map. This may produce very large source maps, but it guarantees that the source will be available on any computer no matter how the CSS is served.
example
```
sass.renderSync({
file:"style.scss",
sourceMap:"out.map",
sourceMapContents:true
})
```
defaultvalue
`false`
###
Optional sourceMapEmbed
sourceMapEmbed?: boolean
Whether to embed the contents of the source map file in the generated CSS, rather than creating a separate file and linking to it from the CSS.
example
```
sass.renderSync({
file:"style.scss",
sourceMap:"out.map",
sourceMapEmbed:true
});
```
defaultvalue
`false`
###
Optional sourceMapRoot
sourceMapRoot?: string
If this is passed, it's prepended to all the links from the source map to the Sass source files.
sass Interface LegacySharedOptions<sync>
Options for [render](../modules#render) and [renderSync](../modules#renderSync) that are shared between [LegacyFileOptions](legacyfileoptions) and [LegacyStringOptions](legacystringoptions).
deprecated
This only works with the legacy [render](../modules#render) and [renderSync](../modules#renderSync) APIs. Use [Options](options) with [compile](../modules#compile), [compileString](../modules#compileString), [compileAsync](../modules#compileAsync), and [compileStringAsync](../modules#compileStringAsync) instead.
### Type parameters
* #### sync: "sync" | "async"
This lets the TypeScript checker verify that [LegacyAsyncImporter](../modules#LegacyAsyncImporter)s and [LegacyAsyncFunction](../modules#LegacyAsyncFunction)s aren't passed to [renderSync](../modules#renderSync).
### Hierarchy
* LegacySharedOptions
+ [LegacyFileOptions](legacyfileoptions)
+ [LegacyStringOptions](legacystringoptions)
Index
-----
### Input
* [includePaths](legacysharedoptions#includePaths)
### Output
* [charset](legacysharedoptions#charset)
* [indentType](legacysharedoptions#indentType)
* [indentWidth](legacysharedoptions#indentWidth)
* [linefeed](legacysharedoptions#linefeed)
* [outputStyle](legacysharedoptions#outputStyle)
### Plugins
* [functions](legacysharedoptions#functions)
* [importer](legacysharedoptions#importer)
### Messages
* [logger](legacysharedoptions#logger)
* [quietDeps](legacysharedoptions#quietDeps)
* [verbose](legacysharedoptions#verbose)
### Source Maps
* [omitSourceMapUrl](legacysharedoptions#omitSourceMapUrl)
* [outFile](legacysharedoptions#outFile)
* [sourceMap](legacysharedoptions#sourceMap)
* [sourceMapContents](legacysharedoptions#sourceMapContents)
* [sourceMapEmbed](legacysharedoptions#sourceMapEmbed)
* [sourceMapRoot](legacysharedoptions#sourceMapRoot)
Input
-----
###
Optional includePaths
includePaths?: string[]
Compatibility (SASS\_PATH):
Dart Sass since 1.15.0
Node Sass since 3.9.0
[▶](javascript:;) Earlier versions of Dart Sass and Node Sass didn’t support the `SASS_PATH` environment variable.
This array of strings option provides [load paths](../../at-rules/import#load-paths) for Sass to look for stylesheets. Earlier load paths will take precedence over later ones.
```
sass.renderSync({
file:"style.scss",
includePaths: ["node\_modules/bootstrap/dist/css"]
});
```
Load paths are also loaded from the `SASS_PATH` environment variable, if it’s set. This variable should be a list of paths separated by `;` (on Windows) or `:` (on other operating systems). Load paths from the `includePaths` option take precedence over load paths from `SASS_PATH`.
```
$ SASS\_PATH=node\_modules/bootstrap/dist/css sass style.scss style.css
```
Output
------
###
Optional charset
charset?: boolean
Compatibility:
Dart Sass since 1.39.0
Node Sass ✗ By default, if the CSS document contains non-ASCII characters, Sass adds a `@charset` declaration (in expanded output mode) or a byte-order mark (in compressed mode) to indicate its encoding to browsers or other consumers. If `charset` is `false`, these annotations are omitted.
###
Optional indentType
indentType?: "space" | "tab"
Compatibility:
Dart Sass ✓
Node Sass since 3.0.0
Whether the generated CSS should use spaces or tabs for indentation.
```
constresult = sass.renderSync({
file:"style.scss",
indentType:"tab",
indentWidth:1
});
result.css.toString();
// "h1 {\n\tfont-size: 40px;\n}\n"
```
defaultvalue
`'space'`
###
Optional indentWidth
indentWidth?: number
Compatibility:
Dart Sass ✓
Node Sass since 3.0.0
How many spaces or tabs (depending on [indentType](legacysharedoptions#indentType)) should be used per indentation level in the generated CSS. It must be between 0 and 10 (inclusive).
defaultvalue
`2`
###
Optional linefeed
linefeed?: "cr" | "crlf" | "lf" | "lfcr"
Compatibility:
Dart Sass ✓
Node Sass since 3.0.0
Which character sequence to use at the end of each line in the generated CSS. It can have the following values:
* `'lf'` uses U+000A LINE FEED.
* `'lfcr'` uses U+000A LINE FEED followed by U+000D CARRIAGE RETURN.
* `'cr'` uses U+000D CARRIAGE RETURN.
* `'crlf'` uses U+000D CARRIAGE RETURN followed by U+000A LINE FEED.
defaultvalue
`'lf'`
###
Optional outputStyle
outputStyle?: "expanded" | "compressed" | "nested" | "compact"
The output style of the compiled CSS. There are four possible output styles:
* `"expanded"` (the default for Dart Sass) writes each selector and declaration on its own line.
* `"compressed"` removes as many extra characters as possible, and writes the entire stylesheet on a single line.
* `"nested"` (the default for Node Sass, not supported by Dart Sass) indents CSS rules to match the nesting of the Sass source.
* `"compact"` (not supported by Dart Sass) puts each CSS rule on its own single line.
example
```
constsource = `
h1 {
font-size: 40px;
code {
font-face: Roboto Mono;
}
}`;
letresult = sass.renderSync({
data:source,
outputStyle:"expanded"
});
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
// h1 code {
// font-face: Roboto Mono;
// }
result = sass.renderSync({
data:source,
outputStyle:"compressed"
});
console.log(result.css.toString());
// h1{font-size:40px}h1 code{font-face:Roboto Mono}
result = sass.renderSync({
data:source,
outputStyle:"nested"
});
console.log(result.css.toString());
// h1 {
// font-size: 40px; }
// h1 code {
// font-face: Roboto Mono; }
result = sass.renderSync({
data:source,
outputStyle:"compact"
});
console.log(result.css.toString());
// h1 { font-size: 40px; }
// h1 code { font-face: Roboto Mono; }
```
Plugins
-------
###
Optional functions
functions?: {}
Additional built-in Sass functions that are available in all stylesheets. This option takes an object whose keys are Sass function signatures and whose values are [LegacyFunction](../modules#LegacyFunction)s. Each function should take the same arguments as its signature.
Functions are passed JavaScript representations of [Sass value types](../../js-api#value-types), and must return the same.
### ⚠️ Heads up!
When writing custom functions, it’s important to ensure that all the arguments are the types you expect. Otherwise, users’ stylesheets could crash in hard-to-debug ways or, worse, compile to meaningless CSS.
example
```
sass.render({
data:`
h1 {
font-size: pow(2, 5) \* 1px;
}`,
functions: {
// This function uses the synchronous API, and can be passed to either
// renderSync() or render().
'pow($base, $exponent)':function(base, exponent) {
if (!(baseinstanceofsass.types.Number)) {
throw"$base: Expected a number.";
} elseif (base.getUnit()) {
throw"$base: Expected a unitless number.";
}
if (!(exponentinstanceofsass.types.Number)) {
throw"$exponent: Expected a number.";
} elseif (exponent.getUnit()) {
throw"$exponent: Expected a unitless number.";
}
returnnewsass.types.Number(
Math.pow(base.getValue(), exponent.getValue()));
},
// This function uses the asynchronous API, and can only be passed to
// render().
'sqrt($number)':function(number, done) {
if (!(numberinstanceofsass.types.Number)) {
throw"$number: Expected a number.";
} elseif (number.getUnit()) {
throw"$number: Expected a unitless number.";
}
done(newsass.types.Number(Math.sqrt(number.getValue())));
}
}
}, function(err, result) {
console.log(result.css.toString());
// h1 {
// font-size: 32px;
// }
});
```
#### Type declaration
* #####
[key: string]: [LegacyFunction](../modules#LegacyFunction)<sync>
###
Optional importer
importer?: [LegacyImporter](../modules#LegacyImporter)<sync> | [LegacyImporter](../modules#LegacyImporter)<sync>[]
Compatibility:
Dart Sass ✓
Node Sass since 3.0.0
[▶](javascript:;)
Versions of Node Sass before 3.0.0 don’t support arrays of importers, nor do they support importers that return `Error` objects.
Versions of Node Sass before 2.0.0 don’t support the `importer` option at all.
Compatibility (Import order):
Dart Sass since 1.20.2
Node Sass ✗ [▶](javascript:;)
Versions of Dart Sass before 1.20.2 preferred resolving imports using [includePaths](legacysharedoptions#includePaths) before resolving them using custom importers.
All versions of Node Sass currently pass imports to importers before loading them relative to the file in which the `@import` appears. This behavior is considered incorrect and should not be relied on because it violates the principle of *locality*, which says that it should be possible to reason about a stylesheet without knowing everything about how the entire system is set up. If a user tries to import a stylesheet relative to another stylesheet, that import should *always* work. It shouldn’t be possible for some configuration somewhere else to break it.
Additional handler(s) for loading files when a [`@use` rule](../../at-rules/use) or an [`@import` rule](../../at-rules/import) is encountered. It can either be a single [LegacyImporter](../modules#LegacyImporter) function, or an array of [LegacyImporter](../modules#LegacyImporter)s.
Importers take the URL of the `@import` or `@use` rule and return a [LegacyImporterResult](../modules#LegacyImporterResult) indicating how to handle that rule. For more details, see [LegacySyncImporter](../modules#LegacySyncImporter) and [LegacyAsyncImporter](../modules#LegacyAsyncImporter).
Loads are resolved by trying, in order:
* Loading a file from disk relative to the file in which the `@use` or `@import` appeared.
* Each custom importer.
* Loading a file relative to the current working directory.
* Each load path in [includePaths](legacysharedoptions#includePaths).
* Each load path specified in the `SASS_PATH` environment variable, which should be semicolon-separated on Windows and colon-separated elsewhere.
example
```
sass.render({
file:"style.scss",
importer: [
// This importer uses the synchronous API, and can be passed to either
// renderSync() or render().
function(url, prev) {
// This generates a stylesheet from scratch for `@use "big-headers"`.
if (url != "big-headers") returnnull;
return {
contents:`
h1 {
font-size: 40px;
}`
};
},
// This importer uses the asynchronous API, and can only be passed to
// render().
function(url, prev, done) {
// Convert `@use "foo/bar"` to "node\_modules/foo/sass/bar".
constcomponents = url.split('/');
constinnerPath = components.slice(1).join('/');
done({
file:`node\_modules/${components.first}/sass/${innerPath}`
});
}
]
}, function(err, result) {
// ...
});
```
Messages
--------
###
Optional logger
logger?: [Logger](logger)
Compatibility:
Dart Sass since 1.43.0
Node Sass ✗ An object to use to handle warnings and/or debug messages from Sass.
By default, Sass emits warnings and debug messages to standard error, but if [Logger.warn](logger#warn) or [Logger.debug](logger#debug) is set, this will invoke them instead.
The special value [Logger.silent](../modules/logger#silent) can be used to easily silence all messages.
###
Optional quietDeps
quietDeps?: boolean
Compatibility:
Dart Sass since 1.35.0
Node Sass ✗ If this option is set to `true`, Sass won’t print warnings that are caused by dependencies. A “dependency” is defined as any file that’s loaded through [loadPaths](options#loadPaths) or [importer](legacysharedoptions#importer). Stylesheets that are imported relative to the entrypoint are not considered dependencies.
This is useful for silencing deprecation warnings that you can’t fix on your own. However, please *also* notify your dependencies of the deprecations so that they can get fixed as soon as possible!
### ⚠️ Heads up!
If [render](../modules#render) or [renderSync](../modules#renderSync) is called without [LegacyFileOptions.file](legacyfileoptions#file) or [LegacyStringOptions.file](legacystringoptions#file), *all* stylesheets it loads will be considered dependencies. Since it doesn’t have a path of its own, everything it loads is coming from a load path rather than a relative import.
defaultvalue
`false`
###
Optional verbose
verbose?: boolean
Compatibility:
Dart Sass since 1.35.0
Node Sass ✗ By default, Dart Sass will print only five instances of the same deprecation warning per compilation to avoid deluging users in console noise. If you set `verbose` to `true`, it will instead print every deprecation warning it encounters.
defaultvalue
`false`
Source Maps
-----------
###
Optional omitSourceMapUrl
omitSourceMapUrl?: boolean
If `true`, Sass won't add a link from the generated CSS to the source map.
```
constresult = sass.renderSync({
file:"style.scss",
sourceMap:"out.map",
omitSourceMapUrl:true
})
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
```
defaultvalue
`false`
###
Optional outFile
outFile?: string
The location that Sass expects the generated CSS to be saved to. It’s used to determine the URL used to link from the generated CSS to the source map, and from the source map to the Sass source files.
### ⚠️ Heads up!
Despite the name, Sass does *not* write the CSS output to this file. The caller must do that themselves.
```
result = sass.renderSync({
file:"style.scss",
sourceMap:true,
outFile:"out.css"
})
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
// /\*# sourceMappingURL=out.css.map \* /
```
###
Optional sourceMap
sourceMap?: string | boolean
Whether or not Sass should generate a source map. If it does, the source map will be available as [LegacyResult.map](legacyresult#map) (unless [sourceMapEmbed](legacysharedoptions#sourceMapEmbed) is `true`).
If this option is a string, it’s the path that the source map is expected to be written to, which is used to link to the source map from the generated CSS and to link *from* the source map to the Sass source files. Note that if `sourceMap` is a string and [outFile](legacysharedoptions#outFile) isn’t passed, Sass assumes that the CSS will be written to the same directory as the file option if it’s passed.
If this option is `true`, the path is assumed to be [outFile](legacysharedoptions#outFile) with `.map` added to the end. If it’s `true` and [outFile](legacysharedoptions#outFile) isn’t passed, it has no effect.
example
```
letresult = sass.renderSync({
file:"style.scss",
sourceMap:"out.map"
})
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
// /\*# sourceMappingURL=out.map \* /
result = sass.renderSync({
file:"style.scss",
sourceMap:true,
outFile:"out.css"
})
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
// /\*# sourceMappingURL=out.css.map \* /
```
defaultvalue
`false`
###
Optional sourceMapContents
sourceMapContents?: boolean
Whether to embed the entire contents of the Sass files that contributed to the generated CSS in the source map. This may produce very large source maps, but it guarantees that the source will be available on any computer no matter how the CSS is served.
example
```
sass.renderSync({
file:"style.scss",
sourceMap:"out.map",
sourceMapContents:true
})
```
defaultvalue
`false`
###
Optional sourceMapEmbed
sourceMapEmbed?: boolean
Whether to embed the contents of the source map file in the generated CSS, rather than creating a separate file and linking to it from the CSS.
example
```
sass.renderSync({
file:"style.scss",
sourceMap:"out.map",
sourceMapEmbed:true
});
```
defaultvalue
`false`
###
Optional sourceMapRoot
sourceMapRoot?: string
If this is passed, it's prepended to all the links from the source map to the Sass source files.
| programming_docs |
sass Interface LegacyStringOptions<sync>
If [data](legacystringoptions#data) is passed, Sass will use it as the contents of the stylesheet to compile.
deprecated
This only works with the legacy [render](../modules#render) and [renderSync](../modules#renderSync) APIs. Use [StringOptions](../modules#StringOptions) with [compile](../modules#compile), [compileString](../modules#compileString), [compileAsync](../modules#compileAsync), and [compileStringAsync](../modules#compileStringAsync) instead.
### Type parameters
* #### sync: "sync" | "async"
This lets the TypeScript checker verify that [LegacyAsyncImporter](../modules#LegacyAsyncImporter)s and [LegacyAsyncFunction](../modules#LegacyAsyncFunction)s aren't passed to [renderSync](../modules#renderSync).
### Hierarchy
* [LegacySharedOptions](legacysharedoptions)<sync>
+ LegacyStringOptions
Index
-----
### Input
* [data](legacystringoptions#data)
* [file](legacystringoptions#file)
* [includePaths](legacystringoptions#includePaths)
* [indentedSyntax](legacystringoptions#indentedSyntax)
### Output
* [charset](legacystringoptions#charset)
* [indentType](legacystringoptions#indentType)
* [indentWidth](legacystringoptions#indentWidth)
* [linefeed](legacystringoptions#linefeed)
* [outputStyle](legacystringoptions#outputStyle)
### Plugins
* [functions](legacystringoptions#functions)
* [importer](legacystringoptions#importer)
### Messages
* [logger](legacystringoptions#logger)
* [quietDeps](legacystringoptions#quietDeps)
* [verbose](legacystringoptions#verbose)
### Source Maps
* [omitSourceMapUrl](legacystringoptions#omitSourceMapUrl)
* [outFile](legacystringoptions#outFile)
* [sourceMap](legacystringoptions#sourceMap)
* [sourceMapContents](legacystringoptions#sourceMapContents)
* [sourceMapEmbed](legacystringoptions#sourceMapEmbed)
* [sourceMapRoot](legacystringoptions#sourceMapRoot)
Input
-----
### data
data: string
The contents of the stylesheet to compile. Unless [file](legacystringoptions#file) is passed as well, the stylesheet’s URL is set to `"stdin"`.
By default, this stylesheet is parsed as SCSS. This can be controlled using [indentedSyntax](legacystringoptions#indentedSyntax).
example
```
sass.renderSync({
data:`
h1 {
font-size: 40px;
}`
});
```
###
Optional file
file?: string
If `file` and [data](legacystringoptions#data) are both passed, `file` is used as the path of the stylesheet for error reporting, but [data](legacystringoptions#data) is used as the contents of the stylesheet. In this case, `file`’s extension is not used to determine the syntax of the stylesheet.
###
Optional includePaths
includePaths?: string[]
Compatibility (SASS\_PATH):
Dart Sass since 1.15.0
Node Sass since 3.9.0
[▶](javascript:;) Earlier versions of Dart Sass and Node Sass didn’t support the `SASS_PATH` environment variable.
This array of strings option provides [load paths](../../at-rules/import#load-paths) for Sass to look for stylesheets. Earlier load paths will take precedence over later ones.
```
sass.renderSync({
file:"style.scss",
includePaths: ["node\_modules/bootstrap/dist/css"]
});
```
Load paths are also loaded from the `SASS_PATH` environment variable, if it’s set. This variable should be a list of paths separated by `;` (on Windows) or `:` (on other operating systems). Load paths from the `includePaths` option take precedence over load paths from `SASS_PATH`.
```
$ SASS\_PATH=node\_modules/bootstrap/dist/css sass style.scss style.css
```
###
Optional indentedSyntax
indentedSyntax?: boolean
This flag controls whether [data](legacystringoptions#data) is parsed as the indented syntax or not.
example
```
sass.renderSync({
data:`
h1
font-size: 40px`,
indentedSyntax:true
});
```
defaultvalue
`false`
Output
------
###
Optional charset
charset?: boolean
Compatibility:
Dart Sass since 1.39.0
Node Sass ✗ By default, if the CSS document contains non-ASCII characters, Sass adds a `@charset` declaration (in expanded output mode) or a byte-order mark (in compressed mode) to indicate its encoding to browsers or other consumers. If `charset` is `false`, these annotations are omitted.
###
Optional indentType
indentType?: "space" | "tab"
Compatibility:
Dart Sass ✓
Node Sass since 3.0.0
Whether the generated CSS should use spaces or tabs for indentation.
```
constresult = sass.renderSync({
file:"style.scss",
indentType:"tab",
indentWidth:1
});
result.css.toString();
// "h1 {\n\tfont-size: 40px;\n}\n"
```
defaultvalue
`'space'`
###
Optional indentWidth
indentWidth?: number
Compatibility:
Dart Sass ✓
Node Sass since 3.0.0
How many spaces or tabs (depending on [indentType](legacystringoptions#indentType)) should be used per indentation level in the generated CSS. It must be between 0 and 10 (inclusive).
defaultvalue
`2`
###
Optional linefeed
linefeed?: "cr" | "crlf" | "lf" | "lfcr"
Compatibility:
Dart Sass ✓
Node Sass since 3.0.0
Which character sequence to use at the end of each line in the generated CSS. It can have the following values:
* `'lf'` uses U+000A LINE FEED.
* `'lfcr'` uses U+000A LINE FEED followed by U+000D CARRIAGE RETURN.
* `'cr'` uses U+000D CARRIAGE RETURN.
* `'crlf'` uses U+000D CARRIAGE RETURN followed by U+000A LINE FEED.
defaultvalue
`'lf'`
###
Optional outputStyle
outputStyle?: "expanded" | "compressed" | "nested" | "compact"
The output style of the compiled CSS. There are four possible output styles:
* `"expanded"` (the default for Dart Sass) writes each selector and declaration on its own line.
* `"compressed"` removes as many extra characters as possible, and writes the entire stylesheet on a single line.
* `"nested"` (the default for Node Sass, not supported by Dart Sass) indents CSS rules to match the nesting of the Sass source.
* `"compact"` (not supported by Dart Sass) puts each CSS rule on its own single line.
example
```
constsource = `
h1 {
font-size: 40px;
code {
font-face: Roboto Mono;
}
}`;
letresult = sass.renderSync({
data:source,
outputStyle:"expanded"
});
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
// h1 code {
// font-face: Roboto Mono;
// }
result = sass.renderSync({
data:source,
outputStyle:"compressed"
});
console.log(result.css.toString());
// h1{font-size:40px}h1 code{font-face:Roboto Mono}
result = sass.renderSync({
data:source,
outputStyle:"nested"
});
console.log(result.css.toString());
// h1 {
// font-size: 40px; }
// h1 code {
// font-face: Roboto Mono; }
result = sass.renderSync({
data:source,
outputStyle:"compact"
});
console.log(result.css.toString());
// h1 { font-size: 40px; }
// h1 code { font-face: Roboto Mono; }
```
Plugins
-------
###
Optional functions
functions?: {}
Additional built-in Sass functions that are available in all stylesheets. This option takes an object whose keys are Sass function signatures and whose values are [LegacyFunction](../modules#LegacyFunction)s. Each function should take the same arguments as its signature.
Functions are passed JavaScript representations of [Sass value types](../../js-api#value-types), and must return the same.
### ⚠️ Heads up!
When writing custom functions, it’s important to ensure that all the arguments are the types you expect. Otherwise, users’ stylesheets could crash in hard-to-debug ways or, worse, compile to meaningless CSS.
example
```
sass.render({
data:`
h1 {
font-size: pow(2, 5) \* 1px;
}`,
functions: {
// This function uses the synchronous API, and can be passed to either
// renderSync() or render().
'pow($base, $exponent)':function(base, exponent) {
if (!(baseinstanceofsass.types.Number)) {
throw"$base: Expected a number.";
} elseif (base.getUnit()) {
throw"$base: Expected a unitless number.";
}
if (!(exponentinstanceofsass.types.Number)) {
throw"$exponent: Expected a number.";
} elseif (exponent.getUnit()) {
throw"$exponent: Expected a unitless number.";
}
returnnewsass.types.Number(
Math.pow(base.getValue(), exponent.getValue()));
},
// This function uses the asynchronous API, and can only be passed to
// render().
'sqrt($number)':function(number, done) {
if (!(numberinstanceofsass.types.Number)) {
throw"$number: Expected a number.";
} elseif (number.getUnit()) {
throw"$number: Expected a unitless number.";
}
done(newsass.types.Number(Math.sqrt(number.getValue())));
}
}
}, function(err, result) {
console.log(result.css.toString());
// h1 {
// font-size: 32px;
// }
});
```
#### Type declaration
* #####
[key: string]: [LegacyFunction](../modules#LegacyFunction)<sync>
###
Optional importer
importer?: [LegacyImporter](../modules#LegacyImporter)<sync> | [LegacyImporter](../modules#LegacyImporter)<sync>[]
Compatibility:
Dart Sass ✓
Node Sass since 3.0.0
[▶](javascript:;)
Versions of Node Sass before 3.0.0 don’t support arrays of importers, nor do they support importers that return `Error` objects.
Versions of Node Sass before 2.0.0 don’t support the `importer` option at all.
Compatibility (Import order):
Dart Sass since 1.20.2
Node Sass ✗ [▶](javascript:;)
Versions of Dart Sass before 1.20.2 preferred resolving imports using [includePaths](legacystringoptions#includePaths) before resolving them using custom importers.
All versions of Node Sass currently pass imports to importers before loading them relative to the file in which the `@import` appears. This behavior is considered incorrect and should not be relied on because it violates the principle of *locality*, which says that it should be possible to reason about a stylesheet without knowing everything about how the entire system is set up. If a user tries to import a stylesheet relative to another stylesheet, that import should *always* work. It shouldn’t be possible for some configuration somewhere else to break it.
Additional handler(s) for loading files when a [`@use` rule](../../at-rules/use) or an [`@import` rule](../../at-rules/import) is encountered. It can either be a single [LegacyImporter](../modules#LegacyImporter) function, or an array of [LegacyImporter](../modules#LegacyImporter)s.
Importers take the URL of the `@import` or `@use` rule and return a [LegacyImporterResult](../modules#LegacyImporterResult) indicating how to handle that rule. For more details, see [LegacySyncImporter](../modules#LegacySyncImporter) and [LegacyAsyncImporter](../modules#LegacyAsyncImporter).
Loads are resolved by trying, in order:
* Loading a file from disk relative to the file in which the `@use` or `@import` appeared.
* Each custom importer.
* Loading a file relative to the current working directory.
* Each load path in [includePaths](legacystringoptions#includePaths).
* Each load path specified in the `SASS_PATH` environment variable, which should be semicolon-separated on Windows and colon-separated elsewhere.
example
```
sass.render({
file:"style.scss",
importer: [
// This importer uses the synchronous API, and can be passed to either
// renderSync() or render().
function(url, prev) {
// This generates a stylesheet from scratch for `@use "big-headers"`.
if (url != "big-headers") returnnull;
return {
contents:`
h1 {
font-size: 40px;
}`
};
},
// This importer uses the asynchronous API, and can only be passed to
// render().
function(url, prev, done) {
// Convert `@use "foo/bar"` to "node\_modules/foo/sass/bar".
constcomponents = url.split('/');
constinnerPath = components.slice(1).join('/');
done({
file:`node\_modules/${components.first}/sass/${innerPath}`
});
}
]
}, function(err, result) {
// ...
});
```
Messages
--------
###
Optional logger
logger?: [Logger](logger)
Compatibility:
Dart Sass since 1.43.0
Node Sass ✗ An object to use to handle warnings and/or debug messages from Sass.
By default, Sass emits warnings and debug messages to standard error, but if [Logger.warn](logger#warn) or [Logger.debug](logger#debug) is set, this will invoke them instead.
The special value [Logger.silent](../modules/logger#silent) can be used to easily silence all messages.
###
Optional quietDeps
quietDeps?: boolean
Compatibility:
Dart Sass since 1.35.0
Node Sass ✗ If this option is set to `true`, Sass won’t print warnings that are caused by dependencies. A “dependency” is defined as any file that’s loaded through [loadPaths](options#loadPaths) or [importer](legacystringoptions#importer). Stylesheets that are imported relative to the entrypoint are not considered dependencies.
This is useful for silencing deprecation warnings that you can’t fix on your own. However, please *also* notify your dependencies of the deprecations so that they can get fixed as soon as possible!
### ⚠️ Heads up!
If [render](../modules#render) or [renderSync](../modules#renderSync) is called without [LegacyFileOptions.file](legacyfileoptions#file) or [LegacyStringOptions.file](legacystringoptions#file), *all* stylesheets it loads will be considered dependencies. Since it doesn’t have a path of its own, everything it loads is coming from a load path rather than a relative import.
defaultvalue
`false`
###
Optional verbose
verbose?: boolean
Compatibility:
Dart Sass since 1.35.0
Node Sass ✗ By default, Dart Sass will print only five instances of the same deprecation warning per compilation to avoid deluging users in console noise. If you set `verbose` to `true`, it will instead print every deprecation warning it encounters.
defaultvalue
`false`
Source Maps
-----------
###
Optional omitSourceMapUrl
omitSourceMapUrl?: boolean
If `true`, Sass won't add a link from the generated CSS to the source map.
```
constresult = sass.renderSync({
file:"style.scss",
sourceMap:"out.map",
omitSourceMapUrl:true
})
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
```
defaultvalue
`false`
###
Optional outFile
outFile?: string
The location that Sass expects the generated CSS to be saved to. It’s used to determine the URL used to link from the generated CSS to the source map, and from the source map to the Sass source files.
### ⚠️ Heads up!
Despite the name, Sass does *not* write the CSS output to this file. The caller must do that themselves.
```
result = sass.renderSync({
file:"style.scss",
sourceMap:true,
outFile:"out.css"
})
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
// /\*# sourceMappingURL=out.css.map \* /
```
###
Optional sourceMap
sourceMap?: string | boolean
Whether or not Sass should generate a source map. If it does, the source map will be available as [LegacyResult.map](legacyresult#map) (unless [sourceMapEmbed](legacystringoptions#sourceMapEmbed) is `true`).
If this option is a string, it’s the path that the source map is expected to be written to, which is used to link to the source map from the generated CSS and to link *from* the source map to the Sass source files. Note that if `sourceMap` is a string and [outFile](legacystringoptions#outFile) isn’t passed, Sass assumes that the CSS will be written to the same directory as the file option if it’s passed.
If this option is `true`, the path is assumed to be [outFile](legacystringoptions#outFile) with `.map` added to the end. If it’s `true` and [outFile](legacystringoptions#outFile) isn’t passed, it has no effect.
example
```
letresult = sass.renderSync({
file:"style.scss",
sourceMap:"out.map"
})
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
// /\*# sourceMappingURL=out.map \* /
result = sass.renderSync({
file:"style.scss",
sourceMap:true,
outFile:"out.css"
})
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
// /\*# sourceMappingURL=out.css.map \* /
```
defaultvalue
`false`
###
Optional sourceMapContents
sourceMapContents?: boolean
Whether to embed the entire contents of the Sass files that contributed to the generated CSS in the source map. This may produce very large source maps, but it guarantees that the source will be available on any computer no matter how the CSS is served.
example
```
sass.renderSync({
file:"style.scss",
sourceMap:"out.map",
sourceMapContents:true
})
```
defaultvalue
`false`
###
Optional sourceMapEmbed
sourceMapEmbed?: boolean
Whether to embed the contents of the source map file in the generated CSS, rather than creating a separate file and linking to it from the CSS.
example
```
sass.renderSync({
file:"style.scss",
sourceMap:"out.map",
sourceMapEmbed:true
});
```
defaultvalue
`false`
###
Optional sourceMapRoot
sourceMapRoot?: string
If this is passed, it's prepended to all the links from the source map to the Sass source files.
sass Interface CompileResult The result of compiling Sass to CSS. Returned by [compile](../modules#compile), [compileAsync](../modules#compileAsync), [compileString](../modules#compileString), and [compileStringAsync](../modules#compileStringAsync).
### Hierarchy
* CompileResult
Index
-----
### Properties
* [css](compileresult#css)
* [loadedUrls](compileresult#loadedUrls)
* [sourceMap](compileresult#sourceMap)
Properties
----------
### css
css: string
The generated CSS.
Note that this *never* includes a `sourceMapUrl` comment—it's up to the caller to determine where to save the source map and how to link to it from the stylesheet.
### loadedUrls
loadedUrls: [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL)[]
The canonical URLs of all the stylesheets that were loaded during the Sass compilation. The order of these URLs is not guaranteed.
###
Optional sourceMap
sourceMap?: RawSourceMap
The object representation of the source map that maps locations in the generated CSS back to locations in the Sass source code.
This typically uses absolute `file:` URLs to refer to Sass files, although this can be controlled by having a custom [Importer](importer) return [ImporterResult.sourceMapUrl](importerresult#sourceMapUrl).
This is set if and only if [Options.sourceMap](options#sourceMap) is `true`.
sass Interface LegacyException
The exception type thrown by [renderSync](../modules#renderSync) and passed as the error to [render](../modules#render)'s callback.
deprecated
This is only thrown by the legacy [render](../modules#render) and [renderSync](../modules#renderSync) APIs. Use [compile](../modules#compile), [compileString](../modules#compileString), [compileAsync](../modules#compileAsync), and [compileStringAsync](../modules#compileStringAsync) instead.
### Hierarchy
* Error
+ LegacyException
Index
-----
### Properties
* [column](legacyexception#column)
* [file](legacyexception#file)
* [formatted](legacyexception#formatted)
* [line](legacyexception#line)
* [message](legacyexception#message)
* [name](legacyexception#name)
* [stack](legacyexception#stack)
* [status](legacyexception#status)
Properties
----------
###
Optional column
column?: number
The (1-based) column number within [line](legacyexception#line) at which the error occurred, if this exception is associated with a specific Sass file location.
###
Optional file
file?: string
If this exception was caused by an error in a Sass file, this will represent the Sass file's location. It can be in one of three formats:
* If the Sass file was loaded from disk, this is the path to that file.
* If the Sass file was generated by an importer, this is its canonical URL.
* If the Sass file was passed as [LegacyStringOptions.data](legacystringoptions#data) without a corresponding [LegacyStringOptions.file](legacystringoptions#file), this is the special string `"stdin"`.
### formatted
formatted: string
The error message. For Dart Sass, this is the same as the result of calling [toString](../classes/exception#toString), which is itself the same as [message](legacyexception#message) but with the prefix "Error:".
###
Optional line
line?: number
The (1-based) line number on which the error occurred, if this exception is associated with a specific Sass file location.
### message
message: string
The error message. For Dart Sass, when possible this includes a highlighted indication of where in the source file the error occurred as well as the Sass stack trace.
### name
name: string
###
Optional stack
stack?: string
### status
status: number
Analogous to the exit code for an executable. `1` for an error caused by a Sass file, `3` for any other type of error.
| programming_docs |
sass Interface Options<sync> Options that can be passed to [compile](../modules#compile), [compileAsync](../modules#compileAsync), [compileString](../modules#compileString), or [compileStringAsync](../modules#compileStringAsync).
### Type parameters
* #### sync: "sync" | "async"
This lets the TypeScript checker verify that asynchronous [Importer](importer)s, [FileImporter](fileimporter)s, and [CustomFunction](../modules#CustomFunction)s aren't passed to [compile](../modules#compile) or [compileString](../modules#compileString).
### Hierarchy
* Options
+ [StringOptionsWithoutImporter](stringoptionswithoutimporter)
Index
-----
### Input
* [loadPaths](options#loadPaths)
### Output
* [charset](options#charset)
* [sourceMap](options#sourceMap)
* [sourceMapIncludeSources](options#sourceMapIncludeSources)
* [style](options#style)
### Plugins
* [functions](options#functions)
* [importers](options#importers)
### Messages
* [alertAscii](options#alertAscii)
* [alertColor](options#alertColor)
* [logger](options#logger)
* [quietDeps](options#quietDeps)
* [verbose](options#verbose)
Input
-----
###
Optional loadPaths
loadPaths?: string[]
Paths in which to look for stylesheets loaded by rules like [`@use`](../../at-rules/use) and [`@import`](../../at-rules/import).
A load path `loadPath` is equivalent to the following [FileImporter](fileimporter):
```
{
findFileUrl(url) {
// Load paths only support relative URLs.
if (/^[a-z]+:/i.test(url)) returnnull;
returnnewURL(url, pathToFileURL(loadPath));
}
}
```
Output
------
###
Optional charset
charset?: boolean
Compatibility:
Dart Sass since 1.54.0
Node Sass ✗ If `true`, the compiler may prepend `@charset "UTF-8";` or U+FEFF (byte-order marker) if it outputs non-ASCII CSS.
If `false`, the compiler never emits these byte sequences. This is ideal when concatenating or embedding in HTML `<style>` tags. (The output will still be UTF-8.)
defaultvalue
`true`
###
Optional sourceMap
sourceMap?: boolean
Whether or not Sass should generate a source map. If it does, the source map will be available as [CompileResult.sourceMap](compileresult#sourceMap).
### ⚠️ Heads up!
Sass doesn't automatically add a `sourceMappingURL` comment to the generated CSS. It's up to callers to do that, since callers have full knowledge of where the CSS and the source map will exist in relation to one another and how they'll be served to the browser.
defaultvalue
`false`
###
Optional sourceMapIncludeSources
sourceMapIncludeSources?: boolean
Whether Sass should include the sources in the generated source map.
This option has no effect if [sourceMap](options#sourceMap) is `false`.
defaultvalue
`false`
###
Optional style
style?: [OutputStyle](../modules#OutputStyle)
The [OutputStyle](../modules#OutputStyle) of the compiled CSS.
example
```
constsource = `
h1 {
font-size: 40px;
code {
font-face: Roboto Mono;
}
}`;
letresult = sass.compileString(source, {style:"expanded"});
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
// h1 code {
// font-face: Roboto Mono;
// }
result = sass.compileString(source, {style:"compressed"})
console.log(result.css.toString());
// h1{font-size:40px}h1 code{font-face:Roboto Mono}
```
Plugins
-------
###
Optional functions
functions?: Record<string, [CustomFunction](../modules#CustomFunction)<sync>>
Additional built-in Sass functions that are available in all stylesheets. This option takes an object whose keys are Sass function signatures like you'd write for the [`@function rule`](../../at-rules/function) and whose values are [CustomFunction](../modules#CustomFunction)s.
Functions are passed JavaScript representations of [Sass value types](../../js-api#value-types), and must return the same.
When writing custom functions, it's important to make them as user-friendly and as close to the standards set by Sass's core functions as possible. Some good guidelines to follow include:
* Use `Value.assert*` methods, like [Value.assertString](../classes/value#assertString), to cast untyped `Value` objects to more specific types. For values that were passed directly as arguments, pass in the argument name as well. This ensures that the user gets good error messages when they pass in the wrong type to your function.
* Individual classes may have more specific `assert*` methods, like [SassNumber.assertInt](../classes/sassnumber#assertInt), which should be used when possible.
* In Sass, every value counts as a list. Rather than trying to detect the [SassList](../classes/sasslist) type, you should use [Value.asList](../classes/value#asList) to treat all values as lists.
* When manipulating values like lists, strings, and numbers that have metadata (comma versus space separated, bracketed versus unbracketed, quoted versus unquoted, units), the output metadata should match the input metadata.
* When in doubt, lists should default to comma-separated, strings should default to quoted, and numbers should default to unitless.
* In Sass, lists and strings use one-based indexing and use negative indices to index from the end of value. Functions should follow these conventions. [Value.sassIndexToListIndex](../classes/value#sassIndexToListIndex) and [SassString.sassIndexToStringIndex](../classes/sassstring#sassIndexToStringIndex) can be used to do this automatically.
* String indexes in Sass refer to Unicode code points while JavaScript string indices refer to UTF-16 code units. For example, the character U+1F60A SMILING FACE WITH SMILING EYES is a single Unicode code point but is represented in UTF-16 as two code units (`0xD83D` and `0xDE0A`). So in JavaScript, `"a😊b".charCodeAt(1)` returns `0xD83D`, whereas in Sass `str-slice("a😊b", 1, 1)` returns `"😊"`. Functions should follow Sass's convention. [SassString.sassIndexToStringIndex](../classes/sassstring#sassIndexToStringIndex) can be used to do this automatically, and the [SassString.sassLength](../classes/sassstring#sassLength) getter can be used to access a string's length in code points.
example
```
sass.compileString(`
h1 {
font-size: pow(2, 5) \* 1px;
}`, {
functions: {
// Note: in real code, you should use `math.pow()` from the built-in
// `sass:math` module.
'pow($base, $exponent)':function(args) {
constbase = args[0].assertNumber('base').assertNoUnits('base');
constexponent =
args[1].assertNumber('exponent').assertNoUnits('exponent');
returnnewsass.SassNumber(Math.pow(base.value, exponent.value));
}
}
});
```
###
Optional importers
importers?: ([Importer](importer)<sync> | [FileImporter](fileimporter)<sync>)[]
Custom importers that control how Sass resolves loads from rules like [`@use`](../../at-rules/use) and [`@import`](../../at-rules/import).
Loads are resolved by trying, in order:
* The importer that was used to load the current stylesheet, with the loaded URL resolved relative to the current stylesheet's canonical URL.
* Each [Importer](importer) or [FileImporter](fileimporter) in [importers](options#importers), in order.
* Each load path in [loadPaths](options#loadPaths), in order.
If none of these return a Sass file, the load fails and Sass throws an error.
Messages
--------
###
Optional alertAscii
alertAscii?: boolean
If this is `true`, the compiler will exclusively use ASCII characters in its error and warning messages. Otherwise, it may use non-ASCII Unicode characters as well.
defaultvalue
`false`
###
Optional alertColor
alertColor?: boolean
If this is `true`, the compiler will use ANSI color escape codes in its error and warning messages. If it's `false`, it won't use these. If it's undefined, the compiler will determine whether or not to use colors depending on whether the user is using an interactive terminal.
###
Optional logger
logger?: [Logger](logger)
An object to use to handle warnings and/or debug messages from Sass.
By default, Sass emits warnings and debug messages to standard error, but if [Logger.warn](logger#warn) or [Logger.debug](logger#debug) is set, this will invoke them instead.
The special value [Logger.silent](../modules/logger#silent) can be used to easily silence all messages.
###
Optional quietDeps
quietDeps?: boolean
If this option is set to `true`, Sass won’t print warnings that are caused by dependencies. A “dependency” is defined as any file that’s loaded through [loadPaths](options#loadPaths) or [importer](stringoptionswithimporter#importer). Stylesheets that are imported relative to the entrypoint are not considered dependencies.
This is useful for silencing deprecation warnings that you can’t fix on your own. However, please *also* notify your dependencies of the deprecations so that they can get fixed as soon as possible!
### ⚠️ Heads up!
If [compileString](../modules#compileString) or [compileStringAsync](../modules#compileStringAsync) is called without [[StringWithoutImporter.url]], *all* stylesheets it loads will be considered dependencies. Since it doesn’t have a path of its own, everything it loads is coming from a load path rather than a relative import.
defaultvalue
`false`
###
Optional verbose
verbose?: boolean
By default, Dart Sass will print only five instances of the same deprecation warning per compilation to avoid deluging users in console noise. If you set `verbose` to `true`, it will instead print every deprecation warning it encounters.
defaultvalue
`false`
sass Interface StringOptionsWithImporter<sync>
Options that can be passed to [compileString](../modules#compileString) or [compileStringAsync](../modules#compileStringAsync).
If the [StringOptionsWithImporter.importer](stringoptionswithimporter#importer) field is passed, the entrypoint file uses it to load files relative to itself and the [url](stringoptionswithimporter#url) field is mandatory.
### Type parameters
* #### sync: "sync" | "async"
This lets the TypeScript checker verify that asynchronous [Importer](importer)s, [FileImporter](fileimporter)s, and [CustomFunction](../modules#CustomFunction)s aren't passed to [compile](../modules#compile) or [compileString](../modules#compileString).
### Hierarchy
* [StringOptionsWithoutImporter](stringoptionswithoutimporter)<sync>
+ StringOptionsWithImporter
Index
-----
### Input
* [importer](stringoptionswithimporter#importer)
* [loadPaths](stringoptionswithimporter#loadPaths)
* [syntax](stringoptionswithimporter#syntax)
* [url](stringoptionswithimporter#url)
### Output
* [charset](stringoptionswithimporter#charset)
* [sourceMap](stringoptionswithimporter#sourceMap)
* [sourceMapIncludeSources](stringoptionswithimporter#sourceMapIncludeSources)
* [style](stringoptionswithimporter#style)
### Plugins
* [functions](stringoptionswithimporter#functions)
* [importers](stringoptionswithimporter#importers)
### Messages
* [alertAscii](stringoptionswithimporter#alertAscii)
* [alertColor](stringoptionswithimporter#alertColor)
* [logger](stringoptionswithimporter#logger)
* [quietDeps](stringoptionswithimporter#quietDeps)
* [verbose](stringoptionswithimporter#verbose)
Input
-----
### importer
importer: [Importer](importer)<sync> | [FileImporter](fileimporter)<sync>
The importer to use to handle loads that are relative to the entrypoint stylesheet.
A relative load's URL is first resolved relative to [url](stringoptionswithimporter#url), then passed to [importer](stringoptionswithimporter#importer). If the importer doesn't recognize it, it's then passed to [importers](stringoptionswithimporter#importers) and [loadPaths](stringoptionswithimporter#loadPaths).
###
Optional loadPaths
loadPaths?: string[]
Paths in which to look for stylesheets loaded by rules like [`@use`](../../at-rules/use) and [`@import`](../../at-rules/import).
A load path `loadPath` is equivalent to the following [FileImporter](fileimporter):
```
{
findFileUrl(url) {
// Load paths only support relative URLs.
if (/^[a-z]+:/i.test(url)) returnnull;
returnnewURL(url, pathToFileURL(loadPath));
}
}
```
###
Optional syntax
syntax?: [Syntax](../modules#Syntax)
The [Syntax](../modules#Syntax) to use to parse the entrypoint stylesheet.
default
`'scss'`
### url
url: [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL)
The canonical URL of the entrypoint stylesheet. If this is passed along with [importer](stringoptionswithimporter#importer), it's used to resolve relative loads in the entrypoint stylesheet.
Output
------
###
Optional charset
charset?: boolean
Compatibility:
Dart Sass since 1.54.0
Node Sass ✗ If `true`, the compiler may prepend `@charset "UTF-8";` or U+FEFF (byte-order marker) if it outputs non-ASCII CSS.
If `false`, the compiler never emits these byte sequences. This is ideal when concatenating or embedding in HTML `<style>` tags. (The output will still be UTF-8.)
defaultvalue
`true`
###
Optional sourceMap
sourceMap?: boolean
Whether or not Sass should generate a source map. If it does, the source map will be available as [CompileResult.sourceMap](compileresult#sourceMap).
### ⚠️ Heads up!
Sass doesn't automatically add a `sourceMappingURL` comment to the generated CSS. It's up to callers to do that, since callers have full knowledge of where the CSS and the source map will exist in relation to one another and how they'll be served to the browser.
defaultvalue
`false`
###
Optional sourceMapIncludeSources
sourceMapIncludeSources?: boolean
Whether Sass should include the sources in the generated source map.
This option has no effect if [sourceMap](stringoptionswithimporter#sourceMap) is `false`.
defaultvalue
`false`
###
Optional style
style?: [OutputStyle](../modules#OutputStyle)
The [OutputStyle](../modules#OutputStyle) of the compiled CSS.
example
```
constsource = `
h1 {
font-size: 40px;
code {
font-face: Roboto Mono;
}
}`;
letresult = sass.compileString(source, {style:"expanded"});
console.log(result.css.toString());
// h1 {
// font-size: 40px;
// }
// h1 code {
// font-face: Roboto Mono;
// }
result = sass.compileString(source, {style:"compressed"})
console.log(result.css.toString());
// h1{font-size:40px}h1 code{font-face:Roboto Mono}
```
Plugins
-------
###
Optional functions
functions?: Record<string, [CustomFunction](../modules#CustomFunction)<sync>>
Additional built-in Sass functions that are available in all stylesheets. This option takes an object whose keys are Sass function signatures like you'd write for the [`@function rule`](../../at-rules/function) and whose values are [CustomFunction](../modules#CustomFunction)s.
Functions are passed JavaScript representations of [Sass value types](../../js-api#value-types), and must return the same.
When writing custom functions, it's important to make them as user-friendly and as close to the standards set by Sass's core functions as possible. Some good guidelines to follow include:
* Use `Value.assert*` methods, like [Value.assertString](../classes/value#assertString), to cast untyped `Value` objects to more specific types. For values that were passed directly as arguments, pass in the argument name as well. This ensures that the user gets good error messages when they pass in the wrong type to your function.
* Individual classes may have more specific `assert*` methods, like [SassNumber.assertInt](../classes/sassnumber#assertInt), which should be used when possible.
* In Sass, every value counts as a list. Rather than trying to detect the [SassList](../classes/sasslist) type, you should use [Value.asList](../classes/value#asList) to treat all values as lists.
* When manipulating values like lists, strings, and numbers that have metadata (comma versus space separated, bracketed versus unbracketed, quoted versus unquoted, units), the output metadata should match the input metadata.
* When in doubt, lists should default to comma-separated, strings should default to quoted, and numbers should default to unitless.
* In Sass, lists and strings use one-based indexing and use negative indices to index from the end of value. Functions should follow these conventions. [Value.sassIndexToListIndex](../classes/value#sassIndexToListIndex) and [SassString.sassIndexToStringIndex](../classes/sassstring#sassIndexToStringIndex) can be used to do this automatically.
* String indexes in Sass refer to Unicode code points while JavaScript string indices refer to UTF-16 code units. For example, the character U+1F60A SMILING FACE WITH SMILING EYES is a single Unicode code point but is represented in UTF-16 as two code units (`0xD83D` and `0xDE0A`). So in JavaScript, `"a😊b".charCodeAt(1)` returns `0xD83D`, whereas in Sass `str-slice("a😊b", 1, 1)` returns `"😊"`. Functions should follow Sass's convention. [SassString.sassIndexToStringIndex](../classes/sassstring#sassIndexToStringIndex) can be used to do this automatically, and the [SassString.sassLength](../classes/sassstring#sassLength) getter can be used to access a string's length in code points.
example
```
sass.compileString(`
h1 {
font-size: pow(2, 5) \* 1px;
}`, {
functions: {
// Note: in real code, you should use `math.pow()` from the built-in
// `sass:math` module.
'pow($base, $exponent)':function(args) {
constbase = args[0].assertNumber('base').assertNoUnits('base');
constexponent =
args[1].assertNumber('exponent').assertNoUnits('exponent');
returnnewsass.SassNumber(Math.pow(base.value, exponent.value));
}
}
});
```
###
Optional importers
importers?: ([Importer](importer)<sync> | [FileImporter](fileimporter)<sync>)[]
Custom importers that control how Sass resolves loads from rules like [`@use`](../../at-rules/use) and [`@import`](../../at-rules/import).
Loads are resolved by trying, in order:
* The importer that was used to load the current stylesheet, with the loaded URL resolved relative to the current stylesheet's canonical URL.
* Each [Importer](importer) or [FileImporter](fileimporter) in [importers](stringoptionswithimporter#importers), in order.
* Each load path in [loadPaths](stringoptionswithimporter#loadPaths), in order.
If none of these return a Sass file, the load fails and Sass throws an error.
Messages
--------
###
Optional alertAscii
alertAscii?: boolean
If this is `true`, the compiler will exclusively use ASCII characters in its error and warning messages. Otherwise, it may use non-ASCII Unicode characters as well.
defaultvalue
`false`
###
Optional alertColor
alertColor?: boolean
If this is `true`, the compiler will use ANSI color escape codes in its error and warning messages. If it's `false`, it won't use these. If it's undefined, the compiler will determine whether or not to use colors depending on whether the user is using an interactive terminal.
###
Optional logger
logger?: [Logger](logger)
An object to use to handle warnings and/or debug messages from Sass.
By default, Sass emits warnings and debug messages to standard error, but if [Logger.warn](logger#warn) or [Logger.debug](logger#debug) is set, this will invoke them instead.
The special value [Logger.silent](../modules/logger#silent) can be used to easily silence all messages.
###
Optional quietDeps
quietDeps?: boolean
If this option is set to `true`, Sass won’t print warnings that are caused by dependencies. A “dependency” is defined as any file that’s loaded through [loadPaths](stringoptionswithimporter#loadPaths) or [importer](stringoptionswithimporter#importer). Stylesheets that are imported relative to the entrypoint are not considered dependencies.
This is useful for silencing deprecation warnings that you can’t fix on your own. However, please *also* notify your dependencies of the deprecations so that they can get fixed as soon as possible!
### ⚠️ Heads up!
If [compileString](../modules#compileString) or [compileStringAsync](../modules#compileStringAsync) is called without [[StringWithoutImporter.url]], *all* stylesheets it loads will be considered dependencies. Since it doesn’t have a path of its own, everything it loads is coming from a load path rather than a relative import.
defaultvalue
`false`
###
Optional verbose
verbose?: boolean
By default, Dart Sass will print only five instances of the same deprecation warning per compilation to avoid deluging users in console noise. If you set `verbose` to `true`, it will instead print every deprecation warning it encounters.
defaultvalue
`false`
| programming_docs |
sass Interface LegacyPluginThis
The value of `this` in the context of a [LegacyImporter](../modules#LegacyImporter) or [LegacyFunction](../modules#LegacyFunction) callback.
deprecated
This is only used by the legacy [render](../modules#render) and [renderSync](../modules#renderSync) APIs. Use [compile](../modules#compile), [compileString](../modules#compileString), [compileAsync](../modules#compileAsync), and [compileStringAsync](../modules#compileStringAsync) instead.
### Hierarchy
* LegacyPluginThis
+ [LegacyImporterThis](legacyimporterthis)
Index
-----
### Properties
* [options](legacypluginthis#options)
Properties
----------
### options
options: { context: [LegacyPluginThis](legacypluginthis); data?: string; file?: string; includePaths: string; indentType: 0 | 1; indentWidth: number; linefeed: "\r" | "\r\n" | "\n" | "\n\r"; precision: 10; result: { stats: { entry: string; start: number } }; style: 1 }
A partial representation of the options passed to [render](../modules#render) or [renderSync](../modules#renderSync).
#### Type declaration
* ##### context: [LegacyPluginThis](legacypluginthis)
The same [LegacyPluginThis](legacypluginthis) instance that contains this object.
* #####
Optional data?: string
The value passed to [LegacyStringOptions.data](legacystringoptions#data).
* #####
Optional file?: string
The value passed to [LegacyFileOptions.file](legacyfileoptions#file) or [LegacyStringOptions.file](legacystringoptions#file).
* ##### includePaths: string
The value passed to [LegacySharedOptions.includePaths](legacysharedoptions#includePaths) separated by `";"` on Windows or `":"` on other operating systems. This always includes the current working directory as the first entry.
* ##### indentType: 0 | 1
1 if [LegacySharedOptions.indentType](legacysharedoptions#indentType) was `"tab"`, 0 otherwise.
* ##### indentWidth: number
The value passed to [LegacySharedOptions.indentWidth](legacysharedoptions#indentWidth), or `2` otherwise.
* ##### linefeed: "\r" | "\r\n" | "\n" | "\n\r"
The value passed to [LegacySharedOptions.linefeed](legacysharedoptions#linefeed), or `"\n"` otherwise.
* ##### precision: 10
Always the number 10.
* ##### result: { stats: { entry: string; start: number } }
A partially-constructed [LegacyResult](legacyresult) object.
+ ##### stats: { entry: string; start: number }
Partial information about the compilation in progress.
- ##### entry: string
[LegacyFileOptions.file](legacyfileoptions#file) if it was passed, otherwise the string `"data"`.
- ##### start: number
The number of milliseconds between 1 January 1970 at 00:00:00 UTC and the time at which Sass compilation began.
* ##### style: 1
Always the number 1.
sass Interface ImporterResult The result of successfully loading a stylesheet with an [Importer](importer).
### Hierarchy
* ImporterResult
Index
-----
### Properties
* [contents](importerresult#contents)
* [sourceMapUrl](importerresult#sourceMapUrl)
* [syntax](importerresult#syntax)
Properties
----------
### contents
contents: string
The contents of the stylesheet.
###
Optional sourceMapUrl
sourceMapUrl?: [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL)
The URL to use to link to the loaded stylesheet's source code in source maps. A `file:` URL is ideal because it's accessible to both browsers and other build tools, but an `http:` URL is also acceptable.
If this isn't set, it defaults to a `data:` URL that contains the contents of the loaded stylesheet.
### syntax
syntax: [Syntax](../modules#Syntax)
The syntax with which to parse [contents](importerresult#contents).
sass Property Declarations Property Declarations
======================
In Sass as in CSS, property declarations define how elements that match a selector are styled. But Sass adds extra features to make them easier to write and to automate. First and foremost, a declaration's value can be any [SassScript expression](../syntax/structure#expressions), which will be evaluated and included in the result.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
.circle {
$size: 100px;
width: $size;
height: $size;
border-radius: $size * 0.5;
}
```
```
.circle
$size: 100px
width: $size
height: $size
border-radius: $size * 0.5
```
```
.circle {
width: 100px;
height: 100px;
border-radius: 50px;
}
```
Interpolation
--------------
A property’s name can include [interpolation](../interpolation), which makes it possible to dynamically generate properties as needed. You can even interpolate the entire property name!
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
@mixin prefix($property, $value, $prefixes) {
@each $prefix in $prefixes {
-#{$prefix}-#{$property}: $value;
}
#{$property}: $value;
}
.gray {
@include prefix(filter, grayscale(50%), moz webkit);
}
```
```
@mixin prefix($property, $value, $prefixes)
@each $prefix in $prefixes
-#{$prefix}-#{$property}: $value
#{$property}: $value
.gray
@include prefix(filter, grayscale(50%), moz webkit)
```
```
.gray {
-moz-filter: grayscale(50%);
-webkit-filter: grayscale(50%);
filter: grayscale(50%);
}
```
Nesting
--------
Many CSS properties start with the same prefix that acts as a kind of namespace. For example, `font-family`, `font-size`, and `font-weight` all start with `font-`. Sass makes this easier and less redundant by allowing property declarations to be nested. The outer property names are added to the inner, separated by a hyphen.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
* [CSS](#example-3-css)
```
.enlarge {
font-size: 14px;
transition: {
property: font-size;
duration: 4s;
delay: 2s;
}
&:hover { font-size: 36px; }
}
```
```
.enlarge
font-size: 14px
transition:
property: font-size
duration: 4s
delay: 2s
&:hover
font-size: 36px
```
```
.enlarge {
font-size: 14px;
transition-property: font-size;
transition-duration: 4s;
transition-delay: 2s;
}
.enlarge:hover {
font-size: 36px;
}
```
Some of these CSS properties have shorthand versions that use the namespace as the property name. For these, you can write both the shorthand value *and* the more explicit nested versions.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
* [CSS](#example-4-css)
```
.info-page {
margin: auto {
bottom: 10px;
top: 2px;
}
}
```
```
.info-page
margin: auto
bottom: 10px
top: 2px
```
```
.info-page {
margin: auto;
margin-bottom: 10px;
margin-top: 2px;
}
```
Hidden Declarations
--------------------
Sometimes you only want a property declaration to show up some of the time. If a declaration’s value is [`null`](../values/null) or an empty [unquoted string](../values/strings#unquoted), Sass won’t compile that declaration to CSS at all.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
* [CSS](#example-5-css)
```
$rounded-corners: false;
.button {
border: 1px solid black;
border-radius: if($rounded-corners, 5px, null);
}
```
```
$rounded-corners: false
.button
border: 1px solid black
border-radius: if($rounded-corners, 5px, null)
```
```
.button {
border: 1px solid black;
}
```
Custom Properties
------------------
Compatibility (SassScript Syntax):
Dart Sass ✓
LibSass since 3.5.0
Ruby Sass since 3.5.0
[▶](javascript:;)
Older versions of LibSass and Ruby Sass parsed custom property declarations just like any other property declaration, allowing the full range of SassScript expressions as values. Even when using these versions, it’s recommended that you use interpolation to inject SassScript values for forwards-compatibility.
See [the breaking change page](https://sass-lang.com/documentation/breaking-changes/css-vars) for more details.
[CSS custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/--*), also known as CSS variables, have an unusual declaration syntax: they allow almost any text at all in their declaration values. What’s more, those values are accessible to JavaScript, so any value might potentially be relevant to the user. This includes values that would normally be parsed as SassScript.
Because of this, Sass parses custom property declarations differently than other property declarations. All tokens, including those that look like SassScript, are passed through to CSS as-is. The only exception is [interpolation](../interpolation), which is the only way to inject dynamic values into a custom property.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
* [CSS](#example-6-css)
```
$primary: #81899b;
$accent: #302e24;
$warn: #dfa612;
:root {
--primary: #{$primary};
--accent: #{$accent};
--warn: #{$warn};
// Even though this looks like a Sass variable, it's valid CSS so it's not
// evaluated.
--consumed-by-js: $primary;
}
```
```
$primary: #81899b
$accent: #302e24
$warn: #dfa612
:root
--primary: #{$primary}
--accent: #{$accent}
--warn: #{$warn}
// Even though this looks like a Sass variable, it's valid CSS so it's not
// evaluated.
--consumed-by-js: $primary
```
```
:root {
--primary: #81899b;
--accent: #302e24;
--warn: #dfa612;
--consumed-by-js: $primary;
}
```
### ⚠️ Heads up!
Unfortunately, [interpolation](../interpolation) removes quotes from strings, which makes it difficult to use quoted strings as values for custom properties when they come from Sass variables. As a workaround, you can use the [`meta.inspect()` function](../modules/meta#inspect) to preserve the quotes.
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
* [CSS](#example-7-css)
```
@use "sass:meta";
$font-family-sans-serif: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto;
$font-family-monospace: SFMono-Regular, Menlo, Monaco, Consolas;
:root {
--font-family-sans-serif: #{meta.inspect($font-family-sans-serif)};
--font-family-monospace: #{meta.inspect($font-family-monospace)};
}
```
```
@use "sass:meta"
$font-family-sans-serif: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto
$font-family-monospace: SFMono-Regular, Menlo, Monaco, Consolas
:root
--font-family-sans-serif: #{meta.inspect($font-family-sans-serif)}
--font-family-monospace: #{meta.inspect($font-family-monospace)}
```
```
:root {
--font-family-sans-serif: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto;
--font-family-monospace: SFMono-Regular, Menlo, Monaco, Consolas;
}
```
sass Placeholder Selectors Placeholder Selectors
======================
Sass has a special kind of selector known as a “placeholder”. It looks and acts a lot like a class selector, but it starts with a `%` and it's not included in the CSS output. In fact, any complex selector (the ones between the commas) that even *contains* a placeholder selector isn't included in the CSS, nor is any style rule whose selectors all contain placeholders.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
.alert:hover, %strong-alert {
font-weight: bold;
}
%strong-alert:hover {
color: red;
}
```
```
.alert:hover, %strong-alert
font-weight: bold
%strong-alert:hover
color: red
```
```
.alert:hover {
font-weight: bold;
}
```
What’s the use of a selector that isn’t emitted? It can still be [extended](../at-rules/extend)! Unlike class selectors, placeholders don’t clutter up the CSS if they aren’t extended and they don’t mandate that users of a library use specific class names for their HTML.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
%toolbelt {
box-sizing: border-box;
border-top: 1px rgba(#000, .12) solid;
padding: 16px 0;
width: 100%;
&:hover { border: 2px rgba(#000, .5) solid; }
}
.action-buttons {
@extend %toolbelt;
color: #4285f4;
}
.reset-buttons {
@extend %toolbelt;
color: #cddc39;
}
```
```
%toolbelt
box-sizing: border-box
border-top: 1px rgba(#000, .12) solid
padding: 16px 0
width: 100%
&:hover
border: 2px rgba(#000, .5) solid
.action-buttons
@extend %toolbelt
color: #4285f4
.reset-buttons
@extend %toolbelt
color: #cddc39
```
```
.action-buttons, .reset-buttons {
box-sizing: border-box;
border-top: 1px rgba(0, 0, 0, 0.12) solid;
padding: 16px 0;
width: 100%;
}
.action-buttons:hover, .reset-buttons:hover {
border: 2px rgba(0, 0, 0, 0.5) solid;
}
.action-buttons {
color: #4285f4;
}
.reset-buttons {
color: #cddc39;
}
```
Placeholder selectors are useful when writing a Sass library where each style rule may or may not be used. As a rule of thumb, if you’re writing a stylesheet just for your own app, it’s often better to just extend a class selector if one is available.
sass Parent Selector Parent Selector
================
The parent selector, `&`, is a special selector invented by Sass that’s used in [nested selectors](../style-rules#nesting) to refer to the outer selector. It makes it possible to re-use the outer selector in more complex ways, like adding a [pseudo-class](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes) or adding a selector *before* the parent.
When a parent selector is used in an inner selector, it’s replaced with the corresponding outer selector. This happens instead of the normal nesting behavior.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
.alert {
// The parent selector can be used to add pseudo-classes to the outer
// selector.
&:hover {
font-weight: bold;
}
// It can also be used to style the outer selector in a certain context, such
// as a body set to use a right-to-left language.
[dir=rtl] & {
margin-left: 0;
margin-right: 10px;
}
// You can even use it as an argument to pseudo-class selectors.
:not(&) {
opacity: 0.8;
}
}
```
```
.alert
// The parent selector can be used to add pseudo-classes to the outer
// selector.
&:hover
font-weight: bold
// It can also be used to style the outer selector in a certain context, such
// as a body set to use a right-to-left language.
[dir=rtl] &
margin-left: 0
margin-right: 10px
// You can even use it as an argument to pseudo-class selectors.
:not(&)
opacity: 0.8
```
```
.alert:hover {
font-weight: bold;
}
[dir=rtl] .alert {
margin-left: 0;
margin-right: 10px;
}
:not(.alert) {
opacity: 0.8;
}
```
### ⚠️ Heads up!
Because the parent selector could be replaced by a type selector like `h1`, it’s only allowed at the beginning of compound selectors where a type selector would also be allowed. For example, `span&` is not allowed.
We’re looking into loosening this restriction, though. If you’d like to help make that happen, check out [this GitHub issue](https://github.com/sass/sass/issues/1425).
Adding Suffixes
----------------
You can also use the parent selector to add extra suffixes to the outer selector. This is particularly useful when using a methodology like [BEM](http://getbem.com/) that uses highly structured class names. As long as the outer selector ends with an alphanumeric name (like class, ID, and element selectors), you can use the parent selector to append additional text.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
.accordion {
max-width: 600px;
margin: 4rem auto;
width: 90%;
font-family: "Raleway", sans-serif;
background: #f4f4f4;
&__copy {
display: none;
padding: 1rem 1.5rem 2rem 1.5rem;
color: gray;
line-height: 1.6;
font-size: 14px;
font-weight: 500;
&--open {
display: block;
}
}
}
```
```
.accordion
max-width: 600px
margin: 4rem auto
width: 90%
font-family: "Raleway", sans-serif
background: #f4f4f4
&__copy
display: none
padding: 1rem 1.5rem 2rem 1.5rem
color: gray
line-height: 1.6
font-size: 14px
font-weight: 500
&--open
display: block
```
```
.accordion {
max-width: 600px;
margin: 4rem auto;
width: 90%;
font-family: "Raleway", sans-serif;
background: #f4f4f4;
}
.accordion__copy {
display: none;
padding: 1rem 1.5rem 2rem 1.5rem;
color: gray;
line-height: 1.6;
font-size: 14px;
font-weight: 500;
}
.accordion__copy--open {
display: block;
}
```
In SassScript
--------------
The parent selector can also be used within SassScript. It’s a special expression that returns the current parent selector in the same format used by [selector functions](../modules/selector#selector-values): a comma-separated list (the selector list) that contains space-separated lists (the complex selectors) that contain unquoted strings (the compound selectors).
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
* [CSS](#example-3-css)
```
.main aside:hover,
.sidebar p {
parent-selector: &;
// => ((unquote(".main") unquote("aside:hover")),
// (unquote(".sidebar") unquote("p")))
}
```
```
.main aside:hover,
.sidebar p
parent-selector: &
// => ((unquote(".main") unquote("aside:hover")),
// (unquote(".sidebar") unquote("p")))
```
```
.main aside:hover,
.sidebar p {
parent-selector: .main aside:hover, .sidebar p;
}
```
If the `&` expression is used outside any style rules, it returns `null`. Since `null` is [falsey](../at-rules/control/if#truthiness-and-falsiness), this means you can easily use it to determine whether a mixin is being called in a style rule or not.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
* [CSS](#example-4-css)
```
@mixin app-background($color) {
#{if(&, '&.app-background', '.app-background')} {
background-color: $color;
color: rgba(#fff, 0.75);
}
}
@include app-background(#036);
.sidebar {
@include app-background(#c6538c);
}
```
```
@mixin app-background($color)
#{if(&, '&.app-background', '.app-background')}
background-color: $color
color: rgba(#fff, 0.75)
@include app-background(#036)
.sidebar
@include app-background(#c6538c)
```
```
.app-background {
background-color: #036;
color: rgba(255, 255, 255, 0.75);
}
.sidebar.app-background {
background-color: #c6538c;
color: rgba(255, 255, 255, 0.75);
}
```
### Advanced Nesting
You can use `&` as a normal SassScript expression, which means you can pass it to functions or include it in interpolation—even in other selectors! Using it in combination with [selector functions](../modules/selector#selector-values) and the [`@at-root` rule](../at-rules/at-root) allows you to nest selectors in very powerful ways.
For example, suppose you want to write a selector that matches the outer selector *and* an element selector. You could write a mixin like this one that uses the [`selector.unify()` function](../modules/selector#unify) to combine `&` with a user’s selector.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
* [CSS](#example-5-css)
```
@use "sass:selector";
@mixin unify-parent($child) {
@at-root #{selector.unify(&, $child)} {
@content;
}
}
.wrapper .field {
@include unify-parent("input") {
/* ... */
}
@include unify-parent("select") {
/* ... */
}
}
```
```
@use "sass:selector"
@mixin unify-parent($child)
@at-root #{selector.unify(&, $child)}
@content
.wrapper .field
@include unify-parent("input")
/* ... */
@include unify-parent("select")
/* ... */
```
```
.wrapper input.field {
/* ... */
}
.wrapper select.field {
/* ... */
}
```
### ⚠️ Heads up!
When Sass is nesting selectors, it doesn’t know what interpolation was used to generate them. This means it will automatically add the outer selector to the inner selector *even if* you used `&` as a SassScript expression. That’s why you need to explicitly use the [`@at-root` rule](../at-rules/at-root) to tell Sass not to include the outer selector.
sass Booleans Booleans
=========
Booleans are the logical values `true` and `false`. In addition their literal forms, booleans are returned by [equality](../operators/equality) and [relational](../operators/relational) operators, as well as many built-in functions like [`math.comparable()`](../modules/math#comparable) and [`map.has-key()`](../modules/map#has-key).
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@use "sass:math";
@debug 1px == 2px; // false
@debug 1px == 1px; // true
@debug 10px < 3px; // false
@debug math.comparable(100px, 3in); // true
```
```
@use "sass:math"
@debug 1px == 2px // false
@debug 1px == 1px // true
@debug 10px < 3px // false
@debug math.comparable(100px, 3in) // true
```
You can work with booleans using [boolean operators](../operators/boolean). The `and` operator returns `true` if *both* sides are `true`, and the `or` operator returns `true` if *either* side is `true`. The `not` operator returns the opposite of a single boolean value.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
```
@debug true and true; // true
@debug true and false; // false
@debug true or false; // true
@debug false or false; // false
@debug not true; // false
@debug not false; // true
```
```
@debug true and true // true
@debug true and false // false
@debug true or false // true
@debug false or false // false
@debug not true // false
@debug not false // true
```
Using Booleans
---------------
You can use booleans to choose whether or not to do various things in Sass. The [`@if` rule](../at-rules/control/if) evaluates a block of styles if its argument is `true`:
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
* [CSS](#example-3-css)
```
@mixin avatar($size, $circle: false) {
width: $size;
height: $size;
@if $circle {
border-radius: $size / 2;
}
}
.square-av {
@include avatar(100px, $circle: false);
}
.circle-av {
@include avatar(100px, $circle: true);
}
```
```
@mixin avatar($size, $circle: false)
width: $size
height: $size
@if $circle
border-radius: $size / 2
.square-av
@include avatar(100px, $circle: false)
.circle-av
@include avatar(100px, $circle: true)
```
```
.square-av {
width: 100px;
height: 100px;
}
.circle-av {
width: 100px;
height: 100px;
border-radius: 50px;
}
```
The [`if()` function](../modules#if) returns one value if its argument is `true` and another if its argument is `false`:
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
```
@debug if(true, 10px, 30px); // 10px
@debug if(false, 10px, 30px); // 30px
```
```
@debug if(true, 10px, 30px) // 10px
@debug if(false, 10px, 30px) // 30px
```
Truthiness and Falsiness
-------------------------
Anywhere `true` or `false` are allowed, you can use other values as well. The values `false` and [`null`](null) are *falsey*, which means Sass considers them to indicate falsehood and cause conditions to fail. Every other value is considered *truthy*, so Sass considers them to work like `true` and cause conditions to succeed.
For example, if you want to check if a string contains a space, you can just write `string.index($string, " ")`. The [`string.index()` function](../modules/string#index) returns `null` if the string isn’t found and a number otherwise.
### ⚠️ Heads up!
Some languages consider more values falsey than just `false` and `null`. Sass isn’t one of those languages! Empty strings, empty lists, and the number `0` are all truthy in Sass.
| programming_docs |
sass Colors Colors
=======
Compatibility (Level 4 Syntax):
Dart Sass since 1.14.0
LibSass since 3.6.0
Ruby Sass since 3.6.0
[▶](javascript:;) LibSass and older versions of Dart or Ruby Sass don’t support [hex colors with an alpha channel](https://drafts.csswg.org/css-color/#hex-notation).
Sass has built-in support for color values. Just like CSS colors, they represent points in the [sRGB color space](https://en.wikipedia.org/wiki/SRGB), although many Sass [color functions](../modules/color) operate using [HSL coordinates](https://en.wikipedia.org/wiki/HSL_and_HSV) (which are just another way of expressing sRGB colors). Sass colors can be written as hex codes (`#f2ece4` or `#b37399aa`), [CSS color names](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#Color_keywords) (`midnightblue`, `transparent`), or the functions [`rgb()`](../modules#rgb), [`rgba()`](../modules#rgba), [`hsl()`](../modules#hsl), and [`hsla()`](../modules#hsla).
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@debug #f2ece4; // #f2ece4
@debug #b37399aa; // rgba(179, 115, 153, 67%)
@debug midnightblue; // #191970
@debug rgb(204, 102, 153); // #c69
@debug rgba(107, 113, 127, 0.8); // rgba(107, 113, 127, 0.8)
@debug hsl(228, 7%, 86%); // #dadbdf
@debug hsla(20, 20%, 85%, 0.7); // rgb(225, 215, 210, 0.7)
```
```
@debug #f2ece4 // #f2ece4
@debug #b37399aa // rgba(179, 115, 153, 67%)
@debug midnightblue // #191970
@debug rgb(204, 102, 153) // #c69
@debug rgba(107, 113, 127, 0.8) // rgba(107, 113, 127, 0.8)
@debug hsl(228, 7%, 86%) // #dadbdf
@debug hsla(20, 20%, 85%, 0.7) // rgb(225, 215, 210, 0.7)
```
### 💡 Fun fact:
No matter how a Sass color is originally written, it can be used with both HSL-based and RGB-based functions!
CSS supports many different formats that can all represent the same color: its name, its hex code, and [functional notation](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Which format Sass chooses to compile a color to depends on the color itself, how it was written in the original stylesheet, and the current output mode. Because it can vary so much, stylesheet authors shouldn’t rely on any particular output format for colors they write.
Sass supports many useful [color functions](../modules/color) that can be used to create new colors based on existing ones by [mixing colors together](../modules/color#mix) or [scaling their hue, saturation, or lightness](../modules/color#scale).
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
```
$venus: #998099;
@debug scale-color($venus, $lightness: +15%); // #a893a8
@debug mix($venus, midnightblue); // #594d85
```
```
$venus: #998099
@debug scale-color($venus, $lightness: +15%) // #a893a8
@debug mix($venus, midnightblue) // #594d85
```
sass Functions Functions
==========
Compatibility (Argument Type):
Dart Sass ✓
LibSass since 3.5.0
Ruby Sass since 3.5.0
[▶](javascript:;)
In older versions of LibSass and Ruby Sass, the [`call()` function](../modules/meta#call) took a string representing a function’s name. This was changed to take a function value instead in preparation for a new module system where functions are no longer global and so a given name may not always refer to the same function.
Passing a string to `call()` still works in all implementations, but it’s deprecated and will be disallowed in future versions.
[Functions](../at-rules/function) can be values too! You can’t directly write a function as a value, but you can pass a function’s name to the [`meta.get-function()` function](../modules/meta#get-function) to get it as a value. Once you have a function value, you can pass it to the [`meta.call()` function](../modules/meta#call) to call it. This is useful for writing *higher-order functions* that call other functions.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
@use "sass:list";
@use "sass:meta";
@use "sass:string";
/// Return a copy of $list with all elements for which $condition returns `true`
/// removed.
@function remove-where($list, $condition) {
$new-list: ();
$separator: list.separator($list);
@each $element in $list {
@if not meta.call($condition, $element) {
$new-list: list.append($new-list, $element, $separator: $separator);
}
}
@return $new-list;
}
$fonts: Tahoma, Geneva, "Helvetica Neue", Helvetica, Arial, sans-serif;
content {
@function contains-helvetica($string) {
@return string.index($string, "Helvetica");
}
font-family: remove-where($fonts, meta.get-function("contains-helvetica"));
}
```
```
@use "sass:list"
@use "sass:meta"
@use "sass:string"
/// Return a copy of $list with all elements for which $condition returns `true`
/// removed.
@function remove-where($list, $condition)
$new-list: ()
$separator: list.separator($list)
@each $element in $list
@if not meta.call($condition, $element)
$new-list: list.append($new-list, $element, $separator: $separator)
@return $new-list
$fonts: Tahoma, Geneva, "Helvetica Neue", Helvetica, Arial, sans-serif
.content
@function contains-helvetica($string)
@return string.index($string, "Helvetica")
font-family: remove-where($fonts, meta.get-function("contains-helvetica"))
```
```
.content {
font-family: Tahoma, Geneva, Arial, sans-serif;
}
```
sass Maps Maps
=====
Maps in Sass hold pairs of keys and values, and make it easy to look up a value by its corresponding key. They’re written `(<expression>: <expression>, <expression>: <expression>)`. The [expression](../syntax/structure#expressions) before the `:` is the key, and the expression after is the value associated with that key. The keys must be unique, but the values may be duplicated. Unlike <lists>, maps *must* be written with parentheses around them. A map with no pairs is written `()`.
### 💡 Fun fact:
Astute readers may note that an empty map, `()`, is written the same as an empty list. That’s because it counts as both a map and a list. In fact, *all* maps count as lists! Every map counts as a list that contains a two-element list for each key/value pair. For example, `(1: 2, 3: 4)` counts as `(1 2, 3
4)`.
Maps allow any Sass values to be used as their keys. The [`==` operator](../operators/equality) is used to determine whether two keys are the same.
### ⚠️ Heads up!
Most of the time, it’s a good idea to use [quoted strings](strings#quoted) rather than [unquoted strings](strings#unquoted) for map keys. This is because some values, such as color names, may *look* like unquoted strings but actually be other types. To avoid confusing problems down the line, just use quotes!
Using Maps
-----------
Since maps aren’t valid CSS values, they don’t do much of anything on their own. That’s why Sass provides a bunch of [functions](../modules/map) to create maps and access the values they contain.
### Look Up a Value
Maps are all about associating keys and values, so naturally there’s a way to get the value associated with a key: the [`map.get($map, $key)` function](../modules/map#get)! This function returns the value in the map associated with the given key. It returns [`null`](null) if the map doesn’t contain the key.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
$font-weights: ("regular": 400, "medium": 500, "bold": 700);
@debug map.get($font-weights, "medium"); // 500
@debug map.get($font-weights, "extra-bold"); // null
```
```
$font-weights: ("regular": 400, "medium": 500, "bold": 700)
@debug map.get($font-weights, "medium") // 500
@debug map.get($font-weights, "extra-bold") // null
```
### Do Something for Every Pair
This doesn’t actually use a function, but it’s still one of the most common ways to use maps. The [`@each` rule](../at-rules/control/each) evaluates a block of styles for each key/value pair in a map. The key and the value are assigned to variables so they can easily be accessed in the block.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
$icons: ("eye": "\f112", "start": "\f12e", "stop": "\f12f");
@each $name, $glyph in $icons {
.icon-#{$name}:before {
display: inline-block;
font-family: "Icon Font";
content: $glyph;
}
}
```
```
$icons: ("eye": "\f112", "start": "\f12e", "stop": "\f12f")
@each $name, $glyph in $icons
.icon-#{$name}:before
display: inline-block
font-family: "Icon Font"
content: $glyph
```
```
@charset "UTF-8";
.icon-eye:before {
display: inline-block;
font-family: "Icon Font";
content: "";
}
.icon-start:before {
display: inline-block;
font-family: "Icon Font";
content: "";
}
.icon-stop:before {
display: inline-block;
font-family: "Icon Font";
content: "";
}
```
### Add to a Map
It’s also useful to add new pairs to a map, or to replace the value for an existing key. The [`map.set($map, $key, $value)` function](../modules/map#set) does this: it returns a copy of `$map` with the value at `$key` set to `$value`.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
@use "sass:map";
$font-weights: ("regular": 400, "medium": 500, "bold": 700);
@debug map.set($font-weights, "extra-bold", 900);
// ("regular": 400, "medium": 500, "bold": 700, "extra-bold": 900)
@debug map.set($font-weights, "bold", 900);
// ("regular": 400, "medium": 500, "bold": 900)
```
```
@use "sass:map"
$font-weights: ("regular": 400, "medium": 500, "bold": 700)
@debug map.set($font-weights, "extra-bold": 900)
// ("regular": 400, "medium": 500, "bold": 700, "extra-bold": 900)
@debug map.set($font-weights, "bold", 900)
// ("regular": 400, "medium": 500, "bold": 900)
```
Instead of setting values one-by-one, you can also merge two existing maps using [`map.merge($map1, $map2)`](../modules/map#merge).
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
```
@use "sass:map";
$light-weights: ("lightest": 100, "light": 300);
$heavy-weights: ("medium": 500, "bold": 700);
@debug map.merge($light-weights, $heavy-weights);
// ("lightest": 100, "light": 300, "medium": 500, "bold": 700)
```
```
@use "sass:map"
$light-weights: ("lightest": 100, "light": 300)
$heavy-weights: ("medium": 500, "bold": 700)
@debug map.merge($light-weights, $heavy-weights)
// ("lightest": 100, "light": 300, "medium": 500, "bold": 700)
```
If both maps have the same keys, the second map’s values are used in the map that gets returned.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
```
@use "sass:map";
$weights: ("light": 300, "medium": 500);
@debug map.merge($weights, ("medium": 700));
// ("light": 300, "medium": 700)
```
```
@use "sass:map";
$weights: ("light": 300, "medium": 500)
@debug map.merge($weights, ("medium": 700))
// ("light": 300, "medium": 700)
```
Note that because Sass maps are [immutable](#immutability), `map.set()` and `map.merge()` do not modify the original list.
Immutability
-------------
Maps in Sass are *immutable*, which means that the contents of a map value never changes. Sass’s map functions all return new maps rather than modifying the originals. Immutability helps avoid lots of sneaky bugs that can creep in when the same map is shared across different parts of the stylesheet.
You can still update your state over time by assigning new maps to the same variable, though. This is often used in functions and mixins to track configuration in a map.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
```
@use "sass:map";
$prefixes-by-browser: ("firefox": moz, "safari": webkit, "ie": ms);
@mixin add-browser-prefix($browser, $prefix) {
$prefixes-by-browser: map.merge($prefixes-by-browser, ($browser: $prefix)) !global;
}
@include add-browser-prefix("opera", o);
@debug $prefixes-by-browser;
// ("firefox": moz, "safari": webkit, "ie": ms, "opera": o)
```
```
@use "sass:map"
$prefixes-by-browser: ("firefox": moz, "safari": webkit, "ie": ms)
@mixin add-browser-prefix($browser, $prefix)
$prefixes-by-browser: map.merge($prefixes-by-browser, ($browser: $prefix)) !global
@include add-browser-prefix("opera", o)
@debug $prefixes-by-browser
// ("firefox": moz, "safari": webkit, "ie": ms, "opera": o)
```
sass Strings Strings
========
Strings are sequences of characters (specifically [Unicode code points](https://en.wikipedia.org/wiki/Code_point)). Sass supports two kinds of strings whose internal structure is the same but which are rendered differently: [quoted strings](#quoted), like `"Helvetica Neue"`, and [unquoted strings](#unquoted) (also known as *identifiers*), like `bold`. Together, these cover the different kinds of text that appear in CSS.
### 💡 Fun fact:
You can convert a quoted string to an unquoted string using the [`string.unquote()` function](../modules/string#unquote), and you can convert an unquoted string to a quoted string using the [`string.quote()` function](../modules/string#quote).
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@use "sass:string";
@debug string.unquote(".widget:hover"); // .widget:hover
@debug string.quote(bold); // "bold"
```
```
@use "sass:string"
@debug string.unquote(".widget:hover") // .widget:hover
@debug string.quote(bold) // "bold"
```
Escapes
--------
All Sass strings support the standard CSS [escape codes](https://developer.mozilla.org/en-US/docs/Web/CSS/string#Syntax):
* Any character other than a letter from A to F or a number from 0 to 9 (even a newline!) can be included as part of a string by writing `\` in front of it.
* Any character can be included as part of a string by writing `\` followed by its [Unicode code point number](https://en.wikipedia.org/wiki/List_of_Unicode_characters) written in [hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal). You can optionally include a space after the code point number to indicate where the Unicode number ends.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
```
@debug "\""; // '"'
@debug \.widget; // \.widget
@debug "\a"; // "\a" (a string containing only a newline)
@debug "line1\a line2"; // "line1\a line2"
@debug "Nat + Liz \1F46D"; // "Nat + Liz 👭"
```
```
@debug "\"" // '"'
@debug \.widget // \.widget
@debug "\a" // "\a" (a string containing only a newline)
@debug "line1\a line2" // "line1\a line2" (foo and bar are separated by a newline)
@debug "Nat + Liz \1F46D" // "Nat + Liz 👭"
```
### 💡 Fun fact:
For characters that are allowed to appear in strings, writing the Unicode escape produces exactly the same string as writing the character itself.
Quoted
-------
Quoted strings are written between either single or double quotes, as in `"Helvetica Neue"`. They can contain [interpolation](../interpolation), as well as any unescaped character except for:
* `\`, which can be escaped as `\\`;
* `'` or `"`, whichever was used to define that string, which can be escaped as `\'` or `\"`;
* newlines, which can be escaped as `\a` (including a trailing space).
Quoted strings are guaranteed to be compiled to CSS strings that have the same contents as the original Sass strings. The exact format may vary based on the implementation or configuration—a string containing a double quote may be compiled to `"\""` or `'"'`, and a non-[ASCII](https://en.wikipedia.org/wiki/ASCII) character may or may not be escaped. But that should be parsed the same in any standards-compliant CSS implementation, including all browsers.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
@debug "Helvetica Neue"; // "Helvetica Neue"
@debug "C:\\Program Files"; // "C:\\Program Files"
@debug "\"Don't Fear the Reaper\""; // "\"Don't Fear the Reaper\""
@debug "line1\a line2"; // "line1\a line2"
$roboto-variant: "Mono";
@debug "Roboto #{$roboto-variant}"; // "Roboto Mono"
```
```
@debug "Helvetica Neue" // "Helvetica Neue"
@debug "C:\\Program Files" // "C:\\Program Files"
@debug "\"Don't Fear the Reaper\"" // "\"Don't Fear the Reaper\""
@debug "line1\a line2" // "line1\a line2"
$roboto-variant: "Mono"
@debug "Roboto #{$roboto-variant}" // "Roboto Mono"
```
### 💡 Fun fact:
When a quoted string is injected into another value via interpolation, [its quotes are removed](../interpolation#quoted-strings)! This makes it easy to write strings containing selectors, for example, that can be injected into style rules without adding quotes.
Unquoted
---------
Unquoted strings are written as CSS [identifiers](https://drafts.csswg.org/css-syntax-3/#ident-token-diagram), following the syntax diagram below. They may include [interpolation](../interpolation) anywhere.
Railroad diagram copyright © 2018 W3C® (MIT, ERCIM, Keio, Beihang). W3C [liability](http://www.w3.org/Consortium/Legal/ipr-notice#Legal_Disclaimer), [trademark](http://www.w3.org/Consortium/Legal/ipr-notice#W3C_Trademarks) and [permissive document license](http://www.w3.org/Consortium/Legal/2015/copyright-software-and-document) rules apply.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
```
@debug bold; // bold
@debug -webkit-flex; // -webkit-flex
@debug --123; // --123
$prefix: ms;
@debug -#{$prefix}-flex; // -ms-flex
```
```
@debug bold // bold
@debug -webkit-flex // -webkit-flex
@debug --123 // --123
$prefix: ms
@debug -#{$prefix}-flex // -ms-flex
```
### ⚠️ Heads up!
Not all identifiers are parsed as unquoted strings:
* [CSS color names](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#Color_keywords) are parsed as <colors>.
* `null` is parsed as [Sass’s `null` value](null).
* `true` and `false` are parsed as [Booleans](booleans).
* `not`, `and`, and `or` are parsed as [Boolean operators](../operators/boolean).
Because of this, it’s generally a good idea to write quoted strings unless you’re specifically writing the value of a CSS property that uses unquoted strings.
### Escapes in Unquoted Strings
Compatibility (Normalization):
Dart Sass since 1.11.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) LibSass, Ruby Sass, and older versions of Dart Sass don’t normalize escapes in identifiers. Instead, the text in the unquoted string is the exact text the user wrote. For example, `\1F46D` and `👭` are not considered equivalent.
When an unquoted string is parsed, the literal text of escapes are parsed as part of the string. For example, `\a` is parsed as the characters `\`, `a`, and space. In order to ensure that unquoted strings that have the same meanings in CSS are parsed the same way, though, these escapes are *normalized*. For each code point, whether it’s escaped or unescaped:
* If it’s a valid identifier character, it’s included unescaped in the unquoted string. For example, `\1F46D` returns the unquoted string `👭`.
* If it’s a printable character other than a newline or a tab, it’s included after a `\`. For example, `\21` returns the unquoted string `\!`.
* Otherwise, the lowercase Unicode escape is included with a trailing space. For example, `\7Fx` returns the unquoted string `\7f x`.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
```
@use "sass:string";
@debug \1F46D; // 👭
@debug \21; // \!
@debug \7Fx; // \7f x
@debug string.length(\7Fx); // 5
```
```
@use "sass:string"
@debug \1F46D // 👭
@debug \21 // \!
@debug \7Fx // \7f x
@debug string.length(\7Fx) // 5
```
String Indexes
---------------
Sass has a number of [string functions](../modules/string) that take or return numbers, called *indexes*, that refer to the characters in a string. The index 1 indicates the first character of the string. Note that this is different than many programming languages where indexes start at 0! Sass also makes it easy to refer to the end of a string. The index -1 refers to the last character in a string, -2 refers to the second-to-last, and so on.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
```
@use "sass:string";
@debug string.index("Helvetica Neue", "Helvetica"); // 1
@debug string.index("Helvetica Neue", "Neue"); // 11
@debug string.slice("Roboto Mono", -4); // "Mono"
```
```
@use "sass:string"
@debug string.index("Helvetica Neue", "Helvetica") // 1
@debug string.index("Helvetica Neue", "Neue") // 11
@debug string.slice("Roboto Mono", -4) // "Mono"
```
| programming_docs |
sass null null
=====
The value `null` is the only value of its type. It represents the absence of a value, and is often returned by [functions](../at-rules/function) to indicate the lack of a result.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@use "sass:map";
@use "sass:string";
@debug string.index("Helvetica Neue", "Roboto"); // null
@debug map.get(("large": 20px), "small"); // null
@debug &; // null
```
```
@use "sass:map"
@use "sass:string"
@debug string.index("Helvetica Neue", "Roboto") // null
@debug map.get(("large": 20px), "small") // null
@debug & // null
```
If a [list](lists) contains a `null`, that `null` is omitted from the generated CSS.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
$fonts: ("serif": "Helvetica Neue", "monospace": "Consolas");
h3 {
font: 18px bold map-get($fonts, "sans");
}
```
```
$fonts: ("serif": "Helvetica Neue", "monospace": "Consolas")
h3
font: 18px bold map-get($fonts, "sans")
```
```
h3 {
font: 18px bold;
}
```
If a property value is `null`, that property is omitted entirely.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
* [CSS](#example-3-css)
```
$fonts: ("serif": "Helvetica Neue", "monospace": "Consolas");
h3 {
font: {
size: 18px;
weight: bold;
family: map-get($fonts, "sans");
}
}
```
```
$fonts: ("serif": "Helvetica Neue", "monospace": "Consolas")
h3
font:
size: 18px
weight: bold
family: map-get($fonts, "sans")
```
```
h3 {
font-size: 18px;
font-weight: bold;
}
```
`null` is also [*falsey*](../at-rules/control/if#truthiness-and-falsiness), which means it counts as `false` for any rules or [operators](../operators/boolean) that take booleans. This makes it easy to use values that can be `null` as conditions for [`@if`](../at-rules/control/if) and [`if()`](../modules#if).
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
* [CSS](#example-4-css)
```
@mixin app-background($color) {
#{if(&, '&.app-background', '.app-background')} {
background-color: $color;
color: rgba(#fff, 0.75);
}
}
@include app-background(#036);
.sidebar {
@include app-background(#c6538c);
}
```
```
@mixin app-background($color)
#{if(&, '&.app-background', '.app-background')}
background-color: $color
color: rgba(#fff, 0.75)
@include app-background(#036)
.sidebar
@include app-background(#c6538c)
```
```
.app-background {
background-color: #036;
color: rgba(255, 255, 255, 0.75);
}
.sidebar.app-background {
background-color: #c6538c;
color: rgba(255, 255, 255, 0.75);
}
```
sass Lists Lists
======
Compatibility (Square Brackets):
Dart Sass ✓
LibSass since 3.5.0
Ruby Sass since 3.5.0
[▶](javascript:;) Older implementations of LibSass and Ruby Sass didn’t support lists with square brackets.
Lists contain a sequence of other values. In Sass, elements in lists can be separated by commas (`Helvetica, Arial, sans-serif`), spaces (`10px 15px 0 0`), or [slashes](#slash-separated-lists) as long as it’s consistent within the list. Unlike most other languages, lists in Sass don’t require special brackets; any [expressions](../syntax/structure#expressions) separated with spaces or commas count as a list. However, you’re allowed to write lists with square brackets (`[line1 line2]`), which is useful when using [`grid-template-columns`](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns).
Sass lists can contain one or even zero elements. A single-element list can be written either `(<expression>,)` or `[<expression>]`, and a zero-element list can be written either `()` or `[]`. Also, all [list functions](../modules/list) will treat individual values that aren’t in lists as though they’re lists containing that value, which means you rarely need to explicitly create single-element lists.
### ⚠️ Heads up!
Empty lists without brackets aren’t valid CSS, so Sass won’t let you use one in a property value.
Slash-Separated Lists
----------------------
Lists in Sass can be separated by slashes, to represent values like the `font: 12px/30px` shorthand for setting `font-size` and `line-height` or the `hsl(80 100% 50% / 0.5)` syntax for creating a color with a given opacity value. However, **slash-separated lists can’t currently be written literally.** Sass historically used the `/` character to indicate division, so while existing stylesheets transition to using [`math.div()`](../modules/math#div) slash-separated lists can only be written using [`list.slash()`](../modules/list#slash).
For more details, see [Breaking Change: Slash as Division](https://sass-lang.com/documentation/breaking-changes/slash-div).
Using Lists
------------
Sass provides a handful of [functions](../modules/list) that make it possible to use lists to write powerful style libraries, or to make your app’s stylesheet cleaner and more maintainable.
### Indexes
Many of these functions take or return numbers, called *indexes*, that refer to the elements in a list. The index 1 indicates the first element of the list. Note that this is different than many programming languages where indexes start at 0! Sass also makes it easy to refer to the end of a list. The index -1 refers to the last element in a list, -2 refers to the second-to-last, and so on.
### Access an Element
Lists aren’t much use if you can’t get values out of them. You can use the [`list.nth($list, $n)` function](../modules/list#nth) to get the element at a given index in a list. The first argument is the list itself, and the second is the index of the value you want to get out.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@debug list.nth(10px 12px 16px, 2); // 12px
@debug list.nth([line1, line2, line3], -1); // line3
```
```
@debug list.nth(10px 12px 16px, 2) // 12px
@debug list.nth([line1, line2, line3], -1) // line3
```
### Do Something for Every Element
This doesn’t actually use a function, but it’s still one of the most common ways to use lists. The [`@each` rule](../at-rules/control/each) evaluates a block of styles for each element in a list, and assigns that element to a variable.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
$sizes: 40px, 50px, 80px;
@each $size in $sizes {
.icon-#{$size} {
font-size: $size;
height: $size;
width: $size;
}
}
```
```
$sizes: 40px, 50px, 80px
@each $size in $sizes
.icon-#{$size}
font-size: $size
height: $size
width: $size
```
```
.icon-40px {
font-size: 40px;
height: 40px;
width: 40px;
}
.icon-50px {
font-size: 50px;
height: 50px;
width: 50px;
}
.icon-80px {
font-size: 80px;
height: 80px;
width: 80px;
}
```
### Add to a List
It’s also useful to add elements to a list. The [`list.append($list, $val)` function](../modules/list#append) takes a list and a value, and returns a copy of the list with the value added to the end. Note that because Sass lists are [immutable](#immutability), it doesn’t modify the original list.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
@debug append(10px 12px 16px, 25px); // 10px 12px 16px 25px
@debug append([col1-line1], col1-line2); // [col1-line1, col1-line2]
```
```
@debug append(10px 12px 16px, 25px) // 10px 12px 16px 25px
@debug append([col1-line1], col1-line2) // [col1-line1, col1-line2]
```
### Find an Element in a List
If you need to check if an element is in a list or figure out what index it’s at, use the [`list.index($list, $value)` function](../modules/list#index). This takes a list and a value to locate in that list, and returns the index of that value.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
```
@debug list.index(1px solid red, 1px); // 1
@debug list.index(1px solid red, solid); // 2
@debug list.index(1px solid red, dashed); // null
```
```
@debug list.index(1px solid red, 1px) // 1
@debug list.index(1px solid red, solid) // 2
@debug list.index(1px solid red, dashed) // null
```
If the value isn’t in the list at all, `list.index()` returns [`null`](null). Because `null` is [falsey](../at-rules/control/if#truthiness-and-falsiness), you can use `list.index()` with [`@if`](../at-rules/control/if) or [`if()`](../modules#if) to check whether a list does or doesn’t contain a given value.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
```
@use "sass:list";
$valid-sides: top, bottom, left, right;
@mixin attach($side) {
@if not list.index($valid-sides, $side) {
@error "#{$side} is not a valid side. Expected one of #{$valid-sides}.";
}
// ...
}
```
```
@use "sass:list"
$valid-sides: top, bottom, left, right
@mixin attach($side)
@if not list.index($valid-sides, $side)
@error "#{$side} is not a valid side. Expected one of #{$valid-sides}."
// ...
```
Immutability
-------------
Lists in Sass are *immutable*, which means that the contents of a list value never changes. Sass’s list functions all return new lists rather than modifying the originals. Immutability helps avoid lots of sneaky bugs that can creep in when the same list is shared across different parts of the stylesheet.
You can still update your state over time by assigning new lists to the same variable, though. This is often used in functions and mixins to collect a bunch of values into one list.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
```
@use "sass:list";
@use "sass:map";
$prefixes-by-browser: ("firefox": moz, "safari": webkit, "ie": ms);
@function prefixes-for-browsers($browsers) {
$prefixes: ();
@each $browser in $browsers {
$prefixes: list.append($prefixes, map.get($prefixes-by-browser, $browser));
}
@return $prefixes;
}
@debug prefixes-for-browsers("firefox" "ie"); // moz ms
```
```
@use "sass:list"
@use "sass:map"
$prefixes-by-browser: ("firefox": moz, "safari": webkit, "ie": ms)
@function prefixes-for-browsers($browsers)
$prefixes: ()
@each $browser in $browsers
$prefixes: list.append($prefixes, map.get($prefixes-by-browser, $browser))
@return $prefixes
@debug prefixes-for-browsers("firefox" "ie") // moz ms
```
Argument Lists
---------------
When you declare a mixin or function that takes [arbitrary arguments](../at-rules/mixin#taking-arbitrary-arguments), the value you get is a special list known as an *argument list*. It acts just like a list that contains all the arguments passed to the mixin or function, with one extra feature: if the user passed keyword arguments, they can be accessed as a map by passing the argument list to the [`meta.keywords()` function](../modules/meta#keywords).
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
* [CSS](#example-7-css)
```
@use "sass:meta";
@mixin syntax-colors($args...) {
@debug meta.keywords($args);
// (string: #080, comment: #800, variable: #60b)
@each $name, $color in meta.keywords($args) {
pre span.stx-#{$name} {
color: $color;
}
}
}
@include syntax-colors(
$string: #080,
$comment: #800,
$variable: #60b,
)
```
```
@use "sass:meta"
@mixin syntax-colors($args...)
@debug meta.keywords($args)
// (string: #080, comment: #800, variable: #60b)
@each $name, $color in meta.keywords($args)
pre span.stx-#{$name}
color: $color
@include syntax-colors($string: #080, $comment: #800, $variable: #60b)
```
```
pre span.stx-string {
color: #080;
}
pre span.stx-comment {
color: #800;
}
pre span.stx-variable {
color: #60b;
}
```
sass Numbers Numbers
========
Numbers in Sass have two components: the number itself, and its units. For example, in `16px` the number is `16` and the unit is `px`. Numbers can have no units, and they can have complex units. See [Units](#units) below for more details.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@debug 100; // 100
@debug 0.8; // 0.8
@debug 16px; // 16px
@debug 5px * 2px; // 10px*px (read "square pixels")
```
```
@debug 100 // 100
@debug 0.8 // 0.8
@debug 16px // 16px
@debug 5px * 2px // 10px*px (read "square pixels")
```
Sass numbers support the same formats as CSS numbers, including [scientific notation](https://en.wikipedia.org/wiki/Scientific_notation), which is written with an `e` between the number and its power of 10. Because support for scientific notation in browsers has historically been spotty, Sass always compiles it to fully expanded numbers.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
```
@debug 5.2e3; // 5200
@debug 6e-2; // 0.06
```
```
@debug 5.2e3 // 5200
@debug 6e-2 // 0.06
```
### ⚠️ Heads up!
Sass doesn’t distinguish between whole numbers and decimals, so for example `math.div(5, 2)` returns `2.5` rather than `2`. This is the same behavior as JavaScript, but different than many other programming languages.
Units
------
Sass has powerful support for manipulating units based on how [real-world unit calculations](https://en.wikipedia.org/wiki/Unit_of_measurement#Calculations_with_units_of_measurement) work. When two numbers are multiplied, their units are multiplied as well. When one number is divided by another, the result takes its numerator units from the first number and its denominator units from the second. A number can have any number of units in the numerator and/or denominator.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
@debug 4px * 6px; // 24px*px (read "square pixels")
@debug math.div(5px, 2s); // 2.5px/s (read "pixels per second")
// 3.125px*deg/s*em (read "pixel-degrees per second-em")
@debug 5px * math.div(math.div(30deg, 2s), 24em);
$degrees-per-second: math.div(20deg, 1s);
@debug $degrees-per-second; // 20deg/s
@debug math.div(1, $degrees-per-second); // 0.05s/deg
```
```
@debug 4px * 6px // 24px*px (read "square pixels")
@debug math.div(5px, 2s) // 2.5px/s (read "pixels per second")
// 3.125px*deg/s*em (read "pixel-degrees per second-em")
@debug 5px * math.div(math.div(30deg, 2s), 24em)
$degrees-per-second: math.div(20deg, 1s)
@debug $degrees-per-second // 20deg/s
@debug math.div(1, $degrees-per-second) // 0.05s/deg
```
### ⚠️ Heads up!
Because CSS doesn’t support complex units like square pixels, using a number with complex units as a [property value](../style-rules/declarations) will produce an error. This is a feature in disguise, though; if you aren’t ending up with the right unit, it usually means that something’s wrong with your calculations! And remember, you can always use the [`@debug` rule](../at-rules/debug) to check out the units of any variable or [expression](../syntax/structure#expressions).
Sass will automatically convert between compatible units, although which unit it will choose for the result depends on which implementation of Sass you’re using.If you try to combine incompatible units, like `1in + 1em`, Sass will throw an error.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
```
// CSS defines one inch as 96 pixels.
@debug 1in + 6px; // 102px or 1.0625in
@debug 1in + 1s;
// ^^^^^^^^
// Error: Incompatible units s and in.
```
```
// CSS defines one inch as 96 pixels.
@debug 1in + 6px // 102px or 1.0625in
@debug 1in + 1s
// ^^^^^^^^
// Error: Incompatible units s and in.
```
As in real-world unit calculations, if the numerator contains units that are compatible with units in the denominator (like `math.div(96px, 1in)`), they’ll cancel out. This makes it easy to define a ratio that you can use for converting between units. In the example below, we set the desired speed to one second per 50 pixels, and then multiply that by the number of pixels the transition covers to get the time it should take.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
* [CSS](#example-5-css)
```
$transition-speed: math.div(1s, 50px);
@mixin move($left-start, $left-stop) {
position: absolute;
left: $left-start;
transition: left ($left-stop - $left-start) * $transition-speed;
&:hover {
left: $left-stop;
}
}
.slider {
@include move(10px, 120px);
}
```
```
$transition-speed: math.div(1s, 50px)
@mixin move($left-start, $left-stop)
position: absolute
left: $left-start
transition: left ($left-stop - $left-start) * $transition-speed
&:hover
left: $left-stop
.slider
@include move(10px, 120px)
```
```
.slider {
position: absolute;
left: 10px;
transition: left 2.2s;
}
.slider:hover {
left: 120px;
}
```
### ⚠️ Heads up!
If your arithmetic gives you the wrong unit, you probably need to check your math. You may be leaving off units for a quantity that should have them! Staying unit-clean allows Sass to give you helpful errors when something isn’t right.
You should especially avoid using interpolation like `#{$number}px`. This doesn’t actually create a number! It creates an [unquoted string](strings#unquoted) that *looks* like a number, but won’t work with any [number operations](../operators/numeric) or [functions](../modules/math). Try to make your math unit-clean so that `$number` already has the unit `px`, or write `$number * 1px`.
### ⚠️ Heads up!
Percentages in Sass work just like every other unit. They are *not* interchangeable with decimals, because in CSS decimals and percentages mean different things. For example, `50%` is a number with `%` as its unit, and Sass considers it different than the number `0.5`.
You can convert between decimals and percentages using unit arithmetic. `math.div($percentage, 100%)` will return the corresponding decimal, and `$decimal * 100%` will return the corresponding percentage. You can also use the [`math.percentage()` function](../modules/math#percentage) as a more explicit way of writing `$decimal * 100%`.
Precision
----------
Compatibility (10 Digit Default):
Dart Sass ✓
LibSass ✗
Ruby Sass since 3.5.0
[▶](javascript:;) LibSass and older versions of Ruby Sass default to 5 digits of numeric precision, but can be configured to use a different number. It’s recommended that users configure them for 10 digits for greater accuracy and forwards-compatibility.
Sass numbers support up to 10 digits of precision after the decimal point. This means a few different things:
* Only the first ten digits of a number after the decimal point will be included in the generated CSS.
* Operations like [`==`](../operators/equality) and [`>=`](../operators/relational) will consider two numbers equivalent if they’re the same up to the tenth digit after the decimal point.
* If a number is less than `0.0000000001` away from an integer, it’s considered to be an integer for the purposes of functions like [`list.nth()`](../modules/list#nth) that require integer arguments.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
```
@debug 0.012345678912345; // 0.0123456789
@debug 0.01234567891 == 0.01234567899; // true
@debug 1.00000000009; // 1
@debug 0.99999999991; // 1
```
```
@debug 0.012345678912345 // 0.0123456789
@debug 0.01234567891 == 0.01234567899 // true
@debug 1.00000000009 // 1
@debug 0.99999999991 // 1
```
### 💡 Fun fact:
Numbers are rounded to 10 digits of precision *lazily* when they’re used in a place where precision is relevant. This means that math functions will work with the full number value internally to avoid accumulating extra rounding errors.
sass Calculations Calculations
=============
Calculations are how Sass represents the `calc()` function, as well as similar functions like `clamp()`, `min()`, and `max()`. Sass will simplify these as much as possible, even if they're combined with one another.
Compatibility:
Dart Sass since 1.40.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;)
LibSass, Ruby Sass, and versions of Dart Sass prior to 1.40.0 parse `calc()` as a [special function](../syntax/special-functions#element-progid-and-expression) like `element()`.
LibSass, Ruby Sass, and versions of Dart Sass prior to 1.31.0 parse `clamp()` as a [plain CSS function](../at-rules/function#plain-css-functions) rather than supporting special syntax within it. Versions of Dart Sass between 1.31.0 and 1.40.0 parse `clamp()` as a [special function](../syntax/special-functions#element-progid-and-expression) like `element()`.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@debug calc(400px + 10%); // calc(400px + 10%)
@debug calc(400px / 2); // 200px
@debug min(100px, calc(1rem + 10%)); // min(100px, 1rem + 10%)
```
```
@debug calc(400px + 10%) // calc(400px + 10%)
@debug calc(400px / 2) // 200px
@debug min(100px, calc(1rem + 10%) ; // min(100px, 1rem + 10%)
```
Calculations use a special syntax that’s different from normal SassScript. It’s the same syntax as the CSS `calc()`, but with the additional ability to use [Sass variables](../variables) and call [Sass functions](../modules). This means that `/` is always a division operator within a calculation!
### 💡 Fun fact:
The arguments to a Sass function call use the normal Sass syntax, rather than the special calculation syntax!
You can also use [interpolation](../interpolation) in a calculation. However, if you do, nothing in the parentheses that surround that interpolation will be simplified or type-checked, so it’s easy to end up with extra verbose or even invalid CSS. Rather than writing `calc(10px + #{$var})`, just write `calc(10px + $var)`!
Simplification
---------------
Sass will simplify adjacent operations in calculations if they use units that can be combined at compile-time, such as `1in + 10px` or `5s * 2`. If possible, it’ll even simplify the whole calculation to a single number—for example, `clamp(0px, 30px, 20px)` will return `20px`.
### ⚠️ Heads up!
This means that a calculation expression won’t necessarily always return a calculation! If you’re writing a Sass library, you can always use the [`meta.type-of()`](../modules/meta#type-of) function to determine what type you’re dealing with.
Calculations will also be simplified within other calculations. In particular, if a `calc()` end up inside any other calculation, the function call will be removed and it’ll be replaced by a plain old operation.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
$width: calc(400px + 10%);
.sidebar {
width: $width;
padding-left: calc($width / 4);
}
```
```
$width: calc(400px + 10%)
.sidebar
width: $width
padding-left: calc($width / 4)
==
.sidebar {
width: calc(400px + 10%);
padding-left: calc((400px + 10%) / 4);
}
```
```
.sidebar {
width: calc(400px + 10%);
padding-left: calc($width / 4);
}
```
Operations
-----------
You can’t use calculations with normal SassScript operations like `+` and `*`. If you want to write some math functions that allow calculations just write them within their own `calc()` expressions—if they’re passed a bunch of numbers with compatible units, they’ll return plain numbers as well, and if they’re passed calculations they’ll return calculations.
This restriction is in place to make sure that if calculations *aren’t* wanted, they throw an error as soon as possible. Calculations can’t be used everywhere plain numbers can: they can’t be injected into CSS identifiers (such as `.item-#{$n}`), for example, and they can’t be passed to Sass’s built-in [math functions](../modules/math). Reserving SassScript operations for plain numbers makes it clear exactly where calculations are allowed and where they aren’t.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
$width: calc(100% + 10px);
@debug $width * 2; // Error!
@debug calc($width * 2); // calc((100% + 10px) * 2);
```
```
$width: calc(100% + 10px);
@debug $width * 2; // Error!
@debug calc($width * 2); // calc((100% + 10px) * 2);
```
`min()` and `max()`
--------------------
Compatibility (Special function syntax):
Dart Sass since >=1.11.0 <1.42.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;)
LibSass, Ruby Sass, and versions of Dart Sass prior to 1.11.0 *always* parse `min()` and `max()` as Sass functions. To create a plain CSS `min()` or `max()` call for those implementations, you can write something like `unquote("min(#{$padding}, env(safe-area-inset-left))")` instead.
Versions of Dart Sass between 1.11.0 and 1.40.0, and between 1.40.1 and 1.42.0 parse `min()` and `max()` functions as [special functions](../syntax/special-functions) if they’re valid plain CSS, but parse them as Sass functions if they contain Sass features other than interpolation, like variables or function calls.
Dart Sass 1.41.0 parses `min()` and `max()` functions as calculations, but doesn’t allow unitless numbers to be combined with numbers with units. This was backwards-incompatible with the global `min()` and `max()` functions, so that behavior was reverted.
CSS added support for [`min()` and `max()` functions](https://drafts.csswg.org/css-values-4/#calc-notation) in Values and Units Level 4, from where they were quickly adopted by Safari [to support the iPhoneX](https://webkit.org/blog/7929/designing-websites-for-iphone-x/). But Sass supported its own [`min()`](../modules/math#min) and [`max()`](../modules/math#max) functions long before this, and it needed to be backwards-compatible with all those existing stylesheets. This led to the need for extra-special syntactic cleverness.
If a `min()` or `max()` function call is a valid calculation expression, it will be parsed as a calculation. But as soon as any part of the call contains a SassScript feature that isn’t supported in a calculation, like the [modulo operator](../operators/numeric), it’s parsed as a call to Sass’s core `min()` or `max()` function instead.
Since calculations are simplified to numbers when possible anyway, the only substantive difference is that the Sass functions only support units that can be combined at build time, so `min(12px % 10, 10%)` will throw an error.
### ⚠️ Heads up!
Other calculations don’t allow unitless numbers to be added to, subtracted from, or compared to numbers with units. `min()` and `max()` are different, though: for backwards-compatibility with the global Sass `min()` and `max()` functions which allow unit/unitless mixing for historical reasons, these units can be mixed as long as they’re contained directly within a `min()` or `max()` calculation.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
* [CSS](#example-4-css)
```
$padding: 12px;
.post {
// Since these max() calls are valid calculation expressions, they're
// parsed as calculations.
padding-left: max($padding, env(safe-area-inset-left));
padding-right: max($padding, env(safe-area-inset-right));
}
.sidebar {
// Since these use the SassScript-only modulo operator, they're parsed as
// SassScript function calls.
padding-left: max($padding % 10, 20px);
padding-right: max($padding % 10, 20px);
}
```
```
$padding: 12px
.post
// Since these max() calls are valid calculation expressions, they're
// parsed as calculations.
padding-left: max($padding, env(safe-area-inset-left))
padding-right: max($padding, env(safe-area-inset-right))
.sidebar
// Since these use the SassScript-only modulo operator, they're parsed as
// SassScript function calls.
padding-left: max($padding % 10, 20px)
padding-right: max($padding % 10, 20px)
```
```
.post {
padding-left: max(12px, env(safe-area-inset-left));
padding-right: max(12px, env(safe-area-inset-right));
}
.sidebar {
padding-left: 20px;
padding-right: 20px;
}
```
| programming_docs |
sass Dart Sass Command-Line Interface Dart Sass Command-Line Interface
=================================
Usage
------
The Dart Sass executable can be invoked in one of two modes.
### One-to-One Mode
```
sass <input.scss> [output.css]
```
One-to-one mode compiles a single input file (`input.scss`) to a single output location (`output.css`). If no output location is passed, the compiled CSS is printed to the terminal.
The input file is parsed as [SCSS](../syntax#scss) if its extension is `.scss`, as the [indented syntax](../syntax#the-indented-syntax) if its extension is `.sass`, or as [plain CSS](../at-rules/import#importing-css) if its extension is `.css`. If it doesn’t have one of these three extensions, or if it comes from standard input, it’s parsed as SCSS by default. This can be controlled with the [`--indented` flag](#indented).
The special string `-` can be passed in place of the input file to tell Sass to read the input file from [standard input](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)). Sass will default to parsing it as SCSS unless the [`--indented` flag](#indented) is passed.
### Many-to-many Mode
Compatibility:
Dart Sass since 1.4.0
```
sass [<input.scss>:<output.css>] [<input/>:<output/>]...
```
Many-to-many mode compiles one or more input files to one or more output files. The inputs are separated from the outputs with colons. It can also compile all Sass files in a directory to CSS files with the same names in another directory.
```
# Compiles style.scss to style.css.
$ sass style.scss:style.css
# Compiles light.scss and dark.scss to light.css and dark.css.
$ sass light.scss:light.css dark.scss:dark.css
# Compiles all Sass files in themes/ to CSS files in public/css/.
$ sass themes:public/css
```
When compiling whole directories, Sass will ignore [partial files](../at-rules/import#partials) whose names begin with `_`. You can use partials to separate out your stylesheets without creating a bunch of unnecessary output files.
Options
--------
### Input and Output
These options control how Sass loads its input files and how it produces output files.
#### `--stdin`
This flag is an alternative way of telling Sass that it should read its input file from [standard input](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)). When it’s passed, no input file may be passed.
```
$ echo "h1 {font-size: 40px}" | sass --stdin h1.css
$ echo "h1 {font-size: 40px}" | sass --stdin
h1 {
font-size: 40px;
}
```
The `--stdin` flag may not be used with [many-to-many mode](#many-to-many-mode).
#### `--indented`
This flag tells Sass to parse the input file as the [indented syntax](../syntax#the-indented-syntax). If it’s used in [many-to-many mode](#many-to-many-mode), all input files are parsed as the indented syntax, although files they [use](../at-rules/use) will have their syntax determined as usual. The inverse, `--no-indented`, can be used to force all input files to be parsed as [SCSS](../syntax#scss) instead.
The `--indented` flag is mostly useful when the input file is coming from [standard input](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)), so its syntax can’t be automatically determined.
```
$ echo -e 'h1\n font-size: 40px' | sass --indented -
h1 {
font-size: 40px;
}
```
#### `--load-path`
This option (abbreviated `-I`) adds an additional [load path](../at-rules/use#load-paths) for Sass to look for stylesheets. It can be passed multiple times to provide multiple load paths. Earlier load paths will take precedence over later ones.
```
$ sass --load-path=node_modules/bootstrap/dist/css style.scss style.css
```
#### `--style`
This option (abbreviated `-s`) controls the output style of the resulting CSS. Dart Sass supports two output styles:
* `expanded` (the default) writes each selector and declaration on its own line.
* `compressed` removes as many extra characters as possible, and writes the entire stylesheet on a single line.
```
$ sass --style=expanded style.scss
h1 {
font-size: 40px;
}
$ sass --style=compressed style.scss
h1{font-size:40px}
```
#### `--no-charset`
Compatibility:
Dart Sass since 1.19.0
This flag tells Sass never to emit a `@charset` declaration or a UTF-8 [byte-order mark](https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8). By default, or if `--charset` is passed, Sass will insert either a `@charset` declaration (in expanded output mode) or a byte-order mark (in compressed output mode) if the stylesheet contains any non-ASCII characters.
```
$ echo 'h1::before {content: "👭"}' | sass --no-charset
h1::before {
content: "👭";
}
$ echo 'h1::before {content: "👭"}' | sass --charset
@charset "UTF-8";
h1::before {
content: "👭";
}
```
#### `--error-css`
Compatibility:
Dart Sass since 1.20.0
This flag tells Sass whether to emit a CSS file when an error occurs during compilation. This CSS file describes the error in a comment *and* in the `content` property of `body::before`, so that you can see the error message in the browser without needing to switch back to the terminal.
By default, error CSS is enabled if you’re compiling to at least one file on disk (as opposed to standard output). You can pass `--error-css` explicitly to enable it even when you’re compiling to standard out, or `--no-error-css` to disable it everywhere. When it’s disabled, the [`--update` flag](#update) and [`--watch` flag](#watch) will delete CSS files instead when an error occurs.
```
$ sass --error-css style.scss style.css
/* Error: Incompatible units em and px.
* ,
* 1 | $width: 15px + 2em;
* | ^^^^^^^^^^
* '
* test.scss 1:9 root stylesheet */
body::before {
font-family: "Source Code Pro", "SF Mono", Monaco, Inconsolata, "Fira Mono",
"Droid Sans Mono", monospace, monospace;
white-space: pre;
display: block;
padding: 1em;
margin-bottom: 1em;
border-bottom: 2px solid black;
content: "Error: Incompatible units em and px.\a \2577 \a 1 \2502 $width: 15px + 2em;\a \2502 ^^^^^^^^^^\a \2575 \a test.scss 1:9 root stylesheet";
}
Error: Incompatible units em and px.
╷
1 │ $width: 15px + 2em;
│ ^^^^^^^^^^
╵
test.scss 1:9 root stylesheet
```
#### `--update`
Compatibility:
Dart Sass since 1.4.0
If the `--update` flag is passed, Sass will only compile stylesheets whose dependencies have been modified more recently than the corresponding CSS file was generated. It will also print status messages when updating stylesheets.
```
$ sass --update themes:public/css
Compiled themes/light.scss to public/css/light.css.
```
### Source Maps
Compatibility:
Dart Sass since 1.3.0
Source maps are files that tell browsers or other tools that consume CSS how that CSS corresponds to the Sass files from which it was generated. They make it possible to see and even edit your Sass files in browsers. See instructions for using source maps in [Chrome](https://developers.google.com/web/tools/chrome-devtools/javascript/source-maps) and [Firefox](https://developer.mozilla.org/en-US/docs/Tools/Style_Editor#Source_map_support).
Dart Sass generates source maps by default for every CSS file it emits.
#### `--no-source-map`
If the `--no-source-map` flag is passed, Sass won’t generate any source maps. it cannot be passed along with other source map options.
```
$ sass --no-source-map style.scss style.css
```
#### `--source-map-urls`
This option controls how the source maps that Sass generates link back to the Sass files that contributed to the generated CSS. Dart Sass supports two types of URLs:
* `relative` (the default) uses relative URLs from the location of the source map file to the locations of the Sass source file.
* `absolute` uses the absolute [`file:` URLs](https://en.wikipedia.org/wiki/File_URI_scheme) of the Sass source files. Note that absolute URLs will only work on the same computer that the CSS was compiled.
```
# Generates a URL like "../sass/style.scss".
$ sass --source-map-urls=relative sass/style.scss css/style.css
# Generates a URL like "file:///home/style-wiz/sassy-app/sass/style.scss".
$ sass --source-map-urls=absolute sass/style.scss css/style.css
```
#### `--embed-sources`
This flag tells Sass to embed the entire contents of the Sass files that contributed to the generated CSS in the source map. This may produce very large source maps, but it guarantees that the source will be available on any computer no matter how the CSS is served.
```
$ sass --embed-sources sass/style.scss css.style.css
```
#### `--embed-source-map`
This flag tells Sass to embed the contents of the source map file in the generated CSS, rather than creating a separate file and linking to it from the CSS.
```
$ sass --embed-source-map sass/style.scss css.style.css
```
### Other Options
#### `--watch`
Compatibility:
Dart Sass since 1.6.0
This flag (abbreviated `-w`) acts like the [`--update` flag](#update), but after the first round compilation is done Sass stays open and continues compiling stylesheets whenever they or their dependencies change.
Sass watches only the directories that you pass as-is on the command line, parent directories of filenames you pass on the command line, and load paths. It does not watch additional directories based on a file’s `@import`/`@use`/ `@forward` rules.
```
$ sass --watch themes:public/css
Compiled themes/light.scss to public/css/light.css.
# Then when you edit themes/dark.scss...
Compiled themes/dark.scss to public/css/dark.css.
```
#### `--poll`
Compatibility:
Dart Sass since 1.8.0
This flag, which may only be passed along with `--watch`, tells Sass to manually check for changes to the source files every so often instead of relying on the operating system to notify it when something changes. This may be necessary if you’re editing Sass on a remote drive where the operating system’s notification system doesn’t work.
```
$ sass --watch --poll themes:public/css
Compiled themes/light.scss to public/css/light.css.
# Then when you edit themes/dark.scss...
Compiled themes/dark.scss to public/css/dark.css.
```
#### `--stop-on-error`
Compatibility:
Dart Sass since 1.8.0
This flag tells Sass to stop compiling immediately when an error is detected, rather than trying to compile other Sass files that may not contain errors. It’s mostly useful in [many-to-many mode](#many-to-many-mode).
```
$ sass --stop-on-error themes:public/css
Error: Expected expression.
╷
42 │ h1 {font-face: }
│ ^
╵
themes/light.scss 42:16 root stylesheet
```
#### `--interactive`
Compatibility:
Dart Sass since 1.5.0
This flag (abbreviated `-i`) tells Sass to run in interactive mode, where you can write [SassScript expressions](../syntax/structure#expressions) and see their results. Interactive mode also supports [variables](../variables) and [`@use` rules](../at-rules/use).
```
$ sass --interactive
>> 1px + 1in
97px
>> @use "sass:map"
>> $map: ("width": 100px, "height": 70px)
("width": 100px, "height": 70px)
>> map.get($map, "width")
100px
```
#### `--color`
This flag (abbreviated `-c`) tells Sass to emit [terminal colors](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors), and the inverse `--no-color` tells it not to emit colors. By default, it will emit colors if it looks like it’s being run on a terminal that supports them.
```
$ sass --color style.scss style.css
Error: Incompatible units em and px.
╷
1 │ $width: 15px + 2em
│ ^^^^^^^^^^
╵
style.scss 1:9 root stylesheet
$ sass --no-color style.scss style.css
Error: Incompatible units em and px.
╷
1 │ $width: 15px + 2em
│ ^^^^^^^^^^
╵
style.scss 1:9 root stylesheet
```
#### `--no-unicode`
Compatibility:
Dart Sass since 1.17.0
This flag tells Sass only to emit ASCII characters to the terminal as part of error messages. By default, or if `--unicode` is passed, Sass will emit non-ASCII characters for these messages. This flag does not affect the CSS output.
```
$ sass --no-unicode style.scss style.css
Error: Incompatible units em and px.
,
1 | $width: 15px + 2em;
| ^^^^^^^^^^
'
test.scss 1:9 root stylesheet
$ sass --unicode style.scss style.css
Error: Incompatible units em and px.
╷
1 │ $width: 15px + 2em;
│ ^^^^^^^^^^
╵
test.scss 1:9 root stylesheet
```
#### `--quiet`
This flag (abbreviated `-q`) tells Sass not to emit any warnings when compiling. By default, Sass emits warnings when deprecated features are used or when the [`@warn` rule](../at-rules/warn) is encountered. It also silences the [`@debug` rule](../at-rules/debug).
```
$ sass --quiet style.scss style.css
```
#### `--quiet-deps`
This flag tells Sass not to emit deprecation warnings that come from dependencies. It considers any file that’s transitively imported through a [load path](../at-rules/use#load-paths) to be a “dependency”. This flag doesn’t affect the [`@warn` rule](../at-rules/warn) or the [`@debug` rule](../at-rules/debug).
```
$ sass --load-path=node_modules --quiet-deps style.scss style.css
```
#### `--trace`
This flag tells Sass to print the full Dart or JavaScript stack trace when an error is encountered. It’s used by the Sass team for debugging errors.
```
$ sass --trace style.scss style.css
Error: Expected expression.
╷
42 │ h1 {font-face: }
│ ^
╵
themes/light.scss 42:16 root stylesheet
package:sass/src/visitor/evaluate.dart 1846:7 _EvaluateVisitor._addExceptionSpan
package:sass/src/visitor/evaluate.dart 1128:12 _EvaluateVisitor.visitBinaryOperationExpression
package:sass/src/ast/sass/expression/binary_operation.dart 39:15 BinaryOperationExpression.accept
package:sass/src/visitor/evaluate.dart 1097:25 _EvaluateVisitor.visitVariableDeclaration
package:sass/src/ast/sass/statement/variable_declaration.dart 50:15 VariableDeclaration.accept
package:sass/src/visitor/evaluate.dart 335:13 _EvaluateVisitor.visitStylesheet
package:sass/src/visitor/evaluate.dart 323:5 _EvaluateVisitor.run
package:sass/src/visitor/evaluate.dart 81:10 evaluate
package:sass/src/executable/compile_stylesheet.dart 59:9 compileStylesheet
package:sass/src/executable.dart 62:15 main
```
#### `--help`
This flag (abbreviated `-h`) prints a summary of this documentation.
```
$ sass --help
Compile Sass to CSS.
Usage: sass <input.scss> [output.css]
sass <input.scss>:<output.css> <input/>:<output/>
...
```
#### `--version`
This flag prints the current version of Sass.
```
$ sass --version
1.56.1
```
sass Migrator Migrator
=========
The Sass migrator automatically updates your Sass files to help you move on to the latest and greatest version of the language. Each of its commands migrates a single feature, to give you as much control as possible over what you update and when.
Usage
------
To use the Sass migrator, tell it [which migration](#migrations) you want to run and what Sass files you want to migrate:
```
sass-migrator <migration> <entrypoint.scss...>
```
By default, the migrator will only change files that you explicitly pass on the command line. Passing the [`--migrate-deps` option](#migrate-deps) tells the migrator to also change all the stylesheets that are loaded using the [`@use` rule](../at-rules/use), [`@forward` rule](../at-rules/forward), or [`@import` rule](../at-rules/import). And if you want to do a test run to see what changes will be made without actually saving them, you can pass `[--dry-run](#dry-run) [--verbose](#verbose)` (or `-nv` for short).
```
$ cat style.scss
$body-bg: #000;
$body-color: #111;
@import "bootstrap";
@include media-breakpoint-up(sm) {
.navbar {
display: block;
}
}
$ sass-migrator --migrate-deps module style.scss
$ cat style.scss
@use "bootstrap" with (
$body-bg: #000,
$body-color: #111
);
@include bootstrap.media-breakpoint-up(sm) {
.navbar {
display: block;
}
}
```
Installation
-------------
You can install the Sass migrator from most of the same places that you can install [Dart Sass](https://sass-lang.com/dart-sass):
### Standalone
You can install the Sass migrator on Windows, Mac, or Linux by downloading the package for your operating system [from GitHub](https://github.com/sass/migrator/releases) and [adding it to your `PATH`](https://katiek2.github.io/path-doc/).
### npm
If you use Node.js, you can also install the Sass migrator using [npm](https://www.npmjs.com) by running
```
npm install -g sass-migrator
```
### Chocolatey
If you use [the Chocolatey package manager](https://chocolatey.org) for Windows, you can install the Sass migrator by running
```
choco install sass-migrator
```
### Homebrew
If you use [the Homebrew package manager](https://brew.sh) for Mac OS X, you can install Dart Sass by running
```
brew install sass/sass/migrator
```
Global Options
---------------
These options are available for all migrators.
### `--migrate-deps`
This option (abbreviated `-d`) tells the migrator to change not just the stylesheets that are explicitly passed on the command line, but also any stylesheets that they depend on using the [`@use` rule](../at-rules/use), [`@forward` rule](../at-rules/forward), or [`@import` rule](../at-rules/import).
```
$ sass-migrator module --verbose style.scss
Migrating style.scss
$ sass-migrator module --verbose --migrate-deps style.scss
Migrating style.scss
Migrating _theme.scss
Migrating _fonts.scss
Migrating _grid.scss
```
### ⚠️ Heads up!
The [module migrator](#module) assumes that any stylesheet that is depended on using a [`@use` rule](../at-rules/use) or a [`@forward` rule](../at-rules/forward) has already been migrated to the module system, so it won’t attempt to migrate them, even when the `--migrate-deps` option is passed.
### `--load-path`
This option (abbreviated `-I`) tells the migrator a [load path](../at-rules/use#load-paths) where it should look for stylesheets. It can be passed multiple times to provide multiple load paths. Earlier load paths will take precedence over later ones.
Dependencies loaded from load paths are assumed to be third-party libraries, so the migrator will not migrate them even when the [`--migrate-deps` option](#migrate-deps) is passed.
### `--dry-run`
This flag (abbreviated `-n`) tells the migrator not to save any changes to disk. It instead prints the list of files that it would have changed. This is commonly paired with the [`--verbose` option](#verbose) to print the contents of the changes that would have been made as well.
```
$ sass-migrator module --dry-run --migrate-deps style.scss
Dry run. Logging migrated files instead of overwriting...
style.scss
_theme.scss
_fonts.scss
_grid.scss
```
#### `--no-unicode`
This flag tells the Sass migrator only to emit ASCII characters to the terminal as part of error messages. By default, or if `--unicode` is passed, the migrator will emit non-ASCII characters for these messages. This flag does not affect the CSS output.
```
$ sass-migrator --no-unicode module style.scss
line 1, column 9 of style.scss: Error: Could not find Sass file at 'typography'.
,
1 | @import "typography";
| ^^^^^^^^^^^^
'
Migration failed!
$ sass-migrator --unicode module style.scss
line 1, column 9 of style.scss: Error: Could not find Sass file at 'typography'.
╷
1 │ @import "typography";
│ ^^^^^^^^^^^^
╵
Migration failed!
```
### `--verbose`
This flag (abbreviated `-v`) tells the migrator to print extra information to the console. By default, it just prints the name of files that are changed, but when combined with the [`--dry-run` option](#dry-run) it also prints those files’ new contents.
```
$ sass-migrator module --verbose --dry-run style.scss
Dry run. Logging migrated files instead of overwriting...
<==> style.scss
@use "bootstrap" with (
$body-bg: #000,
$body-color: #111
);
@include bootstrap.media-breakpoint-up(sm) {
.navbar {
display: block;
}
}
$ sass-migrator module --verbose style.scss
Migrating style.scss
```
Migrations
-----------
### Division
This migration converts stylesheets that use [`/` as division](https://sass-lang.com/documentation/breaking-changes/slash-div) to use the built-in `math.div` function instead.
#### `--pessimistic`
By default, the migrator converts `/` operations to `math.div` even when it isn’t sure that it will be division when evaluated. It only leaves them as-is when it can statically determine that they’re doing something else (such as when there’s no SassScript involved, or when one of the operands is a string). The `math.div` function currently functions identically to the `/` operator, so this is safe to do, but may result in new warnings if one of the arguments to `math.div` at runtime is not a number.
If you want to avoid this behavior, you can pass the `--pessimistic` flag. With this flag, the migrator will only convert `/` operations that it knows for sure are doing division. This will prevent any unnecessary `math.div` conversions, but it’s likely to leave some division unmigrated if it can’t be statically determined.
### Module
This migration converts stylesheets that use the old [`@import` rule](../at-rules/import) to load dependencies so that they use the Sass module system via the [`@use` rule](../at-rules/use) instead. It doesn’t just naïvely change `@import`s to `@use`s—it updates stylesheets intelligently so that they keep working the same way they did before, including:
* Adding namespaces to uses of members (variables, mixins, and functions) from other modules.
* Adding new `@use` rules to stylesheets that were using members without importing them.
* Converting overridden default variables to [`with` clauses](../at-rules/use#configuration).
* Automatically removing `-` and `_` prefixes from members that are used from other files (because otherwise they’d be considered [private](../at-rules/use#private-members) and could only be used in the module they’re declared).
* Converting [nested imports](../at-rules/import#nesting) to use the [`meta.load-css()` mixin](../modules/meta#load-css) instead.
### ⚠️ Heads up!
Because the module migrator may need to modify both member definitions *and* member names, it’s important to either run it with the [`--migrate-deps` option](#migrate-deps) or ensure that you pass it all the stylesheets in your package or application.
```
$ cat style.scss
$body-bg: #000;
$body-color: #111;
@import "bootstrap";
@include media-breakpoint-up(sm) {
.navbar {
display: block;
}
}
$ sass-migrator --migrate-deps module style.scss
$ cat style.scss
@use "bootstrap" with (
$body-bg: #000,
$body-color: #111
);
@include bootstrap.media-breakpoint-up(sm) {
.navbar {
display: block;
}
}
```
#### Loading Dependencies
The module migrator needs to be able to read all of the stylesheets depended on by the ones it’s migrating, even if the [`--migrate-deps` option](#migrate-deps) is not passed. If the migrator fails to find a dependency, you’ll get an error.
```
$ ls .
style.scss node_modules
$ sass-migrator module style.scss
Error: Could not find Sass file at 'dependency'.
,
1 | @import "dependency";
| ^^^^^^^^^^^^
'
style.scss 1:9 root stylesheet
Migration failed!
$ sass-migrator --load-path node_modules module style.scss
```
If you use a [load path](../at-rules/use#load-paths) when compiling your stylesheets, make sure to pass that to the migrator using the [`--load-path` option](#load-path).
Unfortunately, the migrator does not support custom importers, but it does have built-in support for resolving URLs starting with `~` by searching in `node_modules`, similar to [what Webpack supports](https://github.com/webpack-contrib/sass-loader#resolving-import-at-rules).
#### `--remove-prefix`
This option (abbreviated `-p`) takes an identifier prefix to remove from the beginning of all variable, mixin, and function names when they’re migrated. Members that don’t start with this prefix will remain unchanged.
The [`@import` rule](../at-rules/import) put all top-level members in one global scope, so when it was the standard way of loading stylesheets, everyone was incentivized to add prefixes to all their member names to avoid accidentally redefining some other stylesheet’s. The module system solves this problem, so it’s useful to automatically strip those old prefixes now that they’re unnecessary.
```
$ cat style.scss
@import "theme";
@mixin app-inverted {
color: $app-bg-color;
background-color: $app-color;
}
$ sass-migrator --migrate-deps module --remove-prefix=app- style.scss
$ cat style.scss
@import "theme";
@mixin inverted {
color: theme.$bg-color;
background-color: theme.$color;
}
```
When you pass this option, the migrator will also generate an [import-only stylesheet](../at-rules/import#import-only-files) that [forwards](../at-rules/forward) all the members with the prefix added back, to preserve backwards-compatibility for users who were importing the library.
This option may be passed multiple times, or with multiple values separated by commas. Each prefix will be removed from any members that have it. If a member matches multiple prefixes, the longest matching prefix will be removed.
#### `--forward`
This option tells the migrator which members to forward using the [`@forward` rule](../at-rules/forward). It supports the following settings:
* `none` (the default) doesn’t forward any members.
* `all` forwards all members except those that started with `-` or `_` in the original stylesheet, since that was commonly used to mark a package-private member before the module system was introduced.
* `prefixed` forwards only members that begin with the prefix passed to the [`--remove-prefix` option](#remove-prefix). This option may only be used in conjunction with the `--remove-prefix` option.
All files that are passed explicitly on the command line will forward members that are transitively loaded by those files using the `@import` rule. Files loaded using the [`--migrate-deps` option](#migrate-deps) will not forward any new members. This option is particularly useful when migrating a Sass library, because it ensures that users of that library will still be able to access all the members it defines.
```
$ cat _index.scss
@import "theme";
@import "typography";
@import "components";
$ sass-migrator --migrate-deps module --forward=all style.scss
$ cat _index.scss
@forward "theme";
@forward "typography";
@forward "components";
```
### Namespace
This migration allows you to easily change the [namespaces](../at-rules/use#choosing-a-namespace) of the `@use` rules in a stylesheet. This is useful if the namespaces that the module migrator generates to resolve conflicts are non-ideal, or if you don’t want to use the default namespace that Sass determines based on the rule’s URL.
#### `--rename`
You can tell the migrator which namespace(s) you want it to change by passing expressions to the `--rename` option.
These expressions are of the form `<old-namespace> to <new-namespace>` or `url <rule-url> to <new-namespace>`. In these expressions, `<old-namespace>` and `<rule-url>` are [regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) which match against the entirety of the existing namespace or the `@use` rule’s URL, respectively.
For simple use cases, this just looks like `--rename 'old to new'`, which would rename a `@use` rule with the namespace `old` to instead be `new`.
However, you can also do this to accomplish more complicated renames. For instance, say that you previously had a stylesheet that looked like this:
```
@import "components/button/lib/mixins";
@import "components/input/lib/mixins";
@import "components/table/lib/mixins";
// ...
```
Since all of these URLs would have the default namespace `mixins` when migrated to `@use` rules, the module migrator may end up generating something like this:
```
@use "components/button/lib/mixins" as button-lib-mixins;
@use "components/input/lib/mixins" as input-lib-mixins;
@use "components/table/lib/mixins" as table-lib-mixins;
// ...
```
This is valid code since the namespaces don’t conflict, but they’re way more complicated than they need to be. The relevant part of the URL is the component name, so we can use the namespace migrator to extract that part out.
If we run the namespace migrator with `--rename 'url components/(\w+)/lib/mixins to \1'`, we’ll end up with:
```
@use "components/button/lib/mixins" as button;
@use "components/input/lib/mixins" as input;
@use "components/table/lib/mixins" as table;
// ...
```
The rename script here says to find all of the `@use` rules whose URLs look like `components/(\w+)/lib/mixins` (`\w+` in a regular expression means to match any word of one or more characters). The `\1` in the output clause means to substitute in the contents of the first set of parentheses in the regular expression (called a [group](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges)).
If you wish to apply multiple renames, you can pass the `--rename` option multiple times, or separate them with a semicolon or a line break. Only the first rename that applies to a given rule will be used, so you could pass something like `--rename 'a to b; b to a'` to swap the namespaces `a` and `b`.
#### `--force`
By default, if two or more `@use` rules have the same namespace after the migration, the migrator will fail, and no changes will be made.
In this case, you’ll usually want to adjust your `--rename` script to avoid creating conflicts, but if you’d prefer to force the migration, you can instead pass `--force`.
With `--force`, if any conflicts are encountered, the first `@use` rule will get its preferred namespace, while subsequent `@use` rules with the same preferred namespace will instead have a numerical suffix added to them.
| programming_docs |
sass Ruby Sass Command-Line Interface Ruby Sass Command-Line Interface
=================================
### ⚠️ Heads up!
[Ruby Sass has reached end of life](https://sass-lang.com/blog/ruby-sass-is-unsupported) and is now totally unmaintained. Please switch to [Dart Sass](https://sass-lang.com/dart-sass) or [LibSass](https://sass-lang.com/libsass) at your earliest convenience.
Usage
------
The Ruby Sass executable can be invoked in one of two modes.
### One-to-One Mode
```
sass [input.scss] [output.css]
```
One-to-one mode compiles a single input file (`input.scss`) to a single output location (`output.css`). If no output location is passed, the compiled CSS is printed to the terminal. If no input *or* output is passed, the CSS is read from [standard input](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)) and printed to the terminal.
The input file is parsed as [SCSS](../syntax#scss) if its extension is `.scss` or as the [indented syntax](../syntax#the-indented-syntax) if its extension is `.sass`. If it doesn’t have one of these two extensions, or if it comes from standard input, it’s parsed as the indented syntax by default. This can be controlled with the [`--scss` flag](#scss).
### Many-to-Many Mode
```
sass [<input.css>:<output.css>] [<input/>:<output/>] [input.css] [input/]...
```
Many-to-many mode compiles one or more input files to one or more output files. The inputs are separated from the outputs with colons. It can also compile all Sass files in a directory to CSS files with the same names in another directory. Many-to-many mode is enabled when any argument contains a colon, *or* when the [`--update` flag](#update) or the [`--watch` flag](#watch) is passed.
If an input file is passed without a corresponding output file, it’s compiled to a CSS file named after the input file, but with the extension replaced with `.css`. If an input directory is passed without a corresponding output directory, all the Sass files within it are compiled to CSS files in the same directory.
```
$ sass style.scss:style.css
write style.css
write style.css.map
$ sass light.scss:light.css dark.scss:dark.css
write light.css
write light.css.map
write dark.css
write dark.css.map
$ sass themes:public/css
write public/css/light.css
write public/css/light.css.map
write public/css/dark.css
write public/css/dark.css.map
```
When compiling whole directories, Sass will ignore [partial files](../at-rules/use#partials) whose names begin with `_`. You can use partials to separate out your stylesheets without creating a bunch of unnecessary output files.
Many-to-many mode will only compile stylesheets whose dependencies have been modified more recently than the corresponding CSS file was generated. It will also print status messages when updating stylesheets.
Options
--------
### Common
#### `--load-path`
This option (abbreviated `-I`) adds an additional [load path](../at-rules/use#load-paths) for Sass to look for stylesheets. It can be passed multiple times to provide multiple load paths. Earlier load paths will take precedence over later ones.
```
$ sass --load-path=node_modules/bootstrap/dist/css style.scss style.css
```
Load paths are also loaded from the `SASS_PATH` [environment variable](https://en.wikipedia.org/wiki/Environment_variable), if it’s set. This variable should be a list of paths separated by `;` (on Windows) or `:` (on other operating systems). Load paths on `SASS_PATH` take precedence over load paths passed on the command line.
```
$ SASS_PATH=node_modules/bootstrap/dist/css sass style.scss style.css
```
#### `--require`
This option (abbreviated `-r`) loads a [Ruby gem](https://rubygems.org/) before running Sass. It can be used to load functions defined in Ruby into your Sass environment.
```
$ sass --require=rails-sass-images style.scss style.css
```
#### `--compass`
This flag loads the [Compass framework](http://compass-style.org/) and makes its mixins and functions available for use in Sass.
```
$ sass --compass style.scss style.css
```
#### `--style`
This option (abbreviated `-t`) controls the output style of the resulting CSS. Ruby Sass supports four output styles:
* `nested` (the default) indents CSS rules to match the nesting of the Sass source.
* `expanded` writes each selector and declaration on its own line.
* `compact` puts each CSS rule on its own single line.
* `compressed` removes as many extra characters as possible, and writes the entire stylesheet on a single line.
```
$ sass --style=nested
h1 {
font-size: 40px; }
h1 code {
font-face: Roboto Mono; }
$ sass --style=expanded style.scss
h1 {
font-size: 40px;
}
h1 code {
font-face: Roboto Mono;
}
$ sass --style=compact style.scss
h1 { font-size: 40px; }
h1 code { font-face: Roboto Mono; }
$ sass --style=compressed style.scss
h1{font-size:40px}h1 code{font-face:Roboto Mono}
```
#### `--help`
This flag (abbreviated `-h` and `-?`) prints a summary of this documentation.
```
$ sass --help
Usage: sass [options] [INPUT] [OUTPUT]
Description:
Converts SCSS or Sass files to CSS.
...
```
#### `--version`
This flag prints the current version of Sass.
```
$ sass --version
```
### Watching and Updating
These options affect [many-to-many mode](#many-to-many-mode).
#### `--watch`
Enables [many-to-many mode](#many-to-many-mode), and causes Sass to stay open and continue compiling stylesheets whenever they or their dependencies change.
```
$ sass --watch themes:public/css
write public/css/light.css
write public/css/light.css.map
# Then when you edit themes/dark.scss...
write public/css/dark.css
write public/css/dark.css.map
```
#### `--poll`
This flag, which may only be passed along with `--watch`, tells Sass to manually check for changes to the source files every so often instead of relying on the operating system to notify it when something changes. This may be necessary if you’re editing Sass on a remote drive where the operating system’s notification system doesn’t work.
```
$ sass --watch --poll themes:public/css
write public/css/light.css
write public/css/light.css.map
# Then when you edit themes/dark.scss...
write public/css/dark.css
write public/css/dark.css.map
```
#### `--update`
This flag enables [many-to-many mode](#many-to-many-mode), even if none of the arguments are colon-separated pairs.
```
$ sass --update style.scss
write style.css
write style.css.map
```
#### `--force`
This flag (abbreviated `-f`) may only be passed in [many-to-many mode](#many-to-many-mode). It causes Sass files to *always* be compiled to CSS files, instead of only being compiled when the source files are more up-to-date than the output.
The `--force` flag may not be passed alongside the [`--watch` flag](#watch).
```
$ sass --force style.scss:style.css
write style.css
write style.css.map
```
#### `--stop-on-error`
This flag may only be passed in [many-to-many mode](#many-to-many-mode). It tells Sass to stop compiling immediately when an error is detected, rather than trying to compile other Sass files that may not contain errors.
```
$ sass --stop-on-error themes:public/css
Error: Invalid CSS after "h1 {font-size: ": expected expression (e.g. 1px, bold), was "}"
on line 1 of test.scss
Use --trace for backtrace.
```
### Input and Output
These options control how Sass loads its input files and how it produces output files.
#### `--scss`
This flag tells Sass to parse [standard input](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)) as [SCSS](../syntax#scss).
```
$ echo "h1 {font-size: 40px}" | sass --scss
h1 {
font-size: 40px;
}
```
#### `--sourcemap`
This option controls how Sass generates source maps, which are files that tell browsers or other tools that consume CSS how that CSS corresponds to the Sass files from which it was generated. They make it possible to see and even edit your Sass files in browsers. See instructions for using source maps in [Chrome](https://developers.google.com/web/tools/chrome-devtools/javascript/source-maps) and [Firefox](https://developer.mozilla.org/en-US/docs/Tools/Style_Editor#Source_map_support). It has four possible values:
* `auto` (the default) uses relative URLs to link from the source map to the Sass stylesheets where possible, and absolute [`file:` URLs](https://en.wikipedia.org/wiki/File_URI_scheme) otherwise.
* `file` always uses absolute absolute `file:` URLs to link from the source map to the Sass stylesheets.
* `inline` includes the text of the Sass stylehseets in the source map directly.
* `none` doesn’t generate source maps at all.
```
# Generates a URL like "../sass/style.scss".
$ sass --sourcemap=auto sass/style.scss css/style.css
# Generates a URL like "file:///home/style-wiz/sassy-app/sass/style.scss".
$ sass --sourcemap=file sass/style.scss css/style.css
# Includes the full text of sass/style.scss in the source map.
$ sass --sourcemap=inline sass/style.scss css/style.css
# Doesn't generate a source map.
$ sass --sourcemap=none sass/style.scss css/style.css
```
#### `--stdin`
This flag (abbreviated `-s`) is tells Sass to read its input file from [standard input](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)). When it’s passed, no input file may be passed.
```
$ echo -e 'h1\n font-size: 40px' | sass --stdin
h1 {
font-size: 40px;
}
```
The `--stdin` flag may not be used with [many-to-many mode](#many-to-many-mode).
#### `--default-encoding`
This option (abbreviated `-E`) controls the default [character encoding](https://en.wikipedia.org/wiki/Character_encoding) that Sass will use to load source files that don’t [explicitly specify](../syntax/parsing#input-encoding) a character encoding. It defaults to the operating system’s default encoding.
```
$ sass --default-encoding=Shift-JIS style.scss style.css
```
#### `--unix-newlines`
This flag tells Sass to generate output files with whose lines are separated with the U+000A LINE FEED character, as opposed to the operating system default (on Windows, this is U+000D CARRIAGE RETURN followed by U+000A LINE FEED). It’s always true on systems that default to Unix-style newlines.
```
$ sass --unix-newlines style.scss style.css
```
#### `--debug-info`
This flag (abbreviated `-g`) causes Sass to emit dummy `@media` queries that indicate where each style rule was defined in the source stylehseet.
### ⚠️ Heads up!
This flag only exists for backwards-compatibility. Source maps are now the recommended way of mapping CSS back to the Sass that generated it.
```
$ sass --debug-info style.scss
@media -sass-debug-info{filename{font-family:file\:\/\/\/home\/style-wiz\/sassy-app\/style\.scss}line{font-family:\000031}}
h1 {
font-size: 40px; }
```
#### `--line-comments`
This flag (also available as `--line-numbers`, abbreviated as `-l`) causes Sass to emit comments for every style rule that indicate where each style rule was defined in the source stylesheet.
```
$ sass --line-numbers style.scss
/* line 1, style.scss */
h1 {
font-size: 40px; }
```
### Other Options
#### `--interactive`
This flag (abbreviated `-i`) tells Sass to run in interactive mode, where you can write [SassScript expressions](../syntax/structure#expressions) and see their results. Interactive mode also supports [variables](../variables).
```
$ sass --interactive
>> 1px + 1in
97px
>> $map: ("width": 100px, "height": 70px)
("width": 100px, "height": 70px)
>> map-get($map, "width")
100px
```
#### `--check`
This flag (abbreviated `-c`) tells Sass to verify that the syntax of its input file is valid without executing that file. If the syntax is valid, it exits with [status](https://en.wikipedia.org/wiki/Exit_status) 0. It can’t be used in [many-to-many mode](#many-to-many-mode).
```
$ sass --check style.scss
```
#### `--precision`
This option tells Sass how many digits of [precision](../values/numbers#precision) to use when emitting decimal numbers.
```
$ echo -e 'h1\n font-size: (100px / 3)' | sass --precision=20
h1 {
font-size: 33.333333333333336px; }
```
#### `--cache-location`
This option tells Sass where to store its cache of parsed files, so it can run faster in future invocations. It defaults to `.sass-cache`.
```
$ sass --cache-location=/tmp/sass-cache style.scss style.css
```
#### `--no-cache`
This flag (abbreviated `-C`) tells Sass not to cache parsed files at all.
```
$ sass --no-cache style.scss style.css
```
#### `--trace`
This flag tells Sass to print the full Ruby stack trace when an error is encountered. It’s used by the Sass team for debugging errors.
```
Traceback (most recent call last):
25: from /usr/share/gems/sass/bin/sass:13:in `<main>'
24: from /usr/share/gems/sass/lib/sass/exec/base.rb:18:in `parse!'
23: from /usr/share/gems/sass/lib/sass/exec/base.rb:50:in `parse'
22: from /usr/share/gems/sass/lib/sass/exec/sass_scss.rb:63:in `process_result'
21: from /usr/share/gems/sass/lib/sass/exec/sass_scss.rb:396:in `run'
20: from /usr/share/gems/sass/lib/sass/engine.rb:290:in `render'
19: from /usr/share/gems/sass/lib/sass/engine.rb:414:in `_to_tree'
18: from /usr/share/gems/sass/lib/sass/scss/parser.rb:41:in `parse'
17: from /usr/share/gems/sass/lib/sass/scss/parser.rb:137:in `stylesheet'
16: from /usr/share/gems/sass/lib/sass/scss/parser.rb:697:in `block_contents'
15: from /usr/share/gems/sass/lib/sass/scss/parser.rb:707:in `block_child'
14: from /usr/share/gems/sass/lib/sass/scss/parser.rb:681:in `ruleset'
13: from /usr/share/gems/sass/lib/sass/scss/parser.rb:689:in `block'
12: from /usr/share/gems/sass/lib/sass/scss/parser.rb:697:in `block_contents'
11: from /usr/share/gems/sass/lib/sass/scss/parser.rb:708:in `block_child'
10: from /usr/share/gems/sass/lib/sass/scss/parser.rb:743:in `declaration_or_ruleset'
9: from /usr/share/gems/sass/lib/sass/scss/parser.rb:820:in `try_declaration'
8: from /usr/share/gems/sass/lib/sass/scss/parser.rb:1281:in `rethrow'
7: from /usr/share/gems/sass/lib/sass/scss/parser.rb:807:in `block in try_declaration'
6: from /usr/share/gems/sass/lib/sass/scss/parser.rb:999:in `value!'
5: from /usr/share/gems/sass/lib/sass/scss/parser.rb:1161:in `sass_script'
4: from /usr/share/gems/sass/lib/sass/script/parser.rb:68:in `parse'
3: from /usr/share/gems/sass/lib/sass/script/parser.rb:855:in `assert_expr'
2: from /usr/share/gems/sass/lib/sass/script/lexer.rb:240:in `expected!'
1: from /usr/share/gems/sass/lib/sass/scss/parser.rb:1305:in `expected'
test.scss:1: Invalid CSS after "h1 {font-size: ": expected expression (e.g. 1px, bold), was "}" (Sass::SyntaxError)
```
#### `--quiet`
This flag (abbreviated `-q`) tells Sass not to emit any warnings when compiling. By default, Sass emits warnings when deprecated features are used or when the [`@warn` rule](../at-rules/warn) is encountered. It also silences the [`@debug` rule](../at-rules/debug).
```
$ sass --quiet style.scss style.css
```
sass Parsing a Stylesheet Parsing a Stylesheet
=====================
A Sass stylesheet is parsed from a sequence of Unicode code points. It's parsed directly, without first being converted to a token stream.
Input Encoding
---------------
Compatibility:
Dart Sass ✗
LibSass ✓
Ruby Sass ✓ [▶](javascript:;) Dart Sass currently *only* supports the UTF-8 encoding. As such, it’s safest to encode all Sass stylesheets as UTF-8.
It’s often the case that a document is initially available only as a sequence of bytes, which must be decoded into Unicode. Sass performs this decoding as follows:
* If the sequence of bytes begins with the UTF-8 or UTF-16 encoding of U+FEFF BYTE ORDER MARK, the corresponding encoding is used.
* If the sequence of bytes begins with the plain ASCII string `@charset`, Sass determines the encoding using step 2 of the CSS algorithm for [determining the fallback encoding](https://drafts.csswg.org/css-syntax-3/#input-byte-stream).
* Otherwise, UTF-8 is used.
Parse Errors
-------------
When Sass encounters invalid syntax in a stylesheet, parsing will fail and an error will be presented to the user with information about the location of the invalid syntax and the reason it was invalid.
Note that this is different than CSS, which specifies how to recover from most errors rather than failing immediately. This is one of the few cases where SCSS isn’t *strictly* a superset of CSS. However, it’s much more useful to Sass users to see errors immediately, rather than having them passed through to the CSS output.
The location of parse errors can be accessed through implementation-specific APIs. For example, in Dart Sass you can access [`SassException.span`](https://pub.dartlang.org/documentation/sass/latest/sass/SassException/span.html), and in Node Sass’s and Dart Sass’s JS API you can access the [`file`, `line`, and `column`](https://github.com/sass/node-sass#error-object) properties.
sass Structure of a Stylesheet Structure of a Stylesheet
==========================
Just like CSS, most Sass stylesheets are mainly made up of style rules that contain property declarations. But Sass stylesheets have many more features that can exist alongside these.
Statements
-----------
A Sass stylesheet is made up of a series of *statements*, which are evaluated in order to build the resulting CSS. Some statements may have *blocks*, defined using `{` and `}`, which contain other statements. For example, a style rule is a statement with a block. That block contains other statements, such as property declarations.
In SCSS, statements are separated by semicolons (which are optional if the statement uses a block). In the indented syntax, they’re just separated by newlines.
### Universal Statements
These types of statements can be used anywhere in a Sass stylesheet:
* [Variable declarations](../variables), like `$var: value`.
* [Flow control at-rules](../at-rules/control), like `@if` and `@each`.
* The [`@error`](../at-rules/error), [`@warn`](../at-rules/warn), and [`@debug`](../at-rules/debug) rules.
### CSS Statements
These statements produce CSS. They can be used anywhere except within a `@function`:
* [Style rules](../style-rules), like `h1 { /* ... */ }`.
* [CSS at-rules](../at-rules/css), like `@media` and `@font-face`.
* [Mixin uses](../at-rules/mixin) using `@include`.
* The [`@at-root` rule](../at-rules/at-root).
### Top-Level Statements
These statements can only be used at the top level of a stylesheet, or nested within a CSS statement at the top level:
* [Module loads](../at-rules/use), using `@use`.
* [Imports](../at-rules/import), using `@import`.
* [Mixin definitions](../at-rules/mixin) using `@mixin`.
* [Function definitions](../at-rules/function) using `@function`.
### Other Statements
* [Property declarations](../style-rules/declarations) like `width: 100px` may only be used within style rules and some CSS at-rules.
* The [`@extend` rule](../at-rules/extend) may only be used within style rules.
Expressions
------------
An *expression* is anything that goes on the right-hand side of a property or variable declaration. Each expression produces a *[value](../values)*. Any valid CSS property value is also a Sass expression, but Sass expressions are much more powerful than plain CSS values. They’re passed as arguments to [mixins](../at-rules/mixin) and [functions](../at-rules/function), used for control flow with the [`@if` rule](../at-rules/control/if), and manipulated using [arithmetic](../operators/numeric). We call Sass’s expression syntax *SassScript*.
### Literals
The simplest expressions just represent static values:
* [Numbers](../values/numbers), which may or may not have units, like `12` or `100px`.
* [Strings](../values/strings), which may or may not have quotes, like `"Helvetica Neue"` or `bold`.
* [Colors](../values/colors), which can be referred to by their hex representation or by name, like `#c6538c` or `blue`.
* The [boolean](../values/booleans) literals `true` or `false`.
* The singleton [`null`](../values/null).
* [Lists of values](../values/lists), which may be separated by spaces or commas and which may be enclosed in square brackets or no brackets at all, like `1.5em 1em 0 2em`, `Helvetica, Arial, sans-serif`, or `[col1-start]`.
* [Maps](../values/maps) that associate values with keys, like `("background": red, "foreground": pink)`.
### Operations
Sass defines syntax for a number of operations:
* [`==` and `!=`](../operators/equality) are used to check if two values are the same.
* [`+`, `-`, `*`, `/`, and `%`](../operators/numeric) have their usual mathematical meaning for numbers, with special behaviors for units that matches the use of units in scientific math.
* [`<`, `<=`, `>`, and `>=`](../operators/relational) check whether two numbers are greater or less than one another.
* [`and`, `or`, and `not`](../operators/boolean) have the usual boolean behavior. Sass considers every value “true” except for `false` and `null`.
* [`+`, `-`, and `/`](../operators/string) can be used to concatenate strings.
* [`(` and `)`](../operators#parentheses) can be used to explicitly control the precedence order of operations.
### Other Expressions
* [Variables](../variables), like `$var`.
* [Function calls](../at-rules/function), like `nth($list, 1)` or `var(--main-bg-color)`, which may call Sass core library functions or user-defined functions, or which may be compiled directly to CSS.
* [Special functions](special-functions), like `calc(1px + 100%)` or `url(http://myapp.com/assets/logo.png)`, that have their own unique parsing rules.
* [The parent selector](../style-rules/parent-selector), `&`.
* The value `!important`, which is parsed as an unquoted string.
| programming_docs |
sass Special Functions Special Functions
==================
CSS defines many functions, and most of them work just fine with Sass’s normal function syntax. They’re parsed as function calls, resolved to [plain CSS functions](../at-rules/function#plain-css-functions), and compiled as-is to CSS. There are a few exceptions, though, which have special syntax that can’t just be parsed as a [SassScript expression](structure#expressions). All special function calls return [unquoted strings](../values/strings#unquoted).
`url()`
--------
The [`url()` function](https://developer.mozilla.org/en-US/docs/Web/CSS/url) is commonly used in CSS, but its syntax is different than other functions: it can take either a quoted *or* unquoted URL. Because an unquoted URL isn’t a valid SassScript expression, Sass needs special logic to parse it.
If the `url()`‘s argument is a valid unquoted URL, Sass parses it as-is, although [interpolation](../interpolation) may also be used to inject SassScript values. If it’s not a valid unquoted URL—for example, if it contains [variables](../variables) or [function calls](../at-rules/function)—it’s parsed as a normal [plain CSS function call](../at-rules/function#plain-css-functions).
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
$roboto-font-path: "../fonts/roboto";
@font-face {
// This is parsed as a normal function call that takes a quoted string.
src: url("#{$roboto-font-path}/Roboto-Thin.woff2") format("woff2");
font-family: "Roboto";
font-weight: 100;
}
@font-face {
// This is parsed as a normal function call that takes an arithmetic
// expression.
src: url($roboto-font-path + "/Roboto-Light.woff2") format("woff2");
font-family: "Roboto";
font-weight: 300;
}
@font-face {
// This is parsed as an interpolated special function.
src: url(#{$roboto-font-path}/Roboto-Regular.woff2) format("woff2");
font-family: "Roboto";
font-weight: 400;
}
```
```
$roboto-font-path: "../fonts/roboto"
@font-face
// This is parsed as a normal function call that takes a quoted string.
src: url("#{$roboto-font-path}/Roboto-Thin.woff2") format("woff2")
font-family: "Roboto"
font-weight: 100
@font-face
// This is parsed as a normal function call that takes an arithmetic
// expression.
src: url($roboto-font-path + "/Roboto-Light.woff2") format("woff2")
font-family: "Roboto"
font-weight: 300
@font-face
// This is parsed as an interpolated special function.
src: url(#{$roboto-font-path}/Roboto-Regular.woff2) format("woff2")
font-family: "Roboto"
font-weight: 400
```
```
@font-face {
src: url("../fonts/roboto/Roboto-Thin.woff2") format("woff2");
font-family: "Roboto";
font-weight: 100;
}
@font-face {
src: url("../fonts/roboto/Roboto-Light.woff2") format("woff2");
font-family: "Roboto";
font-weight: 300;
}
@font-face {
src: url(../fonts/roboto/Roboto-Regular.woff2) format("woff2");
font-family: "Roboto";
font-weight: 400;
}
```
`element()`, `progid:...()`, and `expression()`
------------------------------------------------
Compatibility (calc()):
Dart Sass since <1.40.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;)
LibSass, Ruby Sass, and versions of Dart Sass prior to 1.40.0 parse `calc()` as special syntactic function like `element()`.
Dart Sass versions 1.40.0 and later parse `calc()` as a [calculation](../values/calculations).
Compatibility (clamp()):
Dart Sass since >=1.31.0 <1.40.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;)
LibSass, Ruby Sass, and versions of Dart Sass prior to 1.31.0 parse `clamp()` as a [plain CSS function](../at-rules/function#plain-css-functions) rather than supporting special syntax within it.
Dart Sass versions between 1.31.0 and 1.40.0 parse `clamp()` as special syntactic function like `element()`.
Dart Sass versions 1.40.0 and later parse `clamp()` as a [calculation](../values/calculations).
The [`element()`](https://developer.mozilla.org/en-US/docs/Web/CSS/element) function is defined in the CSS spec, and because its IDs could be parsed as colors, they need special parsing.
[`expression()`](https://blogs.msdn.microsoft.com/ie/2008/10/16/ending-expressions/) and functions beginning with [`progid:`](https://blogs.msdn.microsoft.com/ie/2009/02/19/the-css-corner-using-filters-in-ie8/) are legacy Internet Explorer features that use non-standard syntax. Although they’re no longer supported by recent browsers, Sass continues to parse them for backwards compatibility.
Sass allows *any text* in these function calls, including nested parentheses. Nothing is interpreted as a SassScript expression, with the exception that [interpolation](../interpolation) can be used to inject dynamic values.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
$logo-element: logo-bg;
.logo {
background: element(##{$logo-element});
}
```
```
$logo-element: logo-bg
.logo
background: element(##{$logo-element})
```
```
.logo {
background: element(#logo-bg);
}
```
sass Comments Comments
=========
The way Sass comments work differs substantially between SCSS and the indented syntax. Both syntaxes support two types of comments: comments defined using `/* */` that are (usually) compiled to CSS, and comments defined using `//` that are not.
In SCSS
--------
Comments in SCSS work similarly to comments in other languages like JavaScript. **Single-line comments** start with `//`, and go until the end of the line. Nothing in a single-line comment is emitted as CSS; as far as Sass is concerned, they may as well not exist. They’re also called **silent comments**, because they don’t produce any CSS.
**Multi-line comments** start with `/*` and end at the next `*/`. If a multi-line comment is written somewhere that a [statement](structure#statements) is allowed, it’s compiled to a CSS comment. They’re also called **loud comment**, by contrast with silent comments. A multi-line comment that’s compiled to CSS may contain [interpolation](../interpolation), which will be evaluated before the comment is compiled.
By default, multi-line comments be stripped from the compiled CSS in [compressed mode](../cli/dart-sass#style). If a comment begins with `/*!`, though, it will always be included in the CSS output.
* [SCSS](#example-1-scss)
* [CSS](#example-1-css)
```
// This comment won't be included in the CSS.
/* But this comment will, except in compressed mode. */
/* It can also contain interpolation:
* 1 + 1 = #{1 + 1} */
/*! This comment will be included even in compressed mode. */
p /* Multi-line comments can be written anywhere
* whitespace is allowed. */ .sans {
font: Helvetica, // So can single-line comments.
sans-serif;
}
```
```
/* But this comment will, except in compressed mode. */
/* It can also contain interpolation:
* 1 + 1 = 2 */
/*! This comment will be included even in compressed mode. */
p .sans {
font: Helvetica, sans-serif;
}
```
In Sass
--------
Comments in the indented syntax work a little differently: they’re indentation-based, just like the rest of the syntax. Like SCSS, silent comments written with `//` are never emitted as CSS, but unlike SCSS everything indented beneath the opening `//` is also commented out.
Indented syntax comments that start with `/*` work with indentation the same way, except that they are compiled to CSS. Because the extend of the comment is based on indentation, the closing `*/` is optional. Also like SCSS, `/*` comments can contain [interpolation](../interpolation) and can start with `/*!` to avoid being stripped in compressed mode.
Comments can also be used within [expressions](structure#expressions) in the indented syntax. In this case, they have exactly the same syntax as they do in SCSS.
* [Sass](#example-2-sass)
* [CSS](#example-2-css)
```
// This comment won't be included in the CSS.
This is also commented out.
/* But this comment will, except in compressed mode.
/* It can also contain interpolation:
1 + 1 = #{1 + 1}
/*! This comment will be included even in compressed mode.
p .sans
font: Helvetica, /* Inline comments must be closed. */ sans-serif
```
```
/* But this comment will, except in compressed mode. */
/* It can also contain interpolation:
* 1 + 1 = 2 */
/*! This comment will be included even in compressed mode. */
p .sans {
font: Helvetica, sans-serif;
}
```
Documentation Comments
-----------------------
When writing style libraries using Sass, you can use comments to document the [mixins](../at-rules/mixin), [functions](../at-rules/function), [variables](../variables), and [placeholder selectors](../style-rules/placeholder-selectors) that your library provides, as well as the library itself. These are comments are read by the [SassDoc](http://sassdoc.com) tool, which uses them to generate beautiful documentation. Check out [the Susy grid engine](http://oddbird.net/susy/docs/index.html)’s documentation to see it in action!
Documentation comments are silent comments, written with three slashes (`///`) directly above the thing you’re documenting. SassDoc parses text in the comments as [Markdown](https://www.markdownguide.org/getting-started), and supports many useful [annotations](http://sassdoc.com/annotations/) to describe it in detail.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
/// Computes an exponent.
///
/// @param {number} $base
/// The number to multiply by itself.
/// @param {integer (unitless)} $exponent
/// The number of `$base`s to multiply together.
/// @return {number} `$base` to the power of `$exponent`.
@function pow($base, $exponent) {
$result: 1;
@for $_ from 1 through $exponent {
$result: $result * $base;
}
@return $result;
}
```
```
/// Computes an exponent.
///
/// @param {number} $base
/// The number to multiply by itself.
/// @param {integer (unitless)} $exponent
/// The number of `$base`s to multiply together.
/// @return {number} `$base` to the power of `$exponent`.
@function pow($base, $exponent)
$result: 1
@for $_ from 1 through $exponent
$result: $result * $base
@return $result
```
sass sass:meta sass:meta
==========
Compatibility:
Dart Sass since 1.23.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass currently supports loading built-in modules with `@use`. Users of other implementations must call functions using their global names instead.
Mixins
-------
```
meta.load-css($url, $with: null)
```
Compatibility:
Dart Sass since 1.23.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass currently supports this mixin.
Loads the [module](../at-rules/use) at `$url` and includes its CSS as though it were written as the contents of this mixin. The `$with` parameter provides [configuration](../at-rules/use#configuration) for the modules; if it’s passed, it must be a map from variable names (without `$`) to the values of those variables to use in the loaded module.
If `$url` is relative, it’s interpreted as relative to the file in which `meta.load-css()` is included.
**Like the [`@use` rule](../at-rules/use)**:
* This will only evaluate the given module once, even if it’s loaded multiple times in different ways.
* This cannot provide configuration to a module that’s already been loaded, whether or not it was already loaded with configuration.
**Unlike the [`@use` rule](../at-rules/use)**:
* This doesn’t make any members from the loaded module available in the current module.
* This can be used anywhere in a stylesheet. It can even be nested within style rules to create nested styles!
* The module URL being loaded can come from a variable and include [interpolation](../interpolation).
### ⚠️ Heads up!
The `$url` parameter should be a string containing a URL like you’d pass to the `@use` rule. It shouldn’t be a CSS `url()`!
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
* [CSS](#example-1-css)
```
// dark-theme/_code.scss
$border-contrast: false !default;
code {
background-color: #6b717f;
color: #d2e1dd;
@if $border-contrast {
border-color: #dadbdf;
}
}
```
```
// style.scss
@use "sass:meta";
body.dark {
@include meta.load-css("dark-theme/code",
$with: ("border-contrast": true));
}
```
```
// dark-theme/_code.sass
$border-contrast: false !default
code
background-color: #6b717f
color: #d2e1dd
@if $border-contrast
border-color: #dadbdf
```
```
// style.sass
@use "sass:meta"
body.dark
$configuration: ("border-contrast": true)
@include meta.load-css("dark-theme/code", $with: $configuration)
```
```
body.dark code {
background-color: #6b717f;
color: #d2e1dd;
border-color: #dadbdf;
}
```
Functions
----------
```
meta.calc-args($calc) //=> list
```
Compatibility:
Dart Sass since 1.40.0
LibSass ✗
Ruby Sass ✗ Returns the arguments for the given [calculation](../values/calculations).
If an argument is a number or a nested calculation, it’s returned as that type. Otherwise, it’s returned as an unquoted string.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
```
@debug meta.calc-args(calc(100px + 10%)); // unquote("100px + 10%")
@debug meta.calc-args(clamp(50px, var(--width), 1000px)); // 50px, unquote("var(--width)"), 1000px
```
```
@debug meta.calc-args(calc(100px + 10%)) // unquote("100px + 10%")
@debug meta.calc-args(clamp(50px, var(--width), 1000px)) // 50px, unquote("var(--width)"), 1000px
```
```
meta.calc-name($calc) //=> quoted string
```
Compatibility:
Dart Sass since 1.40.0
LibSass ✗
Ruby Sass ✗ Returns the name of the given [calculation](../values/calculations).
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
@debug meta.calc-name(calc(100px + 10%)); // "calc"
@debug meta.calc-name(clamp(50px, var(--width), 1000px)); // "clamp"
```
```
@debug meta.calc-name(calc(100px + 10%)) // "calc"
@debug meta.calc-name(clamp(50px, var(--width), 1000px)) // "clamp"
```
```
meta.call($function, $args...)
call($function, $args...)
```
Compatibility (Argument Type):
Dart Sass ✓
LibSass since 3.5.0
Ruby Sass since 3.5.0
[▶](javascript:;)
In older versions of LibSass and Ruby Sass, the [`call()` function](meta#call) took a string representing a function’s name. This was changed to take a function value instead in preparation for a new module system where functions are no longer global and so a given name may not always refer to the same function.
Passing a string to `call()` still works in all implementations, but it’s deprecated and will be disallowed in future versions.
Invokes `$function` with `$args` and returns the result.
The `$function` should be a [function](../values/functions) returned by [`meta.get-function()`](#get-function).
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
* [CSS](#example-4-css)
```
@use "sass:list";
@use "sass:meta";
@use "sass:string";
/// Return a copy of $list with all elements for which $condition returns `true`
/// removed.
@function remove-where($list, $condition) {
$new-list: ();
$separator: list.separator($list);
@each $element in $list {
@if not meta.call($condition, $element) {
$new-list: list.append($new-list, $element, $separator: $separator);
}
}
@return $new-list;
}
$fonts: Tahoma, Geneva, "Helvetica Neue", Helvetica, Arial, sans-serif;
content {
@function contains-helvetica($string) {
@return string.index($string, "Helvetica");
}
font-family: remove-where($fonts, meta.get-function("contains-helvetica"));
}
```
```
@use "sass:list"
@use "sass:meta"
@use "sass:string"
/// Return a copy of $list with all elements for which $condition returns `true`
/// removed.
@function remove-where($list, $condition)
$new-list: ()
$separator: list.separator($list)
@each $element in $list
@if not meta.call($condition, $element)
$new-list: list.append($new-list, $element, $separator: $separator)
@return $new-list
$fonts: Tahoma, Geneva, "Helvetica Neue", Helvetica, Arial, sans-serif
.content
@function contains-helvetica($string)
@return string.index($string, "Helvetica")
font-family: remove-where($fonts, meta.get-function("contains-helvetica"))
```
```
.content {
font-family: Tahoma, Geneva, Arial, sans-serif;
}
```
```
meta.content-exists()
content-exists() //=> boolean
```
Returns whether the current mixin was passed a [`@content` block](../at-rules/mixin#content-blocks).
Throws an error if called outside of a mixin.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
```
@mixin debug-content-exists {
@debug meta.content-exists();
@content;
}
@include debug-content-exists; // false
@include debug-content-exists { // true
// Content!
}
```
```
@mixin debug-content-exists
@debug meta.content-exists()
@content
@include debug-content-exists // false
@include debug-content-exists // true
// Content!
```
```
meta.feature-exists($feature)
feature-exists($feature) //=> boolean
```
Returns whether the current Sass implementation supports `$feature`.
The `$feature` must be a string. The currently recognized features are:
* `global-variable-shadowing`, which means that a local variable will [shadow](../variables#shadowing) a global variable unless it has the `!global` flag.
* `extend-selector-pseudoclass`, which means that the [`@extend` rule](../at-rules/extend) will affect selectors nested in pseudo-classes like `:not()`.
* `units-level3`, which means that [unit arithmetic](../values/numbers#units) supports units defined in [CSS Values and Units Level 3](http://www.w3.org/TR/css3-values).
* `at-error`, which means that the [`@error` rule](../at-rules/error) is supported.
* `custom-property`, which means that [custom property declaration](../style-rules/declarations#custom-properties) values don’t support any [expressions](../syntax/structure#expressions) other than [interpolation](../interpolation).
Returns `false` for any unrecognized `$feature`.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
```
@debug meta.feature-exists("at-error"); // true
@debug meta.feature-exists("unrecognized"); // false
```
```
@debug meta.feature-exists("at-error") // true
@debug meta.feature-exists("unrecognized") // false
```
```
meta.function-exists($name, $module: null)
function-exists($name) //=> boolean
```
Returns whether a function named `$name` is defined, either as a built-in function or a user-defined function.
If `$module` is passed, this also checks the module named `$module` for the function definition. `$module` must be a string matching the namespace of a [`@use` rule][] in the current file.
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
```
@use "sass:math";
@debug meta.function-exists("div", "math"); // true
@debug meta.function-exists("scale-color"); // true
@debug meta.function-exists("add"); // false
@function add($num1, $num2) {
@return $num1 + $num2;
}
@debug meta.function-exists("add"); // true
```
```
@use "sass:math"
@debug meta.function-exists("div", "math") // true
@debug meta.function-exists("scale-color") // true
@debug meta.function-exists("add") // false
@function add($num1, $num2)
@return $num1 + $num2
@debug meta.function-exists("add") // true
```
```
meta.get-function($name, $css: false, $module: null)
get-function($name, $css: false, $module: null) //=> function
```
Returns the [function](../values/functions) named `$name`.
If `$module` is `null`, this returns the function named `$name` without a namespace (including [global built-in functions](../modules#global-functions)). Otherwise, `$module` must be a string matching the namespace of a [`@use` rule](../at-rules/use) in the current file, in which case this returns the function in that module named `$name`.
By default, this throws an error if `$name` doesn’t refer to Sass function. However, if `$css` is `true`, it instead returns a [plain CSS function](../at-rules/function#plain-css-functions).
The returned function can be called using [`meta.call()`](#call).
* [SCSS](#example-8-scss)
* [Sass](#example-8-sass)
* [CSS](#example-8-css)
```
@use "sass:list";
@use "sass:meta";
@use "sass:string";
/// Return a copy of $list with all elements for which $condition returns `true`
/// removed.
@function remove-where($list, $condition) {
$new-list: ();
$separator: list.separator($list);
@each $element in $list {
@if not meta.call($condition, $element) {
$new-list: list.append($new-list, $element, $separator: $separator);
}
}
@return $new-list;
}
$fonts: Tahoma, Geneva, "Helvetica Neue", Helvetica, Arial, sans-serif;
content {
@function contains-helvetica($string) {
@return string.index($string, "Helvetica");
}
font-family: remove-where($fonts, meta.get-function("contains-helvetica"));
}
```
```
@use "sass:list"
@use "sass:meta"
@use "sass:string"
/// Return a copy of $list with all elements for which $condition returns `true`
/// removed.
@function remove-where($list, $condition)
$new-list: ()
$separator: list.separator($list)
@each $element in $list
@if not meta.call($condition, $element)
$new-list: list.append($new-list, $element, $separator: $separator)
@return $new-list
$fonts: Tahoma, Geneva, "Helvetica Neue", Helvetica, Arial, sans-serif
.content
@function contains-helvetica($string)
@return string.index($string, "Helvetica")
font-family: remove-where($fonts, meta.get-function("contains-helvetica"))
```
```
.content {
font-family: Tahoma, Geneva, Arial, sans-serif;
}
```
```
meta.global-variable-exists($name, $module: null)
global-variable-exists($name, $module: null) //=> boolean
```
Returns whether a [global variable](../variables#scope) named `$name` (without the `$`) exists.
If `$module` is `null`, this returns whether a variable named `$name` without a namespace exists. Otherwise, `$module` must be a string matching the namespace of a [`@use` rule](../at-rules/use) in the current file, in which case this returns whether that module has a variable named `$name`.
See also [`meta.variable-exists()`](#variable-exists).
* [SCSS](#example-9-scss)
* [Sass](#example-9-sass)
```
@debug meta.global-variable-exists("var1"); // false
$var1: value;
@debug meta.global-variable-exists("var1"); // true
h1 {
// $var2 is local.
$var2: value;
@debug meta.global-variable-exists("var2"); // false
}
```
```
@debug meta.global-variable-exists("var1") // false
$var1: value
@debug meta.global-variable-exists("var1") // true
h1
// $var2 is local.
$var2: value
@debug meta.global-variable-exists("var2") // false
```
```
meta.inspect($value)
inspect($value) //=> unquoted string
```
Returns a string representation of `$value`.
Returns a representation of *any* Sass value, not just those that can be represented in CSS. As such, its return value is not guaranteed to be valid CSS.
### ⚠️ Heads up!
This function is intended for debugging; its output format is not guaranteed to be consistent across Sass versions or implementations.
* [SCSS](#example-10-scss)
* [Sass](#example-10-sass)
```
@debug meta.inspect(10px 20px 30px); // unquote("10px 20px 30px")
@debug meta.inspect(("width": 200px)); // unquote('("width": 200px)')
@debug meta.inspect(null); // unquote("null")
@debug meta.inspect("Helvetica"); // unquote('"Helvetica"')
```
```
@debug meta.inspect(10px 20px 30px) // unquote("10px 20px 30px")
@debug meta.inspect(("width": 200px)) // unquote('("width": 200px)')
@debug meta.inspect(null) // unquote("null")
@debug meta.inspect("Helvetica") // unquote('"Helvetica"')
```
```
meta.keywords($args)
keywords($args) //=> map
```
Returns the keywords passed to a mixin or function that takes [arbitrary arguments](../at-rules/mixin#taking-arbitrary-arguments). The `$args` argument must be an [argument list](../values/lists#argument-lists).
The keywords are returned as a map from argument names as unquoted strings (not including `$`) to the values of those arguments.
* [SCSS](#example-11-scss)
* [Sass](#example-11-sass)
* [CSS](#example-11-css)
```
@use "sass:meta";
@mixin syntax-colors($args...) {
@debug meta.keywords($args);
// (string: #080, comment: #800, variable: #60b)
@each $name, $color in meta.keywords($args) {
pre span.stx-#{$name} {
color: $color;
}
}
}
@include syntax-colors(
$string: #080,
$comment: #800,
$variable: #60b,
)
```
```
@use "sass:meta"
@mixin syntax-colors($args...)
@debug meta.keywords($args)
// (string: #080, comment: #800, variable: #60b)
@each $name, $color in meta.keywords($args)
pre span.stx-#{$name}
color: $color
@include syntax-colors($string: #080, $comment: #800, $variable: #60b)
```
```
pre span.stx-string {
color: #080;
}
pre span.stx-comment {
color: #800;
}
pre span.stx-variable {
color: #60b;
}
```
```
meta.mixin-exists($name, $module: null)
mixin-exists($name, $module: null) //=> boolean
```
Returns whether a [mixin](../at-rules/mixin) named `$name` exists.
If `$module` is `null`, this returns whether a mixin named `$name` without a namespace exists. Otherwise, `$module` must be a string matching the namespace of a [`@use` rule](../at-rules/use) in the current file, in which case this returns whether that module has a mixin named `$name`.
* [SCSS](#example-12-scss)
* [Sass](#example-12-sass)
```
@debug meta.mixin-exists("shadow-none"); // false
@mixin shadow-none {
box-shadow: none;
}
@debug meta.mixin-exists("shadow-none"); // true
```
```
@debug meta.mixin-exists("shadow-none") // false
@mixin shadow-none
box-shadow: none
@debug meta.mixin-exists("shadow-none") // true
```
```
meta.module-functions($module) //=> map
```
Compatibility:
Dart Sass since 1.23.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass currently supports this function.
Returns all the functions defined in a module, as a map from function names to [function values](../values/functions).
The `$module` parameter must be a string matching the namespace of a [`@use` rule](../at-rules/use) in the current file.
* [SCSS](#example-13-scss)
* [Sass](#example-13-sass)
```
// _functions.scss
@function pow($base, $exponent) {
$result: 1;
@for $_ from 1 through $exponent {
$result: $result * $base;
}
@return $result;
}
```
```
@use "sass:map";
@use "sass:meta";
@use "functions";
@debug meta.module-functions("functions"); // ("pow": get-function("pow"))
@debug meta.call(map.get(meta.module-variables("functions"), "pow"), 3, 4); // 16
```
```
// _functions.sass
@function pow($base, $exponent)
$result: 1
@for $_ from 1 through $exponent
$result: $result * $base
@return $result
```
```
@use "sass:map"
@use "sass:meta"
@use "functions"
@debug meta.module-functions("functions") // ("pow": get-function("pow"))
@debug meta.call(map.get(meta.module-variables("functions"), "pow"), 3, 4) // 16
```
```
meta.module-variables($module) //=> map
```
Compatibility:
Dart Sass since 1.23.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass currently supports this function.
Returns all the variables defined in a module, as a map from variable names (without `$`) to the values of those variables.
The `$module` parameter must be a string matching the namespace of a [`@use` rule](../at-rules/use) in the current file.
* [SCSS](#example-14-scss)
* [Sass](#example-14-sass)
```
// _variables.scss
$hopbush: #c69;
$midnight-blue: #036;
$wafer: #e1d7d2;
```
```
@use "sass:meta";
@use "variables";
@debug meta.module-variables("variables");
// (
// "hopbush": #c69,
// "midnight-blue": #036,
// "wafer": #e1d7d2
// )
```
```
// _variables.sass
$hopbush: #c69
$midnight-blue: #036
$wafer: #e1d7d2
```
```
@use "sass:meta"
@use "variables"
@debug meta.module-variables("variables")
// (
// "hopbush": #c69,
// "midnight-blue": #036,
// "wafer": #e1d7d2
// )
```
```
meta.type-of($value)
type-of($value) //=> unquoted string
```
Returns the type of `$value`.
This can return the following values:
* [`number`](../values/numbers)
* [`string`](../values/strings)
* [`color`](../values/colors)
* [`list`](../values/lists)
* [`map`](../values/maps)
* [`calculation`](../values/calculations)
* [`bool`](../values/booleans)
* [`null`](../values/null)
* [`function`](../values/functions)
* [`arglist`](../values/lists#argument-lists)
New possible values may be added in the future. It may return either `list` or `map` for `()`, depending on whether or not it was returned by a [map function](map).
* [SCSS](#example-15-scss)
* [Sass](#example-15-sass)
```
@debug meta.type-of(10px); // number
@debug meta.type-of(10px 20px 30px); // list
@debug meta.type-of(()); // list
```
```
@debug meta.type-of(10px) // number
@debug meta.type-of(10px 20px 30px) // list
@debug meta.type-of(()) // list
```
```
meta.variable-exists($name)
variable-exists($name) //=> boolean
```
Returns whether a variable named `$name` (without the `$`) exists in the current [scope](../variables#scope).
See also [`meta.global-variable-exists()`](#global-variable-exists).
* [SCSS](#example-16-scss)
* [Sass](#example-16-sass)
```
@debug meta.variable-exists("var1"); // false
$var1: value;
@debug meta.variable-exists("var1"); // true
h1 {
// $var2 is local.
$var2: value;
@debug meta.variable-exists("var2"); // true
}
```
```
@debug meta.variable-exists("var1") // false
$var1: value
@debug meta.variable-exists("var1") // true
h1
// $var2 is local.
$var2: value
@debug meta.variable-exists("var2") // true
```
| programming_docs |
sass sass:map sass:map
=========
Compatibility:
Dart Sass since 1.23.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass currently supports loading built-in modules with `@use`. Users of other implementations must call functions using their global names instead.
### 💡 Fun fact:
Sass libraries and design systems tend to share and override configurations that are represented as nested maps (maps that contain maps that contain maps).
To help you work with nested maps, some map functions support deep operations. For example, if you pass multiple keys to `map.get()`, it will follow those keys to find the desired nested map:
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
$config: (a: (b: (c: d)));
@debug map.get($config, a, b, c); // d
```
```
$config: (a: (b: (c: d)))
@debug map.get($config, a, b, c) // d
```
```
map.deep-merge($map1, $map2) //=> map
```
Compatibility:
Dart Sass since 1.27.0
LibSass ✗
Ruby Sass ✗ Identical to [`map.merge()`](#merge), except that nested map values are *also* recursively merged.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
```
$helvetica-light: (
"weights": (
"lightest": 100,
"light": 300
)
);
$helvetica-heavy: (
"weights": (
"medium": 500,
"bold": 700
)
);
@debug map.deep-merge($helvetica-light, $helvetica-heavy);
// (
// "weights": (
// "lightest": 100,
// "light": 300,
// "medium": 500,
// "bold": 700
// )
// )
@debug map.merge($helvetica-light, $helvetica-heavy);
// (
// "weights": (
// "medium: 500,
// "bold": 700
// )
// )
```
```
$helvetica-light: ("weights": ("lightest": 100, "light": 300))
$helvetica-heavy: ("weights": ("medium": 500, "bold": 700))
@debug map.deep-merge($helvetica-light, $helvetica-heavy)
// (
// "weights": (
// "lightest": 100,
// "light": 300,
// "medium": 500,
// "bold": 700
// )
// )
@debug map.merge($helvetica-light, $helvetica-heavy);
// (
// "weights": (
// "medium: 500,
// "bold": 700
// )
// )
```
```
map.deep-remove($map, $key, $keys...) //=> map
```
Compatibility:
Dart Sass since 1.27.0
LibSass ✗
Ruby Sass ✗ If `$keys` is empty, returns a copy of `$map` without a value associated with `$key`.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
$font-weights: ("regular": 400, "medium": 500, "bold": 700);
@debug map.deep-remove($font-weights, "regular");
// ("medium": 500, "bold": 700)
```
```
$font-weights: ("regular": 400, "medium": 500, "bold": 700)
@debug map.deep-remove($font-weights, "regular")
// ("medium": 500, "bold": 700)
```
---
If `$keys` is not empty, follows the set of keys including `$key` and excluding the last key in `$keys`, from left to right, to find the nested map targeted for updating.
Returns a copy of `$map` where the targeted map does not have a value associated with the last key in `$keys`.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
```
$fonts: (
"Helvetica": (
"weights": (
"regular": 400,
"medium": 500,
"bold": 700
)
)
);
@debug map.deep-remove($fonts, "Helvetica", "weights", "regular");
// (
// "Helvetica": (
// "weights: (
// "medium": 500,
// "bold": 700
// )
// )
// )
```
```
$fonts: ("Helvetica": ("weights": ("regular": 400, "medium": 500, "bold": 700)))
@debug map.deep-remove($fonts, "Helvetica", "weights", "regular")
// (
// "Helvetica": (
// "weights: (
// "medium": 500,
// "bold": 700
// )
// )
// )
```
```
map.get($map, $key, $keys...)
map-get($map, $key, $keys...)
```
If `$keys` is empty, returns the value in `$map` associated with `$key`.
If `$map` doesn’t have a value associated with `$key`, returns [`null`](../values/null).
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
```
$font-weights: ("regular": 400, "medium": 500, "bold": 700);
@debug map.get($font-weights, "medium"); // 500
@debug map.get($font-weights, "extra-bold"); // null
```
```
$font-weights: ("regular": 400, "medium": 500, "bold": 700)
@debug map.get($font-weights, "medium") // 500
@debug map.get($font-weights, "extra-bold") // null
```
---
Compatibility:
Dart Sass since 1.27.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass supports calling `map.get()` with more than two arguments.
If `$keys` is not empty, follows the set of keys including `$key` and excluding the last key in `$keys`, from left to right, to find the nested map targeted for searching.
Returns the value in the targeted map associated with the last key in `$keys`.
Returns [`null`](../values/null) if the map does not have a value associated with the key, or if any key in `$keys` is missing from a map or references a value that is not a map.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
```
$fonts: (
"Helvetica": (
"weights": (
"regular": 400,
"medium": 500,
"bold": 700
)
)
);
@debug map.get($fonts, "Helvetica", "weights", "regular"); // 400
@debug map.get($fonts, "Helvetica", "colors"); // null
```
```
$fonts: ("Helvetica": ("weights": ("regular": 400, "medium": 500, "bold": 700)))
@debug map.get($fonts, "Helvetica", "weights", "regular") // 400
@debug map.get($fonts, "Helvetica", "colors") // null
```
```
map.has-key($map, $key, $keys...)
map-has-key($map, $key, $keys...) //=> boolean
```
If `$keys` is empty, returns whether `$map` contains a value associated with `$key`.
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
```
$font-weights: ("regular": 400, "medium": 500, "bold": 700);
@debug map.has-key($font-weights, "regular"); // true
@debug map.has-key($font-weights, "bolder"); // false
```
```
$font-weights: ("regular": 400, "medium": 500, "bold": 700)
@debug map.has-key($font-weights, "regular") // true
@debug map.has-key($font-weights, "bolder") // false
```
---
Compatibility:
Dart Sass since 1.27.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass supports calling `map.has-key()` with more than two arguments.
If `$keys` is not empty, follows the set of keys including `$key` and excluding the last key in `$keys`, from left to right, to find the nested map targeted for searching.
Returns true if the targeted map contains a value associated with the last key in `$keys`.
Returns false if it does not, or if any key in `$keys` is missing from a map or references a value that is not a map.
* [SCSS](#example-8-scss)
* [Sass](#example-8-sass)
```
$fonts: (
"Helvetica": (
"weights": (
"regular": 400,
"medium": 500,
"bold": 700
)
)
);
@debug map.has-key($fonts, "Helvetica", "weights", "regular"); // true
@debug map.has-key($fonts, "Helvetica", "colors"); // false
```
```
$fonts: ("Helvetica": ("weights": ("regular": 400, "medium": 500, "bold": 700)))
@debug map.has-key($fonts, "Helvetica", "weights", "regular") // true
@debug map.has-key($fonts, "Helvetica", "colors") // false
```
```
map.keys($map)
map-keys($map) //=> list
```
Returns a comma-separated list of all the keys in `$map`.
* [SCSS](#example-9-scss)
* [Sass](#example-9-sass)
```
$font-weights: ("regular": 400, "medium": 500, "bold": 700);
@debug map.keys($font-weights); // "regular", "medium", "bold"
```
```
$font-weights: ("regular": 400, "medium": 500, "bold": 700)
@debug map.keys($font-weights) // "regular", "medium", "bold"
```
```
map.merge($map1, $map2)
map-merge($map1, $map2)
map.merge($map1, $keys..., $map2)
map-merge($map1, $keys..., $map2) //=> map
```
### ⚠️ Heads up!
In practice, the actual arguments to `map.merge($map1, $keys..., $map2)` are passed as `map.merge($map1, $args...)`. They are described here as `$map1,
$keys..., $map2` for explanation purposes only.
If no `$keys` are passed, returns a new map with all the keys and values from both `$map1` and `$map2`.
If both `$map1` and `$map2` have the same key, `$map2`‘s value takes precedence.
All keys in the returned map that also appear in `$map1` have the same order as in `$map1`. New keys from `$map2` appear at the end of the map.
* [SCSS](#example-10-scss)
* [Sass](#example-10-sass)
```
$light-weights: ("lightest": 100, "light": 300);
$heavy-weights: ("medium": 500, "bold": 700);
@debug map.merge($light-weights, $heavy-weights);
// ("lightest": 100, "light": 300, "medium": 500, "bold": 700)
```
```
$light-weights: ("lightest": 100, "light": 300)
$heavy-weights: ("medium": 500, "bold": 700)
@debug map.merge($light-weights, $heavy-weights)
// ("lightest": 100, "light": 300, "medium": 500, "bold": 700)
```
---
Compatibility:
Dart Sass since 1.27.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass supports calling `map.merge()` with more than two arguments.
If `$keys` is not empty, follows the `$keys` to find the nested map targeted for merging. If any key in `$keys` is missing from a map or references a value that is not a map, sets the value at that key to an empty map.
Returns a copy of `$map1` where the targeted map is replaced by a new map that contains all the keys and values from both the targeted map and `$map2`.
* [SCSS](#example-11-scss)
* [Sass](#example-11-sass)
```
$fonts: (
"Helvetica": (
"weights": (
"lightest": 100,
"light": 300
)
)
);
$heavy-weights: ("medium": 500, "bold": 700);
@debug map.merge($fonts, "Helvetica", "weights", $heavy-weights);
// (
// "Helvetica": (
// "weights": (
// "lightest": 100,
// "light": 300,
// "medium": 500,
// "bold": 700
// )
// )
// )
```
```
$fonts: ("Helvetica": ("weights": ("lightest": 100, "light": 300)))
$heavy-weights: ("medium": 500, "bold": 700)
@debug map.merge($fonts, "Helvetica", "weights", $heavy-weights)
// (
// "Helvetica": (
// "weights": (
// "lightest": 100,
// "light": 300,
// "medium": 500,
// "bold": 700
// )
// )
// )
```
```
map.remove($map, $keys...)
map-remove($map, $keys...) //=> map
```
Returns a copy of `$map` without any values associated with `$keys`.
If a key in `$keys` doesn’t have an associated value in `$map`, it’s ignored.
* [SCSS](#example-12-scss)
* [Sass](#example-12-sass)
```
$font-weights: ("regular": 400, "medium": 500, "bold": 700);
@debug map.remove($font-weights, "regular"); // ("medium": 500, "bold": 700)
@debug map.remove($font-weights, "regular", "bold"); // ("medium": 500)
@debug map.remove($font-weights, "bolder");
// ("regular": 400, "medium": 500, "bold": 700)
```
```
$font-weights: ("regular": 400, "medium": 500, "bold": 700)
@debug map.remove($font-weights, "regular") // ("medium": 500, "bold": 700)
@debug map.remove($font-weights, "regular", "bold") // ("medium": 500)
@debug map.remove($font-weights, "bolder")
// ("regular": 400, "medium": 500, "bold": 700)
```
```
map.set($map, $key, $value)
map.set($map, $keys..., $key, $value) //=> map
```
### ⚠️ Heads up!
In practice, the actual arguments to `map.set($map, $keys..., $key, $value)` are passed as `map.set($map, $args...)`. They are described here as `$map,
$keys..., $key, $value` for explanation purposes only.
If `$keys` are not passed, returns a copy of `$map` with the value at `$key` set to `$value`.
* [SCSS](#example-13-scss)
* [Sass](#example-13-sass)
```
$font-weights: ("regular": 400, "medium": 500, "bold": 700);
@debug map.set($font-weights, "regular", 300);
// ("regular": 300, "medium": 500, "bold": 700)
```
```
$font-weights: ("regular": 400, "medium": 500, "bold": 700)
@debug map.set($font-weights, "regular", 300)
// ("regular": 300, "medium": 500, "bold": 700)
```
---
Compatibility:
Dart Sass since 1.27.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass supports calling `map.set()` with more than three arguments.
If `$keys` are passed, follows the `$keys` to find the nested map targeted for updating. If any key in `$keys` is missing from a map or references a value that is not a map, sets the value at that key to an empty map.
Returns a copy of `$map` with the targeted map’s value at `$key` set to `$value`.
* [SCSS](#example-14-scss)
* [Sass](#example-14-sass)
```
$fonts: (
"Helvetica": (
"weights": (
"regular": 400,
"medium": 500,
"bold": 700
)
)
);
@debug map.set($fonts, "Helvetica", "weights", "regular", 300);
// (
// "Helvetica": (
// "weights": (
// "regular": 300,
// "medium": 500,
// "bold": 700
// )
// )
// )
```
```
$fonts: ("Helvetica": ("weights": ("regular": 400, "medium": 500, "bold": 700)))
@debug map.set($fonts, "Helvetica", "weights", "regular", 300)
// (
// "Helvetica": (
// "weights": (
// "regular": 300,
// "medium": 500,
// "bold": 700
// )
// )
// )
```
```
map.values($map)
map-values($map) //=> list
```
Returns a comma-separated list of all the values in `$map`.
* [SCSS](#example-15-scss)
* [Sass](#example-15-sass)
```
$font-weights: ("regular": 400, "medium": 500, "bold": 700);
@debug map.values($font-weights); // 400, 500, 700
```
```
$font-weights: ("regular": 400, "medium": 500, "bold": 700)
@debug map.values($font-weights) // 400, 500, 700
```
sass sass:list sass:list
==========
Compatibility:
Dart Sass since 1.23.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass currently supports loading built-in modules with `@use`. Users of other implementations must call functions using their global names instead.
### 💡 Fun fact:
In Sass, every [map](../values/maps) counts as a list that contains a two-element list for each key/value pair. For example, `(1: 2, 3: 4)` counts as `(1 2, 3 4)`. So all these functions work for maps as well!
Individual values also count as lists. All these functions treat `1px` as a list that contains the value `1px`.
```
list.append($list, $val, $separator: auto)
append($list, $val, $separator: auto) //=> list
```
Returns a copy of `$list` with `$val` added to the end.
If `$separator` is `comma`, `space`, or `slash`, the returned list is comma-separated, space-separated, or slash-separated, respectively. If it’s `auto` (the default), the returned list will use the same separator as `$list` (or `space` if `$list` doesn’t have a separator). Other values aren’t allowed.
Note that unlike [`list.join()`](#join), if `$val` is a list it’s nested within the returned list rather than having all its elements added to the returned list.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@debug list.append(10px 20px, 30px); // 10px 20px 30px
@debug list.append((blue, red), green); // blue, red, green
@debug list.append(10px 20px, 30px 40px); // 10px 20px (30px 40px)
@debug list.append(10px, 20px, $separator: comma); // 10px, 20px
@debug list.append((blue, red), green, $separator: space); // blue red green
```
```
@debug list.append(10px 20px, 30px) // 10px 20px 30px
@debug list.append((blue, red), green) // blue, red, green
@debug list.append(10px 20px, 30px 40px) // 10px 20px (30px 40px)
@debug list.append(10px, 20px, $separator: comma) // 10px, 20px
@debug list.append((blue, red), green, $separator: space) // blue red green
```
```
list.index($list, $value)
index($list, $value) //=> number | null
```
Returns the [index](../values/lists#indexes) of `$value` in `$list`.
If `$value` doesn’t appear in `$list`, this returns [`null`](../values/null). If `$value` appears multiple times in `$list`, this returns the index of its first appearance.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
```
@debug list.index(1px solid red, 1px); // 1
@debug list.index(1px solid red, solid); // 2
@debug list.index(1px solid red, dashed); // null
```
```
@debug list.index(1px solid red, 1px) // 1
@debug list.index(1px solid red, solid) // 2
@debug list.index(1px solid red, dashed) // null
```
```
list.is-bracketed($list)
is-bracketed($list) //=> boolean
```
Returns whether `$list` has square brackets.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
@debug list.is-bracketed(1px 2px 3px); // false
@debug list.is-bracketed([1px, 2px, 3px]); // true
```
```
@debug list.is-bracketed(1px 2px 3px) // false
@debug list.is-bracketed([1px, 2px, 3px]) // true
```
```
list.join($list1, $list2, $separator: auto, $bracketed: auto)
join($list1, $list2, $separator: auto, $bracketed: auto) //=> list
```
Returns a new list containing the elements of `$list1` followed by the elements of `$list2`.
### ⚠️ Heads up!
Because individual values count as single-element lists, it’s possible to use `list.join()` to add a value to the end of a list. However, *this is not recommended*, since if that value is a list it will be concatenated, which is probably not what you’re expecting.
Use [`list.append()`](#append) instead to add a single value to a list. Only use `list.join()` to combine two lists together into one.
If `$separator` is `comma`, `space`, or `slash`, the returned list is comma-separated, space-separated, or slash-separated, respectively. If it’s `auto` (the default), the returned list will use the same separator as `$list1` if it has a separator, or else `$list2` if it has a separator, or else `space`. Other values aren’t allowed.
If `$bracketed` is `auto` (the default), the returned list will be bracketed if `$list1` is. Otherwise, the returned list will have square brackets if `$bracketed` is [truthy](../values/booleans#truthiness-and-falsiness) and no brackets if `$bracketed` is falsey.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
```
@debug list.join(10px 20px, 30px 40px); // 10px 20px 30px 40px
@debug list.join((blue, red), (#abc, #def)); // blue, red, #abc, #def
@debug list.join(10px, 20px); // 10px 20px
@debug list.join(10px, 20px, $separator: comma); // 10px, 20px
@debug list.join((blue, red), (#abc, #def), $separator: space); // blue red #abc #def
@debug list.join([10px], 20px); // [10px 20px]
@debug list.join(10px, 20px, $bracketed: true); // [10px 20px]
```
```
@debug list.join(10px 20px, 30px 40px) // 10px 20px 30px 40px
@debug list.join((blue, red), (#abc, #def)) // blue, red, #abc, #def
@debug list.join(10px, 20px) // 10px 20px
@debug list.join(10px, 20px, comma) // 10px, 20px
@debug list.join((blue, red), (#abc, #def), space) // blue red #abc #def
@debug list.join([10px], 20px) // [10px 20px]
@debug list.join(10px, 20px, $bracketed: true) // [10px 20px]
```
```
list.length($list)
length($list) //=> number
```
Returns the length of `$list`.
This can also return the number of pairs in a map.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
```
@debug list.length(10px); // 1
@debug list.length(10px 20px 30px); // 3
@debug list.length((width: 10px, height: 20px)); // 2
```
```
@debug list.length(10px) // 1
@debug list.length(10px 20px 30px) // 3
@debug list.length((width: 10px, height: 20px)) // 2
```
```
list.separator($list)
list-separator($list) //=> unquoted string
```
Returns the name of the separator used by `$list`, either `space`, `comma`, or `slash`.
If `$list` doesn’t have a separator, returns `space`.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
```
@debug list.separator(1px 2px 3px); // space
@debug list.separator(1px, 2px, 3px); // comma
@debug list.separator('Helvetica'); // space
@debug list.separator(()); // space
```
```
@debug list.separator(1px 2px 3px) // space
@debug list.separator(1px, 2px, 3px) // comma
@debug list.separator('Helvetica') // space
@debug list.separator(()) // space
```
```
list.nth($list, $n)
nth($list, $n)
```
Returns the element of `$list` at [index](../values/lists#indexes) `$n`.
If `$n` is negative, it counts from the end of `$list`. Throws an error if there is no element at index `$n`.
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
```
@debug list.nth(10px 12px 16px, 2); // 12px
@debug list.nth([line1, line2, line3], -1); // line3
```
```
@debug list.nth(10px 12px 16px, 2) // 12px
@debug list.nth([line1, line2, line3], -1) // line3
```
```
list.set-nth($list, $n, $value)
set-nth($list, $n, $value) //=> list
```
Returns a copy of `$list` with the element at [index](../values/lists#indexes) `$n` replaced with `$value`.
If `$n` is negative, it counts from the end of `$list`. Throws an error if there is no existing element at index `$n`.
* [SCSS](#example-8-scss)
* [Sass](#example-8-sass)
```
@debug list.set-nth(10px 20px 30px, 1, 2em); // 2em 20px 30px
@debug list.set-nth(10px 20px 30px, -1, 8em); // 10px, 20px, 8em
@debug list.set-nth((Helvetica, Arial, sans-serif), 3, Roboto); // Helvetica, Arial, Roboto
```
```
@debug list.set-nth(10px 20px 30px, 1, 2em); // 2em 20px 30px
@debug list.set-nth(10px 20px 30px, -1, 8em); // 10px, 20px, 8em
@debug list.set-nth((Helvetica, Arial, sans-serif), 3, Roboto); // Helvetica, Arial, Roboto
```
```
list.slash($elements...) //=> list
```
Returns a slash-separated list that contains `$elements`.
### ⚠️ Heads up!
This function is a temporary solution for creating slash-separated lists. Eventually, they’ll be written literally with slashes, as in `1px / 2px / solid`, but for the time being [slashes are used for division](https://sass-lang.com/documentation/breaking-changes/slash-div) so Sass can’t use them for new syntax until the old syntax is removed.
* [SCSS](#example-9-scss)
* [Sass](#example-9-sass)
```
@debug list.slash(1px, 50px, 100px); // 1px / 50px / 100px
```
```
@debug list.slash(1px, 50px, 100px) // 1px / 50px / 100px
```
```
list.zip($lists...)
zip($lists...) //=> list
```
Combines every list in `$lists` into a single list of sub-lists.
Each element in the returned list contains all the elements at that position in `$lists`. The returned list is as long as the shortest list in `$lists`.
The returned list is always comma-separated and the sub-lists are always space-separated.
* [SCSS](#example-10-scss)
* [Sass](#example-10-sass)
```
@debug list.zip(10px 50px 100px, short mid long); // 10px short, 50px mid, 100px long
@debug list.zip(10px 50px 100px, short mid); // 10px short, 50px mid
```
```
@debug list.zip(10px 50px 100px, short mid long) // 10px short, 50px mid, 100px long
@debug list.zip(10px 50px 100px, short mid) // 10px short, 50px mid
```
| programming_docs |
sass sass:string sass:string
============
Compatibility:
Dart Sass since 1.23.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass currently supports loading built-in modules with `@use`. Users of other implementations must call functions using their global names instead.
```
string.quote($string)
quote($string) //=> string
```
Returns `$string` as a quoted string.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@debug string.quote(Helvetica); // "Helvetica"
@debug string.quote("Helvetica"); // "Helvetica"
```
```
@debug string.quote(Helvetica) // "Helvetica"
@debug string.quote("Helvetica") // "Helvetica"
```
```
string.index($string, $substring)
str-index($string, $substring) //=> number
```
Returns the first [index](../values/strings#string-indexes) of `$substring` in `$string`, or `null` if `$string` doesn’t contain `$substring`.
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
```
@debug string.index("Helvetica Neue", "Helvetica"); // 1
@debug string.index("Helvetica Neue", "Neue"); // 11
```
```
@debug string.index("Helvetica Neue", "Helvetica") // 1
@debug string.index("Helvetica Neue", "Neue") // 11
```
```
string.insert($string, $insert, $index)
str-insert($string, $insert, $index) //=> string
```
Returns a copy of `$string` with `$insert` inserted at [`$index`](../values/strings#string-indexes).
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
@debug string.insert("Roboto Bold", " Mono", 7); // "Roboto Mono Bold"
@debug string.insert("Roboto Bold", " Mono", -6); // "Roboto Mono Bold"
```
```
@debug string.insert("Roboto Bold", " Mono", 7) // "Roboto Mono Bold"
@debug string.insert("Roboto Bold", " Mono", -6) // "Roboto Mono Bold"
```
If of `$index` is higher than the length of `$string`, `$insert` is added to the end. If `$index` is smaller than the negative length of the string, `$insert` is added to the beginning.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
```
@debug string.insert("Roboto", " Bold", 100); // "Roboto Bold"
@debug string.insert("Bold", "Roboto ", -100); // "Roboto Bold"
```
```
@debug string.insert("Roboto", " Bold", 100) // "Roboto Bold"
@debug string.insert("Bold", "Roboto ", -100) // "Roboto Bold"
```
```
string.length($string)
str-length($string) //=> number
```
Returns the number of characters in `$string`.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
```
@debug string.length("Helvetica Neue"); // 14
@debug string.length(bold); // 4
@debug string.length(""); // 0
```
```
@debug string.length("Helvetica Neue") // 14
@debug string.length(bold) // 4
@debug string.length("") // 0
```
```
string.slice($string, $start-at, $end-at: -1)
str-slice($string, $start-at, $end-at: -1) //=> string
```
Returns the slice of `$string` starting at [index](../values/strings#string-indexes) `$start-at` and ending at index `$end-at` (both inclusive).
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
```
@debug string.slice("Helvetica Neue", 11); // "Neue"
@debug string.slice("Helvetica Neue", 1, 3); // "Hel"
@debug string.slice("Helvetica Neue", 1, -6); // "Helvetica"
```
```
@debug string.slice("Helvetica Neue", 11) // "Neue"
@debug string.slice("Helvetica Neue", 1, 3) // "Hel"
@debug string.slice("Helvetica Neue", 1, -6) // "Helvetica"
```
```
string.to-upper-case($string)
to-upper-case($string) //=> string
```
Returns a copy of `$string` with the [ASCII](https://en.wikipedia.org/wiki/ASCII) letters converted to upper case.
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
```
@debug string.to-upper-case("Bold"); // "BOLD"
@debug string.to-upper-case(sans-serif); // SANS-SERIF
```
```
@debug string.to-upper-case("Bold") // "BOLD"
@debug string.to-upper-case(sans-serif) // SANS-SERIF
```
```
string.to-lower-case($string)
to-lower-case($string) //=> string
```
Returns a copy of `$string` with the [ASCII](https://en.wikipedia.org/wiki/ASCII) letters converted to lower case.
* [SCSS](#example-8-scss)
* [Sass](#example-8-sass)
```
@debug string.to-lower-case("Bold"); // "bold"
@debug string.to-lower-case(SANS-SERIF); // sans-serif
```
```
@debug string.to-lower-case("Bold") // "bold"
@debug string.to-lower-case(SANS-SERIF) // sans-serif
```
```
string.unique-id()
unique-id() //=> string
```
Returns a randomly-generated unquoted string that’s guaranteed to be a valid CSS identifier and to be unique within the current Sass compilation.
* [SCSS](#example-9-scss)
* [Sass](#example-9-sass)
```
@debug string.unique-id(); // uabtrnzug
@debug string.unique-id(); // u6w1b1def
```
```
@debug string.unique-id(); // uabtrnzug
@debug string.unique-id(); // u6w1b1def
```
```
string.unquote($string)
unquote($string) //=> string
```
Returns `$string` as an unquoted string. This can produce strings that aren’t valid CSS, so use with caution.
* [SCSS](#example-10-scss)
* [Sass](#example-10-sass)
```
@debug string.unquote("Helvetica"); // Helvetica
@debug string.unquote(".widget:hover"); // .widget:hover
```
```
@debug string.unquote("Helvetica") // Helvetica
@debug string.unquote(".widget:hover") // .widget:hover
```
sass sass:selector sass:selector
==============
Compatibility:
Dart Sass since 1.23.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass currently supports loading built-in modules with `@use`. Users of other implementations must call functions using their global names instead.
Selector Values
----------------
The functions in this module inspect and manipulate selectors. Whenever they return a selector, it’s always a comma-separated [list](../values/lists) (the selector list) that contains space-separated lists (the complex selectors) that contain [unquoted strings](../values/strings#unquoted) (the compound selectors). For example, the selector `.main aside:hover, .sidebar p` would be returned as:
```
@debug ((unquote(".main") unquote("aside:hover")),
(unquote(".sidebar") unquote("p")));
// .main aside:hover, .sidebar p
```
Selector arguments to these functions may be in the same format, but they can also just be normal strings (quoted or unquoted), or a combination. For example, `".main aside:hover, .sidebar p"` is a valid selector argument.
```
selector.is-superselector($super, $sub)
is-superselector($super, $sub) //=> boolean
```
Returns whether the selector `$super` matches all the elements that the selector `$sub` matches.
Still returns true even if `$super` matches *more* elements than `$sub`.
The `$super` and `$sub` selectors may contain [placeholder selectors](../style-rules/placeholder-selectors), but not [parent selectors](../style-rules/parent-selector).
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@debug selector.is-superselector("a", "a.disabled"); // true
@debug selector.is-superselector("a.disabled", "a"); // false
@debug selector.is-superselector("a", "sidebar a"); // true
@debug selector.is-superselector("sidebar a", "a"); // false
@debug selector.is-superselector("a", "a"); // true
```
```
@debug selector.is-superselector("a", "a.disabled") // true
@debug selector.is-superselector("a.disabled", "a") // false
@debug selector.is-superselector("a", "sidebar a") // true
@debug selector.is-superselector("sidebar a", "a") // false
@debug selector.is-superselector("a", "a") // true
```
```
selector.append($selectors...)
selector-append($selectors...) //=> selector
```
Combines `$selectors` without [descendant combinators](https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_selectors)—that is, without whitespace between them.
If any selector in `$selectors` is a selector list, each complex selector is combined separately.
The `$selectors` may contain [placeholder selectors](../style-rules/placeholder-selectors), but not [parent selectors](../style-rules/parent-selector).
See also [`selector.nest()`](#nest).
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
```
@debug selector.append("a", ".disabled"); // a.disabled
@debug selector.append(".accordion", "__copy"); // .accordion__copy
@debug selector.append(".accordion", "__copy, __image");
// .accordion__copy, .accordion__image
```
```
@debug selector.append("a", ".disabled") // a.disabled
@debug selector.append(".accordion", "__copy") // .accordion__copy
@debug selector.append(".accordion", "__copy, __image")
// .accordion__copy, .accordion__image
```
```
selector.extend($selector, $extendee, $extender)
selector-extend($selector, $extendee, $extender) //=> selector
```
Extends `$selector` as with the [`@extend` rule](../at-rules/extend).
Returns a copy of `$selector` modified with the following `@extend` rule:
```
#{$extender} {
@extend #{$extendee};
}
```
In other words, replaces all instances of `$extendee` in `$selector` with `$extendee, $extender`. If `$selector` doesn’t contain `$extendee`, returns it as-is.
The `$selector`, `$extendee`, and `$extender` selectors may contain [placeholder selectors](../style-rules/placeholder-selectors), but not [parent selectors](../style-rules/parent-selector).
See also [`selector.replace()`](#replace).
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
@debug selector.extend("a.disabled", "a", ".link"); // a.disabled, .link.disabled
@debug selector.extend("a.disabled", "h1", "h2"); // a.disabled
@debug selector.extend(".guide .info", ".info", ".content nav.sidebar");
// .guide .info, .guide .content nav.sidebar, .content .guide nav.sidebar
```
```
@debug selector.extend("a.disabled", "a", ".link") // a.disabled, .link.disabled
@debug selector.extend("a.disabled", "h1", "h2") // a.disabled
@debug selector.extend(".guide .info", ".info", ".content nav.sidebar")
// .guide .info, .guide .content nav.sidebar, .content .guide nav.sidebar
```
```
selector.nest($selectors...)
selector-nest($selectors...) //=> selector
```
Combines `$selectors` as though they were nested within one another in the stylesheet.
The `$selectors` may contain [placeholder selectors](../style-rules/placeholder-selectors). Unlike other selector functions, all of them except the first may also contain [parent selectors](../style-rules/parent-selector).
See also [`selector.append()`](#append).
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
```
@debug selector.nest("ul", "li"); // ul li
@debug selector.nest(".alert, .warning", "p"); // .alert p, .warning p
@debug selector.nest(".alert", "&:hover"); // .alert:hover
@debug selector.nest(".accordion", "&__copy"); // .accordion__copy
```
```
@debug selector.nest("ul", "li") // ul li
@debug selector.nest(".alert, .warning", "p") // .alert p, .warning p
@debug selector.nest(".alert", "&:hover") // .alert:hover
@debug selector.nest(".accordion", "&__copy") // .accordion__copy
```
```
selector.parse($selector)
selector-parse($selector) //=> selector
```
Returns `$selector` in the [selector value](#selector-values) format.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
```
@debug selector.parse(".main aside:hover, .sidebar p");
// ((unquote(".main") unquote("aside:hover")),
// (unquote(".sidebar") unquote("p")))
```
```
@debug selector.parse(".main aside:hover, .sidebar p")
// ((unquote(".main") unquote("aside:hover")),
// (unquote(".sidebar") unquote("p")))
```
```
selector.replace($selector, $original, $replacement)
selector-replace($selector, $original, $replacement) //=> selector
```
Returns a copy of `$selector` with all instances of `$original` replaced by `$replacement`.
This uses the [`@extend` rule](../at-rules/extend)’s [intelligent unification](../at-rules/extend#how-it-works) to make sure `$replacement` is seamlessly integrated into `$selector`. If `$selector` doesn’t contain `$original`, returns it as-is.
The `$selector`, `$original`, and `$replacement` selectors may contain [placeholder selectors](../style-rules/placeholder-selectors), but not [parent selectors](../style-rules/parent-selector).
See also [`selector.extend()`](#extend).
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
```
@debug selector.replace("a.disabled", "a", ".link"); // .link.disabled
@debug selector.replace("a.disabled", "h1", "h2"); // a.disabled
@debug selector.replace(".guide .info", ".info", ".content nav.sidebar");
// .guide .content nav.sidebar, .content .guide nav.sidebar
```
```
@debug selector.replace("a.disabled", "a", ".link") // .link.disabled
@debug selector.replace("a.disabled", "h1", "h2") // a.disabled
@debug selector.replace(".guide .info", ".info", ".content nav.sidebar")
// .guide .content nav.sidebar, .content .guide nav.sidebar
```
```
selector.unify($selector1, $selector2)
selector-unify($selector1, $selector2) //=> selector | null
```
Returns a selector that matches only elements matched by *both* `$selector1` and `$selector2`.
Returns `null` if `$selector1` and `$selector2` don’t match any of the same elements, or if there’s no selector that can express their overlap.
Like selectors generated by the [`@extend` rule](../at-rules/extend#html-heuristics), the returned selector isn’t guaranteed to match *all* the elements matched by both `$selector1` and `$selector2` if they’re both complex selectors.
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
```
@debug selector.unify("a", ".disabled"); // a.disabled
@debug selector.unify("a.disabled", "a.outgoing"); // a.disabled.outgoing
@debug selector.unify("a", "h1"); // null
@debug selector.unify(".warning a", "main a"); // .warning main a, main .warning a
```
```
@debug selector.unify("a", ".disabled") // a.disabled
@debug selector.unify("a.disabled", "a.outgoing") // a.disabled.outgoing
@debug selector.unify("a", "h1") // null
@debug selector.unify(".warning a", "main a") // .warning main a, main .warning a
```
```
selector.simple-selectors($selector)
simple-selectors($selector) //=> list
```
Returns a list of simple selectors in `$selector`.
The `$selector` must be a single string that contains a compound selector. This means it may not contain combinators (including spaces) or commas.
The returned list is comma-separated, and the simple selectors are unquoted strings.
* [SCSS](#example-8-scss)
* [Sass](#example-8-sass)
```
@debug selector.simple-selectors("a.disabled"); // a, .disabled
@debug selector.simple-selectors("main.blog:after"); // main, .blog, :after
```
```
@debug selector.simple-selectors("a.disabled") // a, .disabled
@debug selector.simple-selectors("main.blog:after") // main, .blog, :after
```
sass sass:math sass:math
==========
Compatibility:
Dart Sass since 1.23.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass currently supports loading built-in modules with `@use`. Users of other implementations must call functions using their global names instead.
Variables
----------
```
math.$e
```
Compatibility:
Dart Sass since 1.25.0
LibSass ✗
Ruby Sass ✗ Equal to the value of the [mathematical constant *e*](https://en.wikipedia.org/wiki/E_(mathematical_constant)).
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@debug math.$e; // 2.7182818285
```
```
@debug math.$e // 2.7182818285
```
```
math.$pi
```
Compatibility:
Dart Sass since 1.25.0
LibSass ✗
Ruby Sass ✗ Equal to the value of the [mathematical constant *π*](https://en.wikipedia.org/wiki/Pi).
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
```
@debug math.$pi; // 3.1415926536
```
```
@debug math.$pi // 3.1415926536
```
Bounding Functions
-------------------
```
math.ceil($number)
ceil($number) //=> number
```
Rounds `$number` up to the next highest whole number.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
@debug math.ceil(4); // 4
@debug math.ceil(4.2); // 5
@debug math.ceil(4.9); // 5
```
```
@debug math.ceil(4) // 4
@debug math.ceil(4.2) // 5
@debug math.ceil(4.9) // 5
```
```
math.clamp($min, $number, $max) //=> number
```
Compatibility:
Dart Sass since 1.25.0
LibSass ✗
Ruby Sass ✗ Restricts `$number` to the range between `$min` and `$max`. If `$number` is less than `$min` this returns `$min`, and if it’s greater than `$max` this returns `$max`.
`$min`, `$number`, and `$max` must have compatible units, or all be unitless.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
```
@debug math.clamp(-1, 0, 1); // 0
@debug math.clamp(1px, -1px, 10px); // 1px
@debug math.clamp(-1in, 1cm, 10mm); // 10mm
```
```
@debug math.clamp(-1, 0, 1) // 0
@debug math.clamp(1px, -1px, 10px) // 1px
@debug math.clamp(-1in, 1cm, 10mm) // 10mm
```
```
math.floor($number)
floor($number) //=> number
```
Rounds `$number` down to the next lowest whole number.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
```
@debug math.floor(4); // 4
@debug math.floor(4.2); // 4
@debug math.floor(4.9); // 4
```
```
@debug math.floor(4) // 4
@debug math.floor(4.2) // 4
@debug math.floor(4.9) // 4
```
```
math.max($number...)
max($number...) //=> number
```
Returns the highest of one or more numbers.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
```
@debug math.max(1px, 4px); // 4px
$widths: 50px, 30px, 100px;
@debug math.max($widths...); // 100px
```
```
@debug math.max(1px, 4px) // 4px
$widths: 50px, 30px, 100px
@debug math.max($widths...) // 100px
```
```
math.min($number...)
min($number...) //=> number
```
Returns the lowest of one or more numbers.
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
```
@debug math.min(1px, 4px); // 1px
$widths: 50px, 30px, 100px;
@debug math.min($widths...); // 30px
```
```
@debug math.min(1px, 4px) // 1px
$widths: 50px, 30px, 100px
@debug math.min($widths...) // 30px
```
```
math.round($number)
round($number) //=> number
```
Rounds `$number` to the nearest whole number.
* [SCSS](#example-8-scss)
* [Sass](#example-8-sass)
```
@debug math.round(4); // 4
@debug math.round(4.2); // 4
@debug math.round(4.9); // 5
```
```
@debug math.round(4) // 4
@debug math.round(4.2) // 4
@debug math.round(4.9) // 5
```
Distance Functions
-------------------
```
math.abs($number)
abs($number) //=> number
```
Returns the [absolute value](https://en.wikipedia.org/wiki/Absolute_value) of `$number`. If `$number` is negative, this returns `-$number`, and if `$number` is positive, it returns `$number` as-is.
* [SCSS](#example-9-scss)
* [Sass](#example-9-sass)
```
@debug math.abs(10px); // 10px
@debug math.abs(-10px); // 10px
```
```
@debug math.abs(10px) // 10px
@debug math.abs(-10px) // 10px
```
```
math.hypot($number...) //=> number
```
Compatibility:
Dart Sass since 1.25.0
LibSass ✗
Ruby Sass ✗ Returns the length of the *n*-dimensional [vector](https://en.wikipedia.org/wiki/Euclidean_vector) that has components equal to each `$number`. For example, for three numbers *a*, *b*, and *c*, this returns the square root of *a² + b² + c²*.
The numbers must either all have compatible units, or all be unitless. And since the numbers’ units may differ, the output takes the unit of the first number.
* [SCSS](#example-10-scss)
* [Sass](#example-10-sass)
```
@debug math.hypot(3, 4); // 5
$lengths: 1in, 10cm, 50px;
@debug math.hypot($lengths...); // 4.0952775683in
```
```
@debug math.hypot(3, 4) // 5
$lengths: 1in, 10cm, 50px
@debug math.hypot($lengths...) // 4.0952775683in
```
Exponential Functions
----------------------
```
math.log($number, $base: null) //=> number
```
Compatibility:
Dart Sass since 1.25.0
LibSass ✗
Ruby Sass ✗ Returns the [logarithm](https://en.wikipedia.org/wiki/Logarithm) of `$number` with respect to `$base`. If `$base` is `null`, the [natural log](https://en.wikipedia.org/wiki/Natural_logarithm) is calculated.
`$number` and `$base` must be unitless.
* [SCSS](#example-11-scss)
* [Sass](#example-11-sass)
```
@debug math.log(10); // 2.302585093
@debug math.log(10, 10); // 1
```
```
@debug math.log(10) // 2.302585093
@debug math.log(10, 10) // 1
```
```
math.pow($base, $exponent) //=> number
```
Compatibility:
Dart Sass since 1.25.0
LibSass ✗
Ruby Sass ✗ Raises `$base` [to the power of](https://en.wikipedia.org/wiki/Exponentiation) `$exponent`.
`$base` and `$exponent` must be unitless.
* [SCSS](#example-12-scss)
* [Sass](#example-12-sass)
```
@debug math.pow(10, 2); // 100
@debug math.pow(100, math.div(1, 3)); // 4.6415888336
@debug math.pow(5, -2); // 0.04
```
```
@debug math.pow(10, 2) // 100
@debug math.pow(100, math.div(1, 3)) // 4.6415888336
@debug math.pow(5, -2) // 0.04
```
```
math.sqrt($number) //=> number
```
Compatibility:
Dart Sass since 1.25.0
LibSass ✗
Ruby Sass ✗ Returns the [square root](https://en.wikipedia.org/wiki/Square_root) of `$number`.
`$number` must be unitless.
* [SCSS](#example-13-scss)
* [Sass](#example-13-sass)
```
@debug math.sqrt(100); // 10
@debug math.sqrt(math.div(1, 3)); // 0.5773502692
@debug math.sqrt(-1); // NaN
```
```
@debug math.sqrt(100) // 10
@debug math.sqrt(math.div(1, 3)) // 0.5773502692
@debug math.sqrt(-1) // NaN
```
Trigonometric Functions
------------------------
```
math.cos($number) //=> number
```
Compatibility:
Dart Sass since 1.25.0
LibSass ✗
Ruby Sass ✗ Returns the [cosine](https://en.wikipedia.org/wiki/Trigonometric_functions#Right-angled_triangle_definitions) of `$number`.
`$number` must be an angle (its units must be compatible with `deg`) or unitless. If `$number` has no units, it is assumed to be in `rad`.
* [SCSS](#example-14-scss)
* [Sass](#example-14-sass)
```
@debug math.cos(100deg); // -0.1736481777
@debug math.cos(1rad); // 0.5403023059
@debug math.cos(1); // 0.5403023059
```
```
@debug math.cos(100deg) // -0.1736481777
@debug math.cos(1rad) // 0.5403023059
@debug math.cos(1) // 0.5403023059
```
```
math.sin($number) //=> number
```
Compatibility:
Dart Sass since 1.25.0
LibSass ✗
Ruby Sass ✗ Returns the [sine](https://en.wikipedia.org/wiki/Trigonometric_functions#Right-angled_triangle_definitions) of `$number`.
`$number` must be an angle (its units must be compatible with `deg`) or unitless. If `$number` has no units, it is assumed to be in `rad`.
* [SCSS](#example-15-scss)
* [Sass](#example-15-sass)
```
@debug math.sin(100deg); // 0.984807753
@debug math.sin(1rad); // 0.8414709848
@debug math.sin(1); // 0.8414709848
```
```
@debug math.sin(100deg) // 0.984807753
@debug math.sin(1rad) // 0.8414709848
@debug math.sin(1) // 0.8414709848
```
```
math.tan($number) //=> number
```
Compatibility:
Dart Sass since 1.25.0
LibSass ✗
Ruby Sass ✗ Returns the [tangent](https://en.wikipedia.org/wiki/Trigonometric_functions#Right-angled_triangle_definitions) of `$number`.
`$number` must be an angle (its units must be compatible with `deg`) or unitless. If `$number` has no units, it is assumed to be in `rad`.
* [SCSS](#example-16-scss)
* [Sass](#example-16-sass)
```
@debug math.tan(100deg); // -5.6712818196
@debug math.tan(1rad); // 1.5574077247
@debug math.tan(1); // 1.5574077247
```
```
@debug math.tan(100deg) // -5.6712818196
@debug math.tan(1rad) // 1.5574077247
@debug math.tan(1) // 1.5574077247
```
```
math.acos($number) //=> number
```
Compatibility:
Dart Sass since 1.25.0
LibSass ✗
Ruby Sass ✗ Returns the [arccosine](https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Basic_properties) of `$number` in `deg`.
`$number` must be unitless.
* [SCSS](#example-17-scss)
* [Sass](#example-17-sass)
```
@debug math.acos(0.5); // 60deg
@debug math.acos(2); // NaNdeg
```
```
@debug math.acos(0.5) // 60deg
@debug math.acos(2) // NaNdeg
```
```
math.asin($number) //=> number
```
Compatibility:
Dart Sass since 1.25.0
LibSass ✗
Ruby Sass ✗ Returns the [arcsine](https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Basic_properties) of `$number` in `deg`.
`$number` must be unitless.
* [SCSS](#example-18-scss)
* [Sass](#example-18-sass)
```
@debug math.asin(0.5); // 30deg
@debug math.asin(2); // NaNdeg
```
```
@debug math.asin(0.5) // 30deg
@debug math.asin(2) // NaNdeg
```
```
math.atan($number) //=> number
```
Compatibility:
Dart Sass since 1.25.0
LibSass ✗
Ruby Sass ✗ Returns the [arctangent](https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Basic_properties) of `$number` in `deg`.
`$number` must be unitless.
* [SCSS](#example-19-scss)
* [Sass](#example-19-sass)
```
@debug math.atan(10); // 84.2894068625deg
```
```
@debug math.atan(10) // 84.2894068625deg
```
```
math.atan2($y, $x) //=> number
```
Compatibility:
Dart Sass since 1.25.0
LibSass ✗
Ruby Sass ✗ Returns the [2-argument arctangent](https://en.wikipedia.org/wiki/Atan2) of `$y` and `$x` in `deg`.
`$y` and `$x` must have compatible units or be unitless.
### 💡 Fun fact:
`math.atan2($y, $x)` is distinct from `atan(math.div($y, $x))` because it preserves the quadrant of the point in question. For example, `math.atan2(1, -1)` corresponds to the point `(-1, 1)` and returns `135deg`. In contrast, `math.atan(math.div(1, -1))` and `math.atan(math.div(-1, 1))` resolve first to `atan(-1)`, so both return `-45deg`.
* [SCSS](#example-20-scss)
* [Sass](#example-20-sass)
```
@debug math.atan2(-1, 1); // 135deg
```
```
@debug math.atan2(-1, 1) // 135deg
```
Unit Functions
---------------
```
math.compatible($number1, $number2)
comparable($number1, $number2) //=> boolean
```
Returns whether `$number1` and `$number2` have compatible units.
If this returns `true`, `$number1` and `$number2` can safely be [added](../operators/numeric), [subtracted](../operators/numeric), and [compared](../operators/relational). Otherwise, doing so will produce errors.
### ⚠️ Heads up!
The global name of this function is `compa**ra**ble`, but when it was added to the `sass:math` module the name was changed to `compa**ti**ble` to more clearly convey what the function does.
* [SCSS](#example-21-scss)
* [Sass](#example-21-sass)
```
@debug math.compatible(2px, 1px); // true
@debug math.compatible(100px, 3em); // false
@debug math.compatible(10cm, 3mm); // true
```
```
@debug math.compatible(2px, 1px) // true
@debug math.compatible(100px, 3em) // false
@debug math.compatible(10cm, 3mm) // true
```
```
math.is-unitless($number)
unitless($number) //=> boolean
```
Returns whether `$number` has no units.
* [SCSS](#example-22-scss)
* [Sass](#example-22-sass)
```
@debug math.is-unitless(100); // true
@debug math.is-unitless(100px); // false
```
```
@debug math.is-unitless(100) // true
@debug math.is-unitless(100px) // false
```
```
math.unit($number)
unit($number) //=> quoted string
```
Returns a string representation of `$number`‘s units.
### ⚠️ Heads up!
This function is intended for debugging; its output format is not guaranteed to be consistent across Sass versions or implementations.
* [SCSS](#example-23-scss)
* [Sass](#example-23-sass)
```
@debug math.unit(100); // ""
@debug math.unit(100px); // "px"
@debug math.unit(5px * 10px); // "px*px"
@debug math.unit(math.div(5px, 1s)); // "px/s"
```
```
@debug math.unit(100) // ""
@debug math.unit(100px) // "px"
@debug math.unit(5px * 10px) // "px*px"
@debug math.unit(math.div(5px, 1s)) // "px/s"
```
Other Functions
----------------
```
math.div($number1, $number2) //=> number
```
Compatibility:
Dart Sass since 1.33.0
LibSass ✗
Ruby Sass ✗ Returns the result of dividing `$number1` by `$number2`.
Any units shared by both numbers will be canceled out. Units in `$number1` that aren’t in `$number2` will end up in the return value’s numerator, and units in `$number2` that aren’t in `$number1` will end up in its denominator.
### ⚠️ Heads up!
For backwards-compatibility purposes, this returns the *exact same result* as [the deprecated `/` operator](https://sass-lang.com/documentation/breaking-changes/slash-div), including concatenating two strings with a `/` character between them. However, this behavior will be removed eventually and shouldn’t be used in new stylesheets.
* [SCSS](#example-24-scss)
* [Sass](#example-24-sass)
```
@debug math.div(1, 2); // 0.5
@debug math.div(100px, 5px); // 20
@debug math.div(100px, 5); // 20px
@debug math.div(100px, 5s); // 20px/s
```
```
@debug math.div(1, 2) // 0.5
@debug math.div(100px, 5px) // 20
@debug math.div(100px, 5) // 20px
@debug math.div(100px, 5s) // 20px/s
```
```
math.percentage($number)
percentage($number) //=> number
```
Converts a unitless `$number` (usually a decimal between 0 and 1) to a percentage.
### 💡 Fun fact:
This function is identical to `$number * 100%`.
* [SCSS](#example-25-scss)
* [Sass](#example-25-sass)
```
@debug math.percentage(0.2); // 20%
@debug math.percentage(math.div(100px, 50px)); // 200%
```
```
@debug math.percentage(0.2) // 20%
@debug math.percentage(math.div(100px, 50px)) // 200%
```
```
math.random($limit: null)
random($limit: null) //=> number
```
If `$limit` is `null`, returns a random decimal number between 0 and 1.
* [SCSS](#example-26-scss)
* [Sass](#example-26-sass)
```
@debug math.random(); // 0.2821251858
@debug math.random(); // 0.6221325814
```
```
@debug math.random() // 0.2821251858
@debug math.random() // 0.6221325814
```
---
If `$limit` is a number greater than or equal to 1, returns a random whole number between 1 and `$limit`.
### ⚠️ Heads up!
`random()` ignores units in `$limit`. [This behavior is deprecated](https://sass-lang.com/documentation/breaking-changes/random-with-units) and `random($limit)` will return a random integer with the same units as the `$limit` argument.
* [SCSS](#example-27-scss)
* [Sass](#example-27-sass)
```
@debug math.random(100px); // 42
```
```
@debug math.random(100px) // 42
```
* [SCSS](#example-28-scss)
* [Sass](#example-28-sass)
```
@debug math.random(10); // 4
@debug math.random(10000); // 5373
```
```
@debug math.random(10) // 4
@debug math.random(10000) // 5373
```
| programming_docs |
sass sass:color sass:color
===========
Compatibility:
Dart Sass since 1.23.0
LibSass ✗
Ruby Sass ✗ [▶](javascript:;) Only Dart Sass currently supports loading built-in modules with `@use`. Users of other implementations must call functions using their global names instead.
```
color.adjust($color,
$red: null, $green: null, $blue: null,
$hue: null, $saturation: null, $lightness: null,
$whiteness: null, $blackness: null,
$alpha: null)
adjust-color(...) //=> color
```
Compatibility ($whiteness and $blackness):
Dart Sass since 1.28.0
LibSass ✗
Ruby Sass ✗ Increases or decreases one or more properties of `$color` by fixed amounts.
Adds the value passed for each keyword argument to the corresponding property of the color, and returns the adjusted color. It’s an error to specify an RGB property (`$red`, `$green`, and/or `$blue`) at the same time as an HSL property (`$hue`, `$saturation`, and/or `$lightness`), or either of those at the same time as an [HWB](https://en.wikipedia.org/wiki/HWB_color_model) property (`$hue`, `$whiteness`, and/or `$blackness`).
All optional arguments must be numbers. The `$red`, `$green`, and `$blue` arguments must be [unitless](../values/numbers#units) and between -255 and 255 (inclusive). The `$hue` argument must have either the unit `deg` or no unit. The `$saturation`, `$lightness`, `$whiteness`, and `$blackness` arguments must be between `-100%` and `100%` (inclusive), and may not be unitless. The `$alpha` argument must be unitless and between -1 and 1 (inclusive).
See also:
* [`color.scale()`](#scale) for fluidly scaling a color’s properties.
* [`color.change()`](#change) for setting a color’s properties.
* [SCSS](#example-1-scss)
* [Sass](#example-1-sass)
```
@debug color.adjust(#6b717f, $red: 15); // #7a717f
@debug color.adjust(#d2e1dd, $red: -10, $blue: 10); // #c8e1e7
@debug color.adjust(#998099, $lightness: -30%, $alpha: -0.4); // rgba(71, 57, 71, 0.6)
```
```
@debug color.adjust(#6b717f, $red: 15) // #7a717f
@debug color.adjust(#d2e1dd, $red: -10, $blue: 10) // #c8e1e7
@debug color.adjust(#998099, $lightness: -30%, $alpha: -0.4) // rgba(71, 57, 71, 0.6)
```
```
adjust-hue($color, $degrees) //=> color
```
Increases or decreases `$color`‘s hue.
The `$hue` must be a number between `-360deg` and `360deg` (inclusive) to add to `$color`’s hue. It may be [unitless](../values/numbers#units) but it may not have any unit other than `deg`.
See also [`color.adjust()`](#adjust), which can adjust any property of a color.
### ⚠️ Heads up!
Because `adjust-hue()` is redundant with [`adjust()`](#adjust), it’s not included directly in the new module system. Instead of `adjust-hue($color, $amount)`, you can write [`color.adjust($color, $hue: $amount)`](#adjust).
* [SCSS](#example-2-scss)
* [Sass](#example-2-sass)
```
// Hue 222deg becomes 282deg.
@debug adjust-hue(#6b717f, 60deg); // #796b7f
// Hue 164deg becomes 104deg.
@debug adjust-hue(#d2e1dd, -60deg); // #d6e1d2
// Hue 210deg becomes 255deg.
@debug adjust-hue(#036, 45); // #1a0066
```
```
// Hue 222deg becomes 282deg.
@debug adjust-hue(#6b717f, 60deg) // #796b7f
// Hue 164deg becomes 104deg.
@debug adjust-hue(#d2e1dd, -60deg) // #d6e1d2
// Hue 210deg becomes 255deg.
@debug adjust-hue(#036, 45) // #1a0066
```
```
color.alpha($color)
alpha($color)
opacity($color) //=> number
```
Returns the alpha channel of `$color` as a number between 0 and 1.
As a special case, this supports the Internet Explorer syntax `alpha(opacity=20)`, for which it returns an [unquoted string](../values/strings#unquoted).
See also:
* [`color.red()`](#red) for getting a color’s red channel.
* [`color.green()`](#green) for getting a color’s green channel.
* [`color.blue()`](#blue) for getting a color’s blue channel.
* [`color.hue()`](#hue) for getting a color’s hue.
* [`color.saturation()`](#saturation) for getting a color’s saturation.
* [`color.lightness()`](#lightness) for getting a color’s lightness.
* [SCSS](#example-3-scss)
* [Sass](#example-3-sass)
```
@debug color.alpha(#e1d7d2); // 1
@debug color.opacity(rgb(210, 225, 221, 0.4)); // 0.4
@debug alpha(opacity=20); // alpha(opacity=20)
```
```
@debug color.alpha(#e1d7d2) // 1
@debug color.opacity(rgb(210, 225, 221, 0.4)) // 0.4
@debug alpha(opacity=20) // alpha(opacity=20)
```
```
color.blackness($color) //=> number
```
Compatibility:
Dart Sass since 1.28.0
LibSass ✗
Ruby Sass ✗ Returns the [HWB](https://en.wikipedia.org/wiki/HWB_color_model) blackness of `$color` as a number between `0%` and `100%`.
See also:
* [`color.red()`](#red) for getting a color’s red channel.
* [`color.green()`](#green) for getting a color’s green channel.
* [`color.hue()`](#hue) for getting a color’s hue.
* [`color.saturation()`](#saturation) for getting a color’s saturation.
* [`color.lightness()`](#lightness) for getting a color’s lightness.
* [`color.whiteness()`](#whiteness) for getting a color’s whiteness.
* [`color.alpha()`](#alpha) for getting a color’s alpha channel.
* [SCSS](#example-4-scss)
* [Sass](#example-4-sass)
```
@debug color.blackness(#e1d7d2); // 11.7647058824%
@debug color.blackness(white); // 0%
@debug color.blackness(black); // 100%
```
```
@debug color.blackness(#e1d7d2) // 11.7647058824%
@debug color.blackness(white) // 0%
@debug color.blackness(black) // 100%
```
```
color.blue($color)
blue($color) //=> number
```
Returns the blue channel of `$color` as a number between 0 and 255.
See also:
* [`color.red()`](#red) for getting a color’s red channel.
* [`color.green()`](#green) for getting a color’s green channel.
* [`color.hue()`](#hue) for getting a color’s hue.
* [`color.saturation()`](#saturation) for getting a color’s saturation.
* [`color.lightness()`](#lightness) for getting a color’s lightness.
* [`color.whiteness()`](#whiteness) for getting a color’s whiteness.
* [`color.blackness()`](#blackness) for getting a color’s blackness.
* [`color.alpha()`](#alpha) for getting a color’s alpha channel.
* [SCSS](#example-5-scss)
* [Sass](#example-5-sass)
```
@debug color.blue(#e1d7d2); // 210
@debug color.blue(white); // 255
@debug color.blue(black); // 0
```
```
@debug color.blue(#e1d7d2) // 210
@debug color.blue(white) // 255
@debug color.blue(black) // 0
```
```
color.change($color,
$red: null, $green: null, $blue: null,
$hue: null, $saturation: null, $lightness: null,
$whiteness: null, $blackness: null,
$alpha: null)
change-color(...) //=> color
```
Compatibility ($whiteness and $blackness):
Dart Sass since 1.28.0
LibSass ✗
Ruby Sass ✗ Sets one or more properties of a color to new values.
Uses the value passed for each keyword argument in place of the corresponding property of the color, and returns the changed color. It’s an error to specify an RGB property (`$red`, `$green`, and/or `$blue`) at the same time as an HSL property (`$hue`, `$saturation`, and/or `$lightness`), or either of those at the same time as an [HWB](https://en.wikipedia.org/wiki/HWB_color_model) property (`$hue`, `$whiteness`, and/or `$blackness`).
All optional arguments must be numbers. The `$red`, `$green`, and `$blue` arguments must be [unitless](../values/numbers#units) and between 0 and 255 (inclusive). The `$hue` argument must have either the unit `deg` or no unit. The `$saturation`, `$lightness`, `$whiteness`, and `$blackness` arguments must be between `0%` and `100%` (inclusive), and may not be unitless. The `$alpha` argument must be unitless and between 0 and 1 (inclusive).
See also:
* [`color.scale()`](#scale) for fluidly scaling a color’s properties.
* [`color.adjust()`](#adjust) for adjusting a color’s properties by fixed amounts.
* [SCSS](#example-6-scss)
* [Sass](#example-6-sass)
```
@debug color.change(#6b717f, $red: 100); // #64717f
@debug color.change(#d2e1dd, $red: 100, $blue: 50); // #64e132
@debug color.change(#998099, $lightness: 30%, $alpha: 0.5); // rgba(85, 68, 85, 0.5)
```
```
@debug color.change(#6b717f, $red: 100) // #64717f
@debug color.change(#d2e1dd, $red: 100, $blue: 50) // #64e132
@debug color.change(#998099, $lightness: 30%, $alpha: 0.5) // rgba(85, 68, 85, 0.5)
```
```
color.complement($color)
complement($color) //=> color
```
Returns the RGB [complement](https://en.wikipedia.org/wiki/Complementary_colors) of `$color`.
This is identical to [`color.adjust($color, $hue: 180deg)`](#adjust).
* [SCSS](#example-7-scss)
* [Sass](#example-7-sass)
```
// Hue 222deg becomes 42deg.
@debug color.complement(#6b717f); // #7f796b
// Hue 164deg becomes 344deg.
@debug color.complement(#d2e1dd); // #e1d2d6
// Hue 210deg becomes 30deg.
@debug color.complement(#036); // #663300
```
```
// Hue 222deg becomes 42deg.
@debug color.complement(#6b717f) // #7f796b
// Hue 164deg becomes 344deg.
@debug color.complement(#d2e1dd) // #e1d2d6
// Hue 210deg becomes 30deg.
@debug color.complement(#036) // #663300
```
```
darken($color, $amount) //=> color
```
Makes `$color` darker.
The `$amount` must be a number between `0%` and `100%` (inclusive). Decreases the HSL lightness of `$color` by that amount.
### ⚠️ Heads up!
The `darken()` function decreases lightness by a fixed amount, which is often not the desired effect. To make a color a certain percentage darker than it was before, use [`color.scale()`](#scale) instead.
Because `darken()` is usually not the best way to make a color darker, it’s not included directly in the new module system. However, if you have to preserve the existing behavior, `darken($color, $amount)` can be written [`color.adjust($color, $lightness: -$amount)`](#adjust).
* [SCSS](#example-8-scss)
* [Sass](#example-8-sass)
```
// #036 has lightness 20%, so when darken() subtracts 30% it just returns black.
@debug darken(#036, 30%); // black
// scale() instead makes it 30% darker than it was originally.
@debug color.scale(#036, $lightness: -30%); // #002447
```
```
// #036 has lightness 20%, so when darken() subtracts 30% it just returns black.
@debug darken(#036, 30%) // black
// scale() instead makes it 30% darker than it was originally.
@debug color.scale(#036, $lightness: -30%) // #002447
```
* [SCSS](#example-9-scss)
* [Sass](#example-9-sass)
```
// Lightness 92% becomes 72%.
@debug darken(#b37399, 20%); // #7c4465
// Lightness 85% becomes 45%.
@debug darken(#f2ece4, 40%); // #b08b5a
// Lightness 20% becomes 0%.
@debug darken(#036, 30%); // black
```
```
// Lightness 92% becomes 72%.
@debug darken(#b37399, 20%) // #7c4465
// Lightness 85% becomes 45%.
@debug darken(#f2ece4, 40%) // #b08b5a
// Lightness 20% becomes 0%.
@debug darken(#036, 30%) // black
```
```
desaturate($color, $amount) //=> color
```
Makes `$color` less saturated.
The `$amount` must be a number between `0%` and `100%` (inclusive). Decreases the HSL saturation of `$color` by that amount.
### ⚠️ Heads up!
The `desaturate()` function decreases saturation by a fixed amount, which is often not the desired effect. To make a color a certain percentage less saturated than it was before, use [`color.scale()`](#scale) instead.
Because `desaturate()` is usually not the best way to make a color less saturated, it’s not included directly in the new module system. However, if you have to preserve the existing behavior, `desaturate($color, $amount)` can be written [`color.adjust($color, $saturation: -$amount)`](#adjust).
* [SCSS](#example-10-scss)
* [Sass](#example-10-sass)
```
// #d2e1dd has saturation 20%, so when desaturate() subtracts 30% it just
// returns gray.
@debug desaturate(#d2e1dd, 30%); // #dadada
// scale() instead makes it 30% less saturated than it was originally.
@debug color.scale(#6b717f, $saturation: -30%); // #6e727c
```
```
// #6b717f has saturation 20%, so when desaturate() subtracts 30% it just
// returns gray.
@debug desaturate(#d2e1dd, 30%) // #dadada
// scale() instead makes it 30% less saturated than it was originally.
@debug color.scale(#6b717f, $saturation: -30%) // #6e727c
```
* [SCSS](#example-11-scss)
* [Sass](#example-11-sass)
```
// Saturation 100% becomes 80%.
@debug desaturate(#036, 20%); // #0a335c
// Saturation 35% becomes 15%.
@debug desaturate(#f2ece4, 20%); // #eeebe8
// Saturation 20% becomes 0%.
@debug desaturate(#d2e1dd, 30%); // #dadada
```
```
// Saturation 100% becomes 80%.
@debug desaturate(#036, 20%) // #0a335c
// Saturation 35% becomes 15%.
@debug desaturate(#f2ece4, 20%) // #eeebe8
// Saturation 20% becomes 0%.
@debug desaturate(#d2e1dd, 30%) // #dadada
```
```
color.grayscale($color)
grayscale($color) //=> color
```
Returns a gray color with the same lightness as `$color`.
This is identical to [`color.change($color, $saturation: 0%)`](#change).
* [SCSS](#example-12-scss)
* [Sass](#example-12-sass)
```
@debug color.grayscale(#6b717f); // #757575
@debug color.grayscale(#d2e1dd); // #dadada
@debug color.grayscale(#036); // #333333
```
```
@debug color.grayscale(#6b717f) // #757575
@debug color.grayscale(#d2e1dd) // #dadada
@debug color.grayscale(#036) // #333333
```
```
color.green($color)
green($color) //=> number
```
Returns the green channel of `$color` as a number between 0 and 255.
See also:
* [`color.red()`](#red) for getting a color’s red channel.
* [`color.blue()`](#blue) for getting a color’s blue channel.
* [`color.hue()`](#hue) for getting a color’s hue.
* [`color.saturation()`](#saturation) for getting a color’s saturation.
* [`color.lightness()`](#lightness) for getting a color’s lightness.
* [`color.whiteness()`](#whiteness) for getting a color’s whiteness.
* [`color.blackness()`](#blackness) for getting a color’s blackness.
* [`color.alpha()`](#alpha) for getting a color’s alpha channel.
* [SCSS](#example-13-scss)
* [Sass](#example-13-sass)
```
@debug color.green(#e1d7d2); // 215
@debug color.green(white); // 255
@debug color.green(black); // 0
```
```
@debug color.green(#e1d7d2) // 215
@debug color.green(white) // 255
@debug color.green(black) // 0
```
```
color.hue($color)
hue($color) //=> number
```
Returns the hue of `$color` as a number between `0deg` and `360deg`.
See also:
* [`color.red()`](#red) for getting a color’s red channel.
* [`color.green()`](#green) for getting a color’s green channel.
* [`color.blue()`](#blue) for getting a color’s blue channel.
* [`color.saturation()`](#saturation) for getting a color’s saturation.
* [`color.lightness()`](#lightness) for getting a color’s lightness.
* [`color.whiteness()`](#whiteness) for getting a color’s whiteness.
* [`color.blackness()`](#blackness) for getting a color’s blackness.
* [`color.alpha()`](#alpha) for getting a color’s alpha channel.
* [SCSS](#example-14-scss)
* [Sass](#example-14-sass)
```
@debug color.hue(#e1d7d2); // 20deg
@debug color.hue(#f2ece4); // 34.2857142857deg
@debug color.hue(#dadbdf); // 228deg
```
```
@debug color.hue(#e1d7d2) // 20deg
@debug color.hue(#f2ece4) // 34.2857142857deg
@debug color.hue(#dadbdf) // 228deg
```
```
color.hwb($hue $whiteness $blackness)
color.hwb($hue $whiteness $blackness / $alpha)
color.hwb($hue, $whiteness, $blackness, $alpha: 1) //=> color
```
Compatibility:
Dart Sass since 1.28.0
LibSass ✗
Ruby Sass ✗ Returns a color with the given [hue, whiteness, and blackness](https://en.wikipedia.org/wiki/HWB_color_model) and the given alpha channel.
The hue is a number between `0deg` and `360deg` (inclusive). The whiteness and blackness are numbers between `0%` and `100%` (inclusive). The hue may be [unitless](../values/numbers#units), but the whiteness and blackness must have unit `%`. The alpha channel can be specified as either a unitless number between 0 and 1 (inclusive), or a percentage between `0%` and `100%` (inclusive).
### ⚠️ Heads up!
Sass’s [special parsing rules](../operators/numeric#slash-separated-values) for slash-separated values make it difficult to pass variables for `$blackness` or `$alpha` when using the `color.hwb($hue $whiteness $blackness / $alpha)` signature. Consider using `color.hwb($hue, $whiteness, $blackness, $alpha)` instead.
* [SCSS](#example-15-scss)
* [Sass](#example-15-sass)
```
@debug color.hwb(210, 0%, 60%); // #036
@debug color.hwb(34, 89%, 5%); // #f2ece4
@debug color.hwb(210 0% 60% / 0.5); // rgba(0, 51, 102, 0.5)
```
```
@debug color.hwb(210, 0%, 60%) // #036
@debug color.hwb(34, 89%, 5%) // #f2ece4
@debug color.hwb(210 0% 60% / 0.5) // rgba(0, 51, 102, 0.5)
```
```
color.ie-hex-str($color)
ie-hex-str($color) //=> unquoted string
```
Returns an unquoted string that represents `$color` in the `#AARRGGBB` format expected by Internet Explorer’s [`-ms-filter`](https://developer.mozilla.org/en-US/docs/Web/CSS/-ms-filter) property.
* [SCSS](#example-16-scss)
* [Sass](#example-16-sass)
```
@debug color.ie-hex-str(#b37399); // #FFB37399
@debug color.ie-hex-str(#808c99); // #FF808C99
@debug color.ie-hex-str(rgba(242, 236, 228, 0.6)); // #99F2ECE4
```
```
@debug color.ie-hex-str(#b37399); // #FFB37399
@debug color.ie-hex-str(#808c99); // #FF808C99
@debug color.ie-hex-str(rgba(242, 236, 228, 0.6)); // #99F2ECE4
```
```
color.invert($color, $weight: 100%)
invert($color, $weight: 100%) //=> color
```
Returns the inverse or [negative](https://en.wikipedia.org/wiki/Negative_(photography)) of `$color`.
The `$weight` must be a number between `0%` and `100%` (inclusive). A higher weight means the result will be closer to the negative, and a lower weight means it will be closer to `$color`. Weight `50%` will always produce `#808080`.
* [SCSS](#example-17-scss)
* [Sass](#example-17-sass)
```
@debug color.invert(#b37399); // #4c8c66
@debug color.invert(black); // white
@debug color.invert(#550e0c, 20%); // #663b3a
```
```
@debug color.invert(#b37399) // #4c8c66
@debug color.invert(black) // white
@debug color.invert(#550e0c, 20%) // #663b3a
```
```
lighten($color, $amount) //=> color
```
Makes `$color` lighter.
The `$amount` must be a number between `0%` and `100%` (inclusive). Increases the HSL lightness of `$color` by that amount.
### ⚠️ Heads up!
The `lighten()` function increases lightness by a fixed amount, which is often not the desired effect. To make a color a certain percentage lighter than it was before, use [`scale()`](#scale) instead.
Because `lighten()` is usually not the best way to make a color lighter, it’s not included directly in the new module system. However, if you have to preserve the existing behavior, `lighten($color, $amount)` can be written [`adjust($color, $lightness: $amount)`](#adjust).
* [SCSS](#example-18-scss)
* [Sass](#example-18-sass)
```
// #e1d7d2 has lightness 85%, so when lighten() adds 30% it just returns white.
@debug lighten(#e1d7d2, 30%); // white
// scale() instead makes it 30% lighter than it was originally.
@debug color.scale(#e1d7d2, $lightness: 30%); // #eae3e0
```
```
// #e1d7d2 has lightness 85%, so when lighten() adds 30% it just returns white.
@debug lighten(#e1d7d2, 30%) // white
// scale() instead makes it 30% lighter than it was originally.
@debug color.scale(#e1d7d2, $lightness: 30%) // #eae3e0
```
* [SCSS](#example-19-scss)
* [Sass](#example-19-sass)
```
// Lightness 46% becomes 66%.
@debug lighten(#6b717f, 20%); // #a1a5af
// Lightness 20% becomes 80%.
@debug lighten(#036, 60%); // #99ccff
// Lightness 85% becomes 100%.
@debug lighten(#e1d7d2, 30%); // white
```
```
// Lightness 46% becomes 66%.
@debug lighten(#6b717f, 20%) // #a1a5af
// Lightness 20% becomes 80%.
@debug lighten(#036, 60%) // #99ccff
// Lightness 85% becomes 100%.
@debug lighten(#e1d7d2, 30%) // white
```
```
color.lightness($color)
lightness($color) //=> number
```
Returns the HSL lightness of `$color` as a number between `0%` and `100%`.
See also:
* [`color.red()`](#red) for getting a color’s red channel.
* [`color.green()`](#green) for getting a color’s green channel.
* [`color.blue()`](#blue) for getting a color’s blue channel.
* [`color.hue()`](#hue) for getting a color’s hue.
* [`color.saturation()`](#saturation) for getting a color’s saturation.
* [`color.whiteness()`](#whiteness) for getting a color’s whiteness.
* [`color.blackness()`](#blackness) for getting a color’s blackness.
* [`color.alpha()`](#alpha) for getting a color’s alpha channel.
* [SCSS](#example-20-scss)
* [Sass](#example-20-sass)
```
@debug color.lightness(#e1d7d2); // 85.2941176471%
@debug color.lightness(#f2ece4); // 92.1568627451%
@debug color.lightness(#dadbdf); // 86.4705882353%
```
```
@debug color.lightness(#e1d7d2) // 85.2941176471%
@debug color.lightness(#f2ece4) // 92.1568627451%
@debug color.lightness(#dadbdf) // 86.4705882353%
```
```
color.mix($color1, $color2, $weight: 50%)
mix($color1, $color2, $weight: 50%) //=> color
```
Returns a color that’s a mixture of `$color1` and `$color2`.
Both the `$weight` and the relative opacity of each color determines how much of each color is in the result. The `$weight` must be a number between `0%` and `100%` (inclusive). A larger weight indicates that more of `$color1` should be used, and a smaller weight indicates that more of `$color2` should be used.
* [SCSS](#example-21-scss)
* [Sass](#example-21-sass)
```
@debug color.mix(#036, #d2e1dd); // #698aa2
@debug color.mix(#036, #d2e1dd, 75%); // #355f84
@debug color.mix(#036, #d2e1dd, 25%); // #9eb6bf
@debug color.mix(rgba(242, 236, 228, 0.5), #6b717f); // rgba(141, 144, 152, 0.75)
```
```
@debug color.mix(#036, #d2e1dd) // #698aa2
@debug color.mix(#036, #d2e1dd, 75%) // #355f84
@debug color.mix(#036, #d2e1dd, 25%) // #9eb6bf
@debug color.mix(rgba(242, 236, 228, 0.5), #6b717f) // rgba(141, 144, 152, 0.75)
```
```
opacify($color, $amount)
fade-in($color, $amount) //=> color
```
Makes `$color` more opaque.
The `$amount` must be a number between `0` and `1` (inclusive). Increases the alpha channel of `$color` by that amount.
### ⚠️ Heads up!
The `opacify()` function increases the alpha channel by a fixed amount, which is often not the desired effect. To make a color a certain percentage more opaque than it was before, use [`scale()`](#scale) instead.
Because `opacify()` is usually not the best way to make a color more opaque, it’s not included directly in the new module system. However, if you have to preserve the existing behavior, `opacify($color, $amount)` can be written [`adjust($color, $alpha: -$amount)`](#adjust).
* [SCSS](#example-22-scss)
* [Sass](#example-22-sass)
```
// rgba(#036, 0.7) has alpha 0.7, so when opacify() adds 0.3 it returns a fully
// opaque color.
@debug opacify(rgba(#036, 0.7), 0.3); // #036
// scale() instead makes it 30% more opaque than it was originally.
@debug color.scale(rgba(#036, 0.7), $alpha: 30%); // rgba(0, 51, 102, 0.79)
```
```
// rgba(#036, 0.7) has alpha 0.7, so when opacify() adds 0.3 it returns a fully
// opaque color.
@debug opacify(rgba(#036, 0.7), 0.3) // #036
// scale() instead makes it 30% more opaque than it was originally.
@debug color.scale(rgba(#036, 0.7), $alpha: 30%) // rgba(0, 51, 102, 0.79)
```
* [SCSS](#example-23-scss)
* [Sass](#example-23-sass)
```
@debug opacify(rgba(#6b717f, 0.5), 0.2); // rgba(107, 113, 127, 0.7)
@debug fade-in(rgba(#e1d7d2, 0.5), 0.4); // rgba(225, 215, 210, 0.9)
@debug opacify(rgba(#036, 0.7), 0.3); // #036
```
```
@debug opacify(rgba(#6b717f, 0.5), 0.2) // rgba(107, 113, 127, 0.7)
@debug fade-in(rgba(#e1d7d2, 0.5), 0.4) // rgba(225, 215, 210, 0.9)
@debug opacify(rgba(#036, 0.7), 0.3) // #036
```
```
color.red($color)
red($color) //=> number
```
Returns the red channel of `$color` as a number between 0 and 255.
See also:
* [`color.green()`](#green) for getting a color’s green channel.
* [`color.blue()`](#blue) for getting a color’s blue channel.
* [`color.hue()`](#hue) for getting a color’s hue.
* [`color.saturation()`](#saturation) for getting a color’s saturation.
* [`color.lightness()`](#lightness) for getting a color’s lightness.
* [`color.whiteness()`](#whiteness) for getting a color’s whiteness.
* [`color.blackness()`](#blackness) for getting a color’s blackness.
* [`color.alpha()`](#alpha) for getting a color’s alpha channel.
* [SCSS](#example-24-scss)
* [Sass](#example-24-sass)
```
@debug color.red(#e1d7d2); // 225
@debug color.red(white); // 255
@debug color.red(black); // 0
```
```
@debug color.red(#e1d7d2) // 225
@debug color.red(white) // 255
@debug color.red(black) // 0
```
```
saturate($color, $amount)
saturate($color, $amount) //=> color
```
Makes `$color` more saturated.
The `$amount` must be a number between `0%` and `100%` (inclusive). Increases the HSL saturation of `$color` by that amount.
### ⚠️ Heads up!
The `saturate()` function increases saturation by a fixed amount, which is often not the desired effect. To make a color a certain percentage more saturated than it was before, use [`scale()`](#scale) instead.
Because `saturate()` is usually not the best way to make a color more saturated, it’s not included directly in the new module system. However, if you have to preserve the existing behavior, `saturate($color, $amount)` can be written [`adjust($color, $saturation: $amount)`](#adjust).
* [SCSS](#example-25-scss)
* [Sass](#example-25-sass)
```
// #0e4982 has saturation 80%, so when saturate() adds 30% it just becomes
// fully saturated.
@debug saturate(#0e4982, 30%); // #004990
// scale() instead makes it 30% more saturated than it was originally.
@debug color.scale(#0e4982, $saturation: 30%); // #0a4986
```
```
// #0e4982 has saturation 80%, so when saturate() adds 30% it just becomes
// fully saturated.
@debug saturate(#0e4982, 30%) // #004990
// scale() instead makes it 30% more saturated than it was originally.
@debug color.scale(#0e4982, $saturation: 30%) // #0a4986
```
* [SCSS](#example-26-scss)
* [Sass](#example-26-sass)
```
// Saturation 50% becomes 70%.
@debug saturate(#c69, 20%); // #e05299
// Saturation 35% becomes 85%.
@debug desaturate(#f2ece4, 50%); // #ebebeb
// Saturation 80% becomes 100%.
@debug saturate(#0e4982, 30%) // #004990
```
```
// Saturation 50% becomes 70%.
@debug saturate(#c69, 20%); // #e05299
// Saturation 35% becomes 85%.
@debug desaturate(#f2ece4, 50%); // #ebebeb
// Saturation 80% becomes 100%.
@debug saturate(#0e4982, 30%) // #004990
```
```
color.saturation($color)
saturation($color) //=> number
```
Returns the HSL saturation of `$color` as a number between `0%` and `100%`.
See also:
* [`color.red()`](#red) for getting a color’s red channel.
* [`color.green()`](#green) for getting a color’s green channel.
* [`color.blue()`](#blue) for getting a color’s blue channel.
* [`color.hue()`](#hue) for getting a color’s hue.
* [`color.lightness()`](#lightness) for getting a color’s lightness.
* [`color.whiteness()`](#whiteness) for getting a color’s whiteness.
* [`color.blackness()`](#blackness) for getting a color’s blackness.
* [`color.alpha()`](#alpha) for getting a color’s alpha channel.
* [SCSS](#example-27-scss)
* [Sass](#example-27-sass)
```
@debug color.saturation(#e1d7d2); // 20%
@debug color.saturation(#f2ece4); // 30%
@debug color.saturation(#dadbdf); // 7.2463768116%
```
```
@debug color.saturation(#e1d7d2) // 20%
@debug color.saturation(#f2ece4) // 30%
@debug color.saturation(#dadbdf) // 7.2463768116%
```
```
color.scale($color,
$red: null, $green: null, $blue: null,
$saturation: null, $lightness: null,
$whiteness: null, $blackness: null,
$alpha: null)
scale-color(...) //=> color
```
Compatibility ($whiteness and $blackness):
Dart Sass since 1.28.0
LibSass ✗
Ruby Sass ✗ Fluidly scales one or more properties of `$color`.
Each keyword argument must be a number between `-100%` and `100%` (inclusive). This indicates how far the corresponding property should be moved from its original position towards the maximum (if the argument is positive) or the minimum (if the argument is negative). This means that, for example, `$lightness: 50%` will make all colors `50%` closer to maximum lightness without making them fully white.
It’s an error to specify an RGB property (`$red`, `$green`, and/or `$blue`) at the same time as an HSL property (`$saturation`, and/or `$lightness`), or either of those at the same time as an [HWB](https://en.wikipedia.org/wiki/HWB_color_model) property (`$whiteness`, and/or `$blackness`).
See also:
* [`color.adjust()`](#adjust) for changing a color’s properties by fixed amounts.
* [`color.change()`](#change) for setting a color’s properties.
* [SCSS](#example-28-scss)
* [Sass](#example-28-sass)
```
@debug color.scale(#6b717f, $red: 15%); // #81717f
@debug color.scale(#d2e1dd, $lightness: -10%, $saturation: 10%); // #b3d4cb
@debug color.scale(#998099, $alpha: -40%); // rgba(153, 128, 153, 0.6)
```
```
@debug color.scale(#6b717f, $red: 15%) // #81717f
@debug color.scale(#d2e1dd, $lightness: -10%, $saturation: 10%) // #b3d4cb
@debug color.scale(#998099, $alpha: -40%) // rgba(153, 128, 153, 0.6)
```
```
transparentize($color, $amount)
fade-out($color, $amount) //=> color
```
Makes `$color` more transparent.
The `$amount` must be a number between `0` and `1` (inclusive). Decreases the alpha channel of `$color` by that amount.
### ⚠️ Heads up!
The `transparentize()` function decreases the alpha channel by a fixed amount, which is often not the desired effect. To make a color a certain percentage more transparent than it was before, use [`color.scale()`](#scale) instead.
Because `transparentize()` is usually not the best way to make a color more transparent, it’s not included directly in the new module system. However, if you have to preserve the existing behavior, `transparentize($color, $amount)` can be written [`color.adjust($color, $alpha: -$amount)`](#adjust).
* [SCSS](#example-29-scss)
* [Sass](#example-29-sass)
```
// rgba(#036, 0.3) has alpha 0.3, so when transparentize() subtracts 0.3 it
// returns a fully transparent color.
@debug transparentize(rgba(#036, 0.3), 0.3); // rgba(0, 51, 102, 0)
// scale() instead makes it 30% more transparent than it was originally.
@debug color.scale(rgba(#036, 0.3), $alpha: -30%); // rgba(0, 51, 102, 0.21)
```
```
// rgba(#036, 0.3) has alpha 0.3, so when transparentize() subtracts 0.3 it
// returns a fully transparent color.
@debug transparentize(rgba(#036, 0.3), 0.3) // rgba(0, 51, 102, 0)
// scale() instead makes it 30% more transparent than it was originally.
@debug color.scale(rgba(#036, 0.3), $alpha: -30%) // rgba(0, 51, 102, 0.21)
```
* [SCSS](#example-30-scss)
* [Sass](#example-30-sass)
```
@debug transparentize(rgba(#6b717f, 0.5), 0.2) // rgba(107, 113, 127, 0.3)
@debug fade-out(rgba(#e1d7d2, 0.5), 0.4) // rgba(225, 215, 210, 0.1)
@debug transparentize(rgba(#036, 0.3), 0.3) // rgba(0, 51, 102, 0)
```
```
@debug transparentize(rgba(#6b717f, 0.5), 0.2) // rgba(107, 113, 127, 0.3)
@debug fade-out(rgba(#e1d7d2, 0.5), 0.4) // rgba(225, 215, 210, 0.1)
@debug transparentize(rgba(#036, 0.3), 0.3) // rgba(0, 51, 102, 0)
```
```
color.whiteness($color) //=> number
```
Compatibility:
Dart Sass since 1.28.0
LibSass ✗
Ruby Sass ✗ Returns the [HWB](https://en.wikipedia.org/wiki/HWB_color_model) whiteness of `$color` as a number between `0%` and `100%`.
See also:
* [`color.red()`](#red) for getting a color’s red channel.
* [`color.green()`](#green) for getting a color’s green channel.
* [`color.hue()`](#hue) for getting a color’s hue.
* [`color.saturation()`](#saturation) for getting a color’s saturation.
* [`color.lightness()`](#lightness) for getting a color’s lightness.
* [`color.blackness()`](#blackness) for getting a color’s blackness.
* [`color.alpha()`](#alpha) for getting a color’s alpha channel.
* [SCSS](#example-31-scss)
* [Sass](#example-31-sass)
```
@debug color.whiteness(#e1d7d2); // 82.3529411765%
@debug color.whiteness(white); // 100%
@debug color.whiteness(black); // 0%
```
```
@debug color.whiteness(#e1d7d2) // 82.3529411765%
@debug color.whiteness(white) // 100%
@debug color.whiteness(black) // 0%
```
| programming_docs |
sanctuary Sanctuary v3.1.0
Sanctuary v3.1.0
================
Refuge from unsafe JavaScript
* [Overview](#section:overview)
* [Sponsors](#section:sponsors)
* [Folktale](#section:folktale)
* [Ramda](#section:ramda)
+ [Totality](#section:totality)
+ [Information preservation](#section:information-preservation)
+ [Invariants](#section:invariants)
+ [Currying](#section:currying)
+ [Variadic functions](#section:variadic-functions)
+ [Implicit context](#section:implicit-context)
+ [Transducers](#section:transducers)
+ [Modularity](#section:modularity)
* [Types](#section:types)
* [Type checking](#section:type-checking)
* [Installation](#section:installation)
* [API](#section:api)
Overview
--------
Sanctuary is a JavaScript functional programming library inspired by [Haskell](https://www.haskell.org/) and [PureScript](http://www.purescript.org/). It's stricter than [Ramda](https://ramdajs.com/), and provides a similar suite of functions.
Sanctuary promotes programs composed of simple, pure functions. Such programs are easier to comprehend, test, and maintain – they are also a pleasure to write.
Sanctuary provides two data types, [Maybe](#section:maybe) and [Either](#section:either), both of which are compatible with [Fantasy Land](https://github.com/fantasyland/fantasy-land/tree/v4.0.1). Thanks to these data types even Sanctuary functions that may fail, such as [`head`](#head), are composable.
Sanctuary makes it possible to write safe code without null checks. In JavaScript it's trivial to introduce a possible run-time type error.
Sanctuary is designed to work in Node.js and in ES5-compatible browsers.
Sponsors
--------
Development of Sanctuary is funded by the following community-minded **partners**:
* [Fink](https://www.fink.no/) is a small, friendly, and passionate gang of IT consultants. We love what we do, which is mostly web and app development, including graphic design, interaction design, back-end and front-end coding, and ensuring the stuff we make works as intended. Our company is entirely employee-owned; we place great importance on the well-being of every employee, both professionally and personally.
Development of Sanctuary is further encouraged by the following generous **supporters**:
* [@voxbono](https://github.com/voxbono)
* [@syves](https://github.com/syves)
* [@Avaq](https://github.com/Avaq)
* [@kabo](https://gitlab.com/kabo)
* [@o0th](https://github.com/o0th)
* [@identinet](https://github.com/identinet)
[Become a sponsor](https://github.com/sponsors/davidchambers) if you would like the Sanctuary ecosystem to grow even stronger.
Folktale
--------
[Folktale](https://folktale.origamitower.com/), like Sanctuary, is a standard library for functional programming in JavaScript. It is well designed and well documented. Whereas Sanctuary treats JavaScript as a member of the ML language family, Folktale embraces JavaScript's object-oriented programming model. Programming with Folktale resembles programming with Scala.
Ramda
-----
[Ramda](https://ramdajs.com/) provides several functions that return problematic values such as `undefined`, `Infinity`, or `NaN` when applied to unsuitable inputs. These are known as [partial functions](https://en.wikipedia.org/wiki/Partial_function). Partial functions necessitate the use of guards or null checks. In order to safely use `R.head`, for example, one must ensure that the array is non-empty:
```
if (R.isEmpty (xs)) {
// ...
} else {
return f (R.head (xs));
}
```
Using the Maybe type renders such guards (and null checks) unnecessary. Changing functions such as `R.head` to return Maybe values was proposed in [ramda/ramda#683](https://github.com/ramda/ramda/issues/683), but was considered too much of a stretch for JavaScript programmers. Sanctuary was released the following month, in January 2015, as a companion library to Ramda.
In addition to broadening in scope in the years since its release, Sanctuary's philosophy has diverged from Ramda's in several respects.
### Totality
Every Sanctuary function is defined for every value that is a member of the function's input type. Such functions are known as [total functions](https://en.wikipedia.org/wiki/Partial_function#Total_function). Ramda, on the other hand, contains a number of [partial functions](https://en.wikipedia.org/wiki/Partial_function).
### Information preservation
Certain Sanctuary functions preserve more information than their Ramda counterparts. Examples:
```
|> R.tail ([]) |> S.tail ([])
[] Nothing
|> R.tail (['foo']) |> S.tail (['foo'])
[] Just ([])
|> R.replace (/^x/) ('') ('abc') |> S.stripPrefix ('x') ('abc')
'abc' Nothing
|> R.replace (/^x/) ('') ('xabc') |> S.stripPrefix ('x') ('xabc')
'abc' Just ('abc')
```
### Invariants
Sanctuary performs rigorous [type checking](#section:type-checking) of inputs and outputs, and throws a descriptive error if a type error is encountered. This allows bugs to be caught and fixed early in the development cycle.
Ramda operates on the [garbage in, garbage out](https://en.wikipedia.org/wiki/Garbage_in,_garbage_out) principle. Functions are documented to take arguments of particular types, but these invariants are not enforced. The problem with this approach in a language as permissive as JavaScript is that there's no guarantee that garbage input will produce garbage output ([ramda/ramda#1413](https://github.com/ramda/ramda/issues/1413)). Ramda performs ad hoc type checking in some such cases ([ramda/ramda#1419](https://github.com/ramda/ramda/pull/1419)).
Sanctuary can be configured to operate in garbage in, garbage out mode. Ramda cannot be configured to enforce its invariants.
### Currying
Sanctuary functions are curried. There is, for example, exactly one way to apply `S.reduce` to `S.add`, `0`, and `xs`:
* `S.reduce (S.add) (0) (xs)`
Ramda functions are also curried, but in a complex manner. There are four ways to apply `R.reduce` to `R.add`, `0`, and `xs`:
* `R.reduce (R.add) (0) (xs)`
* `R.reduce (R.add) (0, xs)`
* `R.reduce (R.add, 0) (xs)`
* `R.reduce (R.add, 0, xs)`
Ramda supports all these forms because curried functions enable partial application, one of the library's tenets, but `f(x)(y)(z)` is considered too unfamiliar and too unattractive to appeal to JavaScript programmers.
Sanctuary's developers prefer a simple, unfamiliar construct to a complex, familiar one. Familiarity can be acquired; complexity is intrinsic.
The lack of breathing room in `f(x)(y)(z)` impairs readability. The simple solution to this problem, proposed in [#438](https://github.com/sanctuary-js/sanctuary/issues/438), is to include a space when applying a function: `f (x) (y) (z)`.
Ramda also provides a special placeholder value, [`R.__`](https://ramdajs.com/docs/#__), that removes the restriction that a function must be applied to its arguments in order. The following expressions are equivalent:
* `R.reduce (R.__, 0, xs) (R.add)`
* `R.reduce (R.add, R.__, xs) (0)`
* `R.reduce (R.__, 0) (R.add) (xs)`
* `R.reduce (R.__, 0) (R.add, xs)`
* `R.reduce (R.__, R.__, xs) (R.add) (0)`
* `R.reduce (R.__, R.__, xs) (R.add, 0)`
### Variadic functions
Ramda provides several functions that take any number of arguments. These are known as [variadic functions](https://en.wikipedia.org/wiki/Variadic_function). Additionally, Ramda provides several functions that take variadic functions as arguments. Although natural in a dynamically typed language, variadic functions are at odds with the type notation Ramda and Sanctuary both use, leading to some indecipherable type signatures such as this one:
```
R.lift :: (*... -> *...) -> ([*]... -> [*])
```
Sanctuary has no variadic functions, nor any functions that take variadic functions as arguments. Sanctuary provides two "lift" functions, each with a helpful type signature:
```
S.lift2 :: Apply f => (a -> b -> c) -> f a -> f b -> f c
S.lift3 :: Apply f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
```
### Implicit context
Ramda provides [`R.bind`](https://ramdajs.com/docs/#bind) and [`R.invoker`](https://ramdajs.com/docs/#invoker) for working with methods. Additionally, many Ramda functions use `Function#call` or `Function#apply` to preserve context. Sanctuary makes no allowances for `this`.
### Transducers
Several Ramda functions act as transducers. Sanctuary provides no support for transducers.
### Modularity
Whereas Ramda has no dependencies, Sanctuary has a modular design: [sanctuary-def](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0) provides type checking, [sanctuary-type-classes](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0) provides Fantasy Land functions and type classes, [sanctuary-show](https://github.com/sanctuary-js/sanctuary-show/tree/v2.0.0) provides string representations, and algebraic data types are provided by [sanctuary-either](https://github.com/sanctuary-js/sanctuary-either/tree/v2.1.0), [sanctuary-maybe](https://github.com/sanctuary-js/sanctuary-maybe/tree/v2.1.0), and [sanctuary-pair](https://github.com/sanctuary-js/sanctuary-pair/tree/v2.1.0). Not only does this approach reduce the complexity of Sanctuary itself, but it allows these components to be reused in other contexts.
Types
-----
Sanctuary uses Haskell-like type signatures to describe the types of values, including functions. `'foo'`, for example, is a member of `String`; `[1, 2, 3]` is a member of `Array Number`. The double colon (`::`) is used to mean "is a member of", so one could write:
```
'foo' :: String
[1, 2, 3] :: Array Number
```
An identifier may appear to the left of the double colon:
```
Math.PI :: Number
```
The arrow (`->`) is used to express a function's type:
```
Math.abs :: Number -> Number
```
That states that `Math.abs` is a unary function that takes an argument of type `Number` and returns a value of type `Number`.
Some functions are parametrically polymorphic: their types are not fixed. Type variables are used in the representations of such functions:
```
S.I :: a -> a
```
`a` is a type variable. Type variables are not capitalized, so they are differentiable from type identifiers (which are always capitalized). By convention type variables have single-character names. The signature above states that `S.I` takes a value of any type and returns a value of the same type. Some signatures feature multiple type variables:
```
S.K :: a -> b -> a
```
It must be possible to replace all occurrences of `a` with a concrete type. The same applies for each other type variable. For the function above, the types with which `a` and `b` are replaced may be different, but needn't be.
Since all Sanctuary functions are curried (they accept their arguments one at a time), a binary function is represented as a unary function that returns a unary function: `* -> * -> *`. This aligns neatly with Haskell, which uses curried functions exclusively. In JavaScript, though, we may wish to represent the types of functions with arities less than or greater than one. The general form is `(<input-types>) -> <output-type>`, where `<input-types>` comprises zero or more comma–space (`,` ) -separated type representations:
* `() -> String`
* `(a, b) -> a`
* `(a, b, c) -> d`
`Number -> Number` can thus be seen as shorthand for `(Number) -> Number`.
Sanctuary embraces types. JavaScript doesn't support algebraic data types, but these can be simulated by providing a group of data constructors that return values with the same set of methods. A value of the Either type, for example, is created via the Left constructor or the Right constructor.
It's necessary to extend Haskell's notation to describe implicit arguments to the *methods* provided by Sanctuary's types. In `x.map(y)`, for example, the `map` method takes an implicit argument `x` in addition to the explicit argument `y`. The type of the value upon which a method is invoked appears at the beginning of the signature, separated from the arguments and return value by a squiggly arrow (`~>`). The type of the `fantasy-land/map` method of the Maybe type is written `Maybe a ~> (a -> b) -> Maybe b`. One could read this as:
*When the `fantasy-land/map` method is invoked on a value of type `Maybe a` (for any type `a`) with an argument of type `a -> b` (for any type `b`), it returns a value of type `Maybe b`.*
The squiggly arrow is also used when representing non-function properties. `Maybe a ~> Boolean`, for example, represents a Boolean property of a value of type `Maybe a`.
Sanctuary supports type classes: constraints on type variables. Whereas `a -> a` implicitly supports every type, `Functor f => (a -> b) -> f a -> f b` requires that `f` be a type that satisfies the requirements of the Functor type class. Type-class constraints appear at the beginning of a type signature, separated from the rest of the signature by a fat arrow (`=>`).
Type checking
-------------
Sanctuary functions are defined via [sanctuary-def](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0) to provide run-time type checking. This is tremendously useful during development: type errors are reported immediately, avoiding circuitous stack traces (at best) and silent failures due to type coercion (at worst). For example:
```
> S.add (2) (true)
! Invalid value
add :: FiniteNumber -> FiniteNumber -> FiniteNumber
^^^^^^^^^^^^
1
1) true :: Boolean
The value at position 1 is not a member of ‘FiniteNumber’.
See https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber for information about the FiniteNumber type.
```
Compare this to the behaviour of Ramda's unchecked equivalent:
```
> R.add (2) (true)
3
```
There is a performance cost to run-time type checking. Type checking is disabled by default if `process.env.NODE_ENV` is `'production'`. If this rule is unsuitable for a given program, one may use [`create`](#create) to create a Sanctuary module based on a different rule. For example:
```
const S = sanctuary.create ({
checkTypes: localStorage.getItem ('SANCTUARY_CHECK_TYPES') === 'true',
env: sanctuary.env,
});
```
Occasionally one may wish to perform an operation that is not type safe, such as mapping over an object with heterogeneous values. This is possible via selective use of [`unchecked`](#unchecked) functions.
Installation
------------
`npm install sanctuary` will install Sanctuary for use in Node.js.
To add Sanctuary to a website, add the following `<script>` element, replacing `X.Y.Z` with a version number greater than or equal to `2.0.2`:
```
<script src="https://cdn.jsdelivr.net/gh/sanctuary-js/[email protected]/dist/bundle.js"></script>
```
Optionally, define aliases for various modules:
```
const S = window.sanctuary;
const $ = window.sanctuaryDef;
// ...
```
API
---
### Configure
#### `[create](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L506) :: { checkTypes :: [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean), env :: [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) [Type](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Type) } -> [Module](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Module)`
Takes an options record and returns a Sanctuary module. `checkTypes` specifies whether to enable type checking. The module's polymorphic functions (such as [`I`](#I)) require each value associated with a type variable to be a member of at least one type in the environment.
A well-typed application of a Sanctuary function will produce the same result regardless of whether type checking is enabled. If type checking is enabled, a badly typed application will produce an exception with a descriptive error message.
The following snippet demonstrates defining a custom type and using `create` to produce a Sanctuary module that is aware of that type:
```
const {create, env} = require ('sanctuary');
const $ = require ('sanctuary-def');
const type = require ('sanctuary-type-identifiers');
// Identity :: a -> Identity a
const Identity = x => {
const identity = Object.create (Identity$prototype);
identity.value = x;
return identity;
};
// identityTypeIdent :: String
const identityTypeIdent = 'my-package/Identity@1';
const Identity$prototype = {
'@@type': identityTypeIdent,
'@@show': function() { return `Identity (${S.show (this.value)})`; },
'fantasy-land/map': function(f) { return Identity (f (this.value)); },
};
// IdentityType :: Type -> Type
const IdentityType = $.UnaryType
('Identity')
('http://example.com/my-package#Identity')
([])
(x => type (x) === identityTypeIdent)
(identity => [identity.value]);
const S = create ({
checkTypes: process.env.NODE_ENV !== 'production',
env: env.concat ([IdentityType ($.Unknown)]),
});
S.map (S.sub (1)) (Identity (43));
// => Identity (42)
```
See also [`env`](#env).
#### `[env](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L582) :: [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) [Type](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Type)`
The Sanctuary module's environment (`(S.create ({checkTypes, env})).env` is a reference to `env`). Useful in conjunction with [`create`](#create).
```
> S.env
[Function, Arguments, Array Unknown, Array2 Unknown Unknown, Boolean, Buffer, Date, Descending Unknown, Either Unknown Unknown, Error, Unknown -> Unknown, HtmlElement, Identity Unknown, JsMap Unknown Unknown, JsSet Unknown, Maybe Unknown, Module, Null, Number, Object, Pair Unknown Unknown, RegExp, StrMap Unknown, String, Symbol, Type, TypeClass, Undefined]
```
#### `[unchecked](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L619) :: [Module](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Module)`
A complete Sanctuary module that performs no type checking. This is useful as it permits operations that Sanctuary's type checking would disallow, such as mapping over an object with heterogeneous values.
See also [`create`](#create).
```
> S.unchecked.map (S.show) ({x: 'foo', y: true, z: 42})
{"x": "\"foo\"", "y": "true", "z": "42"}
```
Opting out of type checking may cause type errors to go unnoticed.
```
> S.unchecked.add (2) ('2')
"22"
```
### Classify
#### `[type](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L641) :: [Any](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Any) -> { namespace :: [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String), name :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String), version :: [NonNegativeInteger](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#NonNegativeInteger) }`
Returns the result of parsing the [type identifier](https://github.com/sanctuary-js/sanctuary-type-identifiers/tree/v3.0.0) of the given value.
```
> S.type (S.Just (42))
{"name": "Maybe", "namespace": Just ("sanctuary-maybe"), "version": 1}
> S.type ([1, 2, 3])
{"name": "Array", "namespace": Nothing, "version": 0}
```
#### `[is](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L666) :: [Type](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Type) -> [Any](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Any) -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Returns `true` [iff](https://en.wikipedia.org/wiki/If_and_only_if) the given value is a member of the specified type. See [`$.test`](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#test) for details.
```
> S.is ($.Array ($.Integer)) ([1, 2, 3])
true
> S.is ($.Array ($.Integer)) ([1, 2, 3.14])
false
```
### Showable
#### `[show](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L681) :: [Any](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Any) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String)`
Alias of [`show`](https://github.com/sanctuary-js/sanctuary-show/tree/v2.0.0#show).
```
> S.show (-0)
"-0"
> S.show (['foo', 'bar', 'baz'])
"[\"foo\", \"bar\", \"baz\"]"
> S.show ({x: 1, y: 2, z: 3})
"{\"x\": 1, \"y\": 2, \"z\": 3}"
> S.show (S.Left (S.Right (S.Just (S.Nothing))))
"Left (Right (Just (Nothing)))"
```
### Fantasy Land
Sanctuary is compatible with the [Fantasy Land](https://github.com/fantasyland/fantasy-land/tree/v4.0.1) specification.
#### `[equals](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L708) :: [Setoid](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Setoid) a => a -> a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Curried version of [`Z.equals`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#equals) that requires two arguments of the same type.
To compare values of different types first use [`create`](#create) to create a Sanctuary module with type checking disabled, then use that module's `equals` function.
```
> S.equals (0) (-0)
true
> S.equals (NaN) (NaN)
true
> S.equals (S.Just ([1, 2, 3])) (S.Just ([1, 2, 3]))
true
> S.equals (S.Just ([1, 2, 3])) (S.Just ([1, 2, 4]))
false
```
#### `[lt](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L741) :: [Ord](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Ord) a => a -> a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Returns `true` [iff](https://en.wikipedia.org/wiki/If_and_only_if) the *second* argument is less than the first according to [`Z.lt`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#lt).
```
> S.filter (S.lt (3)) ([1, 2, 3, 4, 5])
[1, 2]
```
#### `[lte](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L761) :: [Ord](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Ord) a => a -> a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Returns `true` [iff](https://en.wikipedia.org/wiki/If_and_only_if) the *second* argument is less than or equal to the first according to [`Z.lte`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#lte).
```
> S.filter (S.lte (3)) ([1, 2, 3, 4, 5])
[1, 2, 3]
```
#### `[gt](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L781) :: [Ord](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Ord) a => a -> a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Returns `true` [iff](https://en.wikipedia.org/wiki/If_and_only_if) the *second* argument is greater than the first according to [`Z.gt`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#gt).
```
> S.filter (S.gt (3)) ([1, 2, 3, 4, 5])
[4, 5]
```
#### `[gte](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L801) :: [Ord](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Ord) a => a -> a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Returns `true` [iff](https://en.wikipedia.org/wiki/If_and_only_if) the *second* argument is greater than or equal to the first according to [`Z.gte`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#gte).
```
> S.filter (S.gte (3)) ([1, 2, 3, 4, 5])
[3, 4, 5]
```
#### `[min](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L821) :: [Ord](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Ord) a => a -> a -> a`
Returns the smaller of its two arguments (according to [`Z.lte`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#lte)).
See also [`max`](#max).
```
> S.min (10) (2)
2
> S.min (new Date ('1999-12-31')) (new Date ('2000-01-01'))
new Date ("1999-12-31T00:00:00.000Z")
> S.min ('10') ('2')
"10"
```
#### `[max](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L843) :: [Ord](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Ord) a => a -> a -> a`
Returns the larger of its two arguments (according to [`Z.lte`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#lte)).
See also [`min`](#min).
```
> S.max (10) (2)
10
> S.max (new Date ('1999-12-31')) (new Date ('2000-01-01'))
new Date ("2000-01-01T00:00:00.000Z")
> S.max ('10') ('2')
"2"
```
#### `[clamp](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L865) :: [Ord](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Ord) a => a -> a -> a -> a`
Takes a lower bound, an upper bound, and a value of the same type. Returns the value if it is within the bounds; the nearer bound otherwise.
See also [`min`](#min) and [`max`](#max).
```
> S.clamp (0) (100) (42)
42
> S.clamp (0) (100) (-1)
0
> S.clamp ('A') ('Z') ('~')
"Z"
```
#### `[id](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L888) :: [Category](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Category) c => [TypeRep](https://github.com/fantasyland/fantasy-land#type-representatives) c -> c`
[Type-safe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0) version of [`Z.id`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#id).
```
> S.id (Function) (42)
42
```
#### `[concat](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L902) :: [Semigroup](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Semigroup) a => a -> a -> a`
Curried version of [`Z.concat`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#concat).
```
> S.concat ('abc') ('def')
"abcdef"
> S.concat ([1, 2, 3]) ([4, 5, 6])
[1, 2, 3, 4, 5, 6]
> S.concat ({x: 1, y: 2}) ({y: 3, z: 4})
{"x": 1, "y": 3, "z": 4}
> S.concat (S.Just ([1, 2, 3])) (S.Just ([4, 5, 6]))
Just ([1, 2, 3, 4, 5, 6])
> S.concat (Sum (18)) (Sum (24))
Sum (42)
```
#### `[empty](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L928) :: [Monoid](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Monoid) a => [TypeRep](https://github.com/fantasyland/fantasy-land#type-representatives) a -> a`
[Type-safe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0) version of [`Z.empty`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#empty).
```
> S.empty (String)
""
> S.empty (Array)
[]
> S.empty (Object)
{}
> S.empty (Sum)
Sum (0)
```
#### `[invert](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L951) :: [Group](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Group) g => g -> g`
[Type-safe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0) version of [`Z.invert`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#invert).
```
> S.invert (Sum (5))
Sum (-5)
```
#### `[filter](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L965) :: [Filterable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Filterable) f => (a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)) -> f a -> f a`
Curried version of [`Z.filter`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#filter). Discards every element that does not satisfy the predicate.
See also [`reject`](#reject).
```
> S.filter (S.odd) ([1, 2, 3])
[1, 3]
> S.filter (S.odd) ({x: 1, y: 2, z: 3})
{"x": 1, "z": 3}
> S.filter (S.odd) (S.Nothing)
Nothing
> S.filter (S.odd) (S.Just (0))
Nothing
> S.filter (S.odd) (S.Just (1))
Just (1)
```
#### `[reject](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L999) :: [Filterable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Filterable) f => (a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)) -> f a -> f a`
Curried version of [`Z.reject`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#reject). Discards every element that satisfies the predicate.
See also [`filter`](#filter).
```
> S.reject (S.odd) ([1, 2, 3])
[2]
> S.reject (S.odd) ({x: 1, y: 2, z: 3})
{"y": 2}
> S.reject (S.odd) (S.Nothing)
Nothing
> S.reject (S.odd) (S.Just (0))
Just (0)
> S.reject (S.odd) (S.Just (1))
Nothing
```
#### `[map](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1033) :: [Functor](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Functor) f => (a -> b) -> f a -> f b`
Curried version of [`Z.map`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#map).
```
> S.map (Math.sqrt) ([1, 4, 9])
[1, 2, 3]
> S.map (Math.sqrt) ({x: 1, y: 4, z: 9})
{"x": 1, "y": 2, "z": 3}
> S.map (Math.sqrt) (S.Just (9))
Just (3)
> S.map (Math.sqrt) (S.Right (9))
Right (3)
> S.map (Math.sqrt) (S.Pair (99980001) (99980001))
Pair (99980001) (9999)
```
Replacing `Functor f => f` with `Function x` produces the B combinator from combinatory logic (i.e. [`compose`](#compose)):
```
Functor f => (a -> b) -> f a -> f b
(a -> b) -> Function x a -> Function x b
(a -> c) -> Function x a -> Function x c
(b -> c) -> Function x b -> Function x c
(b -> c) -> Function a b -> Function a c
(b -> c) -> (a -> b) -> (a -> c)
```
```
> S.map (Math.sqrt) (S.add (1)) (99)
10
```
#### `[flip](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1079) :: [Functor](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Functor) f => f (a -> b) -> a -> f b`
Curried version of [`Z.flip`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#flip). Maps over the given functions, applying each to the given value.
Replacing `Functor f => f` with `Function x` produces the C combinator from combinatory logic:
```
Functor f => f (a -> b) -> a -> f b
Function x (a -> b) -> a -> Function x b
Function x (a -> c) -> a -> Function x c
Function x (b -> c) -> b -> Function x c
Function a (b -> c) -> b -> Function a c
(a -> b -> c) -> b -> a -> c
```
```
> S.flip (S.concat) ('!') ('foo')
"foo!"
> S.flip ([Math.floor, Math.ceil]) (1.5)
[1, 2]
> S.flip ({floor: Math.floor, ceil: Math.ceil}) (1.5)
{"ceil": 2, "floor": 1}
> S.flip (Cons (Math.floor) (Cons (Math.ceil) (Nil))) (1.5)
Cons (1) (Cons (2) (Nil))
```
#### `[bimap](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1118) :: [Bifunctor](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Bifunctor) f => (a -> b) -> (c -> d) -> f a c -> f b d`
Curried version of [`Z.bimap`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#bimap).
```
> S.bimap (S.toUpper) (Math.sqrt) (S.Pair ('foo') (64))
Pair ("FOO") (8)
> S.bimap (S.toUpper) (Math.sqrt) (S.Left ('foo'))
Left ("FOO")
> S.bimap (S.toUpper) (Math.sqrt) (S.Right (64))
Right (8)
```
#### `[mapLeft](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1138) :: [Bifunctor](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Bifunctor) f => (a -> b) -> f a c -> f b c`
Curried version of [`Z.mapLeft`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#mapLeft). Maps the given function over the left side of a Bifunctor.
```
> S.mapLeft (S.toUpper) (S.Pair ('foo') (64))
Pair ("FOO") (64)
> S.mapLeft (S.toUpper) (S.Left ('foo'))
Left ("FOO")
> S.mapLeft (S.toUpper) (S.Right (64))
Right (64)
```
#### `[promap](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1159) :: [Profunctor](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Profunctor) p => (a -> b) -> (c -> d) -> p b c -> p a d`
Curried version of [`Z.promap`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#promap).
```
> S.promap (Math.abs) (S.add (1)) (Math.sqrt) (-100)
11
```
#### `[alt](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1173) :: [Alt](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Alt) f => f a -> f a -> f a`
Curried version of [`Z.alt`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#alt) with arguments flipped to facilitate partial application.
```
> S.alt (S.Just ('default')) (S.Nothing)
Just ("default")
> S.alt (S.Just ('default')) (S.Just ('hello'))
Just ("hello")
> S.alt (S.Right (0)) (S.Left ('X'))
Right (0)
> S.alt (S.Right (0)) (S.Right (1))
Right (1)
```
#### `[zero](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1202) :: [Plus](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Plus) f => [TypeRep](https://github.com/fantasyland/fantasy-land#type-representatives) f -> f a`
[Type-safe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0) version of [`Z.zero`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#zero).
```
> S.zero (Array)
[]
> S.zero (Object)
{}
> S.zero (S.Maybe)
Nothing
```
#### `[reduce](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1222) :: [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f => (b -> a -> b) -> b -> f a -> b`
Takes a curried binary function, an initial value, and a [Foldable](https://github.com/fantasyland/fantasy-land/tree/v4.0.1#foldable), and applies the function to the initial value and the Foldable's first value, then applies the function to the result of the previous application and the Foldable's second value. Repeats this process until each of the Foldable's values has been used. Returns the initial value if the Foldable is empty; the result of the final application otherwise.
See also [`reduce_`](#reduce_).
```
> S.reduce (S.add) (0) ([1, 2, 3, 4, 5])
15
> S.reduce (xs => x => S.prepend (x) (xs)) ([]) ([1, 2, 3, 4, 5])
[5, 4, 3, 2, 1]
```
#### `[reduce\_](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1256) :: [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f => (a -> b -> b) -> b -> f a -> b`
Variant of [`reduce`](#reduce) that takes a reducing function with arguments flipped.
```
> S.reduce_ (S.append) ([]) (Cons (1) (Cons (2) (Cons (3) (Nil))))
[1, 2, 3]
> S.reduce_ (S.prepend) ([]) (Cons (1) (Cons (2) (Cons (3) (Nil))))
[3, 2, 1]
```
#### `[traverse](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1274) :: ([Applicative](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Applicative) f, [Traversable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Traversable) t) => [TypeRep](https://github.com/fantasyland/fantasy-land#type-representatives) f -> (a -> f b) -> t a -> f (t b)`
Curried version of [`Z.traverse`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#traverse).
```
> S.traverse (Array) (S.words) (S.Just ('foo bar baz'))
[Just ("foo"), Just ("bar"), Just ("baz")]
> S.traverse (Array) (S.words) (S.Nothing)
[Nothing]
> S.traverse (S.Maybe) (S.parseInt (16)) (['A', 'B', 'C'])
Just ([10, 11, 12])
> S.traverse (S.Maybe) (S.parseInt (16)) (['A', 'B', 'C', 'X'])
Nothing
> S.traverse (S.Maybe) (S.parseInt (16)) ({a: 'A', b: 'B', c: 'C'})
Just ({"a": 10, "b": 11, "c": 12})
> S.traverse (S.Maybe) (S.parseInt (16)) ({a: 'A', b: 'B', c: 'C', x: 'X'})
Nothing
```
#### `[sequence](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1303) :: ([Applicative](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Applicative) f, [Traversable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Traversable) t) => [TypeRep](https://github.com/fantasyland/fantasy-land#type-representatives) f -> t (f a) -> f (t a)`
Curried version of [`Z.sequence`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#sequence). Inverts the given `t (f a)` to produce an `f (t a)`.
```
> S.sequence (Array) (S.Just ([1, 2, 3]))
[Just (1), Just (2), Just (3)]
> S.sequence (S.Maybe) ([S.Just (1), S.Just (2), S.Just (3)])
Just ([1, 2, 3])
> S.sequence (S.Maybe) ([S.Just (1), S.Just (2), S.Nothing])
Nothing
> S.sequence (S.Maybe) ({a: S.Just (1), b: S.Just (2), c: S.Just (3)})
Just ({"a": 1, "b": 2, "c": 3})
> S.sequence (S.Maybe) ({a: S.Just (1), b: S.Just (2), c: S.Nothing})
Nothing
```
#### `[ap](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1330) :: [Apply](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Apply) f => f (a -> b) -> f a -> f b`
Curried version of [`Z.ap`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#ap).
```
> S.ap ([Math.sqrt, x => x * x]) ([1, 4, 9, 16, 25])
[1, 2, 3, 4, 5, 1, 16, 81, 256, 625]
> S.ap ({x: Math.sqrt, y: S.add (1), z: S.sub (1)}) ({w: 4, x: 4, y: 4})
{"x": 2, "y": 5}
> S.ap (S.Just (Math.sqrt)) (S.Just (64))
Just (8)
```
Replacing `Apply f => f` with `Function x` produces the S combinator from combinatory logic:
```
Apply f => f (a -> b) -> f a -> f b
Function x (a -> b) -> Function x a -> Function x b
Function x (a -> c) -> Function x a -> Function x c
Function x (b -> c) -> Function x b -> Function x c
Function a (b -> c) -> Function a b -> Function a c
(a -> b -> c) -> (a -> b) -> (a -> c)
```
```
> S.ap (s => n => s.slice (0, n)) (s => Math.ceil (s.length / 2)) ('Haskell')
"Hask"
```
#### `[lift2](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1365) :: [Apply](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Apply) f => (a -> b -> c) -> f a -> f b -> f c`
Promotes a curried binary function to a function that operates on two [Apply](https://github.com/fantasyland/fantasy-land/tree/v4.0.1#apply)s.
```
> S.lift2 (S.add) (S.Just (2)) (S.Just (3))
Just (5)
> S.lift2 (S.add) (S.Just (2)) (S.Nothing)
Nothing
> S.lift2 (S.and) (S.Just (true)) (S.Just (true))
Just (true)
> S.lift2 (S.and) (S.Just (true)) (S.Just (false))
Just (false)
```
#### `[lift3](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1389) :: [Apply](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Apply) f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d`
Promotes a curried ternary function to a function that operates on three [Apply](https://github.com/fantasyland/fantasy-land/tree/v4.0.1#apply)s.
```
> S.lift3 (S.reduce) (S.Just (S.add)) (S.Just (0)) (S.Just ([1, 2, 3]))
Just (6)
> S.lift3 (S.reduce) (S.Just (S.add)) (S.Just (0)) (S.Nothing)
Nothing
```
#### `[apFirst](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1407) :: [Apply](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Apply) f => f a -> f b -> f a`
Curried version of [`Z.apFirst`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#apFirst). Combines two effectful actions, keeping only the result of the first. Equivalent to Haskell's `(<*)` function.
See also [`apSecond`](#apSecond).
```
> S.apFirst ([1, 2]) ([3, 4])
[1, 1, 2, 2]
> S.apFirst (S.Just (1)) (S.Just (2))
Just (1)
```
#### `[apSecond](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1428) :: [Apply](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Apply) f => f a -> f b -> f b`
Curried version of [`Z.apSecond`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#apSecond). Combines two effectful actions, keeping only the result of the second. Equivalent to Haskell's `(*>)` function.
See also [`apFirst`](#apFirst).
```
> S.apSecond ([1, 2]) ([3, 4])
[3, 4, 3, 4]
> S.apSecond (S.Just (1)) (S.Just (2))
Just (2)
```
#### `[of](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1449) :: [Applicative](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Applicative) f => [TypeRep](https://github.com/fantasyland/fantasy-land#type-representatives) f -> a -> f a`
Curried version of [`Z.of`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#of).
```
> S.of (Array) (42)
[42]
> S.of (Function) (42) (null)
42
> S.of (S.Maybe) (42)
Just (42)
> S.of (S.Either) (42)
Right (42)
```
#### `[chain](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1477) :: [Chain](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Chain) m => (a -> m b) -> m a -> m b`
Curried version of [`Z.chain`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#chain).
```
> S.chain (x => [x, x]) ([1, 2, 3])
[1, 1, 2, 2, 3, 3]
> S.chain (n => s => s.slice (0, n)) (s => Math.ceil (s.length / 2)) ('slice')
"sli"
> S.chain (S.parseInt (10)) (S.Just ('123'))
Just (123)
> S.chain (S.parseInt (10)) (S.Just ('XXX'))
Nothing
```
#### `[join](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1500) :: [Chain](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Chain) m => m (m a) -> m a`
[Type-safe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0) version of [`Z.join`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#join). Removes one level of nesting from a nested monadic structure.
```
> S.join ([[1], [2], [3]])
[1, 2, 3]
> S.join ([[[1, 2, 3]]])
[[1, 2, 3]]
> S.join (S.Just (S.Just (1)))
Just (1)
> S.join (S.Pair ('foo') (S.Pair ('bar') ('baz')))
Pair ("foobar") ("baz")
```
Replacing `Chain m => m` with `Function x` produces the W combinator from combinatory logic:
```
Chain m => m (m a) -> m a
Function x (Function x a) -> Function x a
(x -> x -> a) -> (x -> a)
```
```
> S.join (S.concat) ('abc')
"abcabc"
```
#### `[chainRec](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1536) :: [ChainRec](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#ChainRec) m => [TypeRep](https://github.com/fantasyland/fantasy-land#type-representatives) m -> (a -> m ([Either](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Either) a b)) -> a -> m b`
Performs a [`chain`](#chain)-like computation with constant stack usage. Similar to [`Z.chainRec`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#chainRec), but curried and more convenient due to the use of the Either type to indicate completion (via a Right).
```
> S.chainRec (Array) (s => s.length === 2 ? S.map (S.Right) ([s + '!', s + '?']) : S.map (S.Left) ([s + 'o', s + 'n'])) ('')
["oo!", "oo?", "on!", "on?", "no!", "no?", "nn!", "nn?"]
```
#### `[extend](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1565) :: [Extend](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Extend) w => (w a -> b) -> w a -> w b`
Curried version of [`Z.extend`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#extend).
```
> S.extend (S.joinWith ('')) (['x', 'y', 'z'])
["xyz", "yz", "z"]
> S.extend (f => f ([3, 4])) (S.reverse) ([1, 2])
[4, 3, 2, 1]
```
#### `[duplicate](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1582) :: [Extend](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Extend) w => w a -> w (w a)`
[Type-safe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0) version of [`Z.duplicate`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#duplicate). Adds one level of nesting to a comonadic structure.
```
> S.duplicate (S.Just (1))
Just (Just (1))
> S.duplicate ([1])
[[1]]
> S.duplicate ([1, 2, 3])
[[1, 2, 3], [2, 3], [3]]
> S.duplicate (S.reverse) ([1, 2]) ([3, 4])
[4, 3, 2, 1]
```
#### `[extract](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1606) :: [Comonad](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Comonad) w => w a -> a`
[Type-safe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0) version of [`Z.extract`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#extract).
```
> S.extract (S.Pair ('foo') ('bar'))
"bar"
```
#### `[contramap](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1620) :: [Contravariant](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Contravariant) f => (b -> a) -> f a -> f b`
[Type-safe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0) version of [`Z.contramap`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#contramap).
```
> S.contramap (s => s.length) (Math.sqrt) ('Sanctuary')
3
```
### Combinator
#### `[I](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1636) :: a -> a`
The I combinator. Returns its argument. Equivalent to Haskell's `id` function.
```
> S.I ('foo')
"foo"
```
#### `[K](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1654) :: a -> b -> a`
The K combinator. Takes two values and returns the first. Equivalent to Haskell's `const` function.
```
> S.K ('foo') ('bar')
"foo"
> S.map (S.K (42)) (S.range (0) (5))
[42, 42, 42, 42, 42]
```
#### `[T](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1677) :: a -> (a -> b) -> b`
The T ([thrush](https://github.com/raganwald-deprecated/homoiconic/blob/master/2008-10-30/thrush.markdown)) combinator. Takes a value and a function, and returns the result of applying the function to the value. Equivalent to Haskell's `(&)` function.
```
> S.T (42) (S.add (1))
43
> S.map (S.T (100)) ([S.add (1), Math.sqrt])
[101, 10]
```
### Function
#### `[curry2](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1703) :: ((a, b) -> c) -> a -> b -> c`
Curries the given binary function.
```
> S.map (S.curry2 (Math.pow) (10)) ([1, 2, 3])
[10, 100, 1000]
```
#### `[curry3](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1724) :: ((a, b, c) -> d) -> a -> b -> c -> d`
Curries the given ternary function.
```
> const replaceString = S.curry3 ((what, replacement, string) => string.replace (what, replacement))
undefined
> replaceString ('banana') ('orange') ('banana icecream')
"orange icecream"
```
#### `[curry4](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1751) :: ((a, b, c, d) -> e) -> a -> b -> c -> d -> e`
Curries the given quaternary function.
```
> const createRect = S.curry4 ((x, y, width, height) => ({x, y, width, height}))
undefined
> createRect (0) (0) (10) (10)
{"height": 10, "width": 10, "x": 0, "y": 0}
```
#### `[curry5](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1780) :: ((a, b, c, d, e) -> f) -> a -> b -> c -> d -> e -> f`
Curries the given quinary function.
```
> const toUrl = S.curry5 ((protocol, creds, hostname, port, pathname) => protocol + '//' + S.maybe ('') (S.flip (S.concat) ('@')) (creds) + hostname + S.maybe ('') (S.concat (':')) (port) + pathname)
undefined
> toUrl ('https:') (S.Nothing) ('example.com') (S.Just ('443')) ('/foo/bar')
"https://example.com:443/foo/bar"
```
### Composition
#### `[compose](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1817) :: [Semigroupoid](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Semigroupoid) s => s b c -> s a b -> s a c`
Curried version of [`Z.compose`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#compose).
When specialized to Function, `compose` composes two unary functions, from right to left (this is the B combinator from combinatory logic).
The generalized type signature indicates that `compose` is compatible with any [Semigroupoid](https://github.com/fantasyland/fantasy-land/tree/v4.0.1#semigroupoid).
See also [`pipe`](#pipe).
```
> S.compose (Math.sqrt) (S.add (1)) (99)
10
```
#### `[pipe](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1839) :: [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f => f ([Any](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Any) -> [Any](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Any)) -> a -> b`
Takes a sequence of functions assumed to be unary and a value of any type, and returns the result of applying the sequence of transformations to the initial value.
In general terms, `pipe` performs left-to-right composition of a sequence of functions. `pipe ([f, g, h]) (x)` is equivalent to `h (g (f (x)))`.
```
> S.pipe ([S.add (1), Math.sqrt, S.sub (1)]) (99)
9
```
#### `[pipeK](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1863) :: ([Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f, [Chain](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Chain) m) => f ([Any](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Any) -> m [Any](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Any)) -> m a -> m b`
Takes a sequence of functions assumed to be unary that return values with a [Chain](https://github.com/fantasyland/fantasy-land/tree/v4.0.1#chain), and a value of that Chain, and returns the result of applying the sequence of transformations to the initial value.
In general terms, `pipeK` performs left-to-right [Kleisli](https://en.wikipedia.org/wiki/Kleisli_category) composition of an sequence of functions. `pipeK ([f, g, h]) (x)` is equivalent to `chain (h) (chain (g) (chain (f) (x)))`.
```
> S.pipeK ([S.tail, S.tail, S.head]) (S.Just ([1, 2, 3, 4]))
Just (3)
```
#### `[on](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1888) :: (b -> b -> c) -> (a -> b) -> a -> a -> c`
Takes a binary function `f`, a unary function `g`, and two values `x` and `y`. Returns `f (g (x)) (g (y))`.
This is the P combinator from combinatory logic.
```
> S.on (S.concat) (S.reverse) ([1, 2, 3]) ([4, 5, 6])
[3, 2, 1, 6, 5, 4]
```
### Pair
Pair is the canonical product type: a value of type `Pair a b` always contains exactly two values: one of type `a`; one of type `b`.
The implementation is provided by [sanctuary-pair](https://github.com/sanctuary-js/sanctuary-pair/tree/v2.1.0).
#### `[Pair](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1921) :: a -> b -> [Pair](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Pair) a b`
Pair's sole data constructor. Additionally, it serves as the Pair [type representative](https://github.com/fantasyland/fantasy-land/tree/v4.0.1#type-representatives).
```
> S.Pair ('foo') (42)
Pair ("foo") (42)
```
#### `[pair](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1936) :: (a -> b -> c) -> [Pair](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Pair) a b -> c`
Case analysis for the `Pair a b` type.
```
> S.pair (S.concat) (S.Pair ('foo') ('bar'))
"foobar"
```
#### `[fst](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1955) :: [Pair](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Pair) a b -> a`
`fst (Pair (x) (y))` is equivalent to `x`.
```
> S.fst (S.Pair ('foo') (42))
"foo"
```
#### `[snd](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1969) :: [Pair](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Pair) a b -> b`
`snd (Pair (x) (y))` is equivalent to `y`.
```
> S.snd (S.Pair ('foo') (42))
42
```
#### `[swap](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L1983) :: [Pair](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Pair) a b -> [Pair](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Pair) b a`
`swap (Pair (x) (y))` is equivalent to `Pair (y) (x)`.
```
> S.swap (S.Pair ('foo') (42))
Pair (42) ("foo")
```
### Maybe
The Maybe type represents optional values: a value of type `Maybe a` is either Nothing (the empty value) or a Just whose value is of type `a`.
The implementation is provided by [sanctuary-maybe](https://github.com/sanctuary-js/sanctuary-maybe/tree/v2.1.0).
#### `[Maybe](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2004) :: [TypeRep](https://github.com/fantasyland/fantasy-land#type-representatives) [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe)`
Maybe [type representative](https://github.com/fantasyland/fantasy-land/tree/v4.0.1#type-representatives).
#### `[Nothing](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2008) :: [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) a`
The empty value of type `Maybe a`.
```
> S.Nothing
Nothing
```
#### `[Just](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2017) :: a -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) a`
Constructs a value of type `Maybe a` from a value of type `a`.
```
> S.Just (42)
Just (42)
```
#### `[isNothing](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2031) :: [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Returns `true` if the given Maybe is Nothing; `false` if it is a Just.
```
> S.isNothing (S.Nothing)
true
> S.isNothing (S.Just (42))
false
```
#### `[isJust](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2051) :: [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Returns `true` if the given Maybe is a Just; `false` if it is Nothing.
```
> S.isJust (S.Just (42))
true
> S.isJust (S.Nothing)
false
```
#### `[maybe](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2071) :: b -> (a -> b) -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) a -> b`
Takes a value of any type, a function, and a Maybe. If the Maybe is a Just, the return value is the result of applying the function to the Just's value. Otherwise, the first argument is returned.
See also [`maybe_`](#maybe_) and [`fromMaybe`](#fromMaybe).
```
> S.maybe (0) (S.prop ('length')) (S.Just ('refuge'))
6
> S.maybe (0) (S.prop ('length')) (S.Nothing)
0
```
#### `[maybe\_](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2099) :: (() -> b) -> (a -> b) -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) a -> b`
Variant of [`maybe`](#maybe) that takes a thunk so the default value is only computed if required.
```
> function fib(n) { return n <= 1 ? n : fib (n - 2) + fib (n - 1); }
undefined
> S.maybe_ (() => fib (30)) (Math.sqrt) (S.Just (1000000))
1000
> S.maybe_ (() => fib (30)) (Math.sqrt) (S.Nothing)
832040
```
#### `[fromMaybe](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2126) :: a -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) a -> a`
Takes a default value and a Maybe, and returns the Maybe's value if the Maybe is a Just; the default value otherwise.
See also [`maybe`](#maybe), [`fromMaybe_`](#fromMaybe_), and [`maybeToNullable`](#maybeToNullable).
```
> S.fromMaybe (0) (S.Just (42))
42
> S.fromMaybe (0) (S.Nothing)
0
```
#### `[fromMaybe\_](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2147) :: (() -> a) -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) a -> a`
Variant of [`fromMaybe`](#fromMaybe) that takes a thunk so the default value is only computed if required.
```
> function fib(n) { return n <= 1 ? n : fib (n - 2) + fib (n - 1); }
undefined
> S.fromMaybe_ (() => fib (30)) (S.Just (1000000))
1000000
> S.fromMaybe_ (() => fib (30)) (S.Nothing)
832040
```
#### `[justs](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2167) :: ([Filterable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Filterable) f, [Functor](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Functor) f) => f ([Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) a) -> f a`
Discards each element that is Nothing, and unwraps each element that is a Just. Related to Haskell's `catMaybes` function.
See also [`lefts`](#lefts) and [`rights`](#rights).
```
> S.justs ([S.Just ('foo'), S.Nothing, S.Just ('baz')])
["foo", "baz"]
```
#### `[mapMaybe](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2187) :: ([Filterable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Filterable) f, [Functor](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Functor) f) => (a -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) b) -> f a -> f b`
Takes a function and a structure, applies the function to each element of the structure, and returns the "successful" results. If the result of applying the function to an element is Nothing, the result is discarded; if the result is a Just, the Just's value is included.
```
> S.mapMaybe (S.head) ([[], [1, 2, 3], [], [4, 5, 6], []])
[1, 4]
> S.mapMaybe (S.head) ({x: [1, 2, 3], y: [], z: [4, 5, 6]})
{"x": 1, "z": 4}
```
#### `[maybeToNullable](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2207) :: [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) a -> [Nullable](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Nullable) a`
Returns the given Maybe's value if the Maybe is a Just; `null` otherwise. [Nullable](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Nullable) is defined in [sanctuary-def](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0).
See also [`fromMaybe`](#fromMaybe).
```
> S.maybeToNullable (S.Just (42))
42
> S.maybeToNullable (S.Nothing)
null
```
#### `[maybeToEither](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2230) :: a -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) b -> [Either](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Either) a b`
Converts a Maybe to an Either. Nothing becomes a Left (containing the first argument); a Just becomes a Right.
See also [`eitherToMaybe`](#eitherToMaybe).
```
> S.maybeToEither ('Expecting an integer') (S.parseInt (10) ('xyz'))
Left ("Expecting an integer")
> S.maybeToEither ('Expecting an integer') (S.parseInt (10) ('42'))
Right (42)
```
### Either
The Either type represents values with two possibilities: a value of type `Either a b` is either a Left whose value is of type `a` or a Right whose value is of type `b`.
The implementation is provided by [sanctuary-either](https://github.com/sanctuary-js/sanctuary-either/tree/v2.1.0).
#### `[Either](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2261) :: [TypeRep](https://github.com/fantasyland/fantasy-land#type-representatives) [Either](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Either)`
Either [type representative](https://github.com/fantasyland/fantasy-land/tree/v4.0.1#type-representatives).
#### `[Left](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2265) :: a -> [Either](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Either) a b`
Constructs a value of type `Either a b` from a value of type `a`.
```
> S.Left ('Cannot divide by zero')
Left ("Cannot divide by zero")
```
#### `[Right](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2279) :: b -> [Either](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Either) a b`
Constructs a value of type `Either a b` from a value of type `b`.
```
> S.Right (42)
Right (42)
```
#### `[isLeft](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2293) :: [Either](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Either) a b -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Returns `true` if the given Either is a Left; `false` if it is a Right.
```
> S.isLeft (S.Left ('Cannot divide by zero'))
true
> S.isLeft (S.Right (42))
false
```
#### `[isRight](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2313) :: [Either](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Either) a b -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Returns `true` if the given Either is a Right; `false` if it is a Left.
```
> S.isRight (S.Right (42))
true
> S.isRight (S.Left ('Cannot divide by zero'))
false
```
#### `[either](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2333) :: (a -> c) -> (b -> c) -> [Either](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Either) a b -> c`
Takes two functions and an Either, and returns the result of applying the first function to the Left's value, if the Either is a Left, or the result of applying the second function to the Right's value, if the Either is a Right.
See also [`fromLeft`](#fromLeft) and [`fromRight`](#fromRight).
```
> S.either (S.toUpper) (S.show) (S.Left ('Cannot divide by zero'))
"CANNOT DIVIDE BY ZERO"
> S.either (S.toUpper) (S.show) (S.Right (42))
"42"
```
#### `[fromLeft](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2362) :: a -> [Either](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Either) a b -> a`
Takes a default value and an Either, and returns the Left value if the Either is a Left; the default value otherwise.
See also [`either`](#either) and [`fromRight`](#fromRight).
```
> S.fromLeft ('abc') (S.Left ('xyz'))
"xyz"
> S.fromLeft ('abc') (S.Right (123))
"abc"
```
#### `[fromRight](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2385) :: b -> [Either](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Either) a b -> b`
Takes a default value and an Either, and returns the Right value if the Either is a Right; the default value otherwise.
See also [`either`](#either) and [`fromLeft`](#fromLeft).
```
> S.fromRight (123) (S.Right (789))
789
> S.fromRight (123) (S.Left ('abc'))
123
```
#### `[fromEither](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2408) :: b -> [Either](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Either) a b -> b`
Takes a default value and an Either, and returns the Right value if the Either is a Right; the default value otherwise.
The behaviour of `fromEither` is likely to change in a future release. Please use [`fromRight`](#fromRight) instead.
```
> S.fromEither (0) (S.Right (42))
42
> S.fromEither (0) (S.Left (42))
0
```
#### `[lefts](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2432) :: ([Filterable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Filterable) f, [Functor](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Functor) f) => f ([Either](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Either) a b) -> f a`
Discards each element that is a Right, and unwraps each element that is a Left.
See also [`rights`](#rights).
```
> S.lefts ([S.Right (20), S.Left ('foo'), S.Right (10), S.Left ('bar')])
["foo", "bar"]
```
#### `[rights](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2449) :: ([Filterable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Filterable) f, [Functor](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Functor) f) => f ([Either](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Either) a b) -> f b`
Discards each element that is a Left, and unwraps each element that is a Right.
See also [`lefts`](#lefts).
```
> S.rights ([S.Right (20), S.Left ('foo'), S.Right (10), S.Left ('bar')])
[20, 10]
```
#### `[tagBy](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2466) :: (a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)) -> a -> [Either](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Either) a a`
Takes a predicate and a value, and returns a Right of the value if it satisfies the predicate; a Left of the value otherwise.
```
> S.tagBy (S.odd) (0)
Left (0)
> S.tagBy (S.odd) (1)
Right (1)
```
#### `[encase](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2487) :: Throwing e a b -> a -> [Either](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Either) e b`
Takes a function that may throw and returns a pure function.
```
> S.encase (JSON.parse) ('["foo","bar","baz"]')
Right (["foo", "bar", "baz"])
> S.encase (JSON.parse) ('[')
Left (new SyntaxError ("Unexpected end of JSON input"))
```
#### `[eitherToMaybe](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2513) :: [Either](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Either) a b -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) b`
Converts an Either to a Maybe. A Left becomes Nothing; a Right becomes a Just.
See also [`maybeToEither`](#maybeToEither).
```
> S.eitherToMaybe (S.Left ('Cannot divide by zero'))
Nothing
> S.eitherToMaybe (S.Right (42))
Just (42)
```
### Logic
#### `[and](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2538) :: [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean) -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean) -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Boolean "and".
```
> S.and (false) (false)
false
> S.and (false) (true)
false
> S.and (true) (false)
false
> S.and (true) (true)
true
```
#### `[or](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2566) :: [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean) -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean) -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Boolean "or".
```
> S.or (false) (false)
false
> S.or (false) (true)
true
> S.or (true) (false)
true
> S.or (true) (true)
true
```
#### `[not](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2594) :: [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean) -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Boolean "not".
See also [`complement`](#complement).
```
> S.not (false)
true
> S.not (true)
false
```
#### `[complement](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2616) :: (a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)) -> a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Takes a unary predicate and a value of any type, and returns the logical negation of applying the predicate to the value.
See also [`not`](#not).
```
> Number.isInteger (42)
true
> S.complement (Number.isInteger) (42)
false
```
#### `[boolean](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2636) :: a -> a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean) -> a`
Case analysis for the `Boolean` type. `boolean (x) (y) (b)` evaluates to `x` if `b` is `false`; to `y` if `b` is `true`.
```
> S.boolean ('no') ('yes') (false)
"no"
> S.boolean ('no') ('yes') (true)
"yes"
```
#### `[ifElse](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2661) :: (a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)) -> (a -> b) -> (a -> b) -> a -> b`
Takes a unary predicate, a unary "if" function, a unary "else" function, and a value of any type, and returns the result of applying the "if" function to the value if the value satisfies the predicate; the result of applying the "else" function to the value otherwise.
See also [`when`](#when) and [`unless`](#unless).
```
> S.ifElse (x => x < 0) (Math.abs) (Math.sqrt) (-1)
1
> S.ifElse (x => x < 0) (Math.abs) (Math.sqrt) (16)
4
```
#### `[when](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2693) :: (a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)) -> (a -> a) -> a -> a`
Takes a unary predicate, a unary function, and a value of any type, and returns the result of applying the function to the value if the value satisfies the predicate; the value otherwise.
See also [`unless`](#unless) and [`ifElse`](#ifElse).
```
> S.when (x => x >= 0) (Math.sqrt) (16)
4
> S.when (x => x >= 0) (Math.sqrt) (-1)
-1
```
#### `[unless](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2717) :: (a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)) -> (a -> a) -> a -> a`
Takes a unary predicate, a unary function, and a value of any type, and returns the result of applying the function to the value if the value does not satisfy the predicate; the value otherwise.
See also [`when`](#when) and [`ifElse`](#ifElse).
```
> S.unless (x => x < 0) (Math.sqrt) (16)
4
> S.unless (x => x < 0) (Math.sqrt) (-1)
-1
```
### Array
#### `[array](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2743) :: b -> (a -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) a -> b) -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) a -> b`
Case analysis for the `Array a` type.
```
> S.array (S.Nothing) (head => tail => S.Just (head)) ([])
Nothing
> S.array (S.Nothing) (head => tail => S.Just (head)) ([1, 2, 3])
Just (1)
> S.array (S.Nothing) (head => tail => S.Just (tail)) ([])
Nothing
> S.array (S.Nothing) (head => tail => S.Just (tail)) ([1, 2, 3])
Just ([2, 3])
```
#### `[head](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2773) :: [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f => f a -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) a`
Returns Just the first element of the given structure if the structure contains at least one element; Nothing otherwise.
```
> S.head ([1, 2, 3])
Just (1)
> S.head ([])
Nothing
> S.head (Cons (1) (Cons (2) (Cons (3) (Nil))))
Just (1)
> S.head (Nil)
Nothing
```
#### `[last](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2806) :: [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f => f a -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) a`
Returns Just the last element of the given structure if the structure contains at least one element; Nothing otherwise.
```
> S.last ([1, 2, 3])
Just (3)
> S.last ([])
Nothing
> S.last (Cons (1) (Cons (2) (Cons (3) (Nil))))
Just (3)
> S.last (Nil)
Nothing
```
#### `[tail](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2838) :: ([Applicative](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Applicative) f, [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f, [Monoid](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Monoid) (f a)) => f a -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) (f a)`
Returns Just all but the first of the given structure's elements if the structure contains at least one element; Nothing otherwise.
```
> S.tail ([1, 2, 3])
Just ([2, 3])
> S.tail ([])
Nothing
> S.tail (Cons (1) (Cons (2) (Cons (3) (Nil))))
Just (Cons (2) (Cons (3) (Nil)))
> S.tail (Nil)
Nothing
```
#### `[init](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2872) :: ([Applicative](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Applicative) f, [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f, [Monoid](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Monoid) (f a)) => f a -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) (f a)`
Returns Just all but the last of the given structure's elements if the structure contains at least one element; Nothing otherwise.
```
> S.init ([1, 2, 3])
Just ([1, 2])
> S.init ([])
Nothing
> S.init (Cons (1) (Cons (2) (Cons (3) (Nil))))
Just (Cons (1) (Cons (2) (Nil)))
> S.init (Nil)
Nothing
```
#### `[take](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2906) :: ([Applicative](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Applicative) f, [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f, [Monoid](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Monoid) (f a)) => [Integer](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Integer) -> f a -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) (f a)`
Returns Just the first N elements of the given structure if N is non-negative and less than or equal to the size of the structure; Nothing otherwise.
```
> S.take (0) (['foo', 'bar'])
Just ([])
> S.take (1) (['foo', 'bar'])
Just (["foo"])
> S.take (2) (['foo', 'bar'])
Just (["foo", "bar"])
> S.take (3) (['foo', 'bar'])
Nothing
> S.take (3) (Cons (1) (Cons (2) (Cons (3) (Cons (4) (Cons (5) (Nil))))))
Just (Cons (1) (Cons (2) (Cons (3) (Nil))))
```
#### `[drop](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2961) :: ([Applicative](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Applicative) f, [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f, [Monoid](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Monoid) (f a)) => [Integer](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Integer) -> f a -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) (f a)`
Returns Just all but the first N elements of the given structure if N is non-negative and less than or equal to the size of the structure; Nothing otherwise.
```
> S.drop (0) (['foo', 'bar'])
Just (["foo", "bar"])
> S.drop (1) (['foo', 'bar'])
Just (["bar"])
> S.drop (2) (['foo', 'bar'])
Just ([])
> S.drop (3) (['foo', 'bar'])
Nothing
> S.drop (3) (Cons (1) (Cons (2) (Cons (3) (Cons (4) (Cons (5) (Nil))))))
Just (Cons (4) (Cons (5) (Nil)))
```
#### `[takeLast](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L2993) :: ([Applicative](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Applicative) f, [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f, [Monoid](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Monoid) (f a)) => [Integer](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Integer) -> f a -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) (f a)`
Returns Just the last N elements of the given structure if N is non-negative and less than or equal to the size of the structure; Nothing otherwise.
```
> S.takeLast (0) (['foo', 'bar'])
Just ([])
> S.takeLast (1) (['foo', 'bar'])
Just (["bar"])
> S.takeLast (2) (['foo', 'bar'])
Just (["foo", "bar"])
> S.takeLast (3) (['foo', 'bar'])
Nothing
> S.takeLast (3) (Cons (1) (Cons (2) (Cons (3) (Cons (4) (Nil)))))
Just (Cons (2) (Cons (3) (Cons (4) (Nil))))
```
#### `[dropLast](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3026) :: ([Applicative](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Applicative) f, [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f, [Monoid](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Monoid) (f a)) => [Integer](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Integer) -> f a -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) (f a)`
Returns Just all but the last N elements of the given structure if N is non-negative and less than or equal to the size of the structure; Nothing otherwise.
```
> S.dropLast (0) (['foo', 'bar'])
Just (["foo", "bar"])
> S.dropLast (1) (['foo', 'bar'])
Just (["foo"])
> S.dropLast (2) (['foo', 'bar'])
Just ([])
> S.dropLast (3) (['foo', 'bar'])
Nothing
> S.dropLast (3) (Cons (1) (Cons (2) (Cons (3) (Cons (4) (Nil)))))
Just (Cons (1) (Nil))
```
#### `[takeWhile](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3059) :: (a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)) -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) a -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) a`
Discards the first element that does not satisfy the predicate, and all subsequent elements.
See also [`dropWhile`](#dropWhile).
```
> S.takeWhile (S.odd) ([3, 3, 3, 7, 6, 3, 5, 4])
[3, 3, 3, 7]
> S.takeWhile (S.even) ([3, 3, 3, 7, 6, 3, 5, 4])
[]
```
#### `[dropWhile](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3086) :: (a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)) -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) a -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) a`
Retains the first element that does not satisfy the predicate, and all subsequent elements.
See also [`takeWhile`](#takeWhile).
```
> S.dropWhile (S.odd) ([3, 3, 3, 7, 6, 3, 5, 4])
[6, 3, 5, 4]
> S.dropWhile (S.even) ([3, 3, 3, 7, 6, 3, 5, 4])
[3, 3, 3, 7, 6, 3, 5, 4]
```
#### `[size](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3113) :: [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f => f a -> [NonNegativeInteger](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#NonNegativeInteger)`
Returns the number of elements of the given structure.
```
> S.size ([])
0
> S.size (['foo', 'bar', 'baz'])
3
> S.size (Nil)
0
> S.size (Cons ('foo') (Cons ('bar') (Cons ('baz') (Nil))))
3
> S.size (S.Nothing)
0
> S.size (S.Just ('quux'))
1
> S.size (S.Pair ('ignored!') ('counted!'))
1
```
#### `[all](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3145) :: [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f => (a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)) -> f a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Returns `true` [iff](https://en.wikipedia.org/wiki/If_and_only_if) all the elements of the structure satisfy the predicate.
See also [`any`](#any) and [`none`](#none).
```
> S.all (S.odd) ([])
true
> S.all (S.odd) ([1, 3, 5])
true
> S.all (S.odd) ([1, 2, 3])
false
```
#### `[any](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3168) :: [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f => (a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)) -> f a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Returns `true` [iff](https://en.wikipedia.org/wiki/If_and_only_if) any element of the structure satisfies the predicate.
See also [`all`](#all) and [`none`](#none).
```
> S.any (S.odd) ([])
false
> S.any (S.odd) ([2, 4, 6])
false
> S.any (S.odd) ([1, 2, 3])
true
```
#### `[none](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3191) :: [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f => (a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)) -> f a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Returns `true` [iff](https://en.wikipedia.org/wiki/If_and_only_if) none of the elements of the structure satisfies the predicate.
Properties:
* `forall p :: a -> Boolean, xs :: Foldable f => f a. S.none (p) (xs) = S.not (S.any (p) (xs))`
* `forall p :: a -> Boolean, xs :: Foldable f => f a. S.none (p) (xs) = S.all (S.complement (p)) (xs)`
See also [`all`](#all) and [`any`](#any).
```
> S.none (S.odd) ([])
true
> S.none (S.odd) ([2, 4, 6])
true
> S.none (S.odd) ([1, 2, 3])
false
```
#### `[append](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3222) :: ([Applicative](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Applicative) f, [Semigroup](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Semigroup) (f a)) => a -> f a -> f a`
Returns the result of appending the first argument to the second.
See also [`prepend`](#prepend).
```
> S.append (3) ([1, 2])
[1, 2, 3]
> S.append (3) (Cons (1) (Cons (2) (Nil)))
Cons (1) (Cons (2) (Cons (3) (Nil)))
> S.append ([1]) (S.Nothing)
Just ([1])
> S.append ([3]) (S.Just ([1, 2]))
Just ([1, 2, 3])
```
#### `[prepend](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3252) :: ([Applicative](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Applicative) f, [Semigroup](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Semigroup) (f a)) => a -> f a -> f a`
Returns the result of prepending the first argument to the second.
See also [`append`](#append).
```
> S.prepend (1) ([2, 3])
[1, 2, 3]
> S.prepend (1) (Cons (2) (Cons (3) (Nil)))
Cons (1) (Cons (2) (Cons (3) (Nil)))
> S.prepend ([1]) (S.Nothing)
Just ([1])
> S.prepend ([1]) (S.Just ([2, 3]))
Just ([1, 2, 3])
```
#### `[joinWith](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3277) :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String)`
Joins the strings of the second argument separated by the first argument.
Properties:
* `forall s :: String, t :: String. S.joinWith (s) (S.splitOn (s) (t)) = t`
See also [`splitOn`](#splitOn) and [`intercalate`](#intercalate).
```
> S.joinWith (':') (['foo', 'bar', 'baz'])
"foo:bar:baz"
```
#### `[elem](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3298) :: ([Setoid](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Setoid) a, [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f) => a -> f a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Takes a value and a structure and returns `true` [iff](https://en.wikipedia.org/wiki/If_and_only_if) the value is an element of the structure.
See also [`find`](#find).
```
> S.elem ('c') (['a', 'b', 'c'])
true
> S.elem ('x') (['a', 'b', 'c'])
false
> S.elem (3) ({x: 1, y: 2, z: 3})
true
> S.elem (8) ({x: 1, y: 2, z: 3})
false
> S.elem (0) (S.Just (0))
true
> S.elem (0) (S.Just (1))
false
> S.elem (0) (S.Nothing)
false
```
#### `[find](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3333) :: [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f => (a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)) -> f a -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) a`
Takes a predicate and a structure and returns Just the leftmost element of the structure that satisfies the predicate; Nothing if there is no such element.
See also [`elem`](#elem).
```
> S.find (S.lt (0)) ([1, -2, 3, -4, 5])
Just (-2)
> S.find (S.lt (0)) ([1, 2, 3, 4, 5])
Nothing
```
#### `[intercalate](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3365) :: ([Monoid](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Monoid) m, [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f) => m -> f m -> m`
Curried version of [`Z.intercalate`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#intercalate). Concatenates the elements of the given structure, separating each pair of adjacent elements with the given separator.
See also [`joinWith`](#joinWith).
```
> S.intercalate (', ') ([])
""
> S.intercalate (', ') (['foo', 'bar', 'baz'])
"foo, bar, baz"
> S.intercalate (', ') (Nil)
""
> S.intercalate (', ') (Cons ('foo') (Cons ('bar') (Cons ('baz') (Nil))))
"foo, bar, baz"
> S.intercalate ([0, 0, 0]) ([])
[]
> S.intercalate ([0, 0, 0]) ([[1], [2, 3], [4, 5, 6], [7, 8], [9]])
[1, 0, 0, 0, 2, 3, 0, 0, 0, 4, 5, 6, 0, 0, 0, 7, 8, 0, 0, 0, 9]
```
#### `[foldMap](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3398) :: ([Monoid](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Monoid) m, [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f) => [TypeRep](https://github.com/fantasyland/fantasy-land#type-representatives) m -> (a -> m) -> f a -> m`
Curried version of [`Z.foldMap`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#foldMap). Deconstructs a foldable by mapping every element to a monoid and concatenating the results.
```
> S.foldMap (String) (f => f.name) ([Math.sin, Math.cos, Math.tan])
"sincostan"
> S.foldMap (Array) (x => [x + 1, x + 2]) ([10, 20, 30])
[11, 12, 21, 22, 31, 32]
```
#### `[unfoldr](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3416) :: (b -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) ([Pair](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Pair) a b)) -> b -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) a`
Takes a function and a seed value, and returns an array generated by applying the function repeatedly. The array is initially empty. The function is initially applied to the seed value. Each application of the function should result in either:
* Nothing, in which case the array is returned; or
* Just a pair, in which case the first element is appended to the array and the function is applied to the second element.
```
> S.unfoldr (n => n < 1000 ? S.Just (S.Pair (n) (2 * n)) : S.Nothing) (1)
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
```
#### `[range](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3447) :: [Integer](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Integer) -> [Integer](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Integer) -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) [Integer](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Integer)`
Returns an array of consecutive integers starting with the first argument and ending with the second argument minus one. Returns `[]` if the second argument is less than or equal to the first argument.
```
> S.range (0) (10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
> S.range (-5) (0)
[-5, -4, -3, -2, -1]
> S.range (0) (-5)
[]
```
#### `[groupBy](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3476) :: (a -> a -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)) -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) a -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) ([Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) a)`
Splits its array argument into an array of arrays of equal, adjacent elements. Equality is determined by the function provided as the first argument. Its behaviour can be surprising for functions that aren't reflexive, transitive, and symmetric (see [equivalence](https://en.wikipedia.org/wiki/Equivalence_relation) relation).
Properties:
* `forall f :: a -> a -> Boolean, xs :: Array a. S.join (S.groupBy (f) (xs)) = xs`
```
> S.groupBy (S.equals) ([1, 1, 2, 1, 1])
[[1, 1], [2], [1, 1]]
> S.groupBy (x => y => x + y === 0) ([2, -3, 3, 3, 3, 4, -4, 4])
[[2], [-3, 3, 3, 3], [4, -4], [4]]
```
#### `[reverse](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3515) :: ([Applicative](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Applicative) f, [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f, [Monoid](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Monoid) (f a)) => f a -> f a`
Reverses the elements of the given structure.
```
> S.reverse ([1, 2, 3])
[3, 2, 1]
> S.reverse (Cons (1) (Cons (2) (Cons (3) (Nil))))
Cons (3) (Cons (2) (Cons (1) (Nil)))
> S.pipe ([S.splitOn (''), S.reverse, S.joinWith ('')]) ('abc')
"cba"
```
#### `[sort](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3535) :: ([Ord](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Ord) a, [Applicative](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Applicative) m, [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) m, [Monoid](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Monoid) (m a)) => m a -> m a`
Performs a [stable sort](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability) of the elements of the given structure, using [`Z.lte`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#lte) for comparisons.
Properties:
* `S.sort (S.sort (m)) = S.sort (m)` (idempotence)
See also [`sortBy`](#sortBy).
```
> S.sort (['foo', 'bar', 'baz'])
["bar", "baz", "foo"]
> S.sort ([S.Left (4), S.Right (3), S.Left (2), S.Right (1)])
[Left (2), Left (4), Right (1), Right (3)]
```
#### `[sortBy](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3559) :: ([Ord](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Ord) b, [Applicative](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Applicative) m, [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) m, [Monoid](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Monoid) (m a)) => (a -> b) -> m a -> m a`
Performs a [stable sort](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability) of the elements of the given structure, using [`Z.lte`](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#lte) to compare the values produced by applying the given function to each element of the structure.
Properties:
* `S.sortBy (f) (S.sortBy (f) (m)) = S.sortBy (f) (m)` (idempotence)
See also [`sort`](#sort).
```
> S.sortBy (S.prop ('rank')) ([{rank: 7, suit: 'spades'}, {rank: 5, suit: 'hearts'}, {rank: 2, suit: 'hearts'}, {rank: 5, suit: 'spades'}])
[{"rank": 2, "suit": "hearts"}, {"rank": 5, "suit": "hearts"}, {"rank": 5, "suit": "spades"}, {"rank": 7, "suit": "spades"}]
> S.sortBy (S.prop ('suit')) ([{rank: 7, suit: 'spades'}, {rank: 5, suit: 'hearts'}, {rank: 2, suit: 'hearts'}, {rank: 5, suit: 'spades'}])
[{"rank": 5, "suit": "hearts"}, {"rank": 2, "suit": "hearts"}, {"rank": 7, "suit": "spades"}, {"rank": 5, "suit": "spades"}]
```
If descending order is desired, one may use [`Descending`](https://github.com/sanctuary-js/sanctuary-descending/tree/v2.1.0#Descending):
```
> S.sortBy (Descending) ([83, 97, 110, 99, 116, 117, 97, 114, 121])
[121, 117, 116, 114, 110, 99, 97, 97, 83]
```
#### `[zip](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3607) :: [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) a -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) b -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) ([Pair](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Pair) a b)`
Returns an array of pairs of corresponding elements from the given arrays. The length of the resulting array is equal to the length of the shorter input array.
See also [`zipWith`](#zipWith).
```
> S.zip (['a', 'b']) (['x', 'y', 'z'])
[Pair ("a") ("x"), Pair ("b") ("y")]
> S.zip ([1, 3, 5]) ([2, 4])
[Pair (1) (2), Pair (3) (4)]
```
#### `[zipWith](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3628) :: (a -> b -> c) -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) a -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) b -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) c`
Returns the result of combining, pairwise, the given arrays using the given binary function. The length of the resulting array is equal to the length of the shorter input array.
See also [`zip`](#zip).
```
> S.zipWith (a => b => a + b) (['a', 'b']) (['x', 'y', 'z'])
["ax", "by"]
> S.zipWith (a => b => [a, b]) ([1, 3, 5]) ([2, 4])
[[1, 2], [3, 4]]
```
### Object
#### `[prop](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3663) :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> a -> b`
Takes a property name and an object with known properties and returns the value of the specified property. If for some reason the object lacks the specified property, a type error is thrown.
For accessing properties of uncertain objects, use [`get`](#get) instead. For accessing string map values by key, use [`value`](#value) instead.
```
> S.prop ('a') ({a: 1, b: 2})
1
```
#### `[props](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3690) :: [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> a -> b`
Takes a property path (an array of property names) and an object with known structure and returns the value at the given path. If for some reason the path does not exist, a type error is thrown.
For accessing property paths of uncertain objects, use [`gets`](#gets) instead.
```
> S.props (['a', 'b', 'c']) ({a: {b: {c: 1}}})
1
```
#### `[get](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3719) :: ([Any](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Any) -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> a -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) b`
Takes a predicate, a property name, and an object and returns Just the value of the specified object property if it exists and the value satisfies the given predicate; Nothing otherwise.
See also [`gets`](#gets), [`prop`](#prop), and [`value`](#value).
```
> S.get (S.is ($.Number)) ('x') ({x: 1, y: 2})
Just (1)
> S.get (S.is ($.Number)) ('x') ({x: '1', y: '2'})
Nothing
> S.get (S.is ($.Number)) ('x') ({})
Nothing
> S.get (S.is ($.Array ($.Number))) ('x') ({x: [1, 2, 3]})
Just ([1, 2, 3])
> S.get (S.is ($.Array ($.Number))) ('x') ({x: [1, 2, 3, null]})
Nothing
```
#### `[gets](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3752) :: ([Any](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Any) -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)) -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> a -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) b`
Takes a predicate, a property path (an array of property names), and an object and returns Just the value at the given path if such a path exists and the value satisfies the given predicate; Nothing otherwise.
See also [`get`](#get).
```
> S.gets (S.is ($.Number)) (['a', 'b', 'c']) ({a: {b: {c: 42}}})
Just (42)
> S.gets (S.is ($.Number)) (['a', 'b', 'c']) ({a: {b: {c: '42'}}})
Nothing
> S.gets (S.is ($.Number)) (['a', 'b', 'c']) ({})
Nothing
```
### StrMap
StrMap is an abbreviation of *string map*. A string map is an object, such as `{foo: 1, bar: 2, baz: 3}`, whose values are all members of the same type. Formally, a value is a member of type `StrMap a` if its [type identifier](https://github.com/sanctuary-js/sanctuary-type-identifiers/tree/v3.0.0) is `'Object'` and the values of its enumerable own properties are all members of type `a`.
#### `[value](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3793) :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [StrMap](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#StrMap) a -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) a`
Retrieve the value associated with the given key in the given string map.
Formally, `value (k) (m)` evaluates to `Just (m[k])` if `k` is an enumerable own property of `m`; `Nothing` otherwise.
See also [`prop`](#prop) and [`get`](#get).
```
> S.value ('foo') ({foo: 1, bar: 2})
Just (1)
> S.value ('bar') ({foo: 1, bar: 2})
Just (2)
> S.value ('baz') ({foo: 1, bar: 2})
Nothing
```
#### `[singleton](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3825) :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> a -> [StrMap](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#StrMap) a`
Takes a string and a value of any type, and returns a string map with a single entry (mapping the key to the value).
```
> S.singleton ('foo') (42)
{"foo": 42}
```
#### `[insert](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3847) :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> a -> [StrMap](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#StrMap) a -> [StrMap](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#StrMap) a`
Takes a string, a value of any type, and a string map, and returns a string map comprising all the entries of the given string map plus the entry specified by the first two arguments (which takes precedence).
Equivalent to Haskell's `insert` function. Similar to Clojure's `assoc` function.
```
> S.insert ('c') (3) ({a: 1, b: 2})
{"a": 1, "b": 2, "c": 3}
> S.insert ('a') (4) ({a: 1, b: 2})
{"a": 4, "b": 2}
```
#### `[remove](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3876) :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [StrMap](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#StrMap) a -> [StrMap](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#StrMap) a`
Takes a string and a string map, and returns a string map comprising all the entries of the given string map except the one whose key matches the given string (if such a key exists).
Equivalent to Haskell's `delete` function. Similar to Clojure's `dissoc` function.
```
> S.remove ('c') ({a: 1, b: 2, c: 3})
{"a": 1, "b": 2}
> S.remove ('c') ({})
{}
```
#### `[keys](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3905) :: [StrMap](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#StrMap) a -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String)`
Returns the keys of the given string map, in arbitrary order.
```
> S.sort (S.keys ({b: 2, c: 3, a: 1}))
["a", "b", "c"]
```
#### `[values](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3919) :: [StrMap](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#StrMap) a -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) a`
Returns the values of the given string map, in arbitrary order.
```
> S.sort (S.values ({a: 1, c: 3, b: 2}))
[1, 2, 3]
```
#### `[pairs](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3936) :: [StrMap](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#StrMap) a -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) ([Pair](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Pair) [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) a)`
Returns the key–value pairs of the given string map, in arbitrary order.
```
> S.sort (S.pairs ({b: 2, a: 1, c: 3}))
[Pair ("a") (1), Pair ("b") (2), Pair ("c") (3)]
```
#### `[fromPairs](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3954) :: [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f => f ([Pair](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Pair) [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) a) -> [StrMap](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#StrMap) a`
Returns a string map containing the key–value pairs specified by the given [Foldable](https://github.com/fantasyland/fantasy-land/tree/v4.0.1#foldable). If a key appears in multiple pairs, the rightmost pair takes precedence.
```
> S.fromPairs ([S.Pair ('a') (1), S.Pair ('b') (2), S.Pair ('c') (3)])
{"a": 1, "b": 2, "c": 3}
> S.fromPairs ([S.Pair ('x') (1), S.Pair ('x') (2)])
{"x": 2}
```
### Number
#### `[negate](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L3981) :: [ValidNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#ValidNumber) -> [ValidNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#ValidNumber)`
Negates its argument.
```
> S.negate (12.5)
-12.5
> S.negate (-42)
42
```
#### `[add](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4001) :: [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber) -> [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber) -> [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber)`
Returns the sum of two (finite) numbers.
```
> S.add (1) (1)
2
```
#### `[sum](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4020) :: [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f => f [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber) -> [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber)`
Returns the sum of the given array of (finite) numbers.
```
> S.sum ([1, 2, 3, 4, 5])
15
> S.sum ([])
0
> S.sum (S.Just (42))
42
> S.sum (S.Nothing)
0
```
#### `[sub](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4043) :: [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber) -> [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber) -> [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber)`
Takes a finite number `n` and returns the *subtract `n`* function.
```
> S.map (S.sub (1)) ([1, 2, 3])
[0, 1, 2]
```
#### `[mult](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4062) :: [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber) -> [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber) -> [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber)`
Returns the product of two (finite) numbers.
```
> S.mult (4) (2)
8
```
#### `[product](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4081) :: [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f => f [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber) -> [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber)`
Returns the product of the given array of (finite) numbers.
```
> S.product ([1, 2, 3, 4, 5])
120
> S.product ([])
1
> S.product (S.Just (42))
42
> S.product (S.Nothing)
1
```
#### `[div](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4104) :: [NonZeroFiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#NonZeroFiniteNumber) -> [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber) -> [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber)`
Takes a non-zero finite number `n` and returns the *divide by `n`* function.
```
> S.map (S.div (2)) ([0, 1, 2, 3])
[0, 0.5, 1, 1.5]
```
#### `[pow](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4124) :: [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber) -> [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber) -> [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber)`
Takes a finite number `n` and returns the *power of `n`* function.
```
> S.map (S.pow (2)) ([-3, -2, -1, 0, 1, 2, 3])
[9, 4, 1, 0, 1, 4, 9]
> S.map (S.pow (0.5)) ([1, 4, 9, 16, 25])
[1, 2, 3, 4, 5]
```
#### `[mean](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4146) :: [Foldable](https://github.com/sanctuary-js/sanctuary-type-classes/tree/v12.1.0#Foldable) f => f [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber) -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) [FiniteNumber](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#FiniteNumber)`
Returns the mean of the given array of (finite) numbers.
```
> S.mean ([1, 2, 3, 4, 5])
Just (3)
> S.mean ([])
Nothing
> S.mean (S.Just (42))
Just (42)
> S.mean (S.Nothing)
Nothing
```
### Integer
#### `[even](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4183) :: [Integer](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Integer) -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Returns `true` if the given integer is even; `false` if it is odd.
```
> S.even (42)
true
> S.even (99)
false
```
#### `[odd](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4203) :: [Integer](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Integer) -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Returns `true` if the given integer is odd; `false` if it is even.
```
> S.odd (99)
true
> S.odd (42)
false
```
### Parse
#### `[parseDate](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4225) :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) [ValidDate](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#ValidDate)`
Takes a string `s` and returns `Just (new Date (s))` if `new Date (s)` evaluates to a [`ValidDate`](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#ValidDate) value; Nothing otherwise.
As noted in [#488](https://github.com/sanctuary-js/sanctuary/issues/488), this function's behaviour is unspecified for some inputs! [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) warns against using the `Date` constructor to parse date strings:
> **Note:** parsing of date strings with the `Date` constructor […] is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
>
>
```
> S.parseDate ('2011-01-19T17:40:00Z')
Just (new Date ("2011-01-19T17:40:00.000Z"))
> S.parseDate ('today')
Nothing
```
#### `[parseFloat](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4291) :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) [Number](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Number)`
Takes a string and returns Just the number represented by the string if it does in fact represent a number; Nothing otherwise.
```
> S.parseFloat ('-123.45')
Just (-123.45)
> S.parseFloat ('foo.bar')
Nothing
```
#### `[parseInt](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4319) :: Radix -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) [Integer](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Integer)`
Takes a radix (an integer between 2 and 36 inclusive) and a string, and returns Just the number represented by the string if it does in fact represent a number in the base specified by the radix; Nothing otherwise.
This function is stricter than [`parseInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt): a string is considered to represent an integer only if all its non-prefix characters are members of the character set specified by the radix.
```
> S.parseInt (10) ('-42')
Just (-42)
> S.parseInt (16) ('0xFF')
Just (255)
> S.parseInt (16) ('0xGG')
Nothing
```
#### `[parseJson](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4359) :: ([Any](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Any) -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) a`
Takes a predicate and a string that may or may not be valid JSON, and returns Just the result of applying `JSON.parse` to the string *if* the result satisfies the predicate; Nothing otherwise.
```
> S.parseJson (S.is ($.Array ($.Integer))) ('[')
Nothing
> S.parseJson (S.is ($.Array ($.Integer))) ('["1","2","3"]')
Nothing
> S.parseJson (S.is ($.Array ($.Integer))) ('[0,1.5,3,4.5]')
Nothing
> S.parseJson (S.is ($.Array ($.Integer))) ('[1,2,3]')
Just ([1, 2, 3])
```
### RegExp
#### `[regex](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4411) :: [RegexFlags](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#RegexFlags) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [RegExp](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#RegExp)`
Takes a [RegexFlags](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#RegexFlags) and a pattern, and returns a RegExp.
```
> S.regex ('g') (':\\d+:')
/:\d+:/g
```
#### `[regexEscape](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4430) :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String)`
Takes a string that may contain regular expression metacharacters, and returns a string with those metacharacters escaped.
Properties:
* `forall s :: String. S.test (S.regex ('') (S.regexEscape (s))) (s) = true`
```
> S.regexEscape ('-=*{XYZ}*=-')
"\\-=\\*\\{XYZ\\}\\*=\\-"
```
#### `[test](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4453) :: [RegExp](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#RegExp) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [Boolean](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Boolean)`
Takes a pattern and a string, and returns `true` [iff](https://en.wikipedia.org/wiki/If_and_only_if) the pattern matches the string.
```
> S.test (/^a/) ('abacus')
true
> S.test (/^a/) ('banana')
false
```
#### `[match](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4476) :: [NonGlobalRegExp](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#NonGlobalRegExp) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) { match :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String), groups :: [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) ([Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String)) }`
Takes a pattern and a string, and returns Just a match record if the pattern matches the string; Nothing otherwise.
`groups :: Array (Maybe String)` acknowledges the existence of optional capturing groups.
Properties:
* `forall p :: Pattern, s :: String. S.head (S.matchAll (S.regex ('g') (p)) (s)) = S.match (S.regex ('') (p)) (s)`
See also [`matchAll`](#matchAll).
```
> S.match (/(good)?bye/) ('goodbye')
Just ({"groups": [Just ("good")], "match": "goodbye"})
> S.match (/(good)?bye/) ('bye')
Just ({"groups": [Nothing], "match": "bye"})
```
#### `[matchAll](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4511) :: [GlobalRegExp](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#GlobalRegExp) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) { match :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String), groups :: [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) ([Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String)) }`
Takes a pattern and a string, and returns an array of match records.
`groups :: Array (Maybe String)` acknowledges the existence of optional capturing groups.
See also [`match`](#match).
```
> S.matchAll (/@([a-z]+)/g) ('Hello, world!')
[]
> S.matchAll (/@([a-z]+)/g) ('Hello, @foo! Hello, @bar! Hello, @baz!')
[{"groups": [Just ("foo")], "match": "@foo"}, {"groups": [Just ("bar")], "match": "@bar"}, {"groups": [Just ("baz")], "match": "@baz"}]
```
### String
#### `[toUpper](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4548) :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String)`
Returns the upper-case equivalent of its argument.
See also [`toLower`](#toLower).
```
> S.toUpper ('ABC def 123')
"ABC DEF 123"
```
#### `[toLower](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4564) :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String)`
Returns the lower-case equivalent of its argument.
See also [`toUpper`](#toUpper).
```
> S.toLower ('ABC def 123')
"abc def 123"
```
#### `[trim](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4580) :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String)`
Strips leading and trailing whitespace characters.
```
> S.trim ('\t\t foo bar \n')
"foo bar"
```
#### `[stripPrefix](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4594) :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String)`
Returns Just the portion of the given string (the second argument) left after removing the given prefix (the first argument) if the string starts with the prefix; Nothing otherwise.
See also [`stripSuffix`](#stripSuffix).
```
> S.stripPrefix ('https://') ('https://sanctuary.js.org')
Just ("sanctuary.js.org")
> S.stripPrefix ('https://') ('http://sanctuary.js.org')
Nothing
```
#### `[stripSuffix](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4621) :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [Maybe](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Maybe) [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String)`
Returns Just the portion of the given string (the second argument) left after removing the given suffix (the first argument) if the string ends with the suffix; Nothing otherwise.
See also [`stripPrefix`](#stripPrefix).
```
> S.stripSuffix ('.md') ('README.md')
Just ("README")
> S.stripSuffix ('.md') ('README')
Nothing
```
#### `[words](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4648) :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String)`
Takes a string and returns the array of words the string contains (words are delimited by whitespace characters).
See also [`unwords`](#unwords).
```
> S.words (' foo bar baz ')
["foo", "bar", "baz"]
```
#### `[unwords](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4671) :: [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String)`
Takes an array of words and returns the result of joining the words with separating spaces.
See also [`words`](#words).
```
> S.unwords (['foo', 'bar', 'baz'])
"foo bar baz"
```
#### `[lines](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4688) :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String)`
Takes a string and returns the array of lines the string contains (lines are delimited by newlines: `'\n'` or `'\r\n'` or `'\r'`). The resulting strings do not contain newlines.
See also [`unlines`](#unlines).
```
> S.lines ('foo\nbar\nbaz\n')
["foo", "bar", "baz"]
```
#### `[unlines](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4710) :: [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String)`
Takes an array of lines and returns the result of joining the lines after appending a terminating line feed (`'\n'`) to each.
See also [`lines`](#lines).
```
> S.unlines (['foo', 'bar', 'baz'])
"foo\nbar\nbaz\n"
```
#### `[splitOn](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4730) :: [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String)`
Returns the substrings of its second argument separated by occurrences of its first argument.
See also [`joinWith`](#joinWith) and [`splitOnRegex`](#splitOnRegex).
```
> S.splitOn ('::') ('foo::bar::baz')
["foo", "bar", "baz"]
```
#### `[splitOnRegex](https://github.com/sanctuary-js/sanctuary/blob/v3.1.0/index.js#L4747) :: [GlobalRegExp](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#GlobalRegExp) -> [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String) -> [Array](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#Array) [String](https://github.com/sanctuary-js/sanctuary-def/tree/v0.22.0#String)`
Takes a pattern and a string, and returns the result of splitting the string at every non-overlapping occurrence of the pattern.
Properties:
* `forall s :: String, t :: String. S.joinWith (s) (S.splitOnRegex (S.regex ('g') (S.regexEscape (s))) (t)) = t`
See also [`splitOn`](#splitOn).
```
> S.splitOnRegex (/[,;][ ]*/g) ('foo, bar, baz')
["foo", "bar", "baz"]
> S.splitOnRegex (/[,;][ ]*/g) ('foo;bar;baz')
["foo", "bar", "baz"]
```
| programming_docs |
dojo dojo/main.cldr dojo/main.cldr
==============
Properties
----------
### monetary
Defined by: [dojo/cldr/monetary](cldr/monetary)
TODOC
### supplemental
Defined by: [dojo/cldr/supplemental](cldr/supplemental)
TODOC
dojo dojo/uacss dojo/uacss
==========
Summary
-------
Applies pre-set CSS classes to the top-level HTML node, based on:
* browser (ex: dj\_ie)
* browser version (ex: dj\_ie6)
* box model (ex: dj\_contentBox)
* text direction (ex: dijitRtl)
In addition, browser, browser version, and box model are combined with an RTL flag when browser text is RTL. ex: dj\_ie-rtl.
Returns the has() method.
See the [dojo/uacss reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/uacss.html) for more information.
dojo dojo/main.colors dojo/main.colors
================
Methods
-------
###
`makeGrey``(g,a)`
Defined by [dojo/colors](colors)
creates a greyscale color with an optional alpha
| Parameter | Type | Description |
| --- | --- | --- |
| g | Number | |
| a | Number | *Optional* |
dojo dojo/main.i18n dojo/main.i18n
==============
Summary
-------
This module implements the [dojo/i18n](i18n)! plugin and the v1.6- i18n API
We choose to include our own plugin to leverage functionality already contained in dojo and thereby reduce the size of the plugin compared to various loader implementations. Also, this allows foreign AMD loaders to be used without their plugins.
Properties
----------
### cache
Defined by: [dojo/i18n](i18n)
### dynamic
Defined by: [dojo/i18n](i18n)
### unitTests
Defined by: [dojo/i18n](i18n)
Methods
-------
###
`getL10nName``(moduleName,bundleName,locale)`
Defined by [dojo/i18n](i18n)
| Parameter | Type | Description |
| --- | --- | --- |
| moduleName | undefined | |
| bundleName | undefined | |
| locale | undefined | |
**Returns:** string
###
`getLocalization``(moduleName,bundleName,locale)`
Defined by [dojo/i18n](i18n)
| Parameter | Type | Description |
| --- | --- | --- |
| moduleName | undefined | |
| bundleName | undefined | |
| locale | undefined | |
**Returns:** undefined
###
`load``(id,require,load)`
Defined by [dojo/i18n](i18n)
id is in one of the following formats
1. /nls/ => load the bundle, localized to config.locale; load all bundles localized to config.extraLocale (if any); return the loaded bundle localized to config.locale.
2. /nls// => load then return the bundle localized to
3. *preload*/nls/\* => for config.locale and all config.extraLocale, load all bundles found in the best-matching bundle rollup. A value of 1 is returned, which is meaningless other than to say the plugin is executing the requested preloads
In cases 1 and 2, is always normalized to an absolute module id upon entry; see normalize. In case 3, it is assumed to be absolute; this is arranged by the builder.
To load a bundle means to insert the bundle into the plugin's cache and publish the bundle value to the loader. Given , , and a particular , the cache key
```
<path>/nls/<bundle>/<locale>
```
will hold the value. Similarly, then plugin will publish this value to the loader by
```
define("<path>/nls/<bundle>/<locale>", <bundle-value>);
```
Given this algorithm, other machinery can provide fast load paths be preplacing values in the plugin's cache, which is public. When a load is demanded the cache is inspected before starting any loading. Explicitly placing values in the plugin cache is an advanced/experimental feature that should not be needed; use at your own risk.
For the normal AMD algorithm, the root bundle is loaded first, which instructs the plugin what additional localized bundles are required for a particular locale. These additional locales are loaded and a mix of the root and each progressively-specific locale is returned. For example:
1. The client demands "dojo/i18n!some/path/nls/someBundle
2. The loader demands load(some/path/nls/someBundle)
3. This plugin require's "some/path/nls/someBundle", which is the root bundle.
4. Assuming config.locale is "ab-cd-ef" and the root bundle indicates that localizations are available for "ab" and "ab-cd-ef" (note the missing "ab-cd", then the plugin requires "some/path/nls/ab/someBundle" and "some/path/nls/ab-cd-ef/someBundle"
5. Upon receiving all required bundles, the plugin constructs the value of the bundle ab-cd-ef as...
```
mixin(mixin(mixin({}, require("some/path/nls/someBundle"),
require("some/path/nls/ab/someBundle")),
require("some/path/nls/ab-cd-ef/someBundle"));
```
This value is inserted into the cache and published to the loader at the key/module-id some/path/nls/someBundle/ab-cd-ef.
The special preload signature (case 3) instructs the plugin to stop servicing all normal requests (further preload requests will be serviced) until all ongoing preloading has completed.
The preload signature instructs the plugin that a special rollup module is available that contains one or more flattened, localized bundles. The JSON array of available locales indicates which locales are available. Here is an example:
```
*preload*some/path/nls/someModule*["root", "ab", "ab-cd-ef"]
```
This indicates the following rollup modules are available:
```
some/path/nls/someModule_ROOT
some/path/nls/someModule_ab
some/path/nls/someModule_ab-cd-ef
```
Each of these modules is a normal AMD module that contains one or more flattened bundles in a hash. For example, assume someModule contained the bundles some/bundle/path/someBundle and some/bundle/path/someOtherBundle, then some/path/nls/someModule\_ab would be expressed as follows:
```
define({
some/bundle/path/someBundle:<value of someBundle, flattened with respect to locale ab>,
some/bundle/path/someOtherBundle:<value of someOtherBundle, flattened with respect to locale ab>,
});
```
E.g., given this design, preloading for locale=="ab" can execute the following algorithm:
```
require(["some/path/nls/someModule_ab"], function(rollup){
for(var p in rollup){
var id = p + "/ab",
cache[id] = rollup[p];
define(id, rollup[p]);
}
});
```
Similarly, if "ab-cd" is requested, the algorithm can determine that "ab" is the best available and load accordingly.
The builder will write such rollups for every layer if a non-empty localeList profile property is provided. Further, the builder will include the following cache entry in the cache associated with any layer.
```
"*now":function(r){r(['dojo/i18n!*preload*<path>/nls/<module>*<JSON array of available locales>']);}
```
The \*now special cache module instructs the loader to apply the provided function to context-require with respect to the particular layer being defined. This causes the plugin to hold all normal service requests until all preloading is complete.
Notice that this algorithm is rarely better than the standard AMD load algorithm. Consider the normal case where the target locale has a single segment and a layer depends on a single bundle:
Without Preloads:
1. Layer loads root bundle.
2. bundle is demanded; plugin loads single localized bundle.
With Preloads:
1. Layer causes preloading of target bundle.
2. bundle is demanded; service is delayed until preloading complete; bundle is returned.
In each case a single transaction is required to load the target bundle. In cases where multiple bundles are required and/or the locale has multiple segments, preloads still requires a single transaction whereas the normal path requires an additional transaction for each additional bundle/locale-segment. However all of these additional transactions can be done concurrently. Owing to this analysis, the entire preloading algorithm can be discard during a build by setting the has feature dojo-preload-i18n-Api to false.
| Parameter | Type | Description |
| --- | --- | --- |
| id | undefined | |
| require | undefined | |
| load | undefined | |
###
`normalize``(id,toAbsMid)`
Defined by [dojo/i18n](i18n)
id may be relative. preload has form `*preload*<path>/nls/<module>*<flattened locales>` and therefore never looks like a relative
| Parameter | Type | Description |
| --- | --- | --- |
| id | undefined | |
| toAbsMid | undefined | |
**Returns:** undefined
###
`normalizeLocale``(locale)`
Defined by [dojo/i18n](i18n)
| Parameter | Type | Description |
| --- | --- | --- |
| locale | undefined | |
**Returns:** undefined
dojo dojo/main.__XhrArgs dojo/main.\_\_XhrArgs
=====================
Summary
-------
In addition to the properties listed for the dojo.\_IoArgs type, the following properties are allowed for dojo.xhr\* methods.
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new main.__XhrArgs()`
Properties
----------
### content
Defined by: [dojo/\_base/xhr](_base/xhr)
Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
### contentType
Defined by: [dojo/\_base/xhr](_base/xhr)
"application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
### failOk
Defined by: [dojo/\_base/xhr](_base/xhr)
false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
### form
Defined by: [dojo/\_base/xhr](_base/xhr)
DOM node for a form. Used to extract the form values and send to the server.
### handleAs
Defined by: [dojo/\_base/xhr](_base/xhr)
Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See [dojo/\_base/xhr.contentHandlers](_base/xhr.contenthandlers)
### headers
Defined by: [dojo/\_base/xhr](_base/xhr)
Additional HTTP headers to send in the request.
### ioPublish
Defined by: [dojo/\_base/xhr](_base/xhr)
Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via [dojo/topic.publish()](topic#publish) for different phases of an IO operation. See [dojo/main.\_\_IoPublish](main.__iopublish) for a list of topics that are published.
### preventCache
Defined by: [dojo/\_base/xhr](_base/xhr)
Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
### rawBody
Defined by: [dojo/\_base/xhr](_base/xhr)
Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for [dojo/\_base/xhr.rawXhrPost](_base/xhr#rawXhrPost) and [dojo/\_base/xhr.rawXhrPut](_base/xhr#rawXhrPut) respectively.
### sync
Defined by: [dojo/\_base/xhr](_base/xhr)
false is default. Indicates whether the request should be a synchronous (blocking) request.
### timeout
Defined by: [dojo/\_base/xhr](_base/xhr)
Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
### url
Defined by: [dojo/\_base/xhr](_base/xhr)
URL to server endpoint.
Methods
-------
###
`error``(response,ioArgs)`
Defined by [dojo/\_base/xhr](_base/xhr)
This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
| Parameter | Type | Description |
| --- | --- | --- |
| response | Object | The response in the format as defined with handleAs. |
| ioArgs | [dojo/main.\_\_IoCallbackArgs](main.__iocallbackargs) | Provides additional information about the request. |
###
`handle``(loadOrError,response,ioArgs)`
Defined by [dojo/\_base/xhr](_base/xhr)
This function will be called at the end of every request, whether or not an error occurs.
| Parameter | Type | Description |
| --- | --- | --- |
| loadOrError | String | Provides a string that tells you whether this function was called because of success (load) or failure (error). |
| response | Object | The response in the format as defined with handleAs. |
| ioArgs | [dojo/main.\_\_IoCallbackArgs](main.__iocallbackargs) | Provides additional information about the request. |
###
`load``(response,ioArgs)`
Defined by [dojo/\_base/xhr](_base/xhr)
This function will be called on a successful HTTP response code.
| Parameter | Type | Description |
| --- | --- | --- |
| response | Object | The response in the format as defined with handleAs. |
| ioArgs | [dojo/main.\_\_IoCallbackArgs](main.__iocallbackargs) | Provides additional information about the request. |
dojo dojo/main.contentHandlers dojo/main.contentHandlers
=========================
Summary
-------
A map of available XHR transport handle types. Name matches the `handleAs` attribute passed to XHR calls.
A map of available XHR transport handle types. Name matches the `handleAs` attribute passed to XHR calls. Each contentHandler is called, passing the xhr object for manipulation. The return value from the contentHandler will be passed to the `load` or `handle` functions defined in the original xhr call.
Examples
--------
### Example 1
Creating a custom content-handler:
```
xhr.contentHandlers.makeCaps = function(xhr){
return xhr.responseText.toUpperCase();
}
// and later:
dojo.xhrGet({
url:"foo.txt",
handleAs:"makeCaps",
load: function(data){ /* data is a toUpper version of foo.txt */ }
});
```
Methods
-------
###
`auto``(xhr)`
Defined by [dojox/rpc/Service](http://dojotoolkit.org/api/1.10/dojox/rpc/Service)
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
###
`javascript``(xhr)`
Defined by [dojo/\_base/xhr](_base/xhr)
A contentHandler which evaluates the response data, expecting it to be valid JavaScript
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`json``(xhr)`
Defined by [dojo/\_base/xhr](_base/xhr)
A contentHandler which returns a JavaScript object created from the response data
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`json-comment-filtered``(xhr)`
Defined by [dojo/\_base/xhr](_base/xhr)
A contentHandler which expects comment-filtered JSON.
A contentHandler which expects comment-filtered JSON. the json-comment-filtered option was implemented to prevent "JavaScript Hijacking", but it is less secure than standard JSON. Use standard JSON instead. JSON prefixing can be used to subvert hijacking.
Will throw a notice suggesting to use application/json mimetype, as json-commenting can introduce security issues. To decrease the chances of hijacking, use the standard `json` contentHandler, and prefix your "JSON" with: {}&&
use djConfig.useCommentedJson = true to turn off the notice
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`json-comment-optional``(xhr)`
Defined by [dojo/\_base/xhr](_base/xhr)
A contentHandler which checks the presence of comment-filtered JSON and alternates between the `json` and `json-comment-filtered` contentHandlers.
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`text``(xhr)`
Defined by [dojo/\_base/xhr](_base/xhr)
A contentHandler which simply returns the plaintext response data
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`xml``(xhr)`
Defined by [dojo/\_base/xhr](_base/xhr)
A contentHandler returning an XML Document parsed from the response data
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
dojo dojo/robot._runsemaphore dojo/robot.\_runsemaphore
=========================
Properties
----------
### lock
Defined by: [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Methods
-------
###
`unlock``()`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
**Returns:** undefined | null
dojo dojo/dom-class dojo/dom-class
==============
Summary
-------
This module defines the core dojo DOM class API.
See the [dojo/dom-class reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dom-class.html) for more information.
Methods
-------
###
`add``(node,classStr)`
Defined by [dojo/dom-class](dom-class)
Adds the specified classes to the end of the class list on the passed node. Will not re-apply duplicate classes.
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | String ID or DomNode reference to add a class string too |
| classStr | String | Array | A String class name to add, or several space-separated class names, or an array of class names. |
Examples
--------
### Example 1
Add a class to some node:
```
require(["dojo/dom-class"], function(domClass){
domClass.add("someNode", "anewClass");
});
```
### Example 2
Add two classes at once:
```
require(["dojo/dom-class"], function(domClass){
domClass.add("someNode", "firstClass secondClass");
});
```
### Example 3
Add two classes at once (using array):
```
require(["dojo/dom-class"], function(domClass){
domClass.add("someNode", ["firstClass", "secondClass"]);
});
```
### Example 4
Available in `dojo/NodeList` for multiple additions
```
require(["dojo/query"], function(query){
query("ul > li").addClass("firstLevel");
});
```
###
`contains``(node,classStr)`
Defined by [dojo/dom-class](dom-class)
Returns whether or not the specified classes are a portion of the class list currently applied to the node.
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | String ID or DomNode reference to check the class for. |
| classStr | String | A string class name to look for. |
**Returns:** boolean
Examples
--------
### Example 1
Do something if a node with id="someNode" has class="aSillyClassName" present
```
if(dojo.hasClass("someNode","aSillyClassName")){ ... }
```
###
`remove``(node,classStr)`
Defined by [dojo/dom-class](dom-class)
Removes the specified classes from node. No `contains()` check is required.
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | String ID or DomNode reference to remove the class from. |
| classStr | String | Array | *Optional*
An optional String class name to remove, or several space-separated class names, or an array of class names. If omitted, all class names will be deleted. |
Examples
--------
### Example 1
Remove a class from some node:
```
require(["dojo/dom-class"], function(domClass){
domClass.remove("someNode", "firstClass");
});
```
### Example 2
Remove two classes from some node:
```
require(["dojo/dom-class"], function(domClass){
domClass.remove("someNode", "firstClass secondClass");
});
```
### Example 3
Remove two classes from some node (using array):
```
require(["dojo/dom-class"], function(domClass){
domClass.remove("someNode", ["firstClass", "secondClass"]);
});
```
### Example 4
Remove all classes from some node:
```
require(["dojo/dom-class"], function(domClass){
domClass.remove("someNode");
});
```
### Example 5
Available in `dojo/NodeList` for multiple removal
```
require(["dojo/query"], function(query){
query("ul > li").removeClass("foo");
});
```
###
`replace``(node,addClassStr,removeClassStr)`
Defined by [dojo/dom-class](dom-class)
Replaces one or more classes on a node if not present. Operates more quickly than calling dojo.removeClass and dojo.addClass
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | String ID or DomNode reference to remove the class from. |
| addClassStr | String | Array | A String class name to add, or several space-separated class names, or an array of class names. |
| removeClassStr | String | Array | *Optional*
A String class name to remove, or several space-separated class names, or an array of class names. |
Examples
--------
### Example 1
```
require(["dojo/dom-class"], function(domClass){
domClass.replace("someNode", "add1 add2", "remove1 remove2");
});
```
### Example 2
Replace all classes with addMe
```
require(["dojo/dom-class"], function(domClass){
domClass.replace("someNode", "addMe");
});
```
### Example 3
Available in `dojo/NodeList` for multiple toggles
```
require(["dojo/query"], function(query){
query(".findMe").replaceClass("addMe", "removeMe");
});
```
###
`toggle``(node,classStr,condition)`
Defined by [dojo/dom-class](dom-class)
Adds a class to node if not present, or removes if present. Pass a boolean condition if you want to explicitly add or remove. Returns the condition that was specified directly or indirectly.
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | String ID or DomNode reference to toggle a class string |
| classStr | String | Array | A String class name to toggle, or several space-separated class names, or an array of class names. |
| condition | Boolean | *Optional*
If passed, true means to add the class, false means to remove. Otherwise dojo.hasClass(node, classStr) is used to detect the class presence. |
**Returns:** Boolean
If passed, true means to add the class, false means to remove. Otherwise dojo.hasClass(node, classStr) is used to detect the class presence.
Examples
--------
### Example 1
```
require(["dojo/dom-class"], function(domClass){
domClass.toggle("someNode", "hovered");
});
```
### Example 2
Forcefully add a class
```
require(["dojo/dom-class"], function(domClass){
domClass.toggle("someNode", "hovered", true);
});
```
### Example 3
Available in `dojo/NodeList` for multiple toggles
```
require(["dojo/query"], function(query){
query(".toggleMe").toggleClass("toggleMe");
});
```
| programming_docs |
dojo dojo/Evented dojo/Evented
============
Summary
-------
A class that can be used as a mixin or base class, to add on() and emit() methods to a class for listening for events and emitting events:
See the [dojo/Evented reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/Evented.html) for more information.
Examples
--------
### Example 1
```
define(["dojo/Evented", "dojo/_base/declare", "dojo/Stateful"
], function(Evented, declare, Stateful){
var EventedStateful = declare([Evented, Stateful], {...});
var instance = new EventedStateful();
instance.on("open", function(event){
... do something with event
});
instance.emit("open", {name:"some event", ...});
```
Methods
-------
###
`emit``(type,event)`
Defined by [dojo/Evented](evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| event | undefined | |
**Returns:** undefined
###
`on``(type,listener)`
Defined by [dojo/Evented](evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| listener | undefined | |
**Returns:** undefined
dojo dojo/number.__RegexpOptions dojo/number.\_\_RegexpOptions
=============================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new number.__RegexpOptions()`
Properties
----------
### locale
Defined by: [dojo/number](number)
override the locale used to determine formatting rules
### pattern
Defined by: [dojo/number](number)
override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization.
### places
Defined by: [dojo/number](number)
number of decimal places to accept: Infinity, a positive number, or a range "n,m". Defined by pattern or Infinity if pattern not provided.
### strict
Defined by: [dojo/number](number)
strict parsing, false by default. Strict parsing requires input as produced by the format() method. Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
### type
Defined by: [dojo/number](number)
choose a format type based on the locale from the following: decimal, scientific (not yet supported), percent, currency. decimal by default.
dojo dojo/mouse dojo/mouse
==========
Summary
-------
This module provide mouse event handling utility functions and exports mouseenter and mouseleave event emulation.
See the [dojo/mouse reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/mouse.html) for more information.
Examples
--------
### Example 1
To use these events, you register a mouseenter like this:
```
define(["dojo/on", dojo/mouse"], function(on, mouse){
on(targetNode, mouse.enter, function(event){
dojo.addClass(targetNode, "highlighted");
});
on(targetNode, mouse.leave, function(event){
dojo.removeClass(targetNode, "highlighted");
});
```
Properties
----------
### enter
Defined by: [dojo/mouse](mouse)
This is an extension event for the mouseenter that IE provides, emulating the behavior on other browsers.
### leave
Defined by: [dojo/mouse](mouse)
This is an extension event for the mouseleave that IE provides, emulating the behavior on other browsers.
Methods
-------
###
`isLeft``()`
Defined by [dojo/mouse](mouse)
Test an event object (from a mousedown event) to see if the left button was pressed.
###
`isMiddle``()`
Defined by [dojo/mouse](mouse)
Test an event object (from a mousedown event) to see if the middle button was pressed.
###
`isRight``()`
Defined by [dojo/mouse](mouse)
Test an event object (from a mousedown event) to see if the right button was pressed.
###
`wheel``(node,listener)`
Defined by [dojo/mouse](mouse)
This is an extension event for the mousewheel that non-Mozilla browsers provide, emulating the behavior on Mozilla based browsers.
| Parameter | Type | Description |
| --- | --- | --- |
| node | undefined | |
| listener | undefined | |
**Returns:** undefined
dojo dojo/has dojo/has
========
Summary
-------
Return the current value of the named feature.
Returns the value of the feature named by name. The feature must have been previously added to the cache by has.add.
Usage
-----
has`(name);`
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | Integer | The name (if a string) or identifier (if an integer) of the feature to test. |
**Returns:** boolean
See the [dojo/has reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/has.html) for more information.
Properties
----------
### cache
Defined by: [dojo/has](has)
Methods
-------
###
`add``(name,test,now,force)`
Defined by [dojo/has](has)
Register a new feature test for some named feature.
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | Integer | The name (if a string) or identifier (if an integer) of the feature to test. |
| test | Function | A test function to register. If a function, queued for testing until actually needed. The test function should return a boolean indicating the presence of a feature or bug. |
| now | Boolean | *Optional*
Optional. Omit if `test` is not a function. Provides a way to immediately run the test and cache the result. |
| force | Boolean | *Optional*
Optional. If the test already exists and force is truthy, then the existing test will be replaced; otherwise, add does not replace an existing test (that is, by default, the first test advice wins). |
**Returns:** undefined
Examples
--------
### Example 1
A redundant test, testFn with immediate execution:
```
has.add("javascript", function(){ return true; }, true);
```
### Example 2
Again with the redundantness. You can do this in your tests, but we should not be doing this in any internal has.js tests
```
has.add("javascript", true);
```
### Example 3
Three things are passed to the testFunction. `global`, `document`, and a generic element from which to work your test should the need arise.
```
has.add("bug-byid", function(g, d, el){
// g == global, typically window, yadda yadda
// d == document object
// el == the generic element. a `has` element.
return false; // fake test, byid-when-form-has-name-matching-an-id is slightly longer
});
```
###
`clearElement``(element)`
Defined by [dojo/has](has)
Deletes the contents of the element passed to test functions.
| Parameter | Type | Description |
| --- | --- | --- |
| element | undefined | |
###
`load``(id,parentRequire,loaded)`
Defined by [dojo/has](has)
Conditional loading of AMD modules based on a has feature test value.
| Parameter | Type | Description |
| --- | --- | --- |
| id | String | Gives the resolved module id to load. |
| parentRequire | Function | The loader require function with respect to the module that contained the plugin resource in it's dependency list. |
| loaded | Function | Callback to loader that consumes result of plugin demand. |
###
`normalize``(id,toAbsMid)`
Defined by [dojo/has](has)
Resolves id into a module id based on possibly-nested tenary expression that branches on has feature test value(s).
| Parameter | Type | Description |
| --- | --- | --- |
| id | undefined | |
| toAbsMid | Function | Resolves a relative module id into an absolute module id |
dojo dojo/colors dojo/colors
===========
Summary
-------
Color utilities, extending Base dojo.Color
See the [dojo/colors reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/colors.html) for more information.
Properties
----------
### ThreeD
Defined by: [dojox/charting/themes/ThreeD](http://dojotoolkit.org/api/1.10/dojox/charting/themes/ThreeD)
dojo dojo/text dojo/text
=========
Summary
-------
This module implements the [dojo/text](text)! plugin and the dojo.cache API.
We choose to include our own plugin to leverage functionality already contained in dojo and thereby reduce the size of the plugin compared to various foreign loader implementations. Also, this allows foreign AMD loaders to be used without their plugins.
CAUTION: this module is designed to optionally function synchronously to support the dojo v1.x synchronous loader. This feature is outside the scope of the CommonJS plugins specification.
See the [dojo/text reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/text.html) for more information.
Properties
----------
### dynamic
Defined by: [dojo/text](text)
Methods
-------
###
`load``(id,require,load)`
Defined by [dojo/text](text)
| Parameter | Type | Description |
| --- | --- | --- |
| id | String | Path to the resource. |
| require | Function | Object that include the function toUrl with given id returns a valid URL from which to load the text. |
| load | Function | Callback function which will be called, when the loading finished. |
###
`normalize``(id,toAbsMid)`
Defined by [dojo/text](text)
| Parameter | Type | Description |
| --- | --- | --- |
| id | undefined | |
| toAbsMid | undefined | |
**Returns:** string
dojo dojo/node dojo/node
=========
Summary
-------
This AMD plugin module allows native Node.js modules to be loaded by AMD modules using the Dojo loader. Note that this plugin will not work with AMD loaders other than the Dojo loader.
See the [dojo/node reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/node.html) for more information.
Examples
--------
### Example 1
```
require(["dojo/node!fs"], function(fs){
var fileData = fs.readFileSync("foo.txt", "utf-8");
});
```
Methods
-------
###
`load``(id,require,load)`
Defined by [dojo/node](node)
Standard AMD plugin interface. See <https://github.com/amdjs/amdjs-api/wiki/Loader-Plugins> for information.
| Parameter | Type | Description |
| --- | --- | --- |
| id | string | |
| require | Function | |
| load | Function | |
###
`normalize``(id,normalize)`
Defined by [dojo/node](node)
Produces a normalized id to be used by node. Relative ids are resolved relative to the requesting module's location in the file system and will return an id with path separators appropriate for the local file system.
| Parameter | Type | Description |
| --- | --- | --- |
| id | string | |
| normalize | Function | |
**Returns:** undefined
dojo dojo/when dojo/when
=========
Summary
-------
Transparently applies callbacks to values and/or promises.
Accepts promises but also transparently handles non-promises. If no callbacks are provided returns a promise, regardless of the initial value. Foreign promises are converted.
If callbacks are provided and the initial value is not a promise, the callback is executed immediately with no error handling. Returns a promise if the initial value is a promise, or the result of the callback otherwise.
Usage
-----
when`(valueOrPromise,callback,errback,progback);`
| Parameter | Type | Description |
| --- | --- | --- |
| valueOrPromise | undefined | Either a regular value or an object with a `then()` method that follows the Promises/A specification. |
| callback | Function | *Optional*
Callback to be invoked when the promise is resolved, or a non-promise is received. |
| errback | Function | *Optional*
Callback to be invoked when the promise is rejected. |
| progback | Function | *Optional*
Callback to be invoked when the promise emits a progress update. |
**Returns:** [dojo/promise/Promise](promise/promise) | summary: | name:
Promise, or if a callback is provided, the result of the callback.
See the [dojo/when reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/when.html) for more information.
Methods
-------
dojo dojo/ready dojo/ready
==========
Summary
-------
Add a function to execute on DOM content loaded and all requested modules have arrived and been evaluated. In most cases, the `domReady` plug-in should suffice and this method should not be needed.
When called in a non-browser environment, just checks that all requested modules have arrived and been evaluated.
Usage
-----
ready`(priority,context,callback);`
| Parameter | Type | Description |
| --- | --- | --- |
| priority | Integer | *Optional*
The order in which to exec this callback relative to other callbacks, defaults to 1000 |
| context | undefined | The context in which to run execute callback, or a callback if not using context |
| callback | Function | *Optional*
The function to execute. |
See the [dojo/ready reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/ready.html) for more information.
Examples
--------
### Example 1
Simple DOM and Modules ready syntax
```
require(["dojo/ready"], function(ready){
ready(function(){ alert("Dom ready!"); });
});
```
### Example 2
Using a priority
```
require(["dojo/ready"], function(ready){
ready(2, function(){ alert("low priority ready!"); })
});
```
### Example 3
Using context
```
require(["dojo/ready"], function(ready){
ready(foo, function(){
// in here, this == foo
});
});
```
### Example 4
Using dojo/hitch style args:
```
require(["dojo/ready"], function(ready){
var foo = { dojoReady: function(){ console.warn(this, "dojo dom and modules ready."); } };
ready(foo, "dojoReady");
});
```
Methods
-------
dojo dojo/fx.Toggler dojo/fx.Toggler
===============
Summary
-------
A simple `dojo.Animation` toggler API.
class constructor for an animation toggler. It accepts a packed set of arguments about what type of animation to use in each direction, duration, etc. All available members are mixed into these animations from the constructor (for example, `node`, `showDuration`, `hideDuration`).
Usage
-----
var foo = new fx.Toggler`(args);` Defined by [dojo/fx/Toggler](fx/toggler)
| Parameter | Type | Description |
| --- | --- | --- |
| args | undefined | |
Examples
--------
### Example 1
```
var t = new dojo/fx/Toggler({
node: "nodeId",
showDuration: 500,
// hideDuration will default to "200"
showFunc: dojo/fx/wipeIn,
// hideFunc will default to "fadeOut"
});
t.show(100); // delay showing for 100ms
// ...time passes...
t.hide();
```
Properties
----------
### hideDuration
Defined by: [dojo/fx/Toggler](fx/toggler)
Time in milliseconds to run the hide Animation
### node
Defined by: [dojo/fx/Toggler](fx/toggler)
the node to target for the showing and hiding animations
### showDuration
Defined by: [dojo/fx/Toggler](fx/toggler)
Time in milliseconds to run the show Animation
Methods
-------
###
`hide``(delay)`
Defined by [dojo/fx/Toggler](fx/toggler)
Toggle the node to hidden
| Parameter | Type | Description |
| --- | --- | --- |
| delay | Integer | *Optional*
Amount of time to stall playing the hide animation |
**Returns:** undefined
###
`hideFunc``(args)`
Defined by [dojo/fx/Toggler](fx/toggler)
The function that returns the `dojo.Animation` to hide the node
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* node (DOMNode|String): The node referenced in the animation
* duration (Integer, optional): Duration of the animation in milliseconds.
* easing (Function, optional): An easing function.
|
**Returns:** undefined
###
`show``(delay)`
Defined by [dojo/fx/Toggler](fx/toggler)
Toggle the node to showing
| Parameter | Type | Description |
| --- | --- | --- |
| delay | Integer | *Optional*
Amount of time to stall playing the show animation |
**Returns:** undefined
###
`showFunc``(args)`
Defined by [dojo/fx/Toggler](fx/toggler)
The function that returns the `dojo.Animation` to show the node
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* node (DOMNode|String): The node referenced in the animation
* duration (Integer, optional): Duration of the animation in milliseconds.
* easing (Function, optional): An easing function.
|
**Returns:** undefined
dojo dojo/window dojo/window
===========
Summary
-------
TODOC
See the [dojo/window reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/window.html) for more information.
Methods
-------
###
`get``(doc)`
Defined by [dojo/window](window)
Get window object associated with document doc.
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | The document to get the associated window for. |
**Returns:** undefined
###
`getBox``(doc)`
Defined by [dojo/window](window)
Returns the dimensions and scroll position of the viewable area of a browser window
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | *Optional* |
**Returns:** object
###
`scrollIntoView``(node,pos)`
Defined by [dojo/window](window)
Scroll the passed node into view using minimal movement, if it is not already.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DomNode | |
| pos | Object | *Optional* |
dojo dojo/fx dojo/fx
=======
Summary
-------
Effects library on top of Base animations
See the [dojo/fx reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/fx.html) for more information.
Properties
----------
### easing
Defined by: [dojo/fx/easing](fx/easing)
Collection of easing functions to use beyond the default `dojo._defaultEasing` function.
Methods
-------
###
`chain``(animations)`
Defined by [dojo/fx](fx)
Chain a list of `dojo/_base/fx.Animation`s to run in sequence
Return a [dojo/\_base/fx.Animation](_base/fx#Animation) which will play all passed [dojo/\_base/fx.Animation](_base/fx#Animation) instances in sequence, firing its own synthesized events simulating a single animation. (eg: onEnd of this animation means the end of the chain, not the individual animations within)
| Parameter | Type | Description |
| --- | --- | --- |
| animations | [dojo/\_base/fx.Animation](_base/fx#Animation)[] | |
**Returns:** instance
Examples
--------
### Example 1
Once `node` is faded out, fade in `otherNode`
```
require(["dojo/fx"], function(fx){
fx.chain([
fx.fadeIn({ node:node }),
fx.fadeOut({ node:otherNode })
]).play();
});
```
###
`combine``(animations)`
Defined by [dojo/fx](fx)
Combine a list of `dojo/_base/fx.Animation`s to run in parallel
Combine an array of [dojo/\_base/fx.Animation](_base/fx#Animation)s to run in parallel, providing a new [dojo/\_base/fx.Animation](_base/fx#Animation) instance encompasing each animation, firing standard animation events.
| Parameter | Type | Description |
| --- | --- | --- |
| animations | [dojo/\_base/fx.Animation](_base/fx#Animation)[] | |
**Returns:** instance
Examples
--------
### Example 1
Fade out `node` while fading in `otherNode` simultaneously
```
require(["dojo/fx"], function(fx){
fx.combine([
fx.fadeIn({ node:node }),
fx.fadeOut({ node:otherNode })
]).play();
});
```
### Example 2
When the longest animation ends, execute a function:
```
require(["dojo/fx"], function(fx){
var anim = fx.combine([
fx.fadeIn({ node: n, duration:700 }),
fx.fadeOut({ node: otherNode, duration: 300 })
]);
aspect.after(anim, "onEnd", function(){
// overall animation is done.
}, true);
anim.play(); // play the animation
});
```
###
`slideTo``(args)`
Defined by [dojo/fx](fx)
Slide a node to a new top/left position
Returns an animation that will slide "node" defined in args Object from its current position to the position defined by (args.left, args.top).
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | A hash-map of standard `dojo/_base/fx.Animation` constructor properties (such as easing: node: duration: and so on). Special args members are `top` and `left`, which indicate the new position to slide to. |
**Returns:** undefined
Examples
--------
### Example 1
```
.slideTo({ node: node, left:"40", top:"50", units:"px" }).play()
```
###
`Toggler``()`
Defined by [dojo/fx/Toggler](fx/toggler)
###
`wipeIn``(args)`
Defined by [dojo/fx](fx)
Expand a node to it's natural height.
Returns an animation that will expand the node defined in 'args' object from it's current height to it's natural height (with no scrollbar). Node must have no margin/border/padding.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | A hash-map of standard `dojo/_base/fx.Animation` constructor properties (such as easing: node: duration: and so on) |
**Returns:** undefined
Examples
--------
### Example 1
```
require(["dojo/fx"], function(fx){
fx.wipeIn({
node:"someId"
}).play()
});
```
###
`wipeOut``(args)`
Defined by [dojo/fx](fx)
Shrink a node to nothing and hide it.
Returns an animation that will shrink node defined in "args" from it's current height to 1px, and then hide it.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | A hash-map of standard `dojo/_base/fx.Animation` constructor properties (such as easing: node: duration: and so on) |
**Returns:** undefined
Examples
--------
### Example 1
```
require(["dojo/fx"], function(fx){
fx.wipeOut({ node:"someId" }).play()
});
```
| programming_docs |
dojo dojo/number.__FormatOptions dojo/number.\_\_FormatOptions
=============================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new number.__FormatOptions()`
Properties
----------
### fractional
Defined by: [dojo/number](number)
If false, show no decimal places, overriding places and pattern settings.
### locale
Defined by: [dojo/number](number)
override the locale used to determine formatting rules
### pattern
Defined by: [dojo/number](number)
override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization. Literal characters in patterns are not supported.
### places
Defined by: [dojo/number](number)
fixed number of decimal places to show. This overrides any information in the provided pattern.
### round
Defined by: [dojo/number](number)
5 rounds to nearest .5; 0 rounds to nearest whole (default). -1 means do not round.
### type
Defined by: [dojo/number](number)
choose a format type based on the locale from the following: decimal, scientific (not yet supported), percent, currency. decimal by default.
dojo dojo/parser dojo/parser
===========
Summary
-------
The Dom/Widget parsing package
See the [dojo/parser reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/parser.html) for more information.
Properties
----------
Methods
-------
###
`construct``(ctor,node,mixin,options,scripts,inherited)`
Defined by [dojo/parser](parser)
Calls new ctor(params, node), where params is the hash of parameters specified on the node, excluding data-dojo-type and data-dojo-mixins. Does not call startup().
| Parameter | Type | Description |
| --- | --- | --- |
| ctor | Function | Widget constructor. |
| node | DOMNode | This node will be replaced/attached to by the widget. It also specifies the arguments to pass to ctor. |
| mixin | Object | *Optional*
Attributes in this object will be passed as parameters to ctor, overriding attributes specified on the node. |
| options | Object | *Optional*
An options object used to hold kwArgs for instantiation. See parse.options argument for details. |
| scripts | DomNode[] | *Optional*
Array of `<script type="dojo/*">` DOMNodes. If not specified, will search for `<script>` tags inside node. |
| inherited | Object | *Optional*
Settings from dir=rtl or lang=... on a node above this node. Overrides options.inherited. |
**Returns:** any | undefined
Instance or Promise for the instance, if markupFactory() itself returned a promise
###
`instantiate``(nodes,mixin,options)`
Defined by [dojo/parser](parser)
Takes array of nodes, and turns them into class instances and potentially calls a startup method to allow them to connect with any children.
| Parameter | Type | Description |
| --- | --- | --- |
| nodes | Array | Array of DOM nodes |
| mixin | Object | *Optional*
An object that will be mixed in with each node in the array. Values in the mixin will override values in the node, if they exist. |
| options | Object | *Optional*
An object used to hold kwArgs for instantiation. See parse.options argument for details. |
**Returns:** any | undefined
Array of instances.
###
`parse``(rootNode,options)`
Defined by [dojo/parser](parser)
Scan the DOM for class instances, and instantiate them.
Search specified node (or root node) recursively for class instances, and instantiate them. Searches for either data-dojo-type="Class" or dojoType="Class" where "Class" is a a fully qualified class name, like [dijit/form/Button](http://dojotoolkit.org/api/1.10/dijit/form/Button)
Using `data-dojo-type`: Attributes using can be mixed into the parameters used to instantiate the Class by using a `data-dojo-props` attribute on the node being converted. `data-dojo-props` should be a string attribute to be converted from JSON.
Using `dojoType`: Attributes are read from the original domNode and converted to appropriate types by looking up the Class prototype values. This is the default behavior from Dojo 1.0 to Dojo 1.5. `dojoType` support is deprecated, and will go away in Dojo 2.0.
| Parameter | Type | Description |
| --- | --- | --- |
| rootNode | DomNode | *Optional*
A default starting root node from which to start the parsing. Can be omitted, defaulting to the entire document. If omitted, the `options` object can be passed in this place. If the `options` object has a `rootNode` member, that is used. |
| options | Object | *Optional*
A hash of options. * noStart: Boolean?: when set will prevent the parser from calling .startup() when locating the nodes.
* rootNode: DomNode?: identical to the function's `rootNode` argument, though allowed to be passed in via this `options object.
* template: Boolean: If true, ignores ContentPane's stopParser flag and parses contents inside of a ContentPane inside of a template. This allows dojoAttachPoint on widgets/nodes nested inside the ContentPane to work.
* inherited: Object: Hash possibly containing dir and lang settings to be applied to parsed widgets, unless there's another setting on a sub-node that overrides
* scope: String: Root for attribute names to search for. If scopeName is dojo, will search for data-dojo-type (or dojoType). For backwards compatibility reasons defaults to dojo.\_scopeName (which is "dojo" except when multi-version support is used, when it will be something like dojo16, dojo20, etc.)
* propsThis: Object: If specified, "this" referenced from data-dojo-props will refer to propsThis. Intended for use from the widgets-in-template feature of `dijit._WidgetsInTemplateMixin`
* contextRequire: Function: If specified, this require is utilised for looking resolving modules instead of the `dojo/parser` context `require()`. Intended for use from the widgets-in-template feature of `dijit._WidgetsInTemplateMixin`.
|
**Returns:** Mixed | Array
Returns a blended object that is an array of the instantiated objects, but also can include a promise that is resolved with the instantiated objects. This is done for backwards compatibility. If the parser auto-requires modules, it will always behave in a promise fashion and `parser.parse().then(function(instances){...})` should be used.
Examples
--------
### Example 1
Parse all widgets on a page:
```
parser.parse();
```
### Example 2
Parse all classes within the node with id="foo"
```
parser.parse(dojo.byId('foo'));
```
### Example 3
Parse all classes in a page, but do not call .startup() on any child
```
parser.parse({ noStart: true })
```
### Example 4
Parse all classes in a node, but do not call .startup()
```
parser.parse(someNode, { noStart:true });
// or
parser.parse({ noStart:true, rootNode: someNode });
```
###
`scan``(root,options)`
Defined by [dojo/parser](parser)
Scan a DOM tree and return an array of objects representing the DOMNodes that need to be turned into widgets.
Search specified node (or document root node) recursively for class instances and return an array of objects that represent potential widgets to be instantiated. Searches for either data-dojo-type="MID" or dojoType="MID" where "MID" is a module ID like "[dijit/form/Button](http://dojotoolkit.org/api/1.10/dijit/form/Button)" or a fully qualified Class name like "[dijit/form/Button](http://dojotoolkit.org/api/1.10/dijit/form/Button)". If the MID is not currently available, scan will attempt to require() in the module.
See parser.parse() for details of markup.
| Parameter | Type | Description |
| --- | --- | --- |
| root | DomNode | *Optional*
A default starting root node from which to start the parsing. Can be omitted, defaulting to the entire document. If omitted, the `options` object can be passed in this place. If the `options` object has a `rootNode` member, that is used. |
| options | Object | a kwArgs options object, see parse() for details |
**Returns:** Promise | undefined
A promise that is resolved with the nodes that have been parsed.
dojo dojo/main.io dojo/main.io
============
Properties
----------
### iframe
Defined by: [dojo/io/iframe](io/iframe)
### script
Defined by: [dojo/io/script](io/script)
TODOC
dojo dojo/request.__Promise dojo/request.\_\_Promise
========================
Extends[dojo/promise/Promise](promise/promise) **Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new request.__Promise()`
Usage
-----
var foo = new request.\_\_Promise`();` Defined by [dojo/promise/Promise](promise/promise)
<The public interface to a deferred. All promises in Dojo are instances of this class.
>The public interface to a deferred. All promises in Dojo are instances of this class.
> Properties
----------
### response
Defined by: [dojo/request](request)
A promise resolving to an object representing the response from the server.
Methods
-------
###
`always``(callbackOrErrback)`
Defined by [dojo/promise/Promise](promise/promise)
Add a callback to be invoked when the promise is resolved or rejected.
| Parameter | Type | Description |
| --- | --- | --- |
| callbackOrErrback | Function | *Optional*
A function that is used both as a callback and errback. |
**Returns:** [dojo/promise/Promise](promise/promise) | undefined
Returns a new promise for the result of the callback/errback.
###
`cancel``(reason,strict)`
Defined by [dojo/promise/Promise](promise/promise)
Inform the deferred it may cancel its asynchronous operation.
Inform the deferred it may cancel its asynchronous operation. The deferred's (optional) canceler is invoked and the deferred will be left in a rejected state. Can affect other promises that originate with the same deferred.
| Parameter | Type | Description |
| --- | --- | --- |
| reason | any | A message that may be sent to the deferred's canceler, explaining why it's being canceled. |
| strict | Boolean | *Optional*
If strict, will throw an error if the deferred has already been fulfilled and consequently cannot be canceled. |
**Returns:** any
Returns the rejection reason if the deferred was canceled normally.
###
`isCanceled``()`
Defined by [dojo/promise/Promise](promise/promise)
Checks whether the promise has been canceled.
**Returns:** Boolean
###
`isFulfilled``()`
Defined by [dojo/promise/Promise](promise/promise)
Checks whether the promise has been resolved or rejected.
**Returns:** Boolean
###
`isRejected``()`
Defined by [dojo/promise/Promise](promise/promise)
Checks whether the promise has been rejected.
**Returns:** Boolean
###
`isResolved``()`
Defined by [dojo/promise/Promise](promise/promise)
Checks whether the promise has been resolved.
**Returns:** Boolean
###
`otherwise``(errback)`
Defined by [dojo/promise/Promise](promise/promise)
Add new errbacks to the promise.
| Parameter | Type | Description |
| --- | --- | --- |
| errback | Function | *Optional*
Callback to be invoked when the promise is rejected. |
**Returns:** [dojo/promise/Promise](promise/promise) | undefined
Returns a new promise for the result of the errback.
###
`then``(callback,errback,progback)`
Defined by [dojo/promise/Promise](promise/promise)
Add new callbacks to the promise.
Add new callbacks to the deferred. Callbacks can be added before or after the deferred is fulfilled.
| Parameter | Type | Description |
| --- | --- | --- |
| callback | Function | *Optional*
Callback to be invoked when the promise is resolved. Receives the resolution value. |
| errback | Function | *Optional*
Callback to be invoked when the promise is rejected. Receives the rejection error. |
| progback | Function | *Optional*
Callback to be invoked when the promise emits a progress update. Receives the progress update. |
**Returns:** [dojo/promise/Promise](promise/promise)
Returns a new promise for the result of the callback(s). This can be used for chaining many asynchronous operations.
###
`toString``()`
Defined by [dojo/promise/Promise](promise/promise)
**Returns:** string
Returns `[object Promise]`.
###
`trace``()`
Defined by [dojo/promise/Promise](promise/promise)
**Returns:** function
###
`traceRejected``()`
Defined by [dojo/promise/Promise](promise/promise)
**Returns:** function
dojo dojo/AdapterRegistry dojo/AdapterRegistry
====================
Summary
-------
A registry to make contextual calling/searching easier.
Objects of this class keep list of arrays in the form [name, check, wrap, directReturn] that are used to determine what the contextual result of a set of checked arguments is. All check/wrap functions in this registry should be of the same arity.
Usage
-----
AdapterRegistry`(returnWrappers);`
| Parameter | Type | Description |
| --- | --- | --- |
| returnWrappers | Boolean | *Optional* |
See the [dojo/AdapterRegistry reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/AdapterRegistry.html) for more information.
Examples
--------
### Example 1
```
// create a new registry
require(["dojo/AdapterRegistry"],
function(AdapterRegistry){
var reg = new AdapterRegistry();
reg.register("handleString",
function(str){
return typeof val == "string"
},
function(str){
// do something with the string here
}
);
reg.register("handleArr",
dojo.isArray,
function(arr){
// do something with the array here
}
);
// now we can pass reg.match() *either* an array or a string and
// the value we pass will get handled by the right function
reg.match("someValue"); // will call the first function
reg.match(["someValue"]); // will call the second
});
```
Properties
----------
### pairs
Defined by: [dojo/AdapterRegistry](adapterregistry)
### returnWrappers
Defined by: [dojo/AdapterRegistry](adapterregistry)
Methods
-------
###
`match``()`
Defined by [dojo/AdapterRegistry](adapterregistry)
Find an adapter for the given arguments. If no suitable adapter is found, throws an exception. match() accepts any number of arguments, all of which are passed to all matching functions from the registered pairs.
**Returns:** undefined
###
`register``(name,check,wrap,directReturn,override)`
Defined by [dojo/AdapterRegistry](adapterregistry)
register a check function to determine if the wrap function or object gets selected
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | a way to identify this matcher. |
| check | Function | a function that arguments are passed to from the adapter's match() function. The check function should return true if the given arguments are appropriate for the wrap function. |
| wrap | Function | |
| directReturn | Boolean | *Optional*
If directReturn is true, the value passed in for wrap will be returned instead of being called. Alternately, the AdapterRegistry can be set globally to "return not call" using the returnWrappers property. Either way, this behavior allows the registry to act as a "search" function instead of a function interception library. |
| override | Boolean | *Optional*
If override is given and true, the check function will be given highest priority. Otherwise, it will be the lowest priority adapter. |
###
`unregister``(name)`
Defined by [dojo/AdapterRegistry](adapterregistry)
Remove a named adapter from the registry
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | The name of the adapter. |
**Returns:** Boolean | boolean
Returns true if operation is successful. Returns false if operation fails.
dojo dojo/html dojo/html
=========
Summary
-------
TODOC
See the [dojo/html reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/html.html) for more information.
Methods
-------
###
`set``(node,cont,params)`
Defined by [dojo/html](html)
inserts (replaces) the given content into the given node. dojo/dom-construct.place(cont, node, "only") may be a better choice for simple HTML insertion.
Unless you need to use the params capabilities of this method, you should use [dojo/dom-construct.place(cont, node, "only")](dom-construct#place). [dojo/dom-construct](dom-construct)..place() has more robust support for injecting an HTML string into the DOM, but it only handles inserting an HTML string as DOM elements, or inserting a DOM node. [dojo/dom-construct](dom-construct)..place does not handle NodeList insertions [dojo/dom-construct.place(cont, node, "only")](dom-construct#place). [dojo/dom-construct.place()](dom-construct#place) has more robust support for injecting an HTML string into the DOM, but it only handles inserting an HTML string as DOM elements, or inserting a DOM node. [dojo/dom-construct.place](dom-construct#place) does not handle NodeList insertions or the other capabilities as defined by the params object for this method.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DomNode | the parent element that will receive the content |
| cont | String | DomNode | NodeList | the content to be set on the parent element. This can be an html string, a node reference or a NodeList, dojo/NodeList, Array or other enumerable list of nodes |
| params | Object | *Optional*
Optional flags/properties to configure the content-setting. See dojo/html/\_ContentSetter |
**Returns:** undefined
Examples
--------
### Example 1
A safe string/node/nodelist content replacement/injection with hooks for extension Example Usage:
```
html.set(node, "some string");
html.set(node, contentNode, {options});
html.set(node, myNode.childNodes, {options});
```
dojo dojo/main.window dojo/main.window
================
Summary
-------
TODOC
Methods
-------
###
`get``(doc)`
Defined by [dojo/window](window)
Get window object associated with document doc.
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | The document to get the associated window for. |
**Returns:** undefined
###
`getBox``(doc)`
Defined by [dojo/window](window)
Returns the dimensions and scroll position of the viewable area of a browser window
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | *Optional* |
**Returns:** object
###
`scrollIntoView``(node,pos)`
Defined by [dojo/window](window)
Scroll the passed node into view using minimal movement, if it is not already.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DomNode | |
| pos | Object | *Optional* |
dojo dojo/router dojo/router
===========
Summary
-------
A singleton-style instance of [dojo/router/RouterBase](router/routerbase). See that module for specifics.
See the [dojo/router reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/router.html) for more information.
Examples
--------
### Example 1
```
router.register("/widgets/:id", function(evt){
// If "/widgets/3" was matched,
// evt.params.id === "3"
xhr.get({
url: "/some/path/" + evt.params.id,
load: function(data){
// ...
}
});
});
```
dojo dojo/html._ContentSetter dojo/html.\_ContentSetter
=========================
Usage
-----
var foo = new html.\_ContentSetter`(params,node);` Defined by [dojo/html](html)
| Parameter | Type | Description |
| --- | --- | --- |
| params | Object | |
| node | String | DomNode | |
Properties
----------
### cleanContent
Defined by: [dojo/html](html)
Should the content be treated as a full html document, and the real content stripped of ,
wrapper before injection ### content
Defined by: [dojo/html](html)
The content to be placed in the node. Can be an HTML string, a node reference, or a enumerable list of nodes
### extractContent
Defined by: [dojo/html](html)
Should the content be treated as a full html document, and the real content stripped of `<html> <body>` wrapper before injection
### id
Defined by: [dojo/html](html)
Usually only used internally, and auto-generated with each instance
### node
Defined by: [dojo/html](html)
An node which will be the parent element that we set content into
### parseContent
Defined by: [dojo/html](html)
Should the node by passed to the parser after the new content is set
### parserScope
Defined by: [dojo/html](html)
Flag passed to parser. Root for attribute names to search for. If scopeName is dojo, will search for data-dojo-type (or dojoType). For backwards compatibility reasons defaults to dojo.\_scopeName (which is "dojo" except when multi-version support is used, when it will be something like dojo16, dojo20, etc.)
### startup
Defined by: [dojo/html](html)
Start the child widgets after parsing them. Only obeyed if parseContent is true.
Methods
-------
###
`empty``()`
Defined by [dojo/html](html)
cleanly empty out existing content
###
`set``(cont,params)`
Defined by [dojo/html](html)
front-end to the set-content sequence
| Parameter | Type | Description |
| --- | --- | --- |
| cont | String | DomNode | NodeList | *Optional*
An html string, node or enumerable list of nodes for insertion into the dom If not provided, the object's content property will be used |
| params | Object | *Optional* |
**Returns:** undefined
###
`setContent``()`
Defined by [dojo/html](html)
sets the content on the node
###
`tearDown``()`
Defined by [dojo/html](html)
manually reset the Setter instance if its being re-used for example for another set()
tearDown() is not called automatically. In normal use, the Setter instance properties are simply allowed to fall out of scope but the tearDown method can be called to explicitly reset this instance.
Events
------
###
`onBegin``()`
Defined by: [dojo/html](html)
Called after instantiation, but before set(); It allows modification of any of the object properties - including the node and content provided - before the set operation actually takes place This default implementation checks for cleanContent and extractContent flags to optionally pre-process html string content
**Returns:** undefined
###
`onContentError``(err)`
Defined by: [dojo/html](html)
| Parameter | Type | Description |
| --- | --- | --- |
| err | undefined | |
**Returns:** string
###
`onEnd``()`
Defined by: [dojo/html](html)
Called after set(), when the new content has been pushed into the node It provides an opportunity for post-processing before handing back the node to the caller This default implementation checks a parseContent flag to optionally run the dojo parser over the new content
**Returns:** undefined
###
`onExecError``(err)`
Defined by: [dojo/html](html)
| Parameter | Type | Description |
| --- | --- | --- |
| err | undefined | |
**Returns:** string
| programming_docs |
dojo dojo/NodeList-traverse dojo/NodeList-traverse
======================
Summary
-------
Adds chainable methods to [dojo/query()](query) / NodeList instances for traversing the DOM
Usage
-----
NodeList-traverse`();` See the [dojo/NodeList-traverse reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/NodeList-traverse.html) for more information.
Methods
-------
dojo dojo/require dojo/require
============
See the [dojo/require reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/require.html) for more information.
Properties
----------
### dynamic
Defined by: [dojo/require](require)
### load
Defined by: [dojo/require](require)
Methods
-------
###
`normalize``(id)`
Defined by [dojo/require](require)
| Parameter | Type | Description |
| --- | --- | --- |
| id | undefined | |
**Returns:** undefined
dojo dojo/NodeList-dom dojo/NodeList-dom
=================
Summary
-------
Adds DOM related methods to NodeList, and returns NodeList constructor.
Usage
-----
NodeList-dom`();` See the [dojo/NodeList-dom reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/NodeList-dom.html) for more information.
Methods
-------
dojo dojo/request.__BaseOptions dojo/request.\_\_BaseOptions
============================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new request.__BaseOptions()`
Properties
----------
### data
Defined by: [dojo/request](request)
Data to transfer. This is ignored for GET and DELETE requests.
### handleAs
Defined by: [dojo/request](request)
How to handle the response from the server. Default is 'text'. Other values are 'json', 'javascript', and 'xml'.
### preventCache
Defined by: [dojo/request](request)
Whether to append a cache-busting parameter to the URL.
### query
Defined by: [dojo/request](request)
Query parameters to append to the URL.
### timeout
Defined by: [dojo/request](request)
Milliseconds to wait for the response. If this time passes, the then the promise is rejected.
dojo dojo/NodeList-html dojo/NodeList-html
==================
Summary
-------
Adds a chainable html method to [dojo/query()](query) / NodeList instances for setting/replacing node content
Usage
-----
NodeList-html`();` See the [dojo/NodeList-html reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/NodeList-html.html) for more information.
Methods
-------
dojo dojo/json dojo/json
=========
Summary
-------
Functions to parse and serialize JSON
See the [dojo/json reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/json.html) for more information.
Methods
-------
###
`parse``(str,strict)`
Defined by [dojo/json](json)
Parses a [JSON](http://json.org) string to return a JavaScript object.
This function follows [native JSON API](https://developer.mozilla.org/en/JSON) Throws for invalid JSON strings. This delegates to eval() if native JSON support is not available. By default this will evaluate any valid JS expression. With the strict parameter set to true, the parser will ensure that only valid JSON strings are parsed (otherwise throwing an error). Without the strict parameter, the content passed to this method must come from a trusted source.
| Parameter | Type | Description |
| --- | --- | --- |
| str | undefined | a string literal of a JSON item, for instance: `'{ "foo": [ "bar", 1, { "baz": "thud" } ] }'` |
| strict | undefined | When set to true, this will ensure that only valid, secure JSON is ever parsed. Make sure this is set to true for untrusted content. Note that on browsers/engines without native JSON support, setting this to true will run slower. |
###
`stringify``(value,replacer,spacer)`
Defined by [dojo/json](json)
Returns a [JSON](http://json.org) serialization of an object.
Returns a [JSON](http://json.org) serialization of an object. This function follows [native JSON API](https://developer.mozilla.org/en/JSON) Note that this doesn't check for infinite recursion, so don't do that!
| Parameter | Type | Description |
| --- | --- | --- |
| value | undefined | A value to be serialized. |
| replacer | undefined | A replacer function that is called for each value and can return a replacement |
| spacer | undefined | A spacer string to be used for pretty printing of JSON |
Examples
--------
### Example 1
simple serialization of a trivial object
```
define(["dojo/json"], function(JSON){
var jsonStr = JSON.stringify({ howdy: "stranger!", isStrange: true });
doh.is('{"howdy":"stranger!","isStrange":true}', jsonStr);
```
dojo dojo/dom-prop.names dojo/dom-prop.names
===================
Properties
----------
### class
Defined by: [dojo/dom-prop](dom-prop)
### colspan
Defined by: [dojo/dom-prop](dom-prop)
### for
Defined by: [dojo/dom-prop](dom-prop)
### frameborder
Defined by: [dojo/dom-prop](dom-prop)
### readonly
Defined by: [dojo/dom-prop](dom-prop)
### rowspan
Defined by: [dojo/dom-prop](dom-prop)
### tabindex
Defined by: [dojo/dom-prop](dom-prop)
### textcontent
Defined by: [dojo/dom-prop](dom-prop)
### valuetype
Defined by: [dojo/dom-prop](dom-prop)
dojo dojo/on dojo/on
=======
Summary
-------
A function that provides core event listening functionality. With this function you can provide a target, event type, and listener to be notified of future matching events that are fired.
To listen for "click" events on a button node, we can do:
```
define(["dojo/on"], function(listen){
on(button, "click", clickHandler);
...
```
Evented JavaScript objects can also have their own events.
```
var obj = new Evented;
on(obj, "foo", fooHandler);
```
And then we could publish a "foo" event:
```
on.emit(obj, "foo", {key: "value"});
```
We can use extension events as well. For example, you could listen for a tap gesture:
```
define(["dojo/on", "dojo/gesture/tap", function(listen, tap){
on(button, tap, tapHandler);
...
```
which would trigger fooHandler. Note that for a simple object this is equivalent to calling:
```
obj.onfoo({key:"value"});
```
If you use on.emit on a DOM node, it will use native event dispatching when possible.
Usage
-----
on`(target,type,listener,dontFix);`
| Parameter | Type | Description |
| --- | --- | --- |
| target | Element | Object | This is the target object or DOM element that to receive events from |
| type | String | Function | This is the name of the event to listen for or an extension event type. |
| listener | Function | This is the function that should be called when the event fires. |
| dontFix | undefined | |
**Returns:** Object | undefined
An object with a remove() method that can be used to stop listening for this event.
See the [dojo/on reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/on.html) for more information.
Methods
-------
###
`emit``(target,type,event)`
Defined by [dojo/on](on)
| Parameter | Type | Description |
| --- | --- | --- |
| target | undefined | |
| type | undefined | |
| event | undefined | |
**Returns:** undefined
###
`matches``(node,selector,context,children,matchesTarget)`
Defined by [dojo/on](on)
Check if a node match the current selector within the constraint of a context
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | The node that originate the event |
| selector | String | The selector to check against |
| context | DOMNode | The context to search in. |
| children | Boolean | Indicates if children elements of the selector should be allowed. This defaults to true |
| matchesTarget | Object | [dojo/query](query) | *Optional*
An object with a property "matches" as a function. Default is dojo/query. Matching DOMNodes will be done against this function The function must return a Boolean. It will have 3 arguments: "node", "selector" and "context" True is expected if "node" is matching the current "selector" in the passed "context" |
**Returns:** DOMNode
The matching node, if any. Else you get false
###
`once``(target,type,listener,dontFix)`
Defined by [dojo/on](on)
This function acts the same as on(), but will only call the listener once. The listener will be called for the first event that takes place and then listener will automatically be removed.
| Parameter | Type | Description |
| --- | --- | --- |
| target | undefined | |
| type | undefined | |
| listener | undefined | |
| dontFix | undefined | |
**Returns:** undefined
###
`parse``(target,type,listener,addListener,dontFix,matchesTarget)`
Defined by [dojo/on](on)
| Parameter | Type | Description |
| --- | --- | --- |
| target | undefined | |
| type | undefined | |
| listener | undefined | |
| addListener | undefined | |
| dontFix | undefined | |
| matchesTarget | undefined | |
**Returns:** undefined
###
`pausable``(target,type,listener,dontFix)`
Defined by [dojo/on](on)
This function acts the same as on(), but with pausable functionality. The returned signal object has pause() and resume() functions. Calling the pause() method will cause the listener to not be called for future events. Calling the resume() method will cause the listener to again be called for future events.
| Parameter | Type | Description |
| --- | --- | --- |
| target | undefined | |
| type | undefined | |
| listener | undefined | |
| dontFix | undefined | |
**Returns:** undefined
###
`selector``(selector,eventType,children)`
Defined by [dojo/on](on)
Creates a new extension event with event delegation. This is based on the provided event type (can be extension event) that only calls the listener when the CSS selector matches the target of the event.
The application must require() an appropriate level of dojo/query to handle the selector.
| Parameter | Type | Description |
| --- | --- | --- |
| selector | undefined | The CSS selector to use for filter events and determine the |this| of the event listener. |
| eventType | undefined | The event to listen for |
| children | undefined | Indicates if children elements of the selector should be allowed. This defaults to true |
**Returns:** it, or programatically by arrow key handling code.
Examples
--------
### Example 1
```
require(["dojo/on", "dojo/mouse", "dojo/query!css2"], function(listen, mouse){
on(node, on.selector(".my-class", mouse.enter), handlerForMyHover);
```
dojo dojo/NodeList-fx dojo/NodeList-fx
================
Summary
-------
Adds dojo.fx animation support to dojo.query() by extending the NodeList class with additional FX functions. NodeList is the array-like object used to hold query results.
Usage
-----
NodeList-fx`();` See the [dojo/NodeList-fx reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/NodeList-fx.html) for more information.
Methods
-------
###
`fadeTo``(args)`
Defined by [dojox/fx/ext-dojo/NodeList](http://dojotoolkit.org/api/1.10/dojox/fx/ext-dojo/NodeList)
fade all elements of the node list to a specified opacity
| Parameter | Type | Description |
| --- | --- | --- |
| args | undefined | |
**Returns:** undefined
Examples
--------
### Example 1
```
// fade all elements with class "bar" to to 50% opacity
dojo.query(".bar").fadeTo({ end: 0.5 }).play();
```
###
`highlight``(args)`
Defined by [dojox/fx/ext-dojo/NodeList](http://dojotoolkit.org/api/1.10/dojox/fx/ext-dojo/NodeList)
highlight all elements of the node list. Returns an instance of dojo.Animation
| Parameter | Type | Description |
| --- | --- | --- |
| args | undefined | |
**Returns:** undefined
Examples
--------
### Example 1
```
// highlight all links with class "foo"
dojo.query("a.foo").hightlight().play();
```
###
`sizeTo``(args)`
Defined by [dojox/fx/ext-dojo/NodeList](http://dojotoolkit.org/api/1.10/dojox/fx/ext-dojo/NodeList)
size all elements of this NodeList. Returns an instance of dojo.Animation
| Parameter | Type | Description |
| --- | --- | --- |
| args | undefined | |
**Returns:** undefined
Examples
--------
### Example 1
```
// size all divs with class "blah"
dojo.query("div.blah").sizeTo({
width:50,
height:50
}).play();
```
###
`slideBy``(args)`
Defined by [dojox/fx/ext-dojo/NodeList](http://dojotoolkit.org/api/1.10/dojox/fx/ext-dojo/NodeList)
slide all elements of this NodeList. Returns an instance of dojo.Animation
| Parameter | Type | Description |
| --- | --- | --- |
| args | undefined | |
**Returns:** undefined
Examples
--------
### Example 1
```
// slide all tables with class "blah" 10 px
dojo.query("table.blah").slideBy({ top:10, left:10 }).play();
```
###
`wipeTo``(args)`
Defined by [dojox/fx/ext-dojo/NodeList](http://dojotoolkit.org/api/1.10/dojox/fx/ext-dojo/NodeList)
Wipe all elements of the NodeList to a specified width: or height:
| Parameter | Type | Description |
| --- | --- | --- |
| args | undefined | |
**Returns:** undefined
Examples
--------
### Example 1
```
dojo.query(".box").wipeTo({ width: 300px }).play();
```
dojo dojo/gears.available dojo/gears.available
====================
Summary
-------
True if client is using Google Gears
dojo dojo/main.date dojo/main.date
==============
Properties
----------
### stamp
Defined by: [dojo/date/stamp](date/stamp)
TODOC
Methods
-------
###
`add``(date,interval,amount)`
Defined by [dojo/date](date)
Add to a Date in intervals of different size, from milliseconds to years
| Parameter | Type | Description |
| --- | --- | --- |
| date | Date | Date object to start with |
| interval | String | A string representing the interval. One of the following: "year", "month", "day", "hour", "minute", "second", "millisecond", "quarter", "week", "weekday" |
| amount | int | How much to add to the date. |
**Returns:** instance
###
`compare``(date1,date2,portion)`
Defined by [dojo/date](date)
Compare two date objects by date, time, or both.
Returns 0 if equal, positive if a > b, else negative.
| Parameter | Type | Description |
| --- | --- | --- |
| date1 | Date | Date object |
| date2 | Date | *Optional*
Date object. If not specified, the current Date is used. |
| portion | String | *Optional*
A string indicating the "date" or "time" portion of a Date object. Compares both "date" and "time" by default. One of the following: "date", "time", "datetime" |
**Returns:** number
###
`difference``(date1,date2,interval)`
Defined by [dojo/date](date)
Get the difference in a specific unit of time (e.g., number of months, weeks, days, etc.) between two dates, rounded to the nearest integer.
| Parameter | Type | Description |
| --- | --- | --- |
| date1 | Date | Date object |
| date2 | Date | *Optional*
Date object. If not specified, the current Date is used. |
| interval | String | *Optional*
A string representing the interval. One of the following: "year", "month", "day", "hour", "minute", "second", "millisecond", "quarter", "week", "weekday" Defaults to "day". |
**Returns:** undefined
###
`getDaysInMonth``(dateObject)`
Defined by [dojo/date](date)
Returns the number of days in the month used by dateObject
| Parameter | Type | Description |
| --- | --- | --- |
| dateObject | Date | |
**Returns:** number | undefined
###
`getTimezoneName``(dateObject)`
Defined by [dojo/date](date)
Get the user's time zone as provided by the browser
Try to get time zone info from toString or toLocaleString method of the Date object -- UTC offset is not a time zone. See <http://www.twinsun.com/tz/tz-link.htm> Note: results may be inconsistent across browsers.
| Parameter | Type | Description |
| --- | --- | --- |
| dateObject | Date | Needed because the timezone may vary with time (daylight savings) |
**Returns:** undefined
###
`isLeapYear``(dateObject)`
Defined by [dojo/date](date)
Determines if the year of the dateObject is a leap year
Leap years are years with an additional day YYYY-02-29, where the year number is a multiple of four with the following exception: If a year is a multiple of 100, then it is only a leap year if it is also a multiple of 400. For example, 1900 was not a leap year, but 2000 is one.
| Parameter | Type | Description |
| --- | --- | --- |
| dateObject | Date | |
**Returns:** boolean
dojo dojo/main.mouseButtons dojo/main.mouseButtons
======================
Properties
----------
### LEFT
Defined by: [dojo/mouse](mouse)
Numeric value of the left mouse button for the platform.
### MIDDLE
Defined by: [dojo/mouse](mouse)
Numeric value of the middle mouse button for the platform.
### RIGHT
Defined by: [dojo/mouse](mouse)
Numeric value of the right mouse button for the platform.
Methods
-------
###
`isButton``(e,button)`
Defined by [dojo/mouse](mouse)
Checks an event object for a pressed button
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | Event object to examine |
| button | Number | The button value (example: dojo.mouseButton.LEFT) |
**Returns:** boolean
###
`isLeft``(e)`
Defined by [dojo/mouse](mouse)
Checks an event object for the pressed left button
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | Event object to examine |
**Returns:** boolean
###
`isMiddle``(e)`
Defined by [dojo/mouse](mouse)
Checks an event object for the pressed middle button
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | Event object to examine |
**Returns:** boolean
###
`isRight``(e)`
Defined by [dojo/mouse](mouse)
Checks an event object for the pressed right button
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | Event object to examine |
**Returns:** boolean
dojo dojo/main.global dojo/main.global
================
Summary
-------
Alias for the current window. 'global' can be modified for temporary context shifting. See also withGlobal().
Use this rather than referring to 'window' to ensure your code runs correctly in managed contexts.
Methods
-------
###
`$``()`
Defined by [dojox/jq](http://dojotoolkit.org/api/1.10/dojox/jq)
**Returns:** undefined
###
`GoogleSearchStoreCallback_undefined_NaN``(start,data,responseCode,errorMsg)`
Defined by [dojox/data/GoogleSearchStore](http://dojotoolkit.org/api/1.10/dojox/data/GoogleSearchStore)
| Parameter | Type | Description |
| --- | --- | --- |
| start | undefined | |
| data | undefined | |
| responseCode | undefined | |
| errorMsg | undefined | |
###
`jQuery``()`
Defined by [dojox/jq](http://dojotoolkit.org/api/1.10/dojox/jq)
**Returns:** undefined
###
`swfIsInHTML``()`
Defined by [dojox/av/FLVideo](http://dojotoolkit.org/api/1.10/dojox/av/FLVideo)
###
`undefined_onload``()`
Defined by [dojo/request/iframe](request/iframe)
dojo dojo/main._contentHandlers dojo/main.\_contentHandlers
===========================
Summary
-------
A map of available XHR transport handle types. Name matches the `handleAs` attribute passed to XHR calls.
A map of available XHR transport handle types. Name matches the `handleAs` attribute passed to XHR calls. Each contentHandler is called, passing the xhr object for manipulation. The return value from the contentHandler will be passed to the `load` or `handle` functions defined in the original xhr call.
Examples
--------
### Example 1
Creating a custom content-handler:
```
xhr.contentHandlers.makeCaps = function(xhr){
return xhr.responseText.toUpperCase();
}
// and later:
dojo.xhrGet({
url:"foo.txt",
handleAs:"makeCaps",
load: function(data){ /* data is a toUpper version of foo.txt */ }
});
```
Methods
-------
###
`auto``(xhr)`
Defined by [dojox/rpc/Service](http://dojotoolkit.org/api/1.10/dojox/rpc/Service)
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
###
`javascript``(xhr)`
Defined by [dojo/\_base/xhr](_base/xhr)
A contentHandler which evaluates the response data, expecting it to be valid JavaScript
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`json``(xhr)`
Defined by [dojo/\_base/xhr](_base/xhr)
A contentHandler which returns a JavaScript object created from the response data
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`json-comment-filtered``(xhr)`
Defined by [dojo/\_base/xhr](_base/xhr)
A contentHandler which expects comment-filtered JSON.
A contentHandler which expects comment-filtered JSON. the json-comment-filtered option was implemented to prevent "JavaScript Hijacking", but it is less secure than standard JSON. Use standard JSON instead. JSON prefixing can be used to subvert hijacking.
Will throw a notice suggesting to use application/json mimetype, as json-commenting can introduce security issues. To decrease the chances of hijacking, use the standard `json` contentHandler, and prefix your "JSON" with: {}&&
use djConfig.useCommentedJson = true to turn off the notice
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`json-comment-optional``(xhr)`
Defined by [dojo/\_base/xhr](_base/xhr)
A contentHandler which checks the presence of comment-filtered JSON and alternates between the `json` and `json-comment-filtered` contentHandlers.
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`text``(xhr)`
Defined by [dojo/\_base/xhr](_base/xhr)
A contentHandler which simply returns the plaintext response data
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`xml``(xhr)`
Defined by [dojo/\_base/xhr](_base/xhr)
A contentHandler returning an XML Document parsed from the response data
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
| programming_docs |
dojo dojo/main.__IoPublish dojo/main.\_\_IoPublish
=======================
Summary
-------
This is a list of IO topics that can be published if djConfig.ioPublish is set to true. IO topics can be published for any Input/Output, network operation. So, dojo.xhr, dojo.io.script and dojo.io.iframe can all trigger these topics to be published.
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new main.__IoPublish()`
Properties
----------
### done
Defined by: [dojo/\_base/xhr](_base/xhr)
"/dojo/io/done" is sent whenever an IO request has completed, either by loading or by erroring. It passes the error and the dojo.Deferred for the request with the topic.
### error
Defined by: [dojo/\_base/xhr](_base/xhr)
"/dojo/io/error" is sent whenever an IO request has errored. It passes the error and the dojo.Deferred for the request with the topic.
### load
Defined by: [dojo/\_base/xhr](_base/xhr)
"/dojo/io/load" is sent whenever an IO request has loaded successfully. It passes the response and the dojo.Deferred for the request with the topic.
### send
Defined by: [dojo/\_base/xhr](_base/xhr)
"/dojo/io/send" is sent whenever a new IO request is started. It passes the dojo.Deferred for the request with the topic.
### start
Defined by: [dojo/\_base/xhr](_base/xhr)
"/dojo/io/start" is sent when there are no outstanding IO requests, and a new IO request is started. No arguments are passed with this topic.
### stop
Defined by: [dojo/\_base/xhr](_base/xhr)
"/dojo/io/stop" is sent when all outstanding IO requests have finished. No arguments are passed with this topic.
dojo dojo/hash dojo/hash
=========
Summary
-------
Gets or sets the hash string in the browser URL.
Handles getting and setting of location.hash.
* If no arguments are passed, acts as a getter.
* If a string is passed, acts as a setter.
Usage
-----
hash`(hash,replace);`
| Parameter | Type | Description |
| --- | --- | --- |
| hash | String | *Optional*
the hash is set - #string. |
| replace | Boolean | *Optional*
If true, updates the hash value in the current history state instead of creating a new history state. |
**Returns:** any | undefined
when used as a getter, returns the current hash string. when used as a setter, returns the new hash string.
See the [dojo/hash reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/hash.html) for more information.
Examples
--------
### Example 1
```
topic.subscribe("/dojo/hashchange", context, callback);
function callback (hashValue){
// do something based on the hash value.
}
```
Methods
-------
dojo dojo/main.fx dojo/main.fx
============
Summary
-------
Effects library on top of Base animations
Properties
----------
### easing
Defined by: [dojo/fx/easing](fx/easing)
Collection of easing functions to use beyond the default `dojo._defaultEasing` function.
Methods
-------
###
`chain``(animations)`
Defined by [dojo/fx](fx)
Chain a list of `dojo/_base/fx.Animation`s to run in sequence
Return a [dojo/\_base/fx.Animation](_base/fx#Animation) which will play all passed [dojo/\_base/fx.Animation](_base/fx#Animation) instances in sequence, firing its own synthesized events simulating a single animation. (eg: onEnd of this animation means the end of the chain, not the individual animations within)
| Parameter | Type | Description |
| --- | --- | --- |
| animations | [dojo/\_base/fx.Animation](_base/fx#Animation)[] | |
**Returns:** instance
Examples
--------
### Example 1
Once `node` is faded out, fade in `otherNode`
```
require(["dojo/fx"], function(fx){
fx.chain([
fx.fadeIn({ node:node }),
fx.fadeOut({ node:otherNode })
]).play();
});
```
###
`combine``(animations)`
Defined by [dojo/fx](fx)
Combine a list of `dojo/_base/fx.Animation`s to run in parallel
Combine an array of [dojo/\_base/fx.Animation](_base/fx#Animation)s to run in parallel, providing a new [dojo/\_base/fx.Animation](_base/fx#Animation) instance encompasing each animation, firing standard animation events.
| Parameter | Type | Description |
| --- | --- | --- |
| animations | [dojo/\_base/fx.Animation](_base/fx#Animation)[] | |
**Returns:** instance
Examples
--------
### Example 1
Fade out `node` while fading in `otherNode` simultaneously
```
require(["dojo/fx"], function(fx){
fx.combine([
fx.fadeIn({ node:node }),
fx.fadeOut({ node:otherNode })
]).play();
});
```
### Example 2
When the longest animation ends, execute a function:
```
require(["dojo/fx"], function(fx){
var anim = fx.combine([
fx.fadeIn({ node: n, duration:700 }),
fx.fadeOut({ node: otherNode, duration: 300 })
]);
aspect.after(anim, "onEnd", function(){
// overall animation is done.
}, true);
anim.play(); // play the animation
});
```
###
`slideTo``(args)`
Defined by [dojo/fx](fx)
Slide a node to a new top/left position
Returns an animation that will slide "node" defined in args Object from its current position to the position defined by (args.left, args.top).
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | A hash-map of standard `dojo/_base/fx.Animation` constructor properties (such as easing: node: duration: and so on). Special args members are `top` and `left`, which indicate the new position to slide to. |
**Returns:** undefined
Examples
--------
### Example 1
```
.slideTo({ node: node, left:"40", top:"50", units:"px" }).play()
```
###
`Toggler``()`
Defined by [dojo/fx/Toggler](fx/toggler)
###
`wipeIn``(args)`
Defined by [dojo/fx](fx)
Expand a node to it's natural height.
Returns an animation that will expand the node defined in 'args' object from it's current height to it's natural height (with no scrollbar). Node must have no margin/border/padding.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | A hash-map of standard `dojo/_base/fx.Animation` constructor properties (such as easing: node: duration: and so on) |
**Returns:** undefined
Examples
--------
### Example 1
```
require(["dojo/fx"], function(fx){
fx.wipeIn({
node:"someId"
}).play()
});
```
###
`wipeOut``(args)`
Defined by [dojo/fx](fx)
Shrink a node to nothing and hide it.
Returns an animation that will shrink node defined in "args" from it's current height to 1px, and then hide it.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | A hash-map of standard `dojo/_base/fx.Animation` constructor properties (such as easing: node: duration: and so on) |
**Returns:** undefined
Examples
--------
### Example 1
```
require(["dojo/fx"], function(fx){
fx.wipeOut({ node:"someId" }).play()
});
```
dojo dojo/cache dojo/cache
==========
Summary
-------
A getter and setter for storing the string content associated with the module and url arguments.
If module is a string that contains slashes, then it is interpretted as a fully resolved path (typically a result returned by require.toUrl), and url should not be provided. This is the preferred signature. If module is a string that does not contain slashes, then url must also be provided and module and url are used to call `dojo.moduleUrl()` to generate a module URL. This signature is deprecated. If value is specified, the cache value for the moduleUrl will be set to that value. Otherwise, dojo.cache will fetch the moduleUrl and store it in its internal cache and return that cached value for the URL. To clear a cache value pass null for value. Since XMLHttpRequest (XHR) is used to fetch the the URL contents, only modules on the same domain of the page can use this capability. The build system can inline the cache values though, to allow for xdomain hosting.
Usage
-----
cache`(module,url,value);`
| Parameter | Type | Description |
| --- | --- | --- |
| module | String | Object | dojo/cldr/supplemental |
| url | String | The rest of the path to append to the path derived from the module argument. If module is an object, then this second argument should be the "value" argument instead. |
| value | String | Object | *Optional*
If a String, the value to use in the cache for the module/url combination. If an Object, it can have two properties: value and sanitize. The value property should be the value to use in the cache, and sanitize can be set to true or false, to indicate if XML declarations should be removed from the value and if the HTML inside a body tag in the value should be extracted as the real value. The value argument or the value property on the value argument are usually only used by the build system as it inlines cache content. |
**Returns:** undefined | null
See the [dojo/cache reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/cache.html) for more information.
Examples
--------
### Example 1
To ask dojo.cache to fetch content and store it in the cache (the dojo["cache"] style of call is used to avoid an issue with the build system erroneously trying to intern this example. To get the build system to intern your dojo.cache calls, use the "dojo.cache" style of call):
```
//If template.html contains "<h1>Hello</h1>" that will be
//the value for the text variable.
//Note: This is pre-AMD, deprecated syntax
var text = dojo["cache"]("my.module", "template.html");
```
### Example 2
To ask dojo.cache to fetch content and store it in the cache, and sanitize the input (the dojo["cache"] style of call is used to avoid an issue with the build system erroneously trying to intern this example. To get the build system to intern your dojo.cache calls, use the "dojo.cache" style of call):
```
//If template.html contains "<html><body><h1>Hello</h1></body></html>", the
//text variable will contain just "<h1>Hello</h1>".
//Note: This is pre-AMD, deprecated syntax
var text = dojo["cache"]("my.module", "template.html", {sanitize: true});
```
### Example 3
Same example as previous, but demonstrates how an object can be passed in as the first argument, then the value argument can then be the second argument.
```
//If template.html contains "<html><body><h1>Hello</h1></body></html>", the
//text variable will contain just "<h1>Hello</h1>".
//Note: This is pre-AMD, deprecated syntax
var text = dojo["cache"](new dojo._Url("my/module/template.html"), {sanitize: true});
```
Methods
-------
dojo dojo/fx.easing dojo/fx.easing
==============
Summary
-------
Collection of easing functions to use beyond the default `dojo._defaultEasing` function.
Easing functions are used to manipulate the iteration through an `dojo.Animation`s \_Line. \_Line being the properties of an Animation, and the easing function progresses through that Line determining how quickly (or slowly) it should go. Or more accurately: modify the value of the \_Line based on the percentage of animation completed.
All functions follow a simple naming convention of "ease type" + "when". If the name of the function ends in Out, the easing described appears towards the end of the animation. "In" means during the beginning, and InOut means both ranges of the Animation will applied, both beginning and end.
One does not call the easing function directly, it must be passed to the `easing` property of an animation.
Examples
--------
### Example 1
```
dojo.require("dojo.fx.easing");
var anim = dojo.fadeOut({
node: 'node',
duration: 2000,
// note there is no ()
easing: dojo.fx.easing.quadIn
}).play();
```
Methods
-------
###
`backIn``(n)`
Defined by [dojo/fx/easing](fx/easing)
An easing function that starts away from the target, and quickly accelerates towards the end value.
Use caution when the easing will cause values to become negative as some properties cannot be set to negative values.
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`backInOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
An easing function combining the effects of `backIn` and `backOut`
An easing function combining the effects of `backIn` and `backOut`. Use caution when the easing will cause values to become negative as some properties cannot be set to negative values.
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`backOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
An easing function that pops past the range briefly, and slowly comes back.
An easing function that pops past the range briefly, and slowly comes back.
Use caution when the easing will cause values to become negative as some properties cannot be set to negative values.
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`bounceIn``(n)`
Defined by [dojo/fx/easing](fx/easing)
An easing function that 'bounces' near the beginning of an Animation
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`bounceInOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
An easing function that 'bounces' at the beginning and end of the Animation
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`bounceOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
An easing function that 'bounces' near the end of an Animation
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`circIn``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`circInOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`circOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** undefined
###
`cubicIn``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** undefined
###
`cubicInOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`cubicOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`elasticIn``(n)`
Defined by [dojo/fx/easing](fx/easing)
An easing function the elastically snaps from the start value
An easing function the elastically snaps from the start value
Use caution when the elasticity will cause values to become negative as some properties cannot be set to negative values.
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** Decimal | number
###
`elasticInOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
An easing function that elasticly snaps around the value, near the beginning and end of the Animation.
An easing function that elasticly snaps around the value, near the beginning and end of the Animation.
Use caution when the elasticity will cause values to become negative as some properties cannot be set to negative values.
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`elasticOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
An easing function that elasticly snaps around the target value, near the end of the Animation
An easing function that elasticly snaps around the target value, near the end of the Animation
Use caution when the elasticity will cause values to become negative as some properties cannot be set to negative values.
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** Decimal | number
###
`expoIn``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** undefined
###
`expoInOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`expoOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`linear``(n)`
Defined by [dojo/fx/easing](fx/easing)
A linear easing function
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** Decimal
###
`quadIn``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** undefined
###
`quadInOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`quadOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`quartIn``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** undefined
###
`quartInOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`quartOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`quintIn``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** undefined
###
`quintInOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`quintOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`sineIn``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`sineInOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`sineOut``(n)`
Defined by [dojo/fx/easing](fx/easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** undefined
dojo dojo/keys dojo/keys
=========
Summary
-------
Definitions for common key values. Client code should test keyCode against these named constants, as the actual codes can vary by browser.
See the [dojo/keys reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/keys.html) for more information.
Properties
----------
### ALT
Defined by: [dojo/keys](keys)
### BACKSPACE
Defined by: [dojo/keys](keys)
### CAPS\_LOCK
Defined by: [dojo/keys](keys)
### CLEAR
Defined by: [dojo/keys](keys)
### copyKey
Defined by: [dojo/keys](keys)
### CTRL
Defined by: [dojo/keys](keys)
### DELETE
Defined by: [dojo/keys](keys)
### DOWN\_ARROW
Defined by: [dojo/keys](keys)
### DOWN\_DPAD
Defined by: [dojo/keys](keys)
### END
Defined by: [dojo/keys](keys)
### ENTER
Defined by: [dojo/keys](keys)
### ESCAPE
Defined by: [dojo/keys](keys)
### F1
Defined by: [dojo/keys](keys)
### F10
Defined by: [dojo/keys](keys)
### F11
Defined by: [dojo/keys](keys)
### F12
Defined by: [dojo/keys](keys)
### F13
Defined by: [dojo/keys](keys)
### F14
Defined by: [dojo/keys](keys)
### F15
Defined by: [dojo/keys](keys)
### F2
Defined by: [dojo/keys](keys)
### F3
Defined by: [dojo/keys](keys)
### F4
Defined by: [dojo/keys](keys)
### F5
Defined by: [dojo/keys](keys)
### F6
Defined by: [dojo/keys](keys)
### F7
Defined by: [dojo/keys](keys)
### F8
Defined by: [dojo/keys](keys)
### F9
Defined by: [dojo/keys](keys)
### HELP
Defined by: [dojo/keys](keys)
### HOME
Defined by: [dojo/keys](keys)
### INSERT
Defined by: [dojo/keys](keys)
### LEFT\_ARROW
Defined by: [dojo/keys](keys)
### LEFT\_DPAD
Defined by: [dojo/keys](keys)
### LEFT\_WINDOW
Defined by: [dojo/keys](keys)
### META
Defined by: [dojo/keys](keys)
### NUM\_LOCK
Defined by: [dojo/keys](keys)
### NUMPAD\_0
Defined by: [dojo/keys](keys)
### NUMPAD\_1
Defined by: [dojo/keys](keys)
### NUMPAD\_2
Defined by: [dojo/keys](keys)
### NUMPAD\_3
Defined by: [dojo/keys](keys)
### NUMPAD\_4
Defined by: [dojo/keys](keys)
### NUMPAD\_5
Defined by: [dojo/keys](keys)
### NUMPAD\_6
Defined by: [dojo/keys](keys)
### NUMPAD\_7
Defined by: [dojo/keys](keys)
### NUMPAD\_8
Defined by: [dojo/keys](keys)
### NUMPAD\_9
Defined by: [dojo/keys](keys)
### NUMPAD\_DIVIDE
Defined by: [dojo/keys](keys)
### NUMPAD\_ENTER
Defined by: [dojo/keys](keys)
### NUMPAD\_MINUS
Defined by: [dojo/keys](keys)
### NUMPAD\_MULTIPLY
Defined by: [dojo/keys](keys)
### NUMPAD\_PERIOD
Defined by: [dojo/keys](keys)
### NUMPAD\_PLUS
Defined by: [dojo/keys](keys)
### PAGE\_DOWN
Defined by: [dojo/keys](keys)
### PAGE\_UP
Defined by: [dojo/keys](keys)
### PAUSE
Defined by: [dojo/keys](keys)
### RIGHT\_ARROW
Defined by: [dojo/keys](keys)
### RIGHT\_DPAD
Defined by: [dojo/keys](keys)
### RIGHT\_WINDOW
Defined by: [dojo/keys](keys)
### SCROLL\_LOCK
Defined by: [dojo/keys](keys)
### SELECT
Defined by: [dojo/keys](keys)
### SHIFT
Defined by: [dojo/keys](keys)
### SPACE
Defined by: [dojo/keys](keys)
### TAB
Defined by: [dojo/keys](keys)
### UP\_ARROW
Defined by: [dojo/keys](keys)
### UP\_DPAD
Defined by: [dojo/keys](keys)
| programming_docs |
dojo dojo/back dojo/back
=========
Summary
-------
Browser history management resources
See the [dojo/back reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/back.html) for more information.
Methods
-------
###
`addToHistory``(args)`
Defined by [dojo/back](back)
adds a state object (args) to the history list.
To support getting back button notifications, the object argument should implement a function called either "back", "backButton", or "handle". The string "back" will be passed as the first and only argument to this callback.
To support getting forward button notifications, the object argument should implement a function called either "forward", "forwardButton", or "handle". The string "forward" will be passed as the first and only argument to this callback.
If you want the browser location string to change, define "changeUrl" on the object. If the value of "changeUrl" is true, then a unique number will be appended to the URL as a fragment identifier (<http://some.domain.com/path#uniquenumber>). If it is any other value that does not evaluate to false, that value will be used as the fragment identifier. For example, if changeUrl: 'page1', then the URL will look like: <http://some.domain.com/path#page1>
There are problems with using [dojo/back](back) with semantically-named fragment identifiers ("hash values" on an URL). In most browsers it will be hard for [dojo/back](back) to know distinguish a back from a forward event in those cases. For back/forward support to work best, the fragment ID should always be a unique value (something using new Date().getTime() for example). If you want to detect hash changes using semantic fragment IDs, then consider using [dojo/hash](hash) instead (in Dojo 1.4+).
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | The state object that will be added to the history list. |
Examples
--------
### Example 1
```
back.addToHistory({
back: function(){ console.log('back pressed'); },
forward: function(){ console.log('forward pressed'); },
changeUrl: true
});
```
###
`getHash``()`
Defined by [dojo/back](back)
**Returns:** undefined
###
`goBack``()`
Defined by [dojo/back](back)
private method. Do not call this directly.
###
`goForward``()`
Defined by [dojo/back](back)
private method. Do not call this directly.
###
`init``()`
Defined by [dojo/back](back)
Initializes the undo stack. This must be called from a
dojo dojo/sniff dojo/sniff
==========
Summary
-------
This module sets has() flags based on the current browser. It returns the has() function.
Usage
-----
sniff`();` See the [dojo/sniff reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/sniff.html) for more information.
Methods
-------
dojo dojo/main.string dojo/main.string
================
Summary
-------
String utilities for Dojo
Methods
-------
###
`escape``(str)`
Defined by [dojo/string](string)
Efficiently escape a string for insertion into HTML (innerHTML or attributes), replacing &, <, >, ", ', and / characters.
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | the string to escape |
###
`pad``(text,size,ch,end)`
Defined by [dojo/string](string)
Pad a string to guarantee that it is at least `size` length by filling with the character `ch` at either the start or end of the string. Pads at the start, by default.
| Parameter | Type | Description |
| --- | --- | --- |
| text | String | the string to pad |
| size | Integer | length to provide padding |
| ch | String | *Optional*
character to pad, defaults to '0' |
| end | Boolean | *Optional*
adds padding at the end if true, otherwise pads at start |
**Returns:** number
Examples
--------
### Example 1
```
// Fill the string to length 10 with "+" characters on the right. Yields "Dojo++++++".
string.pad("Dojo", 10, "+", true);
```
###
`rep``(str,num)`
Defined by [dojo/string](string)
Efficiently replicate a string `n` times.
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | the string to replicate |
| num | Integer | number of times to replicate the string |
**Returns:** string | undefined
###
`substitute``(template,map,transform,thisObject)`
Defined by [dojo/string](string)
Performs parameterized substitutions on a string. Throws an exception if any parameter is unmatched.
| Parameter | Type | Description |
| --- | --- | --- |
| template | String | a string with expressions in the form `${key}` to be replaced or `${key:format}` which specifies a format function. keys are case-sensitive. |
| map | Object | Array | hash to search for substitutions |
| transform | Function | *Optional*
a function to process all parameters before substitution takes place, e.g. mylib.encodeXML |
| thisObject | Object | *Optional*
where to look for optional format function; default to the global namespace |
**Returns:** undefined
Examples
--------
### Example 1
Substitutes two expressions in a string from an Array or Object
```
// returns "File 'foo.html' is not found in directory '/temp'."
// by providing substitution data in an Array
string.substitute(
"File '${0}' is not found in directory '${1}'.",
["foo.html","/temp"]
);
// also returns "File 'foo.html' is not found in directory '/temp'."
// but provides substitution data in an Object structure. Dotted
// notation may be used to traverse the structure.
string.substitute(
"File '${name}' is not found in directory '${info.dir}'.",
{ name: "foo.html", info: { dir: "/temp" } }
);
```
### Example 2
Use a transform function to modify the values:
```
// returns "file 'foo.html' is not found in directory '/temp'."
string.substitute(
"${0} is not found in ${1}.",
["foo.html","/temp"],
function(str){
// try to figure out the type
var prefix = (str.charAt(0) == "/") ? "directory": "file";
return prefix + " '" + str + "'";
}
);
```
### Example 3
Use a formatter
```
// returns "thinger -- howdy"
string.substitute(
"${0:postfix}", ["thinger"], null, {
postfix: function(value, key){
return value + " -- howdy";
}
}
);
```
###
`trim``(str)`
Defined by [dojo/string](string)
Trims whitespace from both sides of the string
This version of trim() was taken from [Steven Levithan's blog](http://blog.stevenlevithan.com/archives/faster-trim-javascript). The short yet performant version of this function is [dojo/\_base/lang.trim()](_base/lang#trim), which is part of Dojo base. Uses String.prototype.trim instead, if available.
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | String to be trimmed |
**Returns:** String | string
Returns the trimmed string
dojo dojo/robot dojo/robot
==========
See the [dojo/robot reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/robot.html) for more information.
Properties
----------
### doc
Defined by: [dojo/robotx](robotx)
### mouseWheelSize
Defined by: [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
### window
Defined by: [dojo/robotx](robotx)
Methods
-------
###
`initRobot``(url)`
Defined by [dojo/robotx](robotx)
Opens the application at the specified URL for testing, redirecting dojo to point to the application environment instead of the test environment.
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to open. Any of the test's dojo.doc calls (e.g. dojo.byId()), and any dijit.registry calls (e.g. dijit.byId()) will point to elements and widgets inside this application. |
###
`keyDown``(charOrCode,delay)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Holds down a single key, like SHIFT or 'a'.
Holds down a single key, like SHIFT or 'a'.
| Parameter | Type | Description |
| --- | --- | --- |
| charOrCode | Integer | char/JS keyCode/dojo.keys.\* constant for the key you want to hold down Warning: holding down a shifted key, like 'A', can have unpredictable results. |
| delay | Integer | *Optional*
Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms:
```
robot.mouseClick({left: true}, 100) // first call; wait 100ms
robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all
```
|
Examples
--------
### Example 1
to hold down the 'a' key immediately, call robot.keyDown('a')
###
`keyPress``(charOrCode,delay,modifiers,asynchronous)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Types a key combination, like SHIFT-TAB.
Types a key combination, like SHIFT-TAB.
| Parameter | Type | Description |
| --- | --- | --- |
| charOrCode | Integer | char/JS keyCode/dojo.keys.\* constant for the key you want to press |
| delay | Integer | *Optional*
Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms:
```
robot.mouseClick({left: true}, 100) // first call; wait 100ms
robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all
```
|
| modifiers | Object | JSON object that represents all of the modifier keys being pressed. It takes the following Boolean attributes: * shift
* alt
* ctrl
* meta
|
| asynchronous | Boolean | If true, the delay happens asynchronously and immediately, outside of the browser's JavaScript thread and any previous calls. This is useful for interacting with the browser's modal dialogs. |
Examples
--------
### Example 1
to press shift-tab immediately, call robot.keyPress(dojo.keys.TAB, 0, {shift: true})
###
`keyUp``(charOrCode,delay)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Releases a single key, like SHIFT or 'a'.
Releases a single key, like SHIFT or 'a'.
| Parameter | Type | Description |
| --- | --- | --- |
| charOrCode | Integer | char/JS keyCode/dojo.keys.\* constant for the key you want to release Warning: releasing a shifted key, like 'A', can have unpredictable results. |
| delay | Integer | *Optional*
Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms:
```
robot.mouseClick({left: true}, 100) // first call; wait 100ms
robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all
```
|
Examples
--------
### Example 1
to release the 'a' key immediately, call robot.keyUp('a')
###
`killRobot``()`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
###
`mouseClick``(buttons,delay)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Convenience function to do a press/release. See robot.mousePress for more info.
Convenience function to do a press/release. See robot.mousePress for more info.
| Parameter | Type | Description |
| --- | --- | --- |
| buttons | Object | |
| delay | Integer | *Optional* |
###
`mouseMove``(x,y,delay,duration,absolute)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Moves the mouse to the specified x,y offset relative to the viewport.
| Parameter | Type | Description |
| --- | --- | --- |
| x | Number | x offset relative to the viewport, in pixels, to move the mouse. |
| y | Number | y offset relative to the viewport, in pixels, to move the mouse. |
| delay | Integer | *Optional*
Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms:
```
robot.mouseClick({left: true}, 100) // first call; wait 100ms
robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all
```
|
| duration | Integer | *Optional*
Approximate time Robot will spend moving the mouse The default is 100ms. This also affects how many mousemove events will be generated, which is the log of the duration. |
| absolute | Boolean | Boolean indicating whether the x and y values are absolute coordinates. If false, then mouseMove expects that the x,y will be relative to the window. (clientX/Y) If true, then mouseMove expects that the x,y will be absolute. (pageX/Y) |
###
`mouseMoveAt``(node,delay,duration,offsetX,offsetY)`
Defined by [dojo/robot](robot)
Moves the mouse over the specified node at the specified relative x,y offset.
Moves the mouse over the specified node at the specified relative x,y offset. If you do not specify an offset, mouseMove will default to move to the middle of the node. Example: to move the mouse over a ComboBox's down arrow node, call doh.mouseMoveAt(dijit.byId('setvaluetest').downArrowNode);
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | Function | The id of the node, or the node itself, to move the mouse to. If you pass an id or a function that returns a node, the node will not be evaluated until the movement executes. This is useful if you need to move the mouse to an node that is not yet present. |
| delay | Integer, optional | Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms:
```
robot.mouseClick({left:true}, 100) // first call; wait 100ms
robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all
```
|
| duration | Integer, optional | Approximate time Robot will spend moving the mouse The default is 100ms. |
| offsetX | Number, optional | x offset relative to the node, in pixels, to move the mouse. The default is half the node's width. |
| offsetY | Number, optional | y offset relative to the node, in pixels, to move the mouse. The default is half the node's height. |
###
`mouseMoveTo``(point,delay,duration,absolute)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Move the mouse from the current position to the specified point. Delays reading contents point until queued command starts running. See mouseMove() for details.
| Parameter | Type | Description |
| --- | --- | --- |
| point | Object | x, y position relative to viewport, or if absolute == true, to document |
| delay | Integer | *Optional* |
| duration | Integer | *Optional* |
| absolute | Boolean | |
###
`mousePress``(buttons,delay)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Presses mouse buttons.
Presses the mouse buttons you pass as true. Example: to press the left mouse button, pass {left: true}. Mouse buttons you don't specify keep their previous pressed state.
| Parameter | Type | Description |
| --- | --- | --- |
| buttons | Object | JSON object that represents all of the mouse buttons being pressed. It takes the following Boolean attributes: * left
* middle
* right
|
| delay | Integer | *Optional*
Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms:
```
robot.mouseClick({left: true}, 100) // first call; wait 100ms
robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all
```
|
###
`mouseRelease``(buttons,delay)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Releases mouse buttons.
Releases the mouse buttons you pass as true. Example: to release the left mouse button, pass {left: true}. Mouse buttons you don't specify keep their previous pressed state. See robot.mousePress for more info.
| Parameter | Type | Description |
| --- | --- | --- |
| buttons | Object | |
| delay | Integer | *Optional* |
###
`mouseWheel``(wheelAmt,delay,duration)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Spins the mouse wheel.
Spins the wheel wheelAmt "notches." Negative wheelAmt scrolls up/away from the user. Positive wheelAmt scrolls down/toward the user. Note: this will all happen in one event. Warning: the size of one mouse wheel notch is an OS setting. You can access this size from robot.mouseWheelSize
| Parameter | Type | Description |
| --- | --- | --- |
| wheelAmt | Number | Number of notches to spin the wheel. Negative wheelAmt scrolls up/away from the user. Positive wheelAmt scrolls down/toward the user. |
| delay | Integer | *Optional*
Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms: robot.mouseClick({left: true}, 100) // first call; wait 100ms robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all |
| duration | Integer | *Optional*
Approximate time Robot will spend moving the mouse By default, the Robot will wheel the mouse as fast as possible. |
###
`scrollIntoView``(node,delay)`
Defined by [dojo/robot](robot)
Scroll the passed node into view, if it is not.
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | Function | The id of the node, or the node itself, to move the mouse to. If you pass an id or a function that returns a node, the node will not be evaluated until the movement executes. This is useful if you need to move the mouse to an node that is not yet present. |
| delay | Number, optional | Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. |
###
`sequence``(f,delay,duration)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Defer an action by adding it to the robot's incrementally delayed queue of actions to execute.
| Parameter | Type | Description |
| --- | --- | --- |
| f | Function | A function containing actions you want to defer. It can return a Promise to delay further actions. |
| delay | Integer | *Optional*
Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms:
```
robot.mouseClick({left: true}, 100) // first call; wait 100ms
robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all
```
|
| duration | Integer | *Optional*
Delay to wait after firing. |
###
`setClipboard``(data,format)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Set clipboard content.
Set data as clipboard content, overriding anything already there. The data will be put to the clipboard using the given format.
| Parameter | Type | Description |
| --- | --- | --- |
| data | String | New clipboard content to set |
| format | String | *Optional*
Set this to "text/html" to put richtext to the clipboard. Otherwise, data is treated as plaintext. By default, plaintext is used. |
###
`startRobot``()`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
**Returns:** undefined
###
`typeKeys``(chars,delay,duration)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Types a string of characters in order, or types a dojo.keys.\* constant.
Types a string of characters in order, or types a dojo.keys.\* constant.
| Parameter | Type | Description |
| --- | --- | --- |
| chars | String | Number | String of characters to type, or a dojo.keys.\* constant |
| delay | Integer | *Optional*
Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms:
```
robot.mouseClick({left: true}, 100) // first call; wait 100ms
robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all
```
|
| duration | Integer | *Optional*
Time, in milliseconds, to spend pressing all of the keys. The default is (string length)\*50 ms. |
Examples
--------
### Example 1
```
robot.typeKeys("dijit.ed", 500);
```
###
`waitForPageToLoad``(submitActions)`
Defined by [dojo/robotx](robotx)
Notifies DOH that the doh.robot is about to make a page change in the application it is driving, returning a doh.Deferred object the user should return in their runTest function as part of a DOH test.
| Parameter | Type | Description |
| --- | --- | --- |
| submitActions | Function | The doh.robot will execute the actions the test passes into the submitActions argument (like clicking the submit button), expecting these actions to create a page change (like a form submit). After these actions execute and the resulting page loads, the next test will start. |
**Returns:** instance
Examples
--------
### Example 1
```
runTest: function(){
return waitForPageLoad(function(){ doh.robot.keyPress(keys.ENTER, 500); });
}
```
Events
------
| programming_docs |
dojo dojo/domReady dojo/domReady
=============
Summary
-------
Plugin to delay require()/define() callback from firing until the DOM has finished loading.
Usage
-----
domReady`(callback);`
| Parameter | Type | Description |
| --- | --- | --- |
| callback | undefined | |
See the [dojo/domReady reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/domReady.html) for more information.
Properties
----------
Methods
-------
###
`load``(id,req,load)`
Defined by [dojo/domReady](domready)
| Parameter | Type | Description |
| --- | --- | --- |
| id | undefined | |
| req | undefined | |
| load | undefined | |
Events
------
dojo dojo/robotx dojo/robotx
===========
See the [dojo/robotx reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/robotx.html) for more information.
Properties
----------
### doc
Defined by: [dojo/robotx](robotx)
### mouseWheelSize
Defined by: [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
### window
Defined by: [dojo/robotx](robotx)
Methods
-------
###
`initRobot``(url)`
Defined by [dojo/robotx](robotx)
Opens the application at the specified URL for testing, redirecting dojo to point to the application environment instead of the test environment.
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to open. Any of the test's dojo.doc calls (e.g. dojo.byId()), and any dijit.registry calls (e.g. dijit.byId()) will point to elements and widgets inside this application. |
###
`keyDown``(charOrCode,delay)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Holds down a single key, like SHIFT or 'a'.
Holds down a single key, like SHIFT or 'a'.
| Parameter | Type | Description |
| --- | --- | --- |
| charOrCode | Integer | char/JS keyCode/dojo.keys.\* constant for the key you want to hold down Warning: holding down a shifted key, like 'A', can have unpredictable results. |
| delay | Integer | *Optional*
Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms:
```
robot.mouseClick({left: true}, 100) // first call; wait 100ms
robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all
```
|
Examples
--------
### Example 1
to hold down the 'a' key immediately, call robot.keyDown('a')
###
`keyPress``(charOrCode,delay,modifiers,asynchronous)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Types a key combination, like SHIFT-TAB.
Types a key combination, like SHIFT-TAB.
| Parameter | Type | Description |
| --- | --- | --- |
| charOrCode | Integer | char/JS keyCode/dojo.keys.\* constant for the key you want to press |
| delay | Integer | *Optional*
Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms:
```
robot.mouseClick({left: true}, 100) // first call; wait 100ms
robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all
```
|
| modifiers | Object | JSON object that represents all of the modifier keys being pressed. It takes the following Boolean attributes: * shift
* alt
* ctrl
* meta
|
| asynchronous | Boolean | If true, the delay happens asynchronously and immediately, outside of the browser's JavaScript thread and any previous calls. This is useful for interacting with the browser's modal dialogs. |
Examples
--------
### Example 1
to press shift-tab immediately, call robot.keyPress(dojo.keys.TAB, 0, {shift: true})
###
`keyUp``(charOrCode,delay)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Releases a single key, like SHIFT or 'a'.
Releases a single key, like SHIFT or 'a'.
| Parameter | Type | Description |
| --- | --- | --- |
| charOrCode | Integer | char/JS keyCode/dojo.keys.\* constant for the key you want to release Warning: releasing a shifted key, like 'A', can have unpredictable results. |
| delay | Integer | *Optional*
Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms:
```
robot.mouseClick({left: true}, 100) // first call; wait 100ms
robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all
```
|
Examples
--------
### Example 1
to release the 'a' key immediately, call robot.keyUp('a')
###
`killRobot``()`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
###
`mouseClick``(buttons,delay)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Convenience function to do a press/release. See robot.mousePress for more info.
Convenience function to do a press/release. See robot.mousePress for more info.
| Parameter | Type | Description |
| --- | --- | --- |
| buttons | Object | |
| delay | Integer | *Optional* |
###
`mouseMove``(x,y,delay,duration,absolute)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Moves the mouse to the specified x,y offset relative to the viewport.
| Parameter | Type | Description |
| --- | --- | --- |
| x | Number | x offset relative to the viewport, in pixels, to move the mouse. |
| y | Number | y offset relative to the viewport, in pixels, to move the mouse. |
| delay | Integer | *Optional*
Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms:
```
robot.mouseClick({left: true}, 100) // first call; wait 100ms
robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all
```
|
| duration | Integer | *Optional*
Approximate time Robot will spend moving the mouse The default is 100ms. This also affects how many mousemove events will be generated, which is the log of the duration. |
| absolute | Boolean | Boolean indicating whether the x and y values are absolute coordinates. If false, then mouseMove expects that the x,y will be relative to the window. (clientX/Y) If true, then mouseMove expects that the x,y will be absolute. (pageX/Y) |
###
`mouseMoveAt``(node,delay,duration,offsetX,offsetY)`
Defined by [dojo/robot](robot)
Moves the mouse over the specified node at the specified relative x,y offset.
Moves the mouse over the specified node at the specified relative x,y offset. If you do not specify an offset, mouseMove will default to move to the middle of the node. Example: to move the mouse over a ComboBox's down arrow node, call doh.mouseMoveAt(dijit.byId('setvaluetest').downArrowNode);
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | Function | The id of the node, or the node itself, to move the mouse to. If you pass an id or a function that returns a node, the node will not be evaluated until the movement executes. This is useful if you need to move the mouse to an node that is not yet present. |
| delay | Integer, optional | Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms:
```
robot.mouseClick({left:true}, 100) // first call; wait 100ms
robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all
```
|
| duration | Integer, optional | Approximate time Robot will spend moving the mouse The default is 100ms. |
| offsetX | Number, optional | x offset relative to the node, in pixels, to move the mouse. The default is half the node's width. |
| offsetY | Number, optional | y offset relative to the node, in pixels, to move the mouse. The default is half the node's height. |
###
`mouseMoveTo``(point,delay,duration,absolute)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Move the mouse from the current position to the specified point. Delays reading contents point until queued command starts running. See mouseMove() for details.
| Parameter | Type | Description |
| --- | --- | --- |
| point | Object | x, y position relative to viewport, or if absolute == true, to document |
| delay | Integer | *Optional* |
| duration | Integer | *Optional* |
| absolute | Boolean | |
###
`mousePress``(buttons,delay)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Presses mouse buttons.
Presses the mouse buttons you pass as true. Example: to press the left mouse button, pass {left: true}. Mouse buttons you don't specify keep their previous pressed state.
| Parameter | Type | Description |
| --- | --- | --- |
| buttons | Object | JSON object that represents all of the mouse buttons being pressed. It takes the following Boolean attributes: * left
* middle
* right
|
| delay | Integer | *Optional*
Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms:
```
robot.mouseClick({left: true}, 100) // first call; wait 100ms
robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all
```
|
###
`mouseRelease``(buttons,delay)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Releases mouse buttons.
Releases the mouse buttons you pass as true. Example: to release the left mouse button, pass {left: true}. Mouse buttons you don't specify keep their previous pressed state. See robot.mousePress for more info.
| Parameter | Type | Description |
| --- | --- | --- |
| buttons | Object | |
| delay | Integer | *Optional* |
###
`mouseWheel``(wheelAmt,delay,duration)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Spins the mouse wheel.
Spins the wheel wheelAmt "notches." Negative wheelAmt scrolls up/away from the user. Positive wheelAmt scrolls down/toward the user. Note: this will all happen in one event. Warning: the size of one mouse wheel notch is an OS setting. You can access this size from robot.mouseWheelSize
| Parameter | Type | Description |
| --- | --- | --- |
| wheelAmt | Number | Number of notches to spin the wheel. Negative wheelAmt scrolls up/away from the user. Positive wheelAmt scrolls down/toward the user. |
| delay | Integer | *Optional*
Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms: robot.mouseClick({left: true}, 100) // first call; wait 100ms robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all |
| duration | Integer | *Optional*
Approximate time Robot will spend moving the mouse By default, the Robot will wheel the mouse as fast as possible. |
###
`scrollIntoView``(node,delay)`
Defined by [dojo/robot](robot)
Scroll the passed node into view, if it is not.
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | Function | The id of the node, or the node itself, to move the mouse to. If you pass an id or a function that returns a node, the node will not be evaluated until the movement executes. This is useful if you need to move the mouse to an node that is not yet present. |
| delay | Number, optional | Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. |
###
`sequence``(f,delay,duration)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Defer an action by adding it to the robot's incrementally delayed queue of actions to execute.
| Parameter | Type | Description |
| --- | --- | --- |
| f | Function | A function containing actions you want to defer. It can return a Promise to delay further actions. |
| delay | Integer | *Optional*
Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms:
```
robot.mouseClick({left: true}, 100) // first call; wait 100ms
robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all
```
|
| duration | Integer | *Optional*
Delay to wait after firing. |
###
`setClipboard``(data,format)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Set clipboard content.
Set data as clipboard content, overriding anything already there. The data will be put to the clipboard using the given format.
| Parameter | Type | Description |
| --- | --- | --- |
| data | String | New clipboard content to set |
| format | String | *Optional*
Set this to "text/html" to put richtext to the clipboard. Otherwise, data is treated as plaintext. By default, plaintext is used. |
###
`startRobot``()`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
**Returns:** undefined
###
`typeKeys``(chars,delay,duration)`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Types a string of characters in order, or types a dojo.keys.\* constant.
Types a string of characters in order, or types a dojo.keys.\* constant.
| Parameter | Type | Description |
| --- | --- | --- |
| chars | String | Number | String of characters to type, or a dojo.keys.\* constant |
| delay | Integer | *Optional*
Delay, in milliseconds, to wait before firing. The delay is a delta with respect to the previous automation call. For example, the following code ends after 600ms:
```
robot.mouseClick({left: true}, 100) // first call; wait 100ms
robot.typeKeys("dij", 500) // 500ms AFTER previous call; 600ms in all
```
|
| duration | Integer | *Optional*
Time, in milliseconds, to spend pressing all of the keys. The default is (string length)\*50 ms. |
Examples
--------
### Example 1
```
robot.typeKeys("dijit.ed", 500);
```
###
`waitForPageToLoad``(submitActions)`
Defined by [dojo/robotx](robotx)
Notifies DOH that the doh.robot is about to make a page change in the application it is driving, returning a doh.Deferred object the user should return in their runTest function as part of a DOH test.
| Parameter | Type | Description |
| --- | --- | --- |
| submitActions | Function | The doh.robot will execute the actions the test passes into the submitActions argument (like clicking the submit button), expecting these actions to create a page change (like a form submit). After these actions execute and the resulting page loads, the next test will start. |
**Returns:** instance
Examples
--------
### Example 1
```
runTest: function(){
return waitForPageLoad(function(){ doh.robot.keyPress(keys.ENTER, 500); });
}
```
Events
------
dojo dojo/NodeList-data dojo/NodeList-data
==================
Summary
-------
Adds data() and removeData() methods to NodeList, and returns NodeList constructor.
Usage
-----
NodeList-data`();` See the [dojo/NodeList-data reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/NodeList-data.html) for more information.
Methods
-------
dojo dojo/currency.__ParseOptions dojo/currency.\_\_ParseOptions
==============================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new currency.__ParseOptions()`
Properties
----------
### currency
Defined by: [dojo/currency](currency)
an [ISO4217](http://en.wikipedia.org/wiki/ISO_4217) currency code, a three letter sequence like "USD". For use with dojo.currency only.
### fractional
Defined by: [dojo/currency](currency)
Whether to include the fractional portion, where the number of decimal places are implied by the currency or explicit 'places' parameter. The value [true,false] makes the fractional portion optional. By default for currencies, it the fractional portion is optional.
### locale
Defined by: [dojo/number](number)
override the locale used to determine formatting rules
### pattern
Defined by: [dojo/number](number)
override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization. Literal characters in patterns are not supported.
### places
Defined by: [dojo/currency](currency)
fixed number of decimal places to accept. The default is determined based on which currency is used.
### strict
Defined by: [dojo/number](number)
strict parsing, false by default. Strict parsing requires input as produced by the format() method. Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
### symbol
Defined by: [dojo/currency](currency)
localized currency symbol. The default will be looked up in table of supported currencies in `dojo.cldr` A [ISO4217](http://en.wikipedia.org/wiki/ISO_4217) currency code will be used if not found.
### type
Defined by: [dojo/currency](currency)
Should not be set. Value is assumed to be currency.
dojo dojo/dom-construct dojo/dom-construct
==================
See the [dojo/dom-construct reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dom-construct.html) for more information.
Methods
-------
###
`create``(tag,attrs,refNode,pos)`
Defined by [dojo/dom-construct](dom-construct)
Create an element, allowing for optional attribute decoration and placement.
A DOM Element creation function. A shorthand method for creating a node or a fragment, and allowing for a convenient optional attribute setting step, as well as an optional DOM placement reference.
Attributes are set by passing the optional object through `dojo.setAttr`. See `dojo.setAttr` for noted caveats and nuances, and API if applicable.
Placement is done via `dojo.place`, assuming the new node to be the action node, passing along the optional reference node and position.
| Parameter | Type | Description |
| --- | --- | --- |
| tag | DOMNode | String | A string of the element to create (eg: "div", "a", "p", "li", "script", "br"), or an existing DOM node to process. |
| attrs | Object | An object-hash of attributes to set on the newly created node. Can be null, if you don't want to set any attributes/styles. See: `dojo.setAttr` for a description of available attributes. |
| refNode | DOMNode | String | *Optional*
Optional reference node. Used by `dojo.place` to place the newly created node somewhere in the dom relative to refNode. Can be a DomNode reference or String ID of a node. |
| pos | String | *Optional*
Optional positional reference. Defaults to "last" by way of `dojo.place`, though can be set to "first","after","before","last", "replace" or "only" to further control the placement of the new node relative to the refNode. 'refNode' is required if a 'pos' is specified. |
**Returns:** undefined
Examples
--------
### Example 1
Create a DIV:
```
require(["dojo/dom-construct"], function(domConstruct){
var n = domConstruct.create("div");
});
```
### Example 2
Create a DIV with content:
```
require(["dojo/dom-construct"], function(domConstruct){
var n = domConstruct.create("div", { innerHTML:"<p>hi</p>" });
});
```
### Example 3
Place a new DIV in the BODY, with no attributes set
```
require(["dojo/dom-construct"], function(domConstruct){
var n = domConstruct.create("div", null, dojo.body());
});
```
### Example 4
Create an UL, and populate it with LI's. Place the list as the first-child of a node with id="someId":
```
require(["dojo/dom-construct", "dojo/_base/array"],
function(domConstruct, arrayUtil){
var ul = domConstruct.create("ul", null, "someId", "first");
var items = ["one", "two", "three", "four"];
arrayUtil.forEach(items, function(data){
domConstruct.create("li", { innerHTML: data }, ul);
});
});
```
### Example 5
Create an anchor, with an href. Place in BODY:
```
require(["dojo/dom-construct"], function(domConstruct){
domConstruct.create("a", { href:"foo.html", title:"Goto FOO!" }, dojo.body());
});
```
###
`destroy``(node)`
Defined by [dojo/dom-construct](dom-construct)
Removes a node from its parent, clobbering it and all of its children.
Removes a node from its parent, clobbering it and all of its children. Function only works with DomNodes, and returns nothing.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | A String ID or DomNode reference of the element to be destroyed |
Examples
--------
### Example 1
Destroy a node byId:
```
require(["dojo/dom-construct"], function(domConstruct){
domConstruct.destroy("someId");
});
```
###
`empty``(node)`
Defined by [dojo/dom-construct](dom-construct)
safely removes all children of the node.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | a reference to a DOM node or an id. |
Examples
--------
### Example 1
Destroy node's children byId:
```
require(["dojo/dom-construct"], function(domConstruct){
domConstruct.empty("someId");
});
```
###
`place``(node,refNode,position)`
Defined by [dojo/dom-construct](dom-construct)
Attempt to insert node into the DOM, choosing from various positioning options. Returns the first argument resolved to a DOM node.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | DocumentFragment | String | id or node reference, or HTML fragment starting with "<" to place relative to refNode |
| refNode | DOMNode | String | id or node reference to use as basis for placement |
| position | String | Number | *Optional*
string noting the position of node relative to refNode or a number indicating the location in the childNodes collection of refNode. Accepted string values are: * before
* after
* replace
* only
* first
* last
"first" and "last" indicate positions as children of refNode, "replace" replaces refNode, "only" replaces all children. position defaults to "last" if not specified |
**Returns:** DOMNode | undefined
Returned values is the first argument resolved to a DOM node.
.place() is also a method of `dojo/NodeList`, allowing `dojo/query` node lookups.
Examples
--------
### Example 1
Place a node by string id as the last child of another node by string id:
```
require(["dojo/dom-construct"], function(domConstruct){
domConstruct.place("someNode", "anotherNode");
});
```
### Example 2
Place a node by string id before another node by string id
```
require(["dojo/dom-construct"], function(domConstruct){
domConstruct.place("someNode", "anotherNode", "before");
});
```
### Example 3
Create a Node, and place it in the body element (last child):
```
require(["dojo/dom-construct", "dojo/_base/window"
], function(domConstruct, win){
domConstruct.place("<div></div>", win.body());
});
```
### Example 4
Put a new LI as the first child of a list by id:
```
require(["dojo/dom-construct"], function(domConstruct){
domConstruct.place("<li></li>", "someUl", "first");
});
```
###
`toDom``(frag,doc)`
Defined by [dojo/dom-construct](dom-construct)
instantiates an HTML fragment returning the corresponding DOM.
| Parameter | Type | Description |
| --- | --- | --- |
| frag | String | the HTML fragment |
| doc | DocumentNode | *Optional*
optional document to use when creating DOM nodes, defaults to dojo/\_base/window.doc if not specified. |
**Returns:** any | undefined
Document fragment, unless it's a single node in which case it returns the node itself
Examples
--------
### Example 1
Create a table row:
```
require(["dojo/dom-construct"], function(domConstruct){
var tr = domConstruct.toDom("<tr><td>First!</td></tr>");
});
```
| programming_docs |
dojo dojo/main.version dojo/main.version
=================
Summary
-------
Version number of the Dojo Toolkit
Hash about the version, including
* major: Integer: Major version. If total version is "1.2.0beta1", will be 1
* minor: Integer: Minor version. If total version is "1.2.0beta1", will be 2
* patch: Integer: Patch version. If total version is "1.2.0beta1", will be 0
* flag: String: Descriptor flag. If total version is "1.2.0beta1", will be "beta1"
* revision: Number: The Git rev from which dojo was pulled
Properties
----------
### flag
Defined by: [dojo/\_base/kernel](_base/kernel)
### major
Defined by: [dojo/\_base/kernel](_base/kernel)
### minor
Defined by: [dojo/\_base/kernel](_base/kernel)
### patch
Defined by: [dojo/\_base/kernel](_base/kernel)
### revision
Defined by: [dojo/\_base/kernel](_base/kernel)
Methods
-------
###
`toString``()`
Defined by [dojo/\_base/kernel](_base/kernel)
**Returns:** string
dojo dojo/string dojo/string
===========
Summary
-------
String utilities for Dojo
See the [dojo/string reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/string.html) for more information.
Methods
-------
###
`escape``(str)`
Defined by [dojo/string](string)
Efficiently escape a string for insertion into HTML (innerHTML or attributes), replacing &, <, >, ", ', and / characters.
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | the string to escape |
###
`pad``(text,size,ch,end)`
Defined by [dojo/string](string)
Pad a string to guarantee that it is at least `size` length by filling with the character `ch` at either the start or end of the string. Pads at the start, by default.
| Parameter | Type | Description |
| --- | --- | --- |
| text | String | the string to pad |
| size | Integer | length to provide padding |
| ch | String | *Optional*
character to pad, defaults to '0' |
| end | Boolean | *Optional*
adds padding at the end if true, otherwise pads at start |
**Returns:** number
Examples
--------
### Example 1
```
// Fill the string to length 10 with "+" characters on the right. Yields "Dojo++++++".
string.pad("Dojo", 10, "+", true);
```
###
`rep``(str,num)`
Defined by [dojo/string](string)
Efficiently replicate a string `n` times.
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | the string to replicate |
| num | Integer | number of times to replicate the string |
**Returns:** string | undefined
###
`substitute``(template,map,transform,thisObject)`
Defined by [dojo/string](string)
Performs parameterized substitutions on a string. Throws an exception if any parameter is unmatched.
| Parameter | Type | Description |
| --- | --- | --- |
| template | String | a string with expressions in the form `${key}` to be replaced or `${key:format}` which specifies a format function. keys are case-sensitive. |
| map | Object | Array | hash to search for substitutions |
| transform | Function | *Optional*
a function to process all parameters before substitution takes place, e.g. mylib.encodeXML |
| thisObject | Object | *Optional*
where to look for optional format function; default to the global namespace |
**Returns:** undefined
Examples
--------
### Example 1
Substitutes two expressions in a string from an Array or Object
```
// returns "File 'foo.html' is not found in directory '/temp'."
// by providing substitution data in an Array
string.substitute(
"File '${0}' is not found in directory '${1}'.",
["foo.html","/temp"]
);
// also returns "File 'foo.html' is not found in directory '/temp'."
// but provides substitution data in an Object structure. Dotted
// notation may be used to traverse the structure.
string.substitute(
"File '${name}' is not found in directory '${info.dir}'.",
{ name: "foo.html", info: { dir: "/temp" } }
);
```
### Example 2
Use a transform function to modify the values:
```
// returns "file 'foo.html' is not found in directory '/temp'."
string.substitute(
"${0} is not found in ${1}.",
["foo.html","/temp"],
function(str){
// try to figure out the type
var prefix = (str.charAt(0) == "/") ? "directory": "file";
return prefix + " '" + str + "'";
}
);
```
### Example 3
Use a formatter
```
// returns "thinger -- howdy"
string.substitute(
"${0:postfix}", ["thinger"], null, {
postfix: function(value, key){
return value + " -- howdy";
}
}
);
```
###
`trim``(str)`
Defined by [dojo/string](string)
Trims whitespace from both sides of the string
This version of trim() was taken from [Steven Levithan's blog](http://blog.stevenlevithan.com/archives/faster-trim-javascript). The short yet performant version of this function is [dojo/\_base/lang.trim()](_base/lang#trim), which is part of Dojo base. Uses String.prototype.trim instead, if available.
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | String to be trimmed |
**Returns:** String | string
Returns the trimmed string
dojo dojo/dom dojo/dom
========
Summary
-------
This module defines the core dojo DOM API.
See the [dojo/dom reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dom.html) for more information.
Methods
-------
###
`byId``(id,doc)`
Defined by [dojo/dom](dom)
Returns DOM node with matching `id` attribute or falsy value (ex: null or undefined) if not found. If `id` is a DomNode, this function is a no-op.
| Parameter | Type | Description |
| --- | --- | --- |
| id | String | DOMNode | A string to match an HTML id attribute or a reference to a DOM Node |
| doc | Document | *Optional*
Document to work in. Defaults to the current value of dojo/\_base/window.doc. Can be used to retrieve node references from other documents. |
**Returns:** instance
Examples
--------
### Example 1
Look up a node by ID:
```
require(["dojo/dom"], function(dom){
var n = dom.byId("foo");
});
```
### Example 2
Check if a node exists, and use it.
```
require(["dojo/dom"], function(dom){
var n = dom.byId("bar");
if(n){ doStuff() ... }
});
```
### Example 3
Allow string or DomNode references to be passed to a custom function:
```
require(["dojo/dom"], function(dom){
var foo = function(nodeOrId){
nodeOrId = dom.byId(nodeOrId);
// ... more stuff
}
});
```
###
`isDescendant``(node,ancestor)`
Defined by [dojo/dom](dom)
Returns true if node is a descendant of ancestor
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | string id or node reference to test |
| ancestor | DOMNode | String | string id or node reference of potential parent to test against |
**Returns:** boolean
Examples
--------
### Example 1
Test is node id="bar" is a descendant of node id="foo"
```
require(["dojo/dom"], function(dom){
if(dom.isDescendant("bar", "foo")){ ... }
});
```
###
`setSelectable``(node,selectable)`
Defined by [dojo/dom](dom)
| Parameter | Type | Description |
| --- | --- | --- |
| node | undefined | |
| selectable | undefined | |
dojo dojo/main.dnd dojo/main.dnd
=============
Properties
----------
### autoscroll
Defined by: [dojo/dnd/autoscroll](dnd/autoscroll)
Used by [dojo/dnd/Manager](dnd/manager) to scroll document or internal node when the user drags near the edge of the viewport or a scrollable node
### move
Defined by: [dojo/dnd/move](dnd/move)
Methods
-------
###
`AutoSource``()`
Defined by [dojo/dnd/AutoSource](dnd/autosource)
###
`Avatar``()`
Defined by [dojo/dnd/Avatar](dnd/avatar)
###
`Container``()`
Defined by [dojo/dnd/Container](dnd/container)
###
`Manager``()`
Defined by [dojo/dnd/Manager](dnd/manager)
###
`Moveable``()`
Defined by [dojo/dnd/Moveable](dnd/moveable)
###
`Mover``()`
Defined by [dojo/dnd/Mover](dnd/mover)
###
`Selector``()`
Defined by [dojo/dnd/Selector](dnd/selector)
###
`Source``()`
Defined by [dojo/dnd/Source](dnd/source)
###
`Target``()`
Defined by [dojo/dnd/Target](dnd/target)
###
`TimedMoveable``()`
Defined by [dojo/dnd/TimedMoveable](dnd/timedmoveable)
dojo dojo/number dojo/number
===========
Summary
-------
localized formatting and parsing routines for Number
See the [dojo/number reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/number.html) for more information.
Properties
----------
Methods
-------
###
`format``(value,options)`
Defined by [dojo/number](number)
Format a Number as a String, using locale-specific settings
Create a string from a Number using a known localized pattern. Formatting patterns appropriate to the locale are chosen from the [Common Locale Data Repository](http://unicode.org/cldr) as well as the appropriate symbols and delimiters. If value is Infinity, -Infinity, or is not a valid JavaScript number, return null.
| Parameter | Type | Description |
| --- | --- | --- |
| value | Number | the number to be formatted |
| options | Object | *Optional*
An object with the following properties:* pattern (String, optional): override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization. Literal characters in patterns are not supported.
* type (String, optional): choose a format type based on the locale from the following: decimal, scientific (not yet supported), percent, currency. decimal by default.
* places (Number, optional): fixed number of decimal places to show. This overrides any information in the provided pattern.
* round (Number, optional): 5 rounds to nearest .5; 0 rounds to nearest whole (default). -1 means do not round.
* locale (String, optional): override the locale used to determine formatting rules
* fractional (Boolean, optional): If false, show no decimal places, overriding places and pattern settings.
|
**Returns:** null | undefined
###
`parse``(expression,options)`
Defined by [dojo/number](number)
Convert a properly formatted string to a primitive Number, using locale-specific settings.
Create a Number from a string using a known localized pattern. Formatting patterns are chosen appropriate to the locale and follow the syntax described by [unicode.org TR35](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) Note that literal characters in patterns are not supported.
| Parameter | Type | Description |
| --- | --- | --- |
| expression | String | A string representation of a Number |
| options | Object | *Optional*
An object with the following properties:* pattern (String, optional): override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization. Literal characters in patterns are not supported.
* type (String, optional): choose a format type based on the locale from the following: decimal, scientific (not yet supported), percent, currency. decimal by default.
* locale (String, optional): override the locale used to determine formatting rules
* strict (Boolean, optional): strict parsing, false by default. Strict parsing requires input as produced by the format() method. Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
* fractional (Boolean|Array, optional): Whether to include the fractional portion, where the number of decimal places are implied by pattern or explicit 'places' parameter. The value [true,false] makes the fractional portion optional.
|
**Returns:** number
###
`regexp``(options)`
Defined by [dojo/number](number)
Builds the regular needed to parse a number
Returns regular expression with positive and negative match, group and decimal separators
| Parameter | Type | Description |
| --- | --- | --- |
| options | Object | *Optional*
An object with the following properties:* pattern (String, optional): override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization.
* type (String, optional): choose a format type based on the locale from the following: decimal, scientific (not yet supported), percent, currency. decimal by default.
* locale (String, optional): override the locale used to determine formatting rules
* strict (Boolean, optional): strict parsing, false by default. Strict parsing requires input as produced by the format() method. Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
* places (Number|String, optional): number of decimal places to accept: Infinity, a positive number, or a range "n,m". Defined by pattern or Infinity if pattern not provided.
|
**Returns:** undefined
###
`round``(value,places,increment)`
Defined by [dojo/number](number)
Rounds to the nearest value with the given number of decimal places, away from zero
Rounds to the nearest value with the given number of decimal places, away from zero if equal. Similar to Number.toFixed(), but compensates for browser quirks. Rounding can be done by fractional increments also, such as the nearest quarter. NOTE: Subject to floating point errors. See [dojox/math/round](http://dojotoolkit.org/api/1.10/dojox/math/round) for experimental workaround.
| Parameter | Type | Description |
| --- | --- | --- |
| value | Number | The number to round |
| places | Number | *Optional*
The number of decimal places where rounding takes place. Defaults to 0 for whole rounding. Must be non-negative. |
| increment | Number | *Optional*
Rounds next place to nearest value of increment/10. 10 by default. |
**Returns:** number
Examples
--------
### Example 1
```
>>> number.round(-0.5)
-1
>>> number.round(162.295, 2)
162.29 // note floating point error. Should be 162.3
>>> number.round(10.71, 0, 2.5)
10.75
```
dojo dojo/dom-prop dojo/dom-prop
=============
See the [dojo/dom-prop reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dom-prop.html) for more information.
Properties
----------
### names
Defined by: [dojo/dom-prop](dom-prop)
Methods
-------
###
`get``(node,name)`
Defined by [dojo/dom-prop](dom-prop)
Gets a property on an HTML element.
Handles normalized getting of properties on DOM nodes.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to get the property on |
| name | String | the name of the property to get. |
**Returns:** any | undefined
the value of the requested property or its default value
Examples
--------
### Example 1
```
// get the current value of the "foo" property on a node
require(["dojo/dom-prop", "dojo/dom"], function(domProp, dom){
domProp.get(dom.byId("nodeId"), "foo");
// or we can just pass the id:
domProp.get("nodeId", "foo");
});
```
###
`set``(node,name,value)`
Defined by [dojo/dom-prop](dom-prop)
Sets a property on an HTML element.
Handles normalized setting of properties on DOM nodes.
When passing functions as values, note that they will not be directly assigned to slots on the node, but rather the default behavior will be removed and the new behavior will be added using `dojo.connect()`, meaning that event handler properties will be normalized and that some caveats with regards to non-standard behaviors for onsubmit apply. Namely that you should cancel form submission using `dojo.stopEvent()` on the passed event object instead of returning a boolean value from the handler itself.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to set the property on |
| name | String | Object | the name of the property to set, or a hash object to set multiple properties at once. |
| value | String | *Optional*
The value to set for the property |
**Returns:** any | undefined
the DOM node
Examples
--------
### Example 1
```
// use prop() to set the tab index
require(["dojo/dom-prop"], function(domProp){
domProp.set("nodeId", "tabIndex", 3);
});
```
### Example 2
Set multiple values at once, including event handlers:
```
require(["dojo/dom-prop"], function(domProp){
domProp.set("formId", {
"foo": "bar",
"tabIndex": -1,
"method": "POST",
});
});
```
dojo dojo/NodeList dojo/NodeList
=============
Summary
-------
Array-like object which adds syntactic sugar for chaining, common iteration operations, animation, and node manipulation. NodeLists are most often returned as the result of [dojo/query()](query) calls.
NodeList instances provide many utilities that reflect core Dojo APIs for Array iteration and manipulation, DOM manipulation, and event handling. Instead of needing to dig up functions in the dojo package, NodeLists generally make the full power of Dojo available for DOM manipulation tasks in a simple, chainable way.
Usage
-----
NodeList`(array);`
| Parameter | Type | Description |
| --- | --- | --- |
| array | undefined | |
**Returns:** Array
See the [dojo/NodeList reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/NodeList.html) for more information.
Examples
--------
### Example 1
create a node list from a node
```
require(["dojo/query", "dojo/dom"
], function(query, dom){
query.NodeList(dom.byId("foo"));
});
```
### Example 2
get a NodeList from a CSS query and iterate on it
```
require(["dojo/on", "dojo/dom"
], function(on, dom){
var l = query(".thinger");
l.forEach(function(node, index, nodeList){
console.log(index, node.innerHTML);
});
});
```
### Example 3
use native and Dojo-provided array methods to manipulate a NodeList without needing to use dojo.\* functions explicitly:
```
require(["dojo/query", "dojo/dom-construct", "dojo/dom"
], function(query, domConstruct, dom){
var l = query(".thinger");
// since NodeLists are real arrays, they have a length
// property that is both readable and writable and
// push/pop/shift/unshift methods
console.log(l.length);
l.push(domConstruct.create("span"));
// dojo's normalized array methods work too:
console.log( l.indexOf(dom.byId("foo")) );
// ...including the special "function as string" shorthand
console.log( l.every("item.nodeType == 1") );
// NodeLists can be [..] indexed, or you can use the at()
// function to get specific items wrapped in a new NodeList:
var node = l[3]; // the 4th element
var newList = l.at(1, 3); // the 2nd and 4th elements
});
```
### Example 4
chainability is a key advantage of NodeLists:
```
require(["dojo/query", "dojo/NodeList-dom"
], function(query){
query(".thinger")
.onclick(function(e){ /* ... */ })
.at(1, 3, 8) // get a subset
.style("padding", "5px")
.forEach(console.log);
});
```
Properties
----------
### events
Defined by: [dojo/\_base/NodeList](_base/nodelist)
Methods
-------
###
`addClass``(className)`
Defined by [dojo/NodeList-dom](nodelist-dom)
adds the specified class to every node in the list
| Parameter | Type | Description |
| --- | --- | --- |
| className | String | Array | A String class name to add, or several space-separated class names, or an array of class names. |
###
`addClassFx``(cssClass,args)`
Defined by [dojox/fx/ext-dojo/NodeList-style](http://dojotoolkit.org/api/1.10/dojox/fx/ext-dojo/NodeList-style)
Animate the effects of adding a class to all nodes in this list. see `dojox.fx.addClass`
| Parameter | Type | Description |
| --- | --- | --- |
| cssClass | undefined | |
| args | undefined | |
**Returns:** [object Value(type: function, value: undefined)]
Examples
--------
### Example 1
```
// fade all elements with class "bar" to to 50% opacity
dojo.query(".bar").addClassFx("bar").play();
```
###
`addContent``(content,position)`
Defined by [dojo/NodeList-dom](nodelist-dom)
add a node, NodeList or some HTML as a string to every item in the list. Returns the original list.
a copy of the HTML content is added to each item in the list, with an optional position argument. If no position argument is provided, the content is appended to the end of each item.
| Parameter | Type | Description |
| --- | --- | --- |
| content | String | DomNode | Object | [dojo/NodeList](nodelist) | the content to be set on the parent element. This can be an html string, a node reference or a NodeList, dojo/NodeList, Array or other enumerable list of nodes |
| position | String | Integer | *Optional*
can be one of: * "last"||"end" (default)
* "first||"start"
* "before"
* "after"
* "replace" (replaces nodes in this NodeList with new content)
* "only" (removes other children of the nodes so new content is the only child)
or an offset in the childNodes property |
**Returns:** function
add a node, NodeList or some HTML as a string to every item in the list. Returns the original list.
Examples
--------
### Example 1
appends content to the end if the position is omitted
```
require(["dojo/query", "dojo/NodeList-dom"
], function(query){
query("h3 > p").addContent("hey there!");
});
```
### Example 2
add something to the front of each element that has a "thinger" property:
```
require(["dojo/query", "dojo/NodeList-dom"
], function(query){
query("[thinger]").addContent("...", "first");
});
```
### Example 3
adds a header before each element of the list
```
require(["dojo/query", "dojo/NodeList-dom"
], function(query){
query(".note").addContent("<h4>NOTE:</h4>", "before");
});
```
### Example 4
add a clone of a DOM node to the end of every element in the list, removing it from its existing parent.
```
require(["dojo/dom", "dojo/query", "dojo/NodeList-dom"
], function(dom, query){
query(".note").addContent(dom.byId("foo"));
});
```
### Example 5
Append nodes from a templatized string.
```
require(["dojo/string", "dojo/query", "dojo/NodeList-dom"
], function(string, query){
query(".note").addContent({
template: '<b>${id}: </b><span>${name}</span>',
id: "user332",
name: "Mr. Anderson"
});
});
```
### Example 6
Append nodes from a templatized string that also has widgets parsed.
```
require(["dojo/string", "dojo/parser", "dojo/query", "dojo/NodeList-dom"
], function(string, parser, query){
var notes = query(".note").addContent({
template: '<button dojoType="dijit/form/Button">${text}</button>',
parse: true,
text: "Send"
});
});
```
###
`adopt``(queryOrListOrNode,position)`
Defined by [dojo/NodeList-dom](nodelist-dom)
places any/all elements in queryOrListOrNode at a position relative to the first element in this list. Returns a dojo/NodeList of the adopted elements.
| Parameter | Type | Description |
| --- | --- | --- |
| queryOrListOrNode | String | Array | DomNode | a DOM node or a query string or a query result. Represents the nodes to be adopted relative to the first element of this NodeList. |
| position | String | *Optional*
can be one of: * "last" (default)
* "first"
* "before"
* "after"
* "only"
* "replace"
or an offset in the childNodes property |
**Returns:** undefined
###
`after``(content)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
Places the content after every node in the NodeList.
The content will be cloned if the length of NodeList is greater than 1. Only the DOM nodes are cloned, not any attached event handlers.
| Parameter | Type | Description |
| --- | --- | --- |
| content | String | Element | NodeList | |
**Returns:** any | undefined
dojo/NodeList, the nodes currently in this NodeList will be returned, not the appended content.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div id="foo"><p>Hello Mars</p></div>
<div id="bar"><p>Hello World</p></div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query("div").after("<span>after</span>");
});
```
Results in this DOM structure:
```
<div id="foo"><p>Hello Mars</p></div><span>after</span>
<div id="bar"><p>Hello World</p></div><span>after</span>
```
###
`andSelf``()`
Defined by [dojo/NodeList-traverse](nodelist-traverse)
Adds the nodes from the previous dojo/NodeList to the current dojo/NodeList.
.end() can be used on the returned [dojo/NodeList](nodelist) to get back to the original [dojo/NodeList](nodelist).
**Returns:** undefined
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="red prev">Red One</div>
Some Text
<div class="blue prev">Blue One</div>
<div class="red second">Red Two</div>
<div class="blue">Blue Two</div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-traverse"
], function(query){
query(".second").prevAll().andSelf();
});
```
returns the two divs with class of "prev", as well as the div with class "second".
###
`anim``(properties,duration,easing,onEnd,delay)`
Defined by [dojo/NodeList-fx](nodelist-fx)
Animate one or more CSS properties for all nodes in this list. The returned animation object will already be playing when it is returned. See the docs for `dojo.anim` for full details.
| Parameter | Type | Description |
| --- | --- | --- |
| properties | Object | the properties to animate. does NOT support the `auto` parameter like other NodeList-fx methods. |
| duration | Integer | *Optional*
Optional. The time to run the animations for |
| easing | Function | *Optional*
Optional. The easing function to use. |
| onEnd | Function | *Optional*
A function to be called when the animation ends |
| delay | Integer | *Optional*
how long to delay playing the returned animation |
**Returns:** undefined
Examples
--------
### Example 1
Another way to fade out:
```
require(["dojo/query", "dojo/NodeList-fx"
], function(query){
query(".thinger").anim({ opacity: 0 });
});
```
### Example 2
animate all elements with the "thigner" class to a width of 500 pixels over half a second
```
require(["dojo/query", "dojo/NodeList-fx"
], function(query){
query(".thinger").anim({ width: 500 }, 700);
});
```
###
`animateProperty``(args)`
Defined by [dojo/NodeList-fx](nodelist-fx)
Animate all elements of this NodeList across the properties specified. syntax identical to `dojo.animateProperty`
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | *Optional*
Additional dojo/\_base/fx.Animation arguments to mix into this set with the addition of an `auto` parameter. |
**Returns:** [dojo/\_base/fx.Animation](_base/fx#Animation)|[dojo/NodeList](nodelist) | undefined
A special args member `auto` can be passed to automatically play the animation. If args.auto is present, the original dojo/NodeList will be returned for further chaining. Otherwise the dojo/\_base/fx.Animation instance is returned and must be .play()'ed
Examples
--------
### Example 1
```
require(["dojo/query", "dojo/NodeList-fx"
], function(query){
query(".zork").animateProperty({
duration: 500,
properties: {
color: { start: "black", end: "white" },
left: { end: 300 }
}
}).play();
});
```
### Example 2
```
require(["dojo/query", "dojo/NodeList-fx"
], function(query){
query(".grue").animateProperty({
auto:true,
properties: {
height:240
}
}).onclick(handler);
});
```
###
`append``(content)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
appends the content to every node in the NodeList.
The content will be cloned if the length of NodeList is greater than 1. Only the DOM nodes are cloned, not any attached event handlers.
| Parameter | Type | Description |
| --- | --- | --- |
| content | String | DOMNode | NodeList | |
**Returns:** any | undefined
dojo/NodeList, the nodes currently in this NodeList will be returned, not the appended content.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div id="foo"><p>Hello Mars</p></div>
<div id="bar"><p>Hello World</p></div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query("div").append("<span>append</span>");
});
```
Results in this DOM structure:
```
<div id="foo"><p>Hello Mars</p><span>append</span></div>
<div id="bar"><p>Hello World</p><span>append</span></div>
```
###
`appendTo``(query)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
appends nodes in this NodeList to the nodes matched by the query passed to appendTo.
The nodes in this NodeList will be cloned if the query matches more than one element. Only the DOM nodes are cloned, not any attached event handlers.
| Parameter | Type | Description |
| --- | --- | --- |
| query | String | |
**Returns:** any | undefined
dojo/NodeList, the nodes currently in this NodeList will be returned, not the matched nodes from the query.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<span>append</span>
<p>Hello Mars</p>
<p>Hello World</p>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query("span").appendTo("p");
});
```
Results in this DOM structure:
```
<p>Hello Mars<span>append</span></p>
<p>Hello World<span>append</span></p>
```
###
`at``(index)`
Defined by [dojo/query](query)
Returns a new NodeList comprised of items in this NodeList at the given index or indices.
| Parameter | Type | Description |
| --- | --- | --- |
| index | Integer... | One or more 0-based indices of items in the current NodeList. A negative index will start at the end of the list and go backwards. |
**Returns:** undefined
Examples
--------
### Example 1
Shorten the list to the first, second, and third elements
```
require(["dojo/query"
], function(query){
query("a").at(0, 1, 2).forEach(fn);
});
```
### Example 2
Retrieve the first and last elements of a unordered list:
```
require(["dojo/query"
], function(query){
query("ul > li").at(0, -1).forEach(cb);
});
```
### Example 3
Do something for the first element only, but end() out back to the original list and continue chaining:
```
require(["dojo/query"
], function(query){
query("a").at(0).onclick(fn).end().forEach(function(n){
console.log(n); // all anchors on the page.
})
});
```
###
`attr``(property,value)`
Defined by [dojo/NodeList-dom](nodelist-dom)
gets or sets the DOM attribute for every element in the NodeList. See also `dojo/dom-attr`
| Parameter | Type | Description |
| --- | --- | --- |
| property | String | the attribute to get/set |
| value | String | *Optional*
optional. The value to set the property to |
**Returns:** any
if no value is passed, the result is an array of attribute values If a value is passed, the return is this NodeList
Examples
--------
### Example 1
Make all nodes with a particular class focusable:
```
require(["dojo/query", "dojo/NodeList-dom"], function(query){
query(".focusable").attr("tabIndex", -1);
});
```
### Example 2
Disable a group of buttons:
```
require(["dojo/query", "dojo/NodeList-dom"], function(query){
query("button.group").attr("disabled", true);
});
```
### Example 3
innerHTML can be assigned or retrieved as well:
```
// get the innerHTML (as an array) for each list item
require(["dojo/query", "dojo/NodeList-dom"], function(query){
var ih = query("li.replaceable").attr("innerHTML");
});
```
###
`before``(content)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
Places the content before every node in the NodeList.
The content will be cloned if the length of NodeList is greater than 1. Only the DOM nodes are cloned, not any attached event handlers.
| Parameter | Type | Description |
| --- | --- | --- |
| content | String | DOMNode | NodeList | |
**Returns:** any | undefined
dojo/NodeList, the nodes currently in this NodeList will be returned, not the appended content.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div id="foo"><p>Hello Mars</p></div>
<div id="bar"><p>Hello World</p></div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query("div").before("<span>before</span>");
});
```
Results in this DOM structure:
```
<span>before</span><div id="foo"><p>Hello Mars</p></div>
<span>before</span><div id="bar"><p>Hello World</p></div>
```
###
`children``(query)`
Defined by [dojo/NodeList-traverse](nodelist-traverse)
Returns all immediate child elements for nodes in this dojo/NodeList. Optionally takes a query to filter the child elements.
.end() can be used on the returned [dojo/NodeList](nodelist) to get back to the original [dojo/NodeList](nodelist).
| Parameter | Type | Description |
| --- | --- | --- |
| query | String | *Optional*
a CSS selector. |
**Returns:** any | undefined
all immediate child elements for the nodes in this dojo/NodeList.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="red">Red One</div>
Some Text
<div class="blue">Blue One</div>
<div class="red">Red Two</div>
<div class="blue">Blue Two</div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-traverse"
], function(query){
query(".container").children();
});
```
returns the four divs that are children of the container div.
Running this code:
```
dojo.query(".container").children(".red");
```
returns the two divs that have the class "red".
###
`clone``()`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
Clones all the nodes in this NodeList and returns them as a new NodeList.
Only the DOM nodes are cloned, not any attached event handlers.
**Returns:** any | undefined
a cloned set of the original nodes.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="red">Red One</div>
<div class="blue">Blue One</div>
<div class="red">Red Two</div>
<div class="blue">Blue Two</div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query(".red").clone().appendTo(".container");
});
```
Results in this DOM structure:
```
<div class="container">
<div class="red">Red One</div>
<div class="blue">Blue One</div>
<div class="red">Red Two</div>
<div class="blue">Blue Two</div>
<div class="red">Red One</div>
<div class="red">Red Two</div>
</div>
```
###
`closest``(query,root)`
Defined by [dojo/NodeList-traverse](nodelist-traverse)
Returns closest parent that matches query, including current node in this dojo/NodeList if it matches the query.
.end() can be used on the returned [dojo/NodeList](nodelist) to get back to the original [dojo/NodeList](nodelist).
| Parameter | Type | Description |
| --- | --- | --- |
| query | String | a CSS selector. |
| root | String | DOMNode | *Optional*
If specified, query is relative to "root" rather than document body. |
**Returns:** any | undefined
the closest parent that matches the query, including the current node in this dojo/NodeList if it matches the query.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="red">Red One</div>
Some Text
<div class="blue">Blue One</div>
<div class="red">Red Two</div>
<div class="blue">Blue Two</div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-traverse"
], function(query){
query(".red").closest(".container");
});
```
returns the div with class "container".
###
`concat``(item)`
Defined by [dojo/query](query)
Returns a new NodeList comprised of items in this NodeList as well as items passed in as parameters
This method behaves exactly like the Array.concat method with the caveat that it returns a `NodeList` and not a raw Array. For more details, see the [Array.concat docs](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/concat)
| Parameter | Type | Description |
| --- | --- | --- |
| item | Object | *Optional*
Any number of optional parameters may be passed in to be spliced into the NodeList |
**Returns:** undefined
###
`connect``(methodName,objOrFunc,funcName)`
Defined by [dojo/\_base/NodeList](_base/nodelist)
Attach event handlers to every item of the NodeList. Uses dojo.connect() so event properties are normalized.
Application must manually require() "dojo/\_base/connect" before using this method.
| Parameter | Type | Description |
| --- | --- | --- |
| methodName | String | the name of the method to attach to. For DOM events, this should be the lower-case name of the event |
| objOrFunc | Object | Function | String | if 2 arguments are passed (methodName, objOrFunc), objOrFunc should reference a function or be the name of the function in the global namespace to attach. If 3 arguments are provided (methodName, objOrFunc, funcName), objOrFunc must be the scope to locate the bound function in |
| funcName | String | *Optional*
optional. A string naming the function in objOrFunc to bind to the event. May also be a function reference. |
Examples
--------
### Example 1
add an onclick handler to every button on the page
```
query("div:nth-child(odd)").connect("onclick", function(e){
console.log("clicked!");
});
```
### Example 2
attach foo.bar() to every odd div's onmouseover
```
query("div:nth-child(odd)").connect("onmouseover", foo, "bar");
```
###
`coords``()`
Defined by [dojo/\_base/NodeList](_base/nodelist)
Deprecated: Use position() for border-box x/y/w/h or marginBox() for margin-box w/h/l/t. Returns the box objects of all elements in a node list as an Array (*not* a NodeList). Acts like `domGeom.coords`, though assumes the node passed is each node in this list.
###
`data``(key,value)`
Defined by [dojo/NodeList-data](nodelist-data)
stash or get some arbitrary data on/from these nodes.
Stash or get some arbitrary data on/from these nodes. This private \_data function is exposed publicly on [dojo/NodeList](nodelist), eg: as the result of a [dojo/query](query) call. DIFFERS from jQuery.data in that when used as a getter, the entire list is ALWAYS returned. EVEN WHEN THE LIST IS length == 1.
A single-node version of this function is provided as `dojo._nodeData`, which follows the same signature, though expects a String ID or DomNode reference in the first position, before key/value arguments.
| Parameter | Type | Description |
| --- | --- | --- |
| key | Object | String | *Optional*
If an object, act as a setter and iterate over said object setting data items as defined. If a string, and `value` present, set the data for defined `key` to `value` If a string, and `value` absent, act as a getter, returning the data associated with said `key` |
| value | Anything | *Optional*
The value to set for said `key`, provided `key` is a string (and not an object) |
**Returns:** Object|Anything|Nothing
When used as a setter via `dojo/NodeList`, a NodeList instance is returned for further chaining. When used as a getter via `dojo/NodeList` an ARRAY of items is returned. The items in the array correspond to the elements in the original list. This is true even when the list length is 1, eg: when looking up a node by ID (#foo)
Examples
--------
### Example 1
Set a key `bar` to some data, then retrieve it.
```
require(["dojo/query", "dojo/NodeList-data"], function(query){
query(".foo").data("bar", "touched");
var touched = query(".foo").data("bar");
if(touched[0] == "touched"){ alert('win'); }
});
```
### Example 2
Get all the data items for a given node.
```
require(["dojo/query", "dojo/NodeList-data"], function(query){
var list = query(".foo").data();
var first = list[0];
});
```
### Example 3
Set the data to a complex hash. Overwrites existing keys with new value
```
require(["dojo/query", "dojo/NodeList-data"], function(query){
query(".foo").data({ bar:"baz", foo:"bar" });
```
Then get some random key:
```
query(".foo").data("foo"); // returns [`bar`]
});
```
###
`delegate``(selector,eventName,fn)`
Defined by [dojox/NodeList/delegate](http://dojotoolkit.org/api/1.10/dojox/NodeList/delegate)
Monitor nodes in this NodeList for [bubbled] events on nodes that match selector. Calls fn(evt) for those events, where (inside of fn()), this == the node that matches the selector.
Sets up event handlers that can catch events on any subnodes matching a given selector, including nodes created after delegate() has been called.
This allows an app to setup a single event handler on a high level node, rather than many event handlers on subnodes. For example, one onclick handler for a Tree widget, rather than separate handlers for each node in the tree. Since setting up many event handlers is expensive, this can increase performance.
Note that delegate() will not work for events that don't bubble, like focus. onmouseenter/onmouseleave also don't currently work.
| Parameter | Type | Description |
| --- | --- | --- |
| selector | String | CSS selector valid to `dojo.query`, like ".foo" or "div > span". The selector is relative to the nodes in this NodeList, not the document root. For example myNodeList.delegate("> a", "onclick", ...) will catch events on anchor nodes which are (immediate) children of the nodes in myNodeList. |
| eventName | String | Standard event name used as an argument to `dojo.connect`, like "onclick". |
| fn | Function | Callback function passed the event object, and where this == the node that matches the selector. That means that for example, after setting up a handler via
```
dojo.query("body").delegate("fieldset", "onclick", ...)
```
clicking on a fieldset or *any nodes inside of a fieldset* will be reported as a click on the fieldset itself. |
**Returns:** undefined
Examples
--------
### Example 1
```
dojo.query("navbar").delegate("a", "onclick", function(evt){
console.log("user clicked anchor ", this.node);
});
```
###
`dtl``(template,context)`
Defined by [dojox/dtl/ext-dojo/NodeList](http://dojotoolkit.org/api/1.10/dojox/dtl/ext-dojo/NodeList)
Renders the specified template in each of the NodeList entries.
| Parameter | Type | Description |
| --- | --- | --- |
| template | dojox/dtl/\_\_StringArgs | String | The template string or location |
| context | dojox/dtl/\_\_ObjectArgs | Object | The context object or location |
**Returns:** function
Renders the specified template in each of the NodeList entries.
###
`empty``()`
Defined by [dojo/NodeList-dom](nodelist-dom)
clears all content from each node in the list. Effectively equivalent to removing all child nodes from every item in the list.
**Returns:** undefined
###
`end``()`
Defined by [dojo/query](query)
Ends use of the current `NodeList` by returning the previous NodeList that generated the current NodeList.
Returns the `NodeList` that generated the current `NodeList`. If there is no parent NodeList, an empty NodeList is returned.
**Returns:** undefined | instance
Examples
--------
### Example 1
```
require(["dojo/query", "dojo/NodeList-dom"
], function(query){
query("a")
.filter(".disabled")
// operate on the anchors that only have a disabled class
.style("color", "grey")
.end()
// jump back to the list of anchors
.style(...)
});
```
###
`even``()`
Defined by [dojo/NodeList-traverse](nodelist-traverse)
Returns the even nodes in this dojo/NodeList as a dojo/NodeList.
.end() can be used on the returned [dojo/NodeList](nodelist) to get back to the original [dojo/NodeList](nodelist).
**Returns:** any | undefined
the even nodes in this dojo/NodeList
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="interior red">Red One</div>
<div class="interior blue">Blue One</div>
<div class="interior red">Red Two</div>
<div class="interior blue">Blue Two</div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-traverse"
], function(query){
query(".interior").even();
});
```
returns the two divs with class "blue"
###
`every``(callback,thisObject)`
Defined by [dojo/query](query)
see `dojo/_base/array.every()` and the [Array.every docs](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every). Takes the same structure of arguments and returns as dojo/\_base/array.every() with the caveat that the passed array is implicitly this NodeList
| Parameter | Type | Description |
| --- | --- | --- |
| callback | Function | the callback |
| thisObject | Object | *Optional*
the context |
**Returns:** undefined
###
`fadeIn``(args)`
Defined by [dojo/NodeList-fx](nodelist-fx)
fade in all elements of this NodeList via `dojo.fadeIn`
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | *Optional*
Additional dojo/\_base/fx.Animation arguments to mix into this set with the addition of an `auto` parameter. |
**Returns:** [dojo/\_base/fx.Animation](_base/fx#Animation)|[dojo/NodeList](nodelist) | undefined
A special args member `auto` can be passed to automatically play the animation. If args.auto is present, the original dojo/NodeList will be returned for further chaining. Otherwise the dojo/\_base/fx.Animation instance is returned and must be .play()'ed
Examples
--------
### Example 1
Fade in all tables with class "blah":
```
require(["dojo/query", "dojo/NodeList-fx"
], function(query){
query("table.blah").fadeIn().play();
});
```
###
`fadeOut``(args)`
Defined by [dojo/NodeList-fx](nodelist-fx)
fade out all elements of this NodeList via `dojo.fadeOut`
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | *Optional*
Additional dojo/\_base/fx.Animation arguments to mix into this set with the addition of an `auto` parameter. |
**Returns:** [dojo/\_base/fx.Animation](_base/fx#Animation)|[dojo/NodeList](nodelist) | undefined
A special args member `auto` can be passed to automatically play the animation. If args.auto is present, the original dojo/NodeList will be returned for further chaining. Otherwise the dojo/\_base/fx.Animation instance is returned and must be .play()'ed
Examples
--------
### Example 1
Fade out all elements with class "zork":
```
require(["dojo/query", "dojo/NodeList-fx"
], function(query){
query(".zork").fadeOut().play();
});
```
### Example 2
Fade them on a delay and do something at the end:
```
require(["dojo/query", "dojo/aspect", "dojo/NodeList-fx"
], function(query, aspect){
var fo = query(".zork").fadeOut();
aspect.after(fo, "onEnd", function(){ /*...*/ }, true);
fo.play();
});
```
### Example 3
Using `auto`:
```
require(["dojo/query", "dojo/NodeList-fx"
], function(query){
query("li").fadeOut({ auto:true }).filter(filterFn).forEach(doit);
});
```
###
`filter``(filter)`
Defined by [dojo/NodeList-dom](nodelist-dom)
"masks" the built-in javascript filter() method (supported in Dojo via `dojo.filter`) to support passing a simple string filter in addition to supporting filtering function objects.
| Parameter | Type | Description |
| --- | --- | --- |
| filter | String | Function | If a string, a CSS rule like ".thinger" or "div > span". |
**Returns:** undefined
Examples
--------
### Example 1
"regular" JS filter syntax as exposed in dojo.filter:
```
require(["dojo/query", "dojo/NodeList-dom"
], function(query){
query("*").filter(function(item){
// highlight every paragraph
return (item.nodeName == "p");
}).style("backgroundColor", "yellow");
});
```
### Example 2
the same filtering using a CSS selector
```
require(["dojo/query", "dojo/NodeList-dom"
], function(query){
query("*").filter("p").styles("backgroundColor", "yellow");
});
```
###
`first``()`
Defined by [dojo/NodeList-traverse](nodelist-traverse)
Returns the first node in this dojo/NodeList as a dojo/NodeList.
.end() can be used on the returned [dojo/NodeList](nodelist) to get back to the original [dojo/NodeList](nodelist).
**Returns:** any | undefined
the first node in this dojo/NodeList
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="red">Red One</div>
<div class="blue first">Blue One</div>
<div class="red">Red Two</div>
<div class="blue last">Blue Two</div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-traverse"
], function(query){
query(".blue").first();
});
```
returns the div with class "blue" and "first".
###
`forEach``(callback,thisObj)`
Defined by [dojo/query](query)
see `dojo/_base/array.forEach()`. The primary difference is that the acted-on array is implicitly this NodeList. If you want the option to break out of the forEach loop, use every() or some() instead.
| Parameter | Type | Description |
| --- | --- | --- |
| callback | undefined | |
| thisObj | undefined | |
**Returns:** function
see `dojo/_base/array.forEach()`. The primary difference is that the acted-on array is implicitly this NodeList. If you want the option to break out of the forEach loop, use every() or some() instead.
###
`html``(value)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
allows setting the innerHTML of each node in the NodeList, if there is a value passed in, otherwise, reads the innerHTML value of the first node.
This method is simpler than the [dojo/NodeList.html()](nodelist#html) method provided by [dojo/NodeList-html](nodelist-html). This method just does proper innerHTML insertion of HTML fragments, and it allows for the innerHTML to be read for the first node in the node list. Since [dojo/NodeList-html](nodelist-html) already took the "html" name, this method is called "innerHTML". However, if [dojo/NodeList-html](nodelist-html) has not been loaded yet, this module will define an "html" method that can be used instead. Be careful if you are working in an environment where it is possible that [dojo/NodeList-html](nodelist-html) could have been loaded, since its definition of "html" will take precedence. The nodes represented by the value argument will be cloned if more than one node is in this NodeList. The nodes in this NodeList are returned in the "set" usage of this method, not the HTML that was inserted.
| Parameter | Type | Description |
| --- | --- | --- |
| value | String | DOMNode | NodeList | *Optional* |
**Returns:** any | undefined
if no value is passed, the result is String, the innerHTML of the first node. If a value is passed, the return is this dojo/NodeList
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div id="foo"></div>
<div id="bar"></div>
```
This code inserts `<p>Hello World</p>` into both divs:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query("div").innerHTML("<p>Hello World</p>");
});
```
### Example 2
assume a DOM created by this markup:
```
<div id="foo"><p>Hello Mars</p></div>
<div id="bar"><p>Hello World</p></div>
```
This code returns `<p>Hello Mars</p>`:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
var message = query("div").innerHTML();
});
```
###
`indexOf``(value,fromIndex)`
Defined by [dojo/query](query)
see `dojo/_base/array.indexOf()`. The primary difference is that the acted-on array is implicitly this NodeList
For more details on the behavior of indexOf, see Mozilla's [indexOf docs](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf)
| Parameter | Type | Description |
| --- | --- | --- |
| value | Object | The value to search for. |
| fromIndex | Integer | *Optional*
The location to start searching from. Optional. Defaults to 0. |
**Returns:** any | undefined
Positive Integer or 0 for a match, -1 of not found.
###
`innerHTML``(value)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
allows setting the innerHTML of each node in the NodeList, if there is a value passed in, otherwise, reads the innerHTML value of the first node.
This method is simpler than the [dojo/NodeList.html()](nodelist#html) method provided by [dojo/NodeList-html](nodelist-html). This method just does proper innerHTML insertion of HTML fragments, and it allows for the innerHTML to be read for the first node in the node list. Since [dojo/NodeList-html](nodelist-html) already took the "html" name, this method is called "innerHTML". However, if [dojo/NodeList-html](nodelist-html) has not been loaded yet, this module will define an "html" method that can be used instead. Be careful if you are working in an environment where it is possible that [dojo/NodeList-html](nodelist-html) could have been loaded, since its definition of "html" will take precedence. The nodes represented by the value argument will be cloned if more than one node is in this NodeList. The nodes in this NodeList are returned in the "set" usage of this method, not the HTML that was inserted.
| Parameter | Type | Description |
| --- | --- | --- |
| value | String | DOMNode | NodeList | *Optional* |
**Returns:** any | undefined
if no value is passed, the result is String, the innerHTML of the first node. If a value is passed, the return is this dojo/NodeList
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div id="foo"></div>
<div id="bar"></div>
```
This code inserts `<p>Hello World</p>` into both divs:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query("div").innerHTML("<p>Hello World</p>");
});
```
### Example 2
assume a DOM created by this markup:
```
<div id="foo"><p>Hello Mars</p></div>
<div id="bar"><p>Hello World</p></div>
```
This code returns `<p>Hello Mars</p>`:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
var message = query("div").innerHTML();
});
```
###
`insertAfter``(query)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
The nodes in this NodeList will be placed after the nodes matched by the query passed to insertAfter.
The nodes in this NodeList will be cloned if the query matches more than one element. Only the DOM nodes are cloned, not any attached event handlers.
| Parameter | Type | Description |
| --- | --- | --- |
| query | String | |
**Returns:** any | undefined
dojo/NodeList, the nodes currently in this NodeList will be returned, not the matched nodes from the query.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<span>after</span>
<p>Hello Mars</p>
<p>Hello World</p>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query("span").insertAfter("p");
});
```
Results in this DOM structure:
```
<p>Hello Mars</p><span>after</span>
<p>Hello World</p><span>after</span>
```
###
`insertBefore``(query)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
The nodes in this NodeList will be placed after the nodes matched by the query passed to insertAfter.
The nodes in this NodeList will be cloned if the query matches more than one element. Only the DOM nodes are cloned, not any attached event handlers.
| Parameter | Type | Description |
| --- | --- | --- |
| query | String | |
**Returns:** any | undefined
dojo/NodeList, the nodes currently in this NodeList will be returned, not the matched nodes from the query.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<span>before</span>
<p>Hello Mars</p>
<p>Hello World</p>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query("span").insertBefore("p");
});
```
Results in this DOM structure:
```
<span>before</span><p>Hello Mars</p>
<span>before</span><p>Hello World</p>
```
###
`instantiate``(declaredClass,properties)`
Defined by [dojo/query](query)
Create a new instance of a specified class, using the specified properties and each node in the NodeList as a srcNodeRef.
| Parameter | Type | Description |
| --- | --- | --- |
| declaredClass | String | Object | |
| properties | Object | *Optional* |
**Returns:** undefined
Examples
--------
### Example 1
Grabs all buttons in the page and converts them to dijit/form/Button's.
```
var buttons = query("button").instantiate(Button, {showLabel: true});
```
###
`last``()`
Defined by [dojo/NodeList-traverse](nodelist-traverse)
Returns the last node in this dojo/NodeList as a dojo/NodeList.
.end() can be used on the returned [dojo/NodeList](nodelist) to get back to the original [dojo/NodeList](nodelist).
**Returns:** any | undefined
the last node in this dojo/NodeList
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="red">Red One</div>
<div class="blue first">Blue One</div>
<div class="red">Red Two</div>
<div class="blue last">Blue Two</div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-traverse"
], function(query){
query(".blue").last();
});
```
returns the last div with class "blue",
###
`lastIndexOf``(value,fromIndex)`
Defined by [dojo/query](query)
see `dojo/_base/array.lastIndexOf()`. The primary difference is that the acted-on array is implicitly this NodeList
For more details on the behavior of lastIndexOf, see Mozilla's [lastIndexOf docs](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf)
| Parameter | Type | Description |
| --- | --- | --- |
| value | Object | The value to search for. |
| fromIndex | Integer | *Optional*
The location to start searching from. Optional. Defaults to 0. |
**Returns:** any | undefined
Positive Integer or 0 for a match, -1 of not found.
###
`map``(func,obj)`
Defined by [dojo/query](query)
see `dojo/_base/array.map()`. The primary difference is that the acted-on array is implicitly this NodeList and the return is a NodeList (a subclass of Array)
| Parameter | Type | Description |
| --- | --- | --- |
| func | Function | |
| obj | Function | *Optional* |
**Returns:** undefined
###
`marginBox``()`
Defined by [dojo/NodeList-dom](nodelist-dom)
Returns margin-box size of nodes
###
`next``(query)`
Defined by [dojo/NodeList-traverse](nodelist-traverse)
Returns the next element for nodes in this dojo/NodeList. Optionally takes a query to filter the next elements.
.end() can be used on the returned [dojo/NodeList](nodelist) to get back to the original [dojo/NodeList](nodelist).
| Parameter | Type | Description |
| --- | --- | --- |
| query | String | *Optional*
a CSS selector. |
**Returns:** any | undefined
the next element for nodes in this dojo/NodeList.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="red">Red One</div>
Some Text
<div class="blue first">Blue One</div>
<div class="red">Red Two</div>
<div class="blue last">Blue Two</div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-traverse"
], function(query){
query(".first").next();
});
```
returns the div with class "red" and has innerHTML of "Red Two".
Running this code:
```
dojo.query(".last").next(".red");
```
does not return any elements.
###
`nextAll``(query)`
Defined by [dojo/NodeList-traverse](nodelist-traverse)
Returns all sibling elements that come after the nodes in this dojo/NodeList. Optionally takes a query to filter the sibling elements.
.end() can be used on the returned [dojo/NodeList](nodelist) to get back to the original [dojo/NodeList](nodelist).
| Parameter | Type | Description |
| --- | --- | --- |
| query | String | *Optional*
a CSS selector. |
**Returns:** any | undefined
all sibling elements that come after the nodes in this dojo/NodeList.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="red">Red One</div>
Some Text
<div class="blue first">Blue One</div>
<div class="red next">Red Two</div>
<div class="blue next">Blue Two</div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-traverse"
], function(query){
query(".first").nextAll();
});
```
returns the two divs with class of "next".
Running this code:
```
query(".first").nextAll(".red");
```
returns the one div with class "red" and innerHTML "Red Two".
###
`odd``()`
Defined by [dojo/NodeList-traverse](nodelist-traverse)
Returns the odd nodes in this dojo/NodeList as a dojo/NodeList.
.end() can be used on the returned [dojo/NodeList](nodelist) to get back to the original [dojo/NodeList](nodelist).
**Returns:** any | undefined
the odd nodes in this dojo/NodeList
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="interior red">Red One</div>
<div class="interior blue">Blue One</div>
<div class="interior red">Red Two</div>
<div class="interior blue">Blue Two</div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-traverse"
], function(query){
query(".interior").odd();
});
```
returns the two divs with class "red"
###
`on``(eventName,listener)`
Defined by [dojo/query](query)
Listen for events on the nodes in the NodeList. Basic usage is:
| Parameter | Type | Description |
| --- | --- | --- |
| eventName | undefined | |
| listener | undefined | |
**Returns:** undefined
Examples
--------
### Example 1
```
require(["dojo/query"
], function(query){
query(".my-class").on("click", listener);
```
This supports event delegation by using selectors as the first argument with the event names as
pseudo selectors. For example:
```
query("#my-list").on("li:click", listener);
```
This will listen for click events within `<li>` elements that are inside the `#my-list` element.
Because on supports CSS selector syntax, we can use comma-delimited events as well:
```
query("#my-list").on("li button:mouseover, li:click", listener);
});
```
###
`orphan``(filter)`
Defined by [dojo/NodeList-dom](nodelist-dom)
removes elements in this list that match the filter from their parents and returns them as a new NodeList.
| Parameter | Type | Description |
| --- | --- | --- |
| filter | String | *Optional*
CSS selector like ".foo" or "div > span" |
**Returns:** any | undefined
NodeList containing the orphaned elements
###
`parent``(query)`
Defined by [dojo/NodeList-traverse](nodelist-traverse)
Returns immediate parent elements for nodes in this dojo/NodeList. Optionally takes a query to filter the parent elements.
.end() can be used on the returned [dojo/NodeList](nodelist) to get back to the original [dojo/NodeList](nodelist).
| Parameter | Type | Description |
| --- | --- | --- |
| query | String | *Optional*
a CSS selector. |
**Returns:** any | undefined
immediate parent elements for nodes in this dojo/NodeList.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="red">Red One</div>
<div class="blue first"><span class="text">Blue One</span></div>
<div class="red">Red Two</div>
<div class="blue"><span class="text">Blue Two</span></div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-traverse"
], function(query){
query(".text").parent();
});
```
returns the two divs with class "blue".
Running this code:
```
query(".text").parent(".first");
```
returns the one div with class "blue" and "first".
###
`parents``(query)`
Defined by [dojo/NodeList-traverse](nodelist-traverse)
Returns all parent elements for nodes in this dojo/NodeList. Optionally takes a query to filter the child elements.
.end() can be used on the returned [dojo/NodeList](nodelist) to get back to the original [dojo/NodeList](nodelist).
| Parameter | Type | Description |
| --- | --- | --- |
| query | String | *Optional*
a CSS selector. |
**Returns:** any | undefined
all parent elements for nodes in this dojo/NodeList.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="red">Red One</div>
<div class="blue first"><span class="text">Blue One</span></div>
<div class="red">Red Two</div>
<div class="blue"><span class="text">Blue Two</span></div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-traverse"
], function(query){
query(".text").parents();
});
```
returns the two divs with class "blue", the div with class "container",
```
the body element and the html element.
```
Running this code:
```
query(".text").parents(".container");
```
returns the one div with class "container".
###
`place``(queryOrNode,position)`
Defined by [dojo/NodeList-dom](nodelist-dom)
places elements of this node list relative to the first element matched by queryOrNode. Returns the original NodeList. See: `dojo/dom-construct.place`
| Parameter | Type | Description |
| --- | --- | --- |
| queryOrNode | String | Node | may be a string representing any valid CSS3 selector or a DOM node. In the selector case, only the first matching element will be used for relative positioning. |
| position | String | can be one of: * "last" (default)
* "first"
* "before"
* "after"
* "only"
* "replace"
or an offset in the childNodes property |
**Returns:** undefined
###
`position``()`
Defined by [dojo/NodeList-dom](nodelist-dom)
Returns border-box objects (x/y/w/h) of all elements in a node list as an Array (*not* a NodeList). Acts like `dojo/dom-geometry-position`, though assumes the node passed is each node in this list.
**Returns:** undefined
###
`prepend``(content)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
prepends the content to every node in the NodeList.
The content will be cloned if the length of NodeList is greater than 1. Only the DOM nodes are cloned, not any attached event handlers.
| Parameter | Type | Description |
| --- | --- | --- |
| content | String | DOMNode | NodeList | |
**Returns:** any | undefined
dojo/NodeList, the nodes currently in this NodeList will be returned, not the appended content. assume a DOM created by this markup:
```
<div id="foo"><p>Hello Mars</p></div>
<div id="bar"><p>Hello World</p></div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query("div").prepend("<span>prepend</span>");
});
```
Results in this DOM structure:
```
<div id="foo"><span>prepend</span><p>Hello Mars</p></div>
<div id="bar"><span>prepend</span><p>Hello World</p></div>
```
###
`prependTo``(query)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
prepends nodes in this NodeList to the nodes matched by the query passed to prependTo.
The nodes in this NodeList will be cloned if the query matches more than one element. Only the DOM nodes are cloned, not any attached event handlers.
| Parameter | Type | Description |
| --- | --- | --- |
| query | String | |
**Returns:** any | undefined
dojo/NodeList, the nodes currently in this NodeList will be returned, not the matched nodes from the query.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<span>prepend</span>
<p>Hello Mars</p>
<p>Hello World</p>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query("span").prependTo("p");
});
```
Results in this DOM structure:
```
<p><span>prepend</span>Hello Mars</p>
<p><span>prepend</span>Hello World</p>
```
###
`prev``(query)`
Defined by [dojo/NodeList-traverse](nodelist-traverse)
Returns the previous element for nodes in this dojo/NodeList. Optionally takes a query to filter the previous elements.
.end() can be used on the returned [dojo/NodeList](nodelist) to get back to the original [dojo/NodeList](nodelist).
| Parameter | Type | Description |
| --- | --- | --- |
| query | String | *Optional*
a CSS selector. |
**Returns:** any | undefined
the previous element for nodes in this dojo/NodeList.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="red">Red One</div>
Some Text
<div class="blue first">Blue One</div>
<div class="red">Red Two</div>
<div class="blue">Blue Two</div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-traverse"
], function(query){
query(".first").prev();
});
```
returns the div with class "red" and has innerHTML of "Red One".
Running this code:
```
query(".first").prev(".blue");
```
does not return any elements.
###
`prevAll``(query)`
Defined by [dojo/NodeList-traverse](nodelist-traverse)
Returns all sibling elements that come before the nodes in this dojo/NodeList. Optionally takes a query to filter the sibling elements.
The returned nodes will be in reverse DOM order -- the first node in the list will be the node closest to the original node/NodeList. .end() can be used on the returned [dojo/NodeList](nodelist) to get back to the original [dojo/NodeList](nodelist).
| Parameter | Type | Description |
| --- | --- | --- |
| query | String | *Optional*
a CSS selector. |
**Returns:** any | undefined
all sibling elements that come before the nodes in this dojo/NodeList.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="red prev">Red One</div>
Some Text
<div class="blue prev">Blue One</div>
<div class="red second">Red Two</div>
<div class="blue">Blue Two</div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-traverse"
], function(query){
query(".second").prevAll();
});
```
returns the two divs with class of "prev".
Running this code:
```
query(".first").prevAll(".red");
```
returns the one div with class "red prev" and innerHTML "Red One".
###
`query``(queryStr)`
Defined by [dojo/NodeList-dom](nodelist-dom)
Returns a new list whose members match the passed query, assuming elements of the current NodeList as the root for each search.
| Parameter | Type | Description |
| --- | --- | --- |
| queryStr | String | |
**Returns:** function | undefined
Returns a new list whose members match the passed query, assuming elements of the current NodeList as the root for each search.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div id="foo">
<p>
bacon is tasty, <span>dontcha think?</span>
</p>
</div>
<div id="bar">
<p>great comedians may not be funny <span>in person</span></p>
</div>
```
If we are presented with the following definition for a NodeList:
```
require(["dojo/dom", "dojo/query", "dojo/NodeList-dom"
], function(dom, query){
var l = new NodeList(dom.byId("foo"), dom.byId("bar"));
```
it's possible to find all span elements under paragraphs
contained by these elements with this sub-query:
```
var spans = l.query("p span");
});
```
###
`remove``(filter)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
removes elements in this list that match the filter from their parents and returns them as a new NodeList.
| Parameter | Type | Description |
| --- | --- | --- |
| filter | String | *Optional*
CSS selector like ".foo" or "div > span" |
**Returns:** any | undefined
NodeList containing the orphaned elements
###
`removeAttr``(name)`
Defined by [dojo/NodeList-dom](nodelist-dom)
Removes an attribute from each node in the list.
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | the name of the attribute to remove |
###
`removeClass``(className)`
Defined by [dojo/NodeList-dom](nodelist-dom)
removes the specified class from every node in the list
| Parameter | Type | Description |
| --- | --- | --- |
| className | String | Array | *Optional*
An optional String class name to remove, or several space-separated class names, or an array of class names. If omitted, all class names will be deleted. |
**Returns:** any
this list
###
`removeClassFx``(cssClass,args)`
Defined by [dojox/fx/ext-dojo/NodeList-style](http://dojotoolkit.org/api/1.10/dojox/fx/ext-dojo/NodeList-style)
Animate the effect of removing a class to all nodes in this list. see `dojox.fx.removeClass`
| Parameter | Type | Description |
| --- | --- | --- |
| cssClass | undefined | |
| args | undefined | |
**Returns:** [object Value(type: function, value: undefined)]
Examples
--------
### Example 1
```
dojo.query(".box").removeClassFx("bar").play();
```
###
`removeData``(key)`
Defined by [dojo/NodeList-data](nodelist-data)
Remove the data associated with these nodes.
| Parameter | Type | Description |
| --- | --- | --- |
| key | String | *Optional*
If omitted, clean all data for this node. If passed, remove the data item found at `key` |
###
`replaceAll``(query)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
replaces nodes matched by the query passed to replaceAll with the nodes in this NodeList.
The nodes in this NodeList will be cloned if the query matches more than one element. Only the DOM nodes are cloned, not any attached event handlers.
| Parameter | Type | Description |
| --- | --- | --- |
| query | String | |
**Returns:** any | function
The nodes currently in this NodeList will be returned, not the matched nodes from the query. The nodes currently in this NodeLIst could have been cloned, so the returned NodeList will include the cloned nodes.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="spacer">___</div>
<div class="red">Red One</div>
<div class="spacer">___</div>
<div class="blue">Blue One</div>
<div class="spacer">___</div>
<div class="red">Red Two</div>
<div class="spacer">___</div>
<div class="blue">Blue Two</div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query(".red").replaceAll(".blue");
});
```
Results in this DOM structure:
```
<div class="container">
<div class="spacer">___</div>
<div class="spacer">___</div>
<div class="red">Red One</div>
<div class="red">Red Two</div>
<div class="spacer">___</div>
<div class="spacer">___</div>
<div class="red">Red One</div>
<div class="red">Red Two</div>
</div>
```
###
`replaceClass``(addClassStr,removeClassStr)`
Defined by [dojo/NodeList-dom](nodelist-dom)
Replaces one or more classes on a node if not present. Operates more quickly than calling `removeClass()` and `addClass()`
| Parameter | Type | Description |
| --- | --- | --- |
| addClassStr | String | Array | A String class name to add, or several space-separated class names, or an array of class names. |
| removeClassStr | String | Array | *Optional*
A String class name to remove, or several space-separated class names, or an array of class names. |
###
`replaceWith``(content)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
Replaces each node in ths NodeList with the content passed to replaceWith.
The content will be cloned if the length of NodeList is greater than 1. Only the DOM nodes are cloned, not any attached event handlers.
| Parameter | Type | Description |
| --- | --- | --- |
| content | String | DOMNode | NodeList | |
**Returns:** any | function
The nodes currently in this NodeList will be returned, not the replacing content. Note that the returned nodes have been removed from the DOM.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="red">Red One</div>
<div class="blue">Blue One</div>
<div class="red">Red Two</div>
<div class="blue">Blue Two</div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query(".red").replaceWith('<div class="green">Green</div>');
});
```
Results in this DOM structure:
```
<div class="container">
<div class="green">Green</div>
<div class="blue">Blue One</div>
<div class="green">Green</div>
<div class="blue">Blue Two</div>
</div>
```
###
`siblings``(query)`
Defined by [dojo/NodeList-traverse](nodelist-traverse)
Returns all sibling elements for nodes in this dojo/NodeList. Optionally takes a query to filter the sibling elements.
.end() can be used on the returned [dojo/NodeList](nodelist) to get back to the original [dojo/NodeList](nodelist).
| Parameter | Type | Description |
| --- | --- | --- |
| query | String | *Optional*
a CSS selector. |
**Returns:** any | undefined
all sibling elements for nodes in this dojo/NodeList.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="red">Red One</div>
Some Text
<div class="blue first">Blue One</div>
<div class="red">Red Two</div>
<div class="blue">Blue Two</div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-traverse"
], function(query){
query(".first").siblings();
});
```
returns the two divs with class "red" and the other div
```
with class "blue" that does not have "first".
```
Running this code:
```
query(".first").siblings(".red");
```
returns the two div with class "red".
###
`slice``(begin,end)`
Defined by [dojo/query](query)
Returns a new NodeList, maintaining this one in place
This method behaves exactly like the Array.slice method with the caveat that it returns a [dojo/NodeList](nodelist) and not a raw Array. For more details, see Mozilla's [slice documentation](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/slice)
| Parameter | Type | Description |
| --- | --- | --- |
| begin | Integer | Can be a positive or negative integer, with positive integers noting the offset to begin at, and negative integers denoting an offset from the end (i.e., to the left of the end) |
| end | Integer | *Optional*
Optional parameter to describe what position relative to the NodeList's zero index to end the slice at. Like begin, can be positive or negative. |
**Returns:** undefined
###
`slideTo``(args)`
Defined by [dojo/NodeList-fx](nodelist-fx)
slide all elements of the node list to the specified place via `dojo/fx.slideTo()`
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | *Optional*
Additional dojo/\_base/fx.Animation arguments to mix into this set with the addition of an `auto` parameter. |
**Returns:** [dojo/\_base/fx.Animation](_base/fx#Animation)|[dojo/NodeList](nodelist) | undefined
A special args member `auto` can be passed to automatically play the animation. If args.auto is present, the original dojo/NodeList will be returned for further chaining. Otherwise the dojo/\_base/fx.Animation instance is returned and must be .play()'ed
Examples
--------
### Example 1
```
Move all tables with class "blah" to 300/300:
require(["dojo/query", "dojo/NodeList-fx"
], function(query){
query("table.blah").slideTo({
left: 40,
top: 50
}).play();
});
```
###
`some``(callback,thisObject)`
Defined by [dojo/query](query)
Takes the same structure of arguments and returns as `dojo/_base/array.some()` with the caveat that the passed array is implicitly this NodeList. See `dojo/_base/array.some()` and Mozilla's [Array.some documentation](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some).
| Parameter | Type | Description |
| --- | --- | --- |
| callback | Function | the callback |
| thisObject | Object | *Optional*
the context |
**Returns:** undefined
###
`splice``(index,howmany,item)`
Defined by [dojo/query](query)
Returns a new NodeList, manipulating this NodeList based on the arguments passed, potentially splicing in new elements at an offset, optionally deleting elements
This method behaves exactly like the Array.splice method with the caveat that it returns a [dojo/NodeList](nodelist) and not a raw Array. For more details, see Mozilla's [splice documentation](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) For backwards compatibility, calling .end() on the spliced NodeList does not return the original NodeList -- splice alters the NodeList in place.
| Parameter | Type | Description |
| --- | --- | --- |
| index | Integer | begin can be a positive or negative integer, with positive integers noting the offset to begin at, and negative integers denoting an offset from the end (i.e., to the left of the end) |
| howmany | Integer | *Optional*
Optional parameter to describe what position relative to the NodeList's zero index to end the slice at. Like begin, can be positive or negative. |
| item | Object... | *Optional*
Any number of optional parameters may be passed in to be spliced into the NodeList |
**Returns:** undefined
###
`style``(property,value)`
Defined by [dojo/NodeList-dom](nodelist-dom)
gets or sets the CSS property for every element in the NodeList
| Parameter | Type | Description |
| --- | --- | --- |
| property | String | the CSS property to get/set, in JavaScript notation ("lineHieght" instead of "line-height") |
| value | String | *Optional*
optional. The value to set the property to |
**Returns:** any
if no value is passed, the result is an array of strings. If a value is passed, the return is this NodeList
###
`text``(value)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
allows setting the text value of each node in the NodeList, if there is a value passed in, otherwise, returns the text value for all the nodes in the NodeList in one string.
| Parameter | Type | Description |
| --- | --- | --- |
| value | String | |
**Returns:** any | function | string
if no value is passed, the result is String, the text value of the first node. If a value is passed, the return is this dojo/NodeList
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div id="foo"></div>
<div id="bar"></div>
```
This code inserts "Hello World" into both divs:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query("div").text("Hello World");
});
```
### Example 2
assume a DOM created by this markup:
```
<div id="foo"><p>Hello Mars <span>today</span></p></div>
<div id="bar"><p>Hello World</p></div>
```
This code returns "Hello Mars today":
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
var message = query("div").text();
});
```
###
`toggleClass``(className,condition)`
Defined by [dojo/NodeList-dom](nodelist-dom)
Adds a class to node if not present, or removes if present. Pass a boolean condition if you want to explicitly add or remove.
| Parameter | Type | Description |
| --- | --- | --- |
| className | String | the CSS class to add |
| condition | Boolean | *Optional*
If passed, true means to add the class, false means to remove. |
###
`toggleClassFx``(cssClass,force,args)`
Defined by [dojox/fx/ext-dojo/NodeList-style](http://dojotoolkit.org/api/1.10/dojox/fx/ext-dojo/NodeList-style)
Animate the effect of adding or removing a class to all nodes in this list. see `dojox.fx.toggleClass`
| Parameter | Type | Description |
| --- | --- | --- |
| cssClass | undefined | |
| force | undefined | |
| args | undefined | |
**Returns:** [object Value(type: function, value: undefined)]
Examples
--------
### Example 1
```
dojo.query(".box").toggleClass("bar").play();
```
###
`toString``()`
Defined by [dojo/query](query)
**Returns:** undefined
###
`val``(value)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
If a value is passed, allows seting the value property of form elements in this NodeList, or properly selecting/checking the right value for radio/checkbox/select elements. If no value is passed, the value of the first node in this NodeList is returned.
| Parameter | Type | Description |
| --- | --- | --- |
| value | String | Array | |
**Returns:** any | function | undefined | null
if no value is passed, the result is String or an Array, for the value of the first node. If a value is passed, the return is this dojo/NodeList
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<input type="text" value="foo">
<select multiple>
<option value="red" selected>Red</option>
<option value="blue">Blue</option>
<option value="yellow" selected>Yellow</option>
</select>
```
This code gets and sets the values for the form fields above:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query('[type="text"]').val(); //gets value foo
query('[type="text"]').val("bar"); //sets the input's value to "bar"
query("select").val() //gets array value ["red", "yellow"]
query("select").val(["blue", "yellow"]) //Sets the blue and yellow options to selected.
});
```
###
`wipeIn``(args)`
Defined by [dojo/NodeList-fx](nodelist-fx)
wipe in all elements of this NodeList via `dojo/fx.wipeIn()`
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | *Optional*
Additional dojo/\_base/fx.Animation arguments to mix into this set with the addition of an `auto` parameter. |
**Returns:** [dojo/\_base/fx.Animation](_base/fx#Animation)|[dojo/NodeList](nodelist) | undefined
A special args member `auto` can be passed to automatically play the animation. If args.auto is present, the original dojo/NodeList will be returned for further chaining. Otherwise the dojo/\_base/fx.Animation instance is returned and must be .play()'ed
Examples
--------
### Example 1
Fade in all tables with class "blah":
```
require(["dojo/query", "dojo/NodeList-fx"
], function(query){
query("table.blah").wipeIn().play();
});
```
### Example 2
Utilizing `auto` to get the NodeList back:
```
require(["dojo/query", "dojo/NodeList-fx"
], function(query){
query(".titles").wipeIn({ auto:true }).onclick(someFunction);
});
```
###
`wipeOut``(args)`
Defined by [dojo/NodeList-fx](nodelist-fx)
wipe out all elements of this NodeList via `dojo/fx.wipeOut()`
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | *Optional*
Additional dojo/\_base/fx.Animation arguments to mix into this set with the addition of an `auto` parameter. |
**Returns:** [dojo/\_base/fx.Animation](_base/fx#Animation)|[dojo/NodeList](nodelist) | undefined
A special args member `auto` can be passed to automatically play the animation. If args.auto is present, the original dojo/NodeList will be returned for further chaining. Otherwise the dojo/\_base/fx.Animation instance is returned and must be .play()'ed
Examples
--------
### Example 1
Wipe out all tables with class "blah":
```
require(["dojo/query", "dojo/NodeList-fx"
], function(query){
query("table.blah").wipeOut().play();
});
```
###
`wrap``(html)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
Wrap each node in the NodeList with html passed to wrap.
html will be cloned if the NodeList has more than one element. Only DOM nodes are cloned, not any attached event handlers.
| Parameter | Type | Description |
| --- | --- | --- |
| html | String | DOMNode | |
**Returns:** any | function
the nodes in the current NodeList will be returned, not the nodes from html argument.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<b>one</b>
<b>two</b>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query("b").wrap("<div><span></span></div>");
});
```
Results in this DOM structure:
```
<div><span><b>one</b></span></div>
<div><span><b>two</b></span></div>
```
###
`wrapAll``(html)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
Insert html where the first node in this NodeList lives, then place all nodes in this NodeList as the child of the html.
| Parameter | Type | Description |
| --- | --- | --- |
| html | String | DOMNode | |
**Returns:** any | function
the nodes in the current NodeList will be returned, not the nodes from html argument.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="red">Red One</div>
<div class="blue">Blue One</div>
<div class="red">Red Two</div>
<div class="blue">Blue Two</div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query(".red").wrapAll('<div class="allRed"></div>');
});
```
Results in this DOM structure:
```
<div class="container">
<div class="allRed">
<div class="red">Red One</div>
<div class="red">Red Two</div>
</div>
<div class="blue">Blue One</div>
<div class="blue">Blue Two</div>
</div>
```
###
`wrapInner``(html)`
Defined by [dojo/NodeList-manipulate](nodelist-manipulate)
For each node in the NodeList, wrap all its children with the passed in html.
html will be cloned if the NodeList has more than one element. Only DOM nodes are cloned, not any attached event handlers.
| Parameter | Type | Description |
| --- | --- | --- |
| html | String | DOMNode | |
**Returns:** any | function
the nodes in the current NodeList will be returned, not the nodes from html argument.
Examples
--------
### Example 1
assume a DOM created by this markup:
```
<div class="container">
<div class="red">Red One</div>
<div class="blue">Blue One</div>
<div class="red">Red Two</div>
<div class="blue">Blue Two</div>
</div>
```
Running this code:
```
require(["dojo/query", "dojo/NodeList-manipulate"
], function(query){
query(".red").wrapInner('<span class="special"></span>');
});
```
Results in this DOM structure:
```
<div class="container">
<div class="red"><span class="special">Red One</span></div>
<div class="blue">Blue One</div>
<div class="red"><span class="special">Red Two</span></div>
<div class="blue">Blue Two</div>
</div>
```
| programming_docs |
dojo dojo/main.Stateful dojo/main.Stateful
==================
Summary
-------
Base class for objects that provide named properties with optional getter/setter control and the ability to watch for property changes
The class also provides the functionality to auto-magically manage getters and setters for object attributes/properties.
Getters and Setters should follow the format of \_xxxGetter or \_xxxSetter where the xxx is a name of the attribute to handle. So an attribute of "foo" would have a custom getter of \_fooGetter and a custom setter of \_fooSetter.
Examples
--------
### Example 1
```
require(["dojo/Stateful", function(Stateful) {
var obj = new Stateful();
obj.watch("foo", function(){
console.log("foo changed to " + this.get("foo"));
});
obj.set("foo","bar");
});
```
Properties
----------
Methods
-------
###
`get``(name)`
Defined by [dojo/Stateful](stateful)
Get a property on a Stateful instance.
Get a named property on a Stateful object. The property may potentially be retrieved via a getter method in subclasses. In the base class this just retrieves the object's property.
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | The property to get. |
**Returns:** any | undefined
The property value on this Stateful instance.
Examples
--------
### Example 1
```
require(["dojo/Stateful", function(Stateful) {
var stateful = new Stateful({foo: 3});
stateful.get("foo") // returns 3
stateful.foo // returns 3
});
```
###
`postscript``(params)`
Defined by [dojo/Stateful](stateful)
| Parameter | Type | Description |
| --- | --- | --- |
| params | Object | *Optional* |
###
`set``(name,value)`
Defined by [dojo/Stateful](stateful)
Set a property on a Stateful instance
Sets named properties on a stateful object and notifies any watchers of the property. A programmatic setter may be defined in subclasses.
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | The property to set. |
| value | Object | The value to set in the property. |
**Returns:** any | function
The function returns this dojo.Stateful instance.
Examples
--------
### Example 1
```
require(["dojo/Stateful", function(Stateful) {
var stateful = new Stateful();
stateful.watch(function(name, oldValue, value){
// this will be called on the set below
}
stateful.set(foo, 5);
```
set() may also be called with a hash of name/value pairs, ex:
```
stateful.set({
foo: "Howdy",
bar: 3
});
});
```
This is equivalent to calling set(foo, "Howdy") and set(bar, 3)
###
`watch``(name,callback)`
Defined by [dojo/Stateful](stateful)
Watches a property for changes
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | *Optional*
Indicates the property to watch. This is optional (the callback may be the only parameter), and if omitted, all the properties will be watched |
| callback | Function | The function to execute when the property changes. This will be called after the property has been changed. The callback will be called with the |this| set to the instance, the first argument as the name of the property, the second argument as the old value and the third argument as the new value. |
**Returns:** any | object
An object handle for the watch. The unwatch method of this object can be used to discontinue watching this property:
```
var watchHandle = obj.watch("foo", callback);
watchHandle.unwatch(); // callback won't be called now
```
dojo dojo/dom-form dojo/dom-form
=============
Summary
-------
This module defines form-processing functions.
See the [dojo/dom-form reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dom-form.html) for more information.
Methods
-------
###
`fieldToObject``(inputNode)`
Defined by [dojo/dom-form](dom-form)
Serialize a form field to a JavaScript object.
Returns the value encoded in a form field as as a string or an array of strings. Disabled form elements and unchecked radio and checkboxes are skipped. Multi-select elements are returned as an array of string values.
| Parameter | Type | Description |
| --- | --- | --- |
| inputNode | DOMNode | String | |
**Returns:** Object | undefined
###
`toJson``(formNode,prettyPrint)`
Defined by [dojo/dom-form](dom-form)
Create a serialized JSON string from a form node or string ID identifying the form to serialize
| Parameter | Type | Description |
| --- | --- | --- |
| formNode | DOMNode | String | |
| prettyPrint | Boolean | *Optional* |
**Returns:** String | undefined
###
`toObject``(formNode)`
Defined by [dojo/dom-form](dom-form)
Serialize a form node to a JavaScript object.
Returns the values encoded in an HTML form as string properties in an object which it then returns. Disabled form elements, buttons, and other non-value form elements are skipped. Multi-select elements are returned as an array of string values.
| Parameter | Type | Description |
| --- | --- | --- |
| formNode | DOMNode | String | |
**Returns:** object
Examples
--------
### Example 1
This form:
```
<form id="test_form">
<input type="text" name="blah" value="blah">
<input type="text" name="no_value" value="blah" disabled>
<input type="button" name="no_value2" value="blah">
<select type="select" multiple name="multi" size="5">
<option value="blah">blah</option>
<option value="thud" selected>thud</option>
<option value="thonk" selected>thonk</option>
</select>
</form>
```
yields this object structure as the result of a call to formToObject():
```
{
blah: "blah",
multi: [
"thud",
"thonk"
]
};
```
###
`toQuery``(formNode)`
Defined by [dojo/dom-form](dom-form)
Returns a URL-encoded string representing the form passed as either a node or string ID identifying the form to serialize
| Parameter | Type | Description |
| --- | --- | --- |
| formNode | DOMNode | String | |
**Returns:** String | undefined
dojo dojo/debounce dojo/debounce
=============
Summary
-------
Create a function that will only execute after `wait` milliseconds
Create a function that will only execute after `wait` milliseconds of repeated execution. Useful for delaying some event action slightly to allow for rapidly-firing events such as window.resize, node.mousemove and so on.
Usage
-----
debounce`(cb,wait);`
| Parameter | Type | Description |
| --- | --- | --- |
| cb | Function | A callback to fire. Like hitch() and partial(), arguments passed to the returned function curry along to the original callback. |
| wait | Integer | Time to spend caching executions before actually executing. |
Methods
-------
dojo dojo/main.number dojo/main.number
================
Summary
-------
localized formatting and parsing routines for Number
Properties
----------
Methods
-------
###
`format``(value,options)`
Defined by [dojo/number](number)
Format a Number as a String, using locale-specific settings
Create a string from a Number using a known localized pattern. Formatting patterns appropriate to the locale are chosen from the [Common Locale Data Repository](http://unicode.org/cldr) as well as the appropriate symbols and delimiters. If value is Infinity, -Infinity, or is not a valid JavaScript number, return null.
| Parameter | Type | Description |
| --- | --- | --- |
| value | Number | the number to be formatted |
| options | Object | *Optional*
An object with the following properties:* pattern (String, optional): override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization. Literal characters in patterns are not supported.
* type (String, optional): choose a format type based on the locale from the following: decimal, scientific (not yet supported), percent, currency. decimal by default.
* places (Number, optional): fixed number of decimal places to show. This overrides any information in the provided pattern.
* round (Number, optional): 5 rounds to nearest .5; 0 rounds to nearest whole (default). -1 means do not round.
* locale (String, optional): override the locale used to determine formatting rules
* fractional (Boolean, optional): If false, show no decimal places, overriding places and pattern settings.
|
**Returns:** null | undefined
###
`parse``(expression,options)`
Defined by [dojo/number](number)
Convert a properly formatted string to a primitive Number, using locale-specific settings.
Create a Number from a string using a known localized pattern. Formatting patterns are chosen appropriate to the locale and follow the syntax described by [unicode.org TR35](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) Note that literal characters in patterns are not supported.
| Parameter | Type | Description |
| --- | --- | --- |
| expression | String | A string representation of a Number |
| options | Object | *Optional*
An object with the following properties:* pattern (String, optional): override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization. Literal characters in patterns are not supported.
* type (String, optional): choose a format type based on the locale from the following: decimal, scientific (not yet supported), percent, currency. decimal by default.
* locale (String, optional): override the locale used to determine formatting rules
* strict (Boolean, optional): strict parsing, false by default. Strict parsing requires input as produced by the format() method. Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
* fractional (Boolean|Array, optional): Whether to include the fractional portion, where the number of decimal places are implied by pattern or explicit 'places' parameter. The value [true,false] makes the fractional portion optional.
|
**Returns:** number
###
`regexp``(options)`
Defined by [dojo/number](number)
Builds the regular needed to parse a number
Returns regular expression with positive and negative match, group and decimal separators
| Parameter | Type | Description |
| --- | --- | --- |
| options | Object | *Optional*
An object with the following properties:* pattern (String, optional): override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization.
* type (String, optional): choose a format type based on the locale from the following: decimal, scientific (not yet supported), percent, currency. decimal by default.
* locale (String, optional): override the locale used to determine formatting rules
* strict (Boolean, optional): strict parsing, false by default. Strict parsing requires input as produced by the format() method. Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
* places (Number|String, optional): number of decimal places to accept: Infinity, a positive number, or a range "n,m". Defined by pattern or Infinity if pattern not provided.
|
**Returns:** undefined
###
`round``(value,places,increment)`
Defined by [dojo/number](number)
Rounds to the nearest value with the given number of decimal places, away from zero
Rounds to the nearest value with the given number of decimal places, away from zero if equal. Similar to Number.toFixed(), but compensates for browser quirks. Rounding can be done by fractional increments also, such as the nearest quarter. NOTE: Subject to floating point errors. See [dojox/math/round](http://dojotoolkit.org/api/1.10/dojox/math/round) for experimental workaround.
| Parameter | Type | Description |
| --- | --- | --- |
| value | Number | The number to round |
| places | Number | *Optional*
The number of decimal places where rounding takes place. Defaults to 0 for whole rounding. Must be non-negative. |
| increment | Number | *Optional*
Rounds next place to nearest value of increment/10. 10 by default. |
**Returns:** number
Examples
--------
### Example 1
```
>>> number.round(-0.5)
-1
>>> number.round(162.295, 2)
162.29 // note floating point error. Should be 162.3
>>> number.round(10.71, 0, 2.5)
10.75
```
dojo dojo/number.__FormatAbsoluteOptions dojo/number.\_\_FormatAbsoluteOptions
=====================================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new number.__FormatAbsoluteOptions()`
Properties
----------
### decimal
Defined by: [dojo/number](number)
the decimal separator
### group
Defined by: [dojo/number](number)
the group separator
### places
Defined by: [dojo/number](number)
number of decimal places. the range "n,m" will format to m places.
### round
Defined by: [dojo/number](number)
5 rounds to nearest .5; 0 rounds to nearest whole (default). -1 means don't round.
dojo dojo/throttle dojo/throttle
=============
Summary
-------
Create a function that will only execute once per `wait` periods.
Create a function that will only execute once per `wait` periods from last execution when called repeatedly. Useful for preventing excessive calculations in rapidly firing events, such as window.resize, node.mousemove and so on.
Usage
-----
throttle`(cb,wait);`
| Parameter | Type | Description |
| --- | --- | --- |
| cb | Function | The callback to fire. |
| wait | Integer | time to delay before allowing cb to call again. |
Methods
-------
dojo dojo/main.__IoArgs dojo/main.\_\_IoArgs
====================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new main.__IoArgs()`
Properties
----------
### content
Defined by: [dojo/\_base/xhr](_base/xhr)
Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
### form
Defined by: [dojo/\_base/xhr](_base/xhr)
DOM node for a form. Used to extract the form values and send to the server.
### handleAs
Defined by: [dojo/\_base/xhr](_base/xhr)
Acceptable values depend on the type of IO transport (see specific IO calls for more information).
### ioPublish
Defined by: [dojo/\_base/xhr](_base/xhr)
Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via [dojo/topic.publish()](topic#publish) for different phases of an IO operation. See [dojo/main.\_\_IoPublish](main.__iopublish) for a list of topics that are published.
### preventCache
Defined by: [dojo/\_base/xhr](_base/xhr)
Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
### rawBody
Defined by: [dojo/\_base/xhr](_base/xhr)
Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for [dojo/\_base/xhr.rawXhrPost](_base/xhr#rawXhrPost) and [dojo/\_base/xhr.rawXhrPut](_base/xhr#rawXhrPut) respectively.
### timeout
Defined by: [dojo/\_base/xhr](_base/xhr)
Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
### url
Defined by: [dojo/\_base/xhr](_base/xhr)
URL to server endpoint.
Methods
-------
###
`error``(response,ioArgs)`
Defined by [dojo/\_base/xhr](_base/xhr)
This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
| Parameter | Type | Description |
| --- | --- | --- |
| response | Object | The response in the format as defined with handleAs. |
| ioArgs | [dojo/main.\_\_IoCallbackArgs](main.__iocallbackargs) | Provides additional information about the request. |
###
`handle``(loadOrError,response,ioArgs)`
Defined by [dojo/\_base/xhr](_base/xhr)
This function will be called at the end of every request, whether or not an error occurs.
| Parameter | Type | Description |
| --- | --- | --- |
| loadOrError | String | Provides a string that tells you whether this function was called because of success (load) or failure (error). |
| response | Object | The response in the format as defined with handleAs. |
| ioArgs | [dojo/main.\_\_IoCallbackArgs](main.__iocallbackargs) | Provides additional information about the request. |
###
`load``(response,ioArgs)`
Defined by [dojo/\_base/xhr](_base/xhr)
This function will be called on a successful HTTP response code.
| Parameter | Type | Description |
| --- | --- | --- |
| response | Object | The response in the format as defined with handleAs. |
| ioArgs | [dojo/main.\_\_IoCallbackArgs](main.__iocallbackargs) | Provides additional information about the request. |
dojo dojo/main.config dojo/main.config
================
Summary
-------
This module defines the user configuration during bootstrap.
By defining user configuration as a module value, an entire configuration can be specified in a build, thereby eliminating the need for sniffing and or explicitly setting in the global variable dojoConfig. Also, when multiple instances of dojo exist in a single application, each will necessarily be located at an unique absolute module identifier as given by the package configuration. Implementing configuration as a module allows for specifying unique, per-instance configurations.
Examples
--------
### Example 1
Create a second instance of dojo with a different, instance-unique configuration (assume the loader and dojo.js are already loaded).
```
// specify a configuration that creates a new instance of dojo at the absolute module identifier "myDojo"
require({
packages:[{
name:"myDojo",
location:".", //assume baseUrl points to dojo.js
}]
});
// specify a configuration for the myDojo instance
define("myDojo/config", {
// normal configuration variables go here, e.g.,
locale:"fr-ca"
});
// load and use the new instance of dojo
require(["myDojo"], function(dojo){
// dojo is the new instance of dojo
// use as required
});
```
Properties
----------
###
`addOnLoad`
Defined by: [dojo/\_base/config](_base/config)
Adds a callback via [dojo/ready](ready). Useful when Dojo is added after the page loads and djConfig.afterOnLoad is true. Supports the same arguments as [dojo/ready](ready). When using a function reference, use `djConfig.addOnLoad = function(){};`. For object with function name use `djConfig.addOnLoad = [myObject, "functionName"];` and for object with function reference use `djConfig.addOnLoad = [myObject, function(){}];`
### afterOnLoad
Defined by: [dojo/ready](ready)
### baseUrl
Defined by: [dojo/\_base/kernel](_base/kernel)
###
`callback`
Defined by: [dojo/\_base/config](_base/config)
Defines a callback to be used when dependencies are defined before the loader has been loaded. When provided, they cause the loader to execute require(deps, callback) once it has finished loading. Should be used with deps.
### debugContainerId
Defined by: [dojo/\_firebug/firebug](_firebug/firebug)
### debugHeight
Defined by: [dojo/robotx](robotx)
### defaultDuration
Defined by: [dojo/\_base/config](_base/config)
Default duration, in milliseconds, for wipe and fade animations within dijits. Assigned to dijit.defaultDuration.
### deferredInstrumentation
Defined by: [dojo/\_base/config](_base/config)
Whether deferred instrumentation should be loaded or included in builds.
###
`deps`
Defined by: [dojo/\_base/config](_base/config)
Defines dependencies to be used before the loader has been loaded. When provided, they cause the loader to execute require(deps, callback) once it has finished loading. Should be used with callback.
### dojoBlankHtmlUrl
Defined by: [dojo/\_base/config](_base/config)
Used by some modules to configure an empty iframe. Used by [dojo/io/iframe](io/iframe) and [dojo/back](back), and [dijit/popup](http://dojotoolkit.org/api/1.10/dijit/popup) support in IE where an iframe is needed to make sure native controls do not bleed through the popups. Normally this configuration variable does not need to be set, except when using cross-domain/CDN Dojo builds. Save dojo/resources/blank.html to your domain and set `djConfig.dojoBlankHtmlUrl` to the path on your domain your copy of blank.html.
### extraLocale
Defined by: [dojo/\_base/config](_base/config)
No default value. Specifies additional locales whose resources should also be loaded alongside the default locale when calls to `dojo.requireLocalization()` are processed.
### ioPublish
Defined by: [dojo/\_base/config](_base/config)
Set this to true to enable publishing of topics for the different phases of IO operations. Publishing is done via [dojo/topic.publish()](topic#publish). See [dojo/main.\_\_IoPublish](main.__iopublish) for a list of topics that are published.
### isDebug
Defined by: [dojo/\_base/config](_base/config)
Defaults to `false`. If set to `true`, ensures that Dojo provides extended debugging feedback via Firebug. If Firebug is not available on your platform, setting `isDebug` to `true` will force Dojo to pull in (and display) the version of Firebug Lite which is integrated into the Dojo distribution, thereby always providing a debugging/logging console when `isDebug` is enabled. Note that Firebug's `console.*` methods are ALWAYS defined by Dojo. If `isDebug` is false and you are on a platform without Firebug, these methods will be defined as no-ops.
### locale
Defined by: [dojo/\_base/config](_base/config)
The locale to assume for loading localized resources in this page, specified according to [RFC 3066](http://www.ietf.org/rfc/rfc3066.txt). Must be specified entirely in lowercase, e.g. `en-us` and `zh-cn`. See the documentation for `dojo.i18n` and `dojo.requireLocalization` for details on loading localized resources. If no locale is specified, Dojo assumes the locale of the user agent, according to `navigator.userLanguage` or `navigator.language` properties.
### modulePaths
Defined by: [dojo/\_base/config](_base/config)
A map of module names to paths relative to `dojo.baseUrl`. The key/value pairs correspond directly to the arguments which `dojo.registerModulePath` accepts. Specifying `djConfig.modulePaths = { "foo": "../../bar" }` is the equivalent of calling `dojo.registerModulePath("foo", "../../bar");`. Multiple modules may be configured via `djConfig.modulePaths`.
### parseOnLoad
Defined by: [dojo/\_base/config](_base/config)
Run the parser after the page is loaded
### require
Defined by: [dojo/\_base/config](_base/config)
An array of module names to be loaded immediately after dojo.js has been included in a page.
### transparentColor
Defined by: [dojo/\_base/config](_base/config)
Array containing the r, g, b components used as transparent color in dojo.Color; if undefined, [255,255,255] (white) will be used.
### urchin
Defined by: [dojox/analytics/Urchin](http://dojotoolkit.org/api/1.10/dojox/analytics/Urchin)
Used by `dojox.analytics.Urchin` as the default UA-123456-7 account number used when being created. Alternately, you can pass an acct:"" parameter to the constructor a la: new dojox.analytics.Urchin({ acct:"UA-123456-7" });
### useCustomLogger
Defined by: [dojo/\_base/config](_base/config)
If set to a value that evaluates to true such as a string or array and isDebug is true and Firebug is not available or running, then it bypasses the creation of Firebug Lite allowing you to define your own console object.
### useDeferredInstrumentation
Defined by: [dojo/\_base/config](_base/config)
Whether the deferred instrumentation should be used.
* `"report-rejections"`: report each rejection as it occurs.
* `true` or `1` or `"report-unhandled-rejections"`: wait 1 second in an attempt to detect unhandled rejections.
| programming_docs |
dojo dojo/request.__Options dojo/request.\_\_Options
========================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new request.__Options()`
Properties
----------
### data
Defined by: [dojo/request](request)
Data to transfer. This is ignored for GET and DELETE requests.
### handleAs
Defined by: [dojo/request](request)
How to handle the response from the server. Default is 'text'. Other values are 'json', 'javascript', and 'xml'.
### method
Defined by: [dojo/request](request)
The HTTP method to use to make the request. Must be uppercase.
### preventCache
Defined by: [dojo/request](request)
Whether to append a cache-busting parameter to the URL.
### query
Defined by: [dojo/request](request)
Query parameters to append to the URL.
### timeout
Defined by: [dojo/request](request)
Milliseconds to wait for the response. If this time passes, the then the promise is rejected.
dojo dojo/query dojo/query
==========
Summary
-------
This modules provides DOM querying functionality. The module export is a function that can be used to query for DOM nodes by CSS selector and returns a NodeList representing the matching nodes.
[dojo/query](query) is responsible for loading the appropriate query engine and wrapping its results with a `NodeList`. You can use [dojo/query](query) with a specific selector engine by using it as a plugin. For example, if you installed the sizzle package, you could use it as the selector engine with:
```
require(["dojo/query!sizzle"], function(query){
query("div")...
```
The id after the ! can be a module id of the selector engine or one of the following values:
* acme: This is the default engine used by Dojo base, and will ensure that the full Acme engine is always loaded.
* css2: If the browser has a native selector engine, this will be used, otherwise a very minimal lightweight selector engine will be loaded that can do simple CSS2 selectors (by #id, .class, tag, and [name=value] attributes, with standard child or descendant (>) operators) and nothing more.
* css2.1: If the browser has a native selector engine, this will be used, otherwise the full Acme engine will be loaded.
* css3: If the browser has a native selector engine with support for CSS3 pseudo selectors (most modern browsers except IE8), this will be used, otherwise the full Acme engine will be loaded.
* Or the module id of a selector engine can be used to explicitly choose the selector engine
For example, if you are using CSS3 pseudo selectors in module, you can specify that you will need support them with:
```
require(["dojo/query!css3"], function(query){
query('#t > h3:nth-child(odd)')...
```
You can also choose the selector engine/load configuration by setting the query-selector: For example:
```
<script data-dojo-config="query-selector:'css3'" src="dojo.js"></script>
```
Usage
-----
query`(selector,context);`
| Parameter | Type | Description |
| --- | --- | --- |
| selector | String | A CSS selector to search for. |
| context | String | DomNode | *Optional*
An optional context to limit the searching scope. Only nodes under `context` will be scanned. |
**Returns:** instance
See the [dojo/query reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/query.html) for more information.
Examples
--------
### Example 1
add an onclick handler to every submit button in the document which causes the form to be sent via Ajax instead:
```
require(["dojo/query", "dojo/request", "dojo/dom-form", "dojo/dom-construct", "dojo/dom-style"
], function(query, request, domForm, domConstruct, domStyle){
query("input[type='submit']").on("click", function(e){
e.preventDefault(); // prevent sending the form
var btn = e.target;
request.post("http://example.com/", {
data: domForm.toObject(btn.form)
}).then(function(response){
// replace the form with the response
domConstruct.create(div, {innerHTML: response}, btn.form, "after");
domStyle.set(btn.form, "display", "none");
});
});
});
```
Methods
-------
###
`load``(id,parentRequire,loaded)`
Defined by [dojo/query](query)
can be used as AMD plugin to conditionally load new query engine
| Parameter | Type | Description |
| --- | --- | --- |
| id | undefined | |
| parentRequire | undefined | |
| loaded | undefined | |
Examples
--------
### Example 1
```
require(["dojo/query!custom"], function(qsa){
// loaded selector/custom.js as engine
qsa("#foobar").forEach(...);
});
```
###
`NodeList``(array)`
Defined by [dojo/query](query)
Array-like object which adds syntactic sugar for chaining, common iteration operations, animation, and node manipulation. NodeLists are most often returned as the result of dojo/query() calls.
NodeList instances provide many utilities that reflect core Dojo APIs for Array iteration and manipulation, DOM manipulation, and event handling. Instead of needing to dig up functions in the dojo package, NodeLists generally make the full power of Dojo available for DOM manipulation tasks in a simple, chainable way.
| Parameter | Type | Description |
| --- | --- | --- |
| array | undefined | |
**Returns:** Array
Examples
--------
### Example 1
create a node list from a node
```
require(["dojo/query", "dojo/dom"
], function(query, dom){
query.NodeList(dom.byId("foo"));
});
```
### Example 2
get a NodeList from a CSS query and iterate on it
```
require(["dojo/on", "dojo/dom"
], function(on, dom){
var l = query(".thinger");
l.forEach(function(node, index, nodeList){
console.log(index, node.innerHTML);
});
});
```
### Example 3
use native and Dojo-provided array methods to manipulate a NodeList without needing to use dojo.\* functions explicitly:
```
require(["dojo/query", "dojo/dom-construct", "dojo/dom"
], function(query, domConstruct, dom){
var l = query(".thinger");
// since NodeLists are real arrays, they have a length
// property that is both readable and writable and
// push/pop/shift/unshift methods
console.log(l.length);
l.push(domConstruct.create("span"));
// dojo's normalized array methods work too:
console.log( l.indexOf(dom.byId("foo")) );
// ...including the special "function as string" shorthand
console.log( l.every("item.nodeType == 1") );
// NodeLists can be [..] indexed, or you can use the at()
// function to get specific items wrapped in a new NodeList:
var node = l[3]; // the 4th element
var newList = l.at(1, 3); // the 2nd and 4th elements
});
```
### Example 4
chainability is a key advantage of NodeLists:
```
require(["dojo/query", "dojo/NodeList-dom"
], function(query){
query(".thinger")
.onclick(function(e){ /* ... */ })
.at(1, 3, 8) // get a subset
.style("padding", "5px")
.forEach(console.log);
});
```
dojo dojo/i18n dojo/i18n
=========
Summary
-------
This module implements the [dojo/i18n](i18n)! plugin and the v1.6- i18n API
We choose to include our own plugin to leverage functionality already contained in dojo and thereby reduce the size of the plugin compared to various loader implementations. Also, this allows foreign AMD loaders to be used without their plugins.
See the [dojo/i18n reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/i18n.html) for more information.
Properties
----------
### cache
Defined by: [dojo/i18n](i18n)
### dynamic
Defined by: [dojo/i18n](i18n)
### unitTests
Defined by: [dojo/i18n](i18n)
Methods
-------
###
`getL10nName``(moduleName,bundleName,locale)`
Defined by [dojo/i18n](i18n)
| Parameter | Type | Description |
| --- | --- | --- |
| moduleName | undefined | |
| bundleName | undefined | |
| locale | undefined | |
**Returns:** string
###
`getLocalization``(moduleName,bundleName,locale)`
Defined by [dojo/i18n](i18n)
| Parameter | Type | Description |
| --- | --- | --- |
| moduleName | undefined | |
| bundleName | undefined | |
| locale | undefined | |
**Returns:** undefined
###
`load``(id,require,load)`
Defined by [dojo/i18n](i18n)
id is in one of the following formats
1. /nls/ => load the bundle, localized to config.locale; load all bundles localized to config.extraLocale (if any); return the loaded bundle localized to config.locale.
2. /nls// => load then return the bundle localized to
3. *preload*/nls/\* => for config.locale and all config.extraLocale, load all bundles found in the best-matching bundle rollup. A value of 1 is returned, which is meaningless other than to say the plugin is executing the requested preloads
In cases 1 and 2, is always normalized to an absolute module id upon entry; see normalize. In case 3, it is assumed to be absolute; this is arranged by the builder.
To load a bundle means to insert the bundle into the plugin's cache and publish the bundle value to the loader. Given , , and a particular , the cache key
```
<path>/nls/<bundle>/<locale>
```
will hold the value. Similarly, then plugin will publish this value to the loader by
```
define("<path>/nls/<bundle>/<locale>", <bundle-value>);
```
Given this algorithm, other machinery can provide fast load paths be preplacing values in the plugin's cache, which is public. When a load is demanded the cache is inspected before starting any loading. Explicitly placing values in the plugin cache is an advanced/experimental feature that should not be needed; use at your own risk.
For the normal AMD algorithm, the root bundle is loaded first, which instructs the plugin what additional localized bundles are required for a particular locale. These additional locales are loaded and a mix of the root and each progressively-specific locale is returned. For example:
1. The client demands "dojo/i18n!some/path/nls/someBundle
2. The loader demands load(some/path/nls/someBundle)
3. This plugin require's "some/path/nls/someBundle", which is the root bundle.
4. Assuming config.locale is "ab-cd-ef" and the root bundle indicates that localizations are available for "ab" and "ab-cd-ef" (note the missing "ab-cd", then the plugin requires "some/path/nls/ab/someBundle" and "some/path/nls/ab-cd-ef/someBundle"
5. Upon receiving all required bundles, the plugin constructs the value of the bundle ab-cd-ef as...
```
mixin(mixin(mixin({}, require("some/path/nls/someBundle"),
require("some/path/nls/ab/someBundle")),
require("some/path/nls/ab-cd-ef/someBundle"));
```
This value is inserted into the cache and published to the loader at the key/module-id some/path/nls/someBundle/ab-cd-ef.
The special preload signature (case 3) instructs the plugin to stop servicing all normal requests (further preload requests will be serviced) until all ongoing preloading has completed.
The preload signature instructs the plugin that a special rollup module is available that contains one or more flattened, localized bundles. The JSON array of available locales indicates which locales are available. Here is an example:
```
*preload*some/path/nls/someModule*["root", "ab", "ab-cd-ef"]
```
This indicates the following rollup modules are available:
```
some/path/nls/someModule_ROOT
some/path/nls/someModule_ab
some/path/nls/someModule_ab-cd-ef
```
Each of these modules is a normal AMD module that contains one or more flattened bundles in a hash. For example, assume someModule contained the bundles some/bundle/path/someBundle and some/bundle/path/someOtherBundle, then some/path/nls/someModule\_ab would be expressed as follows:
```
define({
some/bundle/path/someBundle:<value of someBundle, flattened with respect to locale ab>,
some/bundle/path/someOtherBundle:<value of someOtherBundle, flattened with respect to locale ab>,
});
```
E.g., given this design, preloading for locale=="ab" can execute the following algorithm:
```
require(["some/path/nls/someModule_ab"], function(rollup){
for(var p in rollup){
var id = p + "/ab",
cache[id] = rollup[p];
define(id, rollup[p]);
}
});
```
Similarly, if "ab-cd" is requested, the algorithm can determine that "ab" is the best available and load accordingly.
The builder will write such rollups for every layer if a non-empty localeList profile property is provided. Further, the builder will include the following cache entry in the cache associated with any layer.
```
"*now":function(r){r(['dojo/i18n!*preload*<path>/nls/<module>*<JSON array of available locales>']);}
```
The \*now special cache module instructs the loader to apply the provided function to context-require with respect to the particular layer being defined. This causes the plugin to hold all normal service requests until all preloading is complete.
Notice that this algorithm is rarely better than the standard AMD load algorithm. Consider the normal case where the target locale has a single segment and a layer depends on a single bundle:
Without Preloads:
1. Layer loads root bundle.
2. bundle is demanded; plugin loads single localized bundle.
With Preloads:
1. Layer causes preloading of target bundle.
2. bundle is demanded; service is delayed until preloading complete; bundle is returned.
In each case a single transaction is required to load the target bundle. In cases where multiple bundles are required and/or the locale has multiple segments, preloads still requires a single transaction whereas the normal path requires an additional transaction for each additional bundle/locale-segment. However all of these additional transactions can be done concurrently. Owing to this analysis, the entire preloading algorithm can be discard during a build by setting the has feature dojo-preload-i18n-Api to false.
| Parameter | Type | Description |
| --- | --- | --- |
| id | undefined | |
| require | undefined | |
| load | undefined | |
###
`normalize``(id,toAbsMid)`
Defined by [dojo/i18n](i18n)
id may be relative. preload has form `*preload*<path>/nls/<module>*<flattened locales>` and therefore never looks like a relative
| Parameter | Type | Description |
| --- | --- | --- |
| id | undefined | |
| toAbsMid | undefined | |
**Returns:** undefined
###
`normalizeLocale``(locale)`
Defined by [dojo/i18n](i18n)
| Parameter | Type | Description |
| --- | --- | --- |
| locale | undefined | |
**Returns:** undefined
dojo dojo/main dojo/main
=========
Summary
-------
This module is the foundational module of the dojo boot sequence; it defines the dojo object.
Properties
----------
### back
Defined by: [dojo/back](back)
Browser history management resources
### baseUrl
Defined by: [dojo/\_base/configSpidermonkey](_base/configspidermonkey)
### behavior
Defined by: [dojo/behavior](behavior)
### cldr
Defined by: [dojo/cldr/monetary](cldr/monetary)
### colors
Defined by: [dojo/colors](colors)
### config
Defined by: [dojo/\_base/kernel](_base/kernel)
This module defines the user configuration during bootstrap.
### connectPublisher
Defined by: [dojo/robotx](robotx)
### contentHandlers
Defined by: [dojo/\_base/xhr](_base/xhr)
A map of available XHR transport handle types. Name matches the `handleAs` attribute passed to XHR calls.
### currency
Defined by: [dojo/currency](currency)
localized formatting and parsing routines for currencies
### data
Defined by: [dojo/data/util/filter](data/util/filter)
### date
Defined by: [dojo/date/stamp](date/stamp)
### dijit
Defined by: [dojo/\_base/kernel](_base/kernel)
### dnd
Defined by: [dojo/dnd/common](dnd/common)
### doc
Defined by: [dojo/\_base/window](_base/window)
Alias for the current document. 'doc' can be modified for temporary context shifting. See also withDoc().
### dojox
Defined by: [dojo/\_base/kernel](_base/kernel)
### fx
Defined by: [dojo/fx](fx)
Effects library on top of Base animations
### gears
Defined by: [dojo/gears](gears)
TODOC
### global
Defined by: [dojo/\_base/window](_base/window)
Alias for the current window. 'global' can be modified for temporary context shifting. See also withGlobal().
### html
Defined by: [dojo/html](html)
TODOC
### i18n
Defined by: [dojo/i18n](i18n)
This module implements the [dojo/i18n](i18n)! plugin and the v1.6- i18n API
### io
Defined by: [dojo/io/iframe](io/iframe)
### isAir
Defined by: [dojo/\_base/sniff](_base/sniff)
True if client is Adobe Air
### isAndroid
Defined by: [dojo/\_base/sniff](_base/sniff)
Version as a Number if client is android browser. undefined otherwise.
### isAsync
Defined by: [dojo/\_base/kernel](_base/kernel)
### isBrowser
Defined by: [dojo/\_base/configFirefoxExtension](_base/configfirefoxextension)
### isChrome
Defined by: [dojo/\_base/sniff](_base/sniff)
Version as a Number if client is Chrome browser. undefined otherwise.
### isCopyKey
Defined by: [dojox/grid/\_Grid](http://dojotoolkit.org/api/1.10/dojox/grid/_Grid)
### isFF
Defined by: [dojo/\_base/configFirefoxExtension](_base/configfirefoxextension)
### isIE
Defined by: [dojo/\_base/sniff](_base/sniff)
Version as a Number if client is MSIE(PC). undefined otherwise. Corresponds to major detected IE version (6, 7, 8, etc.)
### isIos
Defined by: [dojo/\_base/sniff](_base/sniff)
Version as a Number if client is iPhone, iPod, or iPad. undefined otherwise.
### isKhtml
Defined by: [dojo/\_base/sniff](_base/sniff)
Version as a Number if client is a KHTML browser. undefined otherwise. Corresponds to major detected version.
### isMac
Defined by: [dojo/\_base/sniff](_base/sniff)
True if the client runs on Mac
### isMoz
Defined by: [dojo/\_base/configFirefoxExtension](_base/configfirefoxextension)
### isMozilla
Defined by: [dojo/\_base/configFirefoxExtension](_base/configfirefoxextension)
### isOpera
Defined by: [dojo/\_base/sniff](_base/sniff)
Version as a Number if client is Opera. undefined otherwise. Corresponds to major detected version.
### isQuirks
Defined by: [dojo/\_base/configFirefoxExtension](_base/configfirefoxextension)
### isSafari
Defined by: [dojo/\_base/sniff](_base/sniff)
Version as a Number if client is Safari or iPhone. undefined otherwise.
### isSpidermonkey
Defined by: [dojo/\_base/configSpidermonkey](_base/configspidermonkey)
### isWebKit
Defined by: [dojo/\_base/sniff](_base/sniff)
Version as a Number if client is a WebKit-derived browser (Konqueror, Safari, Chrome, etc.). undefined otherwise.
### isWii
Defined by: [dojo/\_base/sniff](_base/sniff)
True if client is Wii
### keys
Defined by: [dojo/keys](keys)
Definitions for common key values. Client code should test keyCode against these named constants, as the actual codes can vary by browser.
### locale
Defined by: [dojo/\_base/configFirefoxExtension](_base/configfirefoxextension)
### mouseButtons
Defined by: [dojo/mouse](mouse)
### number
Defined by: [dojo/number](number)
localized formatting and parsing routines for Number
### parser
Defined by: [dojox/mobile/parser](http://dojotoolkit.org/api/1.10/dojox/mobile/parser)
### publish
Defined by: [dojo/robotx](robotx)
### query
Defined by: [dojo/query](query)
### regexp
Defined by: [dojo/regexp](regexp)
Regular expressions and Builder resources
### rpc
Defined by: [dojo/rpc/RpcService](rpc/rpcservice)
### scopeMap
Defined by: [dojo/\_base/kernel](_base/kernel)
### store
Defined by: [dojo/store/Cache](store/cache)
### string
Defined by: [dojo/string](string)
String utilities for Dojo
### subscribe
Defined by: [dojo/robotx](robotx)
### tests
Defined by: [dojo/tests](tests)
D.O.H. Test files for Dojo unit testing.
### toJsonIndentStr
Defined by: [dojo/\_base/json](_base/json)
### touch
Defined by: [dojo/touch](touch)
This module provides unified touch event handlers by exporting press, move, release and cancel which can also run well on desktop. Based on <http://dvcs.w3.org/hg/webevents/raw-file/tip/touchevents.html> Also, if the dojoClick property is set to truthy on a DOM node, [dojo/touch](touch) generates click events immediately for this node and its descendants (except for descendants that have a dojoClick property set to falsy), to avoid the delay before native browser click events, and regardless of whether evt.preventDefault() was called in a touch.press event listener.
### version
Defined by: [dojo/\_base/kernel](_base/kernel)
Version number of the Dojo Toolkit
### window
Defined by: [dojo/window](window)
TODOC
Methods
-------
###
`AdapterRegistry``(returnWrappers)`
Defined by [dojo/AdapterRegistry](adapterregistry)
A registry to make contextual calling/searching easier.
Objects of this class keep list of arrays in the form [name, check, wrap, directReturn] that are used to determine what the contextual result of a set of checked arguments is. All check/wrap functions in this registry should be of the same arity.
| Parameter | Type | Description |
| --- | --- | --- |
| returnWrappers | Boolean | *Optional* |
Examples
--------
### Example 1
```
// create a new registry
require(["dojo/AdapterRegistry"],
function(AdapterRegistry){
var reg = new AdapterRegistry();
reg.register("handleString",
function(str){
return typeof val == "string"
},
function(str){
// do something with the string here
}
);
reg.register("handleArr",
dojo.isArray,
function(arr){
// do something with the array here
}
);
// now we can pass reg.match() *either* an array or a string and
// the value we pass will get handled by the right function
reg.match("someValue"); // will call the first function
reg.match(["someValue"]); // will call the second
});
```
###
`addClass``(node,classStr)`
Defined by [dojo/dom-class](dom-class)
Adds the specified classes to the end of the class list on the passed node. Will not re-apply duplicate classes.
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | String ID or DomNode reference to add a class string too |
| classStr | String | Array | A String class name to add, or several space-separated class names, or an array of class names. |
Examples
--------
### Example 1
Add a class to some node:
```
require(["dojo/dom-class"], function(domClass){
domClass.add("someNode", "anewClass");
});
```
### Example 2
Add two classes at once:
```
require(["dojo/dom-class"], function(domClass){
domClass.add("someNode", "firstClass secondClass");
});
```
### Example 3
Add two classes at once (using array):
```
require(["dojo/dom-class"], function(domClass){
domClass.add("someNode", ["firstClass", "secondClass"]);
});
```
### Example 4
Available in `dojo/NodeList` for multiple additions
```
require(["dojo/query"], function(query){
query("ul > li").addClass("firstLevel");
});
```
###
`addOnLoad``(priority,context,callback)`
Defined by [dojo/ready](ready)
Add a function to execute on DOM content loaded and all requested modules have arrived and been evaluated. In most cases, the `domReady` plug-in should suffice and this method should not be needed.
When called in a non-browser environment, just checks that all requested modules have arrived and been evaluated.
| Parameter | Type | Description |
| --- | --- | --- |
| priority | Integer | *Optional*
The order in which to exec this callback relative to other callbacks, defaults to 1000 |
| context | undefined | The context in which to run execute callback, or a callback if not using context |
| callback | Function | *Optional*
The function to execute. |
Examples
--------
### Example 1
Simple DOM and Modules ready syntax
```
require(["dojo/ready"], function(ready){
ready(function(){ alert("Dom ready!"); });
});
```
### Example 2
Using a priority
```
require(["dojo/ready"], function(ready){
ready(2, function(){ alert("low priority ready!"); })
});
```
### Example 3
Using context
```
require(["dojo/ready"], function(ready){
ready(foo, function(){
// in here, this == foo
});
});
```
### Example 4
Using dojo/hitch style args:
```
require(["dojo/ready"], function(ready){
var foo = { dojoReady: function(){ console.warn(this, "dojo dom and modules ready."); } };
ready(foo, "dojoReady");
});
```
###
`addOnUnload``(obj,functionName)`
Defined by [dojo/\_base/unload](_base/unload)
Registers a function to be triggered when the page unloads. Deprecated, use on(window, "beforeunload", lang.hitch(obj, functionName)) instead.
The first time that addOnUnload is called Dojo will register a page listener to trigger your unload handler with.
In a browser environment, the functions will be triggered during the window.onbeforeunload event. Be careful of doing too much work in an unload handler. onbeforeunload can be triggered if a link to download a file is clicked, or if the link is a javascript: link. In these cases, the onbeforeunload event fires, but the document is not actually destroyed. So be careful about doing destructive operations in a dojo.addOnUnload callback.
Further note that calling dojo.addOnUnload will prevent browsers from using a "fast back" cache to make page loading via back button instantaneous.
| Parameter | Type | Description |
| --- | --- | --- |
| obj | Object? | Function | *Optional* |
| functionName | String | Function | *Optional* |
Examples
--------
### Example 1
```
var afunc = function() {console.log("global function");};
require(["dojo/_base/unload"], function(unload) {
var foo = {bar: function(){ console.log("bar unloading...");},
data: "mydata"};
unload.addOnUnload(afunc);
unload.addOnUnload(foo, "bar");
unload.addOnUnload(foo, function(){console.log("", this.data);});
});
```
###
`addOnWindowUnload``(obj,functionName)`
Defined by [dojo/\_base/configFirefoxExtension](_base/configfirefoxextension)
registers a function to be triggered when window.onunload fires. Be careful trying to modify the DOM or access JavaScript properties during this phase of page unloading: they may not always be available. Consider dojo.addOnUnload() if you need to modify the DOM or do heavy JavaScript work.
| Parameter | Type | Description |
| --- | --- | --- |
| obj | Object | *Optional* |
| functionName | String | Function | *Optional* |
Examples
--------
### Example 1
```
dojo.addOnWindowUnload(functionPointer)
dojo.addOnWindowUnload(object, "functionName")
dojo.addOnWindowUnload(object, function(){ /* ... */});
```
###
`anim``(node,properties,duration,easing,onEnd,delay)`
Defined by [dojo/\_base/fx](_base/fx)
A simpler interface to `animateProperty()`, also returns an instance of `Animation` but begins the animation immediately, unlike nearly every other Dojo animation API.
Simpler (but somewhat less powerful) version of `animateProperty`. It uses defaults for many basic properties and allows for positional parameters to be used in place of the packed "property bag" which is used for other Dojo animation methods.
The `Animation` object returned will be already playing, so calling play() on it again is (usually) a no-op.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | a DOM node or the id of a node to animate CSS properties on |
| properties | Object | |
| duration | Integer | *Optional*
The number of milliseconds over which the animation should run. Defaults to the global animation default duration (350ms). |
| easing | Function | *Optional*
An easing function over which to calculate acceleration and deceleration of the animation through its duration. A default easing algorithm is provided, but you may plug in any you wish. A large selection of easing algorithms are available in `dojo/fx/easing`. |
| onEnd | Function | *Optional*
A function to be called when the animation finishes running. |
| delay | Integer | *Optional*
The number of milliseconds to delay beginning the animation by. The default is 0. |
**Returns:** undefined
Examples
--------
### Example 1
Fade out a node
```
basefx.anim("id", { opacity: 0 });
```
### Example 2
Fade out a node over a full second
```
basefx.anim("id", { opacity: 0 }, 1000);
```
###
`animateProperty``(args)`
Defined by [dojo/\_base/fx](_base/fx)
Returns an animation that will transition the properties of node defined in `args` depending how they are defined in `args.properties`
Foundation of most [dojo/\_base/fx](_base/fx) animations. It takes an object of "properties" corresponding to style properties, and animates them in parallel over a set duration.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* properties (Object, optional): A hash map of style properties to Objects describing the transition, such as the properties of \_Line with an additional 'units' property
* node (DOMNode|String): The node referenced in the animation
* duration (Integer, optional): Duration of the animation in milliseconds.
* easing (Function, optional): An easing function.
|
**Returns:** instance
Examples
--------
### Example 1
A simple animation that changes the width of the specified node.
```
basefx.animateProperty({
node: "nodeId",
properties: { width: 400 },
}).play();
```
Dojo figures out the start value for the width and converts the
integer specified for the width to the more expressive but verbose form `{ width: { end: '400', units: 'px' } }` which you can also specify directly. Defaults to 'px' if omitted.
### Example 2
Animate width, height, and padding over 2 seconds... the pedantic way:
```
basefx.animateProperty({ node: node, duration:2000,
properties: {
width: { start: '200', end: '400', units:"px" },
height: { start:'200', end: '400', units:"px" },
paddingTop: { start:'5', end:'50', units:"px" }
}
}).play();
```
Note 'paddingTop' is used over 'padding-top'. Multi-name CSS properties
are written using "mixed case", as the hyphen is illegal as an object key.
### Example 3
Plug in a different easing function and register a callback for when the animation ends. Easing functions accept values between zero and one and return a value on that basis. In this case, an exponential-in curve.
```
basefx.animateProperty({
node: "nodeId",
// dojo figures out the start value
properties: { width: { end: 400 } },
easing: function(n){
return (n==0) ? 0 : Math.pow(2, 10 * (n - 1));
},
onEnd: function(node){
// called when the animation finishes. The animation
// target is passed to this function
}
}).play(500); // delay playing half a second
```
### Example 4
Like all `Animation`s, animateProperty returns a handle to the Animation instance, which fires the events common to Dojo FX. Use `aspect.after` to access these events outside of the Animation definition:
```
var anim = basefx.animateProperty({
node:"someId",
properties:{
width:400, height:500
}
});
aspect.after(anim, "onEnd", function(){
console.log("animation ended");
}, true);
// play the animation now:
anim.play();
```
### Example 5
Each property can be a function whose return value is substituted along. Additionally, each measurement (eg: start, end) can be a function. The node reference is passed directly to callbacks.
```
basefx.animateProperty({
node:"mine",
properties:{
height:function(node){
// shrink this node by 50%
return domGeom.position(node).h / 2
},
width:{
start:function(node){ return 100; },
end:function(node){ return 200; }
}
}
}).play();
```
###
`Animation``(args)`
Defined by [dojo/\_base/fx](_base/fx)
A generic animation class that fires callbacks into its handlers object at various states.
A generic animation class that fires callbacks into its handlers object at various states. Nearly all dojo animation functions return an instance of this method, usually without calling the .play() method beforehand. Therefore, you will likely need to call .play() on instances of `Animation` when one is returned.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | The 'magic argument', mixing all the properties into this animation instance. |
###
`attr``(node,name,value)`
Defined by [dojo/\_base/html](_base/html)
Gets or sets an attribute on an HTML element.
Handles normalized getting and setting of attributes on DOM Nodes. If 2 arguments are passed, and a the second argument is a string, acts as a getter.
If a third argument is passed, or if the second argument is a map of attributes, acts as a setter.
When passing functions as values, note that they will not be directly assigned to slots on the node, but rather the default behavior will be removed and the new behavior will be added using `dojo.connect()`, meaning that event handler properties will be normalized and that some caveats with regards to non-standard behaviors for onsubmit apply. Namely that you should cancel form submission using `dojo.stopEvent()` on the passed event object instead of returning a boolean value from the handler itself.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to get or set the attribute on |
| name | String | Object | the name of the attribute to get or set. |
| value | String | *Optional*
The value to set for the attribute |
**Returns:** any | undefined
when used as a getter, the value of the requested attribute or null if that attribute does not have a specified or default value;
when used as a setter, the DOM node
Examples
--------
### Example 1
```
// get the current value of the "foo" attribute on a node
dojo.attr(dojo.byId("nodeId"), "foo");
// or we can just pass the id:
dojo.attr("nodeId", "foo");
```
### Example 2
```
// use attr() to set the tab index
dojo.attr("nodeId", "tabIndex", 3);
```
### Example 3
Set multiple values at once, including event handlers:
```
dojo.attr("formId", {
"foo": "bar",
"tabIndex": -1,
"method": "POST",
"onsubmit": function(e){
// stop submitting the form. Note that the IE behavior
// of returning true or false will have no effect here
// since our handler is connect()ed to the built-in
// onsubmit behavior and so we need to use
// dojo.stopEvent() to ensure that the submission
// doesn't proceed.
dojo.stopEvent(e);
// submit the form with Ajax
dojo.xhrPost({ form: "formId" });
}
});
```
### Example 4
Style is s special case: Only set with an object hash of styles
```
dojo.attr("someNode",{
id:"bar",
style:{
width:"200px", height:"100px", color:"#000"
}
});
```
### Example 5
Again, only set style as an object hash of styles:
```
var obj = { color:"#fff", backgroundColor:"#000" };
dojo.attr("someNode", "style", obj);
// though shorter to use `dojo.style()` in this case:
dojo.style("someNode", obj);
```
###
`blendColors``(start,end,weight,obj)`
Defined by [dojo/\_base/Color](_base/color)
Blend colors end and start with weight from 0 to 1, 0.5 being a 50/50 blend, can reuse a previously allocated Color object for the result
| Parameter | Type | Description |
| --- | --- | --- |
| start | [dojo/\_base/Color](_base/color) | |
| end | [dojo/\_base/Color](_base/color) | |
| weight | Number | |
| obj | [dojo/\_base/Color](_base/color) | *Optional* |
**Returns:** undefined
###
`body``(doc)`
Defined by [dojo/\_base/window](_base/window)
Return the body element of the specified document or of dojo/\_base/window::doc.
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | *Optional* |
**Returns:** undefined
Examples
--------
### Example 1
```
win.body().appendChild(dojo.doc.createElement('div'));
```
###
`byId``(id,doc)`
Defined by [dojo/dom](dom)
Returns DOM node with matching `id` attribute or falsy value (ex: null or undefined) if not found. If `id` is a DomNode, this function is a no-op.
| Parameter | Type | Description |
| --- | --- | --- |
| id | String | DOMNode | A string to match an HTML id attribute or a reference to a DOM Node |
| doc | Document | *Optional*
Document to work in. Defaults to the current value of dojo/\_base/window.doc. Can be used to retrieve node references from other documents. |
**Returns:** instance
Examples
--------
### Example 1
Look up a node by ID:
```
require(["dojo/dom"], function(dom){
var n = dom.byId("foo");
});
```
### Example 2
Check if a node exists, and use it.
```
require(["dojo/dom"], function(dom){
var n = dom.byId("bar");
if(n){ doStuff() ... }
});
```
### Example 3
Allow string or DomNode references to be passed to a custom function:
```
require(["dojo/dom"], function(dom){
var foo = function(nodeOrId){
nodeOrId = dom.byId(nodeOrId);
// ... more stuff
}
});
```
###
`cache``(module,url,value)`
Defined by [dojo/text](text)
A getter and setter for storing the string content associated with the module and url arguments.
If module is a string that contains slashes, then it is interpretted as a fully resolved path (typically a result returned by require.toUrl), and url should not be provided. This is the preferred signature. If module is a string that does not contain slashes, then url must also be provided and module and url are used to call `dojo.moduleUrl()` to generate a module URL. This signature is deprecated. If value is specified, the cache value for the moduleUrl will be set to that value. Otherwise, dojo.cache will fetch the moduleUrl and store it in its internal cache and return that cached value for the URL. To clear a cache value pass null for value. Since XMLHttpRequest (XHR) is used to fetch the the URL contents, only modules on the same domain of the page can use this capability. The build system can inline the cache values though, to allow for xdomain hosting.
| Parameter | Type | Description |
| --- | --- | --- |
| module | String | Object | dojo/cldr/supplemental |
| url | String | The rest of the path to append to the path derived from the module argument. If module is an object, then this second argument should be the "value" argument instead. |
| value | String | Object | *Optional*
If a String, the value to use in the cache for the module/url combination. If an Object, it can have two properties: value and sanitize. The value property should be the value to use in the cache, and sanitize can be set to true or false, to indicate if XML declarations should be removed from the value and if the HTML inside a body tag in the value should be extracted as the real value. The value argument or the value property on the value argument are usually only used by the build system as it inlines cache content. |
**Returns:** undefined | null
Examples
--------
### Example 1
To ask dojo.cache to fetch content and store it in the cache (the dojo["cache"] style of call is used to avoid an issue with the build system erroneously trying to intern this example. To get the build system to intern your dojo.cache calls, use the "dojo.cache" style of call):
```
//If template.html contains "<h1>Hello</h1>" that will be
//the value for the text variable.
//Note: This is pre-AMD, deprecated syntax
var text = dojo["cache"]("my.module", "template.html");
```
### Example 2
To ask dojo.cache to fetch content and store it in the cache, and sanitize the input (the dojo["cache"] style of call is used to avoid an issue with the build system erroneously trying to intern this example. To get the build system to intern your dojo.cache calls, use the "dojo.cache" style of call):
```
//If template.html contains "<html><body><h1>Hello</h1></body></html>", the
//text variable will contain just "<h1>Hello</h1>".
//Note: This is pre-AMD, deprecated syntax
var text = dojo["cache"]("my.module", "template.html", {sanitize: true});
```
### Example 3
Same example as previous, but demonstrates how an object can be passed in as the first argument, then the value argument can then be the second argument.
```
//If template.html contains "<html><body><h1>Hello</h1></body></html>", the
//text variable will contain just "<h1>Hello</h1>".
//Note: This is pre-AMD, deprecated syntax
var text = dojo["cache"](new dojo._Url("my/module/template.html"), {sanitize: true});
```
###
`clearCache``()`
Defined by [dojo/\_base/array](_base/array)
###
`Color``(color)`
Defined by [dojo/\_base/Color](_base/color)
Takes a named string, hex string, array of rgb or rgba values, an object with r, g, b, and a properties, or another `Color` object and creates a new Color instance to work from.
| Parameter | Type | Description |
| --- | --- | --- |
| color | Array | String | Object | |
Examples
--------
### Example 1
Work with a Color instance:
```
require(["dojo/_base/color"], function(Color){
var c = new Color();
c.setColor([0,0,0]); // black
var hex = c.toHex(); // #000000
});
```
### Example 2
Work with a node's color:
```
require(["dojo/_base/color", "dojo/dom-style"], function(Color, domStyle){
var color = domStyle("someNode", "backgroundColor");
var n = new Color(color);
// adjust the color some
n.r *= .5;
console.log(n.toString()); // rgb(128, 255, 255);
});
```
###
`colorFromArray``(a,obj)`
Defined by [dojo/\_base/Color](_base/color)
Builds a `Color` from a 3 or 4 element array, mapping each element in sequence to the rgb(a) values of the color.
| Parameter | Type | Description |
| --- | --- | --- |
| a | Array | |
| obj | [dojo/\_base/Color](_base/color) | *Optional* |
**Returns:** any | undefined
A Color object. If obj is passed, it will be the return value.
Examples
--------
### Example 1
```
require(["dojo/_base/color"], function(Color){
var myColor = new Color().fromArray([237,237,237,0.5]); // grey, 50% alpha
});
```
###
`colorFromHex``(color,obj)`
Defined by [dojo/\_base/Color](_base/color)
Converts a hex string with a '#' prefix to a color object. Supports 12-bit #rgb shorthand. Optionally accepts a `Color` object to update with the parsed value.
| Parameter | Type | Description |
| --- | --- | --- |
| color | String | |
| obj | [dojo/\_base/Color](_base/color) | *Optional* |
**Returns:** any
A Color object. If obj is passed, it will be the return value.
Examples
--------
### Example 1
```
require(["dojo/_base/color"], function(Color){
var thing = new Color().fromHex("#ededed"); // grey, longhand
var thing2 = new Color().fromHex("#000"); // black, shorthand
});
```
###
`colorFromRgb``(color,obj)`
Defined by [dojo/colors](colors)
get rgb(a) array from css-style color declarations
this function can handle all 4 CSS3 Color Module formats: rgb, rgba, hsl, hsla, including rgb(a) with percentage values.
| Parameter | Type | Description |
| --- | --- | --- |
| color | String | |
| obj | [dojo/\_base/Color](_base/color) | *Optional* |
**Returns:** null
###
`colorFromString``(str,obj)`
Defined by [dojo/\_base/Color](_base/color)
Parses `str` for a color value. Accepts hex, rgb, and rgba style color values.
Acceptable input values for str may include arrays of any form accepted by dojo.colorFromArray, hex strings such as "#aaaaaa", or rgb or rgba strings such as "rgb(133, 200, 16)" or "rgba(10, 10, 10, 50)"
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | |
| obj | [dojo/\_base/Color](_base/color) | *Optional* |
**Returns:** any
A Color object. If obj is passed, it will be the return value.
###
`connect``(obj,event,context,method,dontFix)`
Defined by [dojo/\_base/connect](_base/connect)
`dojo.connect` is a deprecated event handling and delegation method in Dojo. It allows one function to "listen in" on the execution of any other, triggering the second whenever the first is called. Many listeners may be attached to a function, and source functions may be either regular function calls or DOM events.
Connects listeners to actions, so that after event fires, a listener is called with the same arguments passed to the original function.
Since `dojo.connect` allows the source of events to be either a "regular" JavaScript function or a DOM event, it provides a uniform interface for listening to all the types of events that an application is likely to deal with though a single, unified interface. DOM programmers may want to think of it as "addEventListener for everything and anything".
When setting up a connection, the `event` parameter must be a string that is the name of the method/event to be listened for. If `obj` is null, `kernel.global` is assumed, meaning that connections to global methods are supported but also that you may inadvertently connect to a global by passing an incorrect object name or invalid reference.
`dojo.connect` generally is forgiving. If you pass the name of a function or method that does not yet exist on `obj`, connect will not fail, but will instead set up a stub method. Similarly, null arguments may simply be omitted such that fewer than 4 arguments may be required to set up a connection See the examples for details.
The return value is a handle that is needed to remove this connection with `dojo.disconnect`.
| Parameter | Type | Description |
| --- | --- | --- |
| obj | Object | *Optional*
The source object for the event function. Defaults to `kernel.global` if null. If obj is a DOM node, the connection is delegated to the DOM event manager (unless dontFix is true). |
| event | String | String name of the event function in obj. I.e. identifies a property `obj[event]`. |
| context | Object | null | The object that method will receive as "this". If context is null and method is a function, then method inherits the context of event. If method is a string then context must be the source object object for method (context[method]). If context is null, kernel.global is used. |
| method | String | Function | A function reference, or name of a function in context. The function identified by method fires after event does. method receives the same arguments as the event. See context argument comments for information on method's scope. |
| dontFix | Boolean | *Optional*
If obj is a DOM node, set dontFix to true to prevent delegation of this connection to the DOM event manager. |
**Returns:** undefined
Examples
--------
### Example 1
When obj.onchange(), do ui.update():
```
dojo.connect(obj, "onchange", ui, "update");
dojo.connect(obj, "onchange", ui, ui.update); // same
```
### Example 2
Using return value for disconnect:
```
var link = dojo.connect(obj, "onchange", ui, "update");
...
dojo.disconnect(link);
```
### Example 3
When onglobalevent executes, watcher.handler is invoked:
```
dojo.connect(null, "onglobalevent", watcher, "handler");
```
### Example 4
When ob.onCustomEvent executes, customEventHandler is invoked:
```
dojo.connect(ob, "onCustomEvent", null, "customEventHandler");
dojo.connect(ob, "onCustomEvent", "customEventHandler"); // same
```
### Example 5
When ob.onCustomEvent executes, customEventHandler is invoked with the same scope (this):
```
dojo.connect(ob, "onCustomEvent", null, customEventHandler);
dojo.connect(ob, "onCustomEvent", customEventHandler); // same
```
### Example 6
When globalEvent executes, globalHandler is invoked with the same scope (this):
```
dojo.connect(null, "globalEvent", null, globalHandler);
dojo.connect("globalEvent", globalHandler); // same
```
###
`contentBox``(node,box)`
Defined by [dojo/\_base/html](_base/html)
Getter/setter for the content-box of node.
Returns an object in the expected format of box (regardless if box is passed). The object might look like: `{ l: 50, t: 200, w: 300: h: 150 }` for a node offset from its parent 50px to the left, 200px from the top with a content width of 300px and a content-height of 150px. Note that the content box may have a much larger border or margin box, depending on the box model currently in use and CSS values set/inherited for node. While the getter will return top and left values, the setter only accepts setting the width and height.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DomNode | String | id or reference to DOM Node to get/set box for |
| box | Object | *Optional*
If passed, denotes that dojo.contentBox() should update/set the content box for node. Box is an object in the above format, but only w (width) and h (height) are supported. All properties are optional if passed. |
**Returns:** undefined
###
`cookie``(name,value,props)`
Defined by [dojo/cookie](cookie)
Get or set a cookie.
If one argument is passed, returns the value of the cookie For two or more arguments, acts as a setter.
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | Name of the cookie |
| value | String | *Optional*
Value for the cookie |
| props | Object | *Optional*
Properties for the cookie |
**Returns:** undefined
Examples
--------
### Example 1
set a cookie with the JSON-serialized contents of an object which will expire 5 days from now:
```
require(["dojo/cookie", "dojo/json"], function(cookie, json){
cookie("configObj", json.stringify(config, {expires: 5 }));
});
```
### Example 2
de-serialize a cookie back into a JavaScript object:
```
require(["dojo/cookie", "dojo/json"], function(cookie, json){
config = json.parse(cookie("configObj"));
});
```
### Example 3
delete a cookie:
```
require(["dojo/cookie"], function(cookie){
cookie("configObj", null, {expires: -1});
});
```
###
`coords``(node,includeScroll)`
Defined by [dojo/\_base/html](_base/html)
Deprecated: Use position() for border-box x/y/w/h or marginBox() for margin-box w/h/l/t.
Returns an object that measures margin-box (w)idth/(h)eight and absolute position x/y of the border-box. Also returned is computed (l)eft and (t)op values in pixels from the node's offsetParent as returned from marginBox(). Return value will be in the form:
```
{ l: 50, t: 200, w: 300: h: 150, x: 100, y: 300 }
```
Does not act as a setter. If includeScroll is passed, the x and
y params are affected as one would expect in dojo.position().
| Parameter | Type | Description |
| --- | --- | --- |
| node | DomNode | String | |
| includeScroll | Boolean | *Optional* |
**Returns:** undefined
###
`create``(tag,attrs,refNode,pos)`
Defined by [dojo/dom-construct](dom-construct)
Create an element, allowing for optional attribute decoration and placement.
A DOM Element creation function. A shorthand method for creating a node or a fragment, and allowing for a convenient optional attribute setting step, as well as an optional DOM placement reference.
Attributes are set by passing the optional object through `dojo.setAttr`. See `dojo.setAttr` for noted caveats and nuances, and API if applicable.
Placement is done via `dojo.place`, assuming the new node to be the action node, passing along the optional reference node and position.
| Parameter | Type | Description |
| --- | --- | --- |
| tag | DOMNode | String | A string of the element to create (eg: "div", "a", "p", "li", "script", "br"), or an existing DOM node to process. |
| attrs | Object | An object-hash of attributes to set on the newly created node. Can be null, if you don't want to set any attributes/styles. See: `dojo.setAttr` for a description of available attributes. |
| refNode | DOMNode | String | *Optional*
Optional reference node. Used by `dojo.place` to place the newly created node somewhere in the dom relative to refNode. Can be a DomNode reference or String ID of a node. |
| pos | String | *Optional*
Optional positional reference. Defaults to "last" by way of `dojo.place`, though can be set to "first","after","before","last", "replace" or "only" to further control the placement of the new node relative to the refNode. 'refNode' is required if a 'pos' is specified. |
**Returns:** undefined
Examples
--------
### Example 1
Create a DIV:
```
require(["dojo/dom-construct"], function(domConstruct){
var n = domConstruct.create("div");
});
```
### Example 2
Create a DIV with content:
```
require(["dojo/dom-construct"], function(domConstruct){
var n = domConstruct.create("div", { innerHTML:"<p>hi</p>" });
});
```
### Example 3
Place a new DIV in the BODY, with no attributes set
```
require(["dojo/dom-construct"], function(domConstruct){
var n = domConstruct.create("div", null, dojo.body());
});
```
### Example 4
Create an UL, and populate it with LI's. Place the list as the first-child of a node with id="someId":
```
require(["dojo/dom-construct", "dojo/_base/array"],
function(domConstruct, arrayUtil){
var ul = domConstruct.create("ul", null, "someId", "first");
var items = ["one", "two", "three", "four"];
arrayUtil.forEach(items, function(data){
domConstruct.create("li", { innerHTML: data }, ul);
});
});
```
### Example 5
Create an anchor, with an href. Place in BODY:
```
require(["dojo/dom-construct"], function(domConstruct){
domConstruct.create("a", { href:"foo.html", title:"Goto FOO!" }, dojo.body());
});
```
###
`declare``(className,superclass,props)`
Defined by [dojo/\_base/declare](_base/declare)
Create a feature-rich constructor from compact notation.
Create a constructor using a compact notation for inheritance and prototype extension.
Mixin ancestors provide a type of multiple inheritance. Prototypes of mixin ancestors are copied to the new class: changes to mixin prototypes will not affect classes to which they have been mixed in.
Ancestors can be compound classes created by this version of declare(). In complex cases all base classes are going to be linearized according to C3 MRO algorithm (see <http://www.python.org/download/releases/2.3/mro/> for more details).
"className" is cached in "declaredClass" property of the new class, if it was supplied. The immediate super class will be cached in "superclass" property of the new class.
Methods in "props" will be copied and modified: "nom" property (the declared name of the method) will be added to all copied functions to help identify them for the internal machinery. Be very careful, while reusing methods: if you use the same function under different names, it can produce errors in some cases.
It is possible to use constructors created "manually" (without declare()) as bases. They will be called as usual during the creation of an instance, their methods will be chained, and even called by "this.inherited()".
Special property "-chains-" governs how to chain methods. It is a dictionary, which uses method names as keys, and hint strings as values. If a hint string is "after", this method will be called after methods of its base classes. If a hint string is "before", this method will be called before methods of its base classes.
If "constructor" is not mentioned in "-chains-" property, it will be chained using the legacy mode: using "after" chaining, calling preamble() method before each constructor, if available, and calling postscript() after all constructors were executed. If the hint is "after", it is chained as a regular method, but postscript() will be called after the chain of constructors. "constructor" cannot be chained "before", but it allows a special hint string: "manual", which means that constructors are not going to be chained in any way, and programmer will call them manually using this.inherited(). In the latter case postscript() will be called after the construction.
All chaining hints are "inherited" from base classes and potentially can be overridden. Be very careful when overriding hints! Make sure that all chained methods can work in a proposed manner of chaining.
Once a method was chained, it is impossible to unchain it. The only exception is "constructor". You don't need to define a method in order to supply a chaining hint.
If a method is chained, it cannot use this.inherited() because all other methods in the hierarchy will be called automatically.
Usually constructors and initializers of any kind are chained using "after" and destructors of any kind are chained as "before". Note that chaining assumes that chained methods do not return any value: any returned value will be discarded.
| Parameter | Type | Description |
| --- | --- | --- |
| className | String | *Optional*
The optional name of the constructor (loosely, a "class") stored in the "declaredClass" property in the created prototype. It will be used as a global name for a created constructor. |
| superclass | Function | Function[] | May be null, a Function, or an Array of Functions. This argument specifies a list of bases (the left-most one is the most deepest base). |
| props | Object | An object whose properties are copied to the created prototype. Add an instance-initialization function by making it a property named "constructor". |
**Returns:** [dojo/\_base/declare.\_\_DeclareCreatedObject](_base/declare.__declarecreatedobject) | undefined
New constructor function.
Examples
--------
### Example 1
```
declare("my.classes.bar", my.classes.foo, {
// properties to be added to the class prototype
someValue: 2,
// initialization function
constructor: function(){
this.myComplicatedObject = new ReallyComplicatedObject();
},
// other functions
someMethod: function(){
doStuff();
}
});
```
### Example 2
```
var MyBase = declare(null, {
// constructor, properties, and methods go here
// ...
});
var MyClass1 = declare(MyBase, {
// constructor, properties, and methods go here
// ...
});
var MyClass2 = declare(MyBase, {
// constructor, properties, and methods go here
// ...
});
var MyDiamond = declare([MyClass1, MyClass2], {
// constructor, properties, and methods go here
// ...
});
```
### Example 3
```
var F = function(){ console.log("raw constructor"); };
F.prototype.method = function(){
console.log("raw method");
};
var A = declare(F, {
constructor: function(){
console.log("A.constructor");
},
method: function(){
console.log("before calling F.method...");
this.inherited(arguments);
console.log("...back in A");
}
});
new A().method();
// will print:
// raw constructor
// A.constructor
// before calling F.method...
// raw method
// ...back in A
```
### Example 4
```
var A = declare(null, {
"-chains-": {
destroy: "before"
}
});
var B = declare(A, {
constructor: function(){
console.log("B.constructor");
},
destroy: function(){
console.log("B.destroy");
}
});
var C = declare(B, {
constructor: function(){
console.log("C.constructor");
},
destroy: function(){
console.log("C.destroy");
}
});
new C().destroy();
// prints:
// B.constructor
// C.constructor
// C.destroy
// B.destroy
```
### Example 5
```
var A = declare(null, {
"-chains-": {
constructor: "manual"
}
});
var B = declare(A, {
constructor: function(){
// ...
// call the base constructor with new parameters
this.inherited(arguments, [1, 2, 3]);
// ...
}
});
```
### Example 6
```
var A = declare(null, {
"-chains-": {
m1: "before"
},
m1: function(){
console.log("A.m1");
},
m2: function(){
console.log("A.m2");
}
});
var B = declare(A, {
"-chains-": {
m2: "after"
},
m1: function(){
console.log("B.m1");
},
m2: function(){
console.log("B.m2");
}
});
var x = new B();
x.m1();
// prints:
// B.m1
// A.m1
x.m2();
// prints:
// A.m2
// B.m2
```
###
`Deferred``(canceller)`
Defined by [dojo/\_base/Deferred](_base/deferred)
Deprecated. This module defines the legacy dojo/\_base/Deferred API. New code should use dojo/Deferred instead.
The Deferred API is based on the concept of promises that provide a generic interface into the eventual completion of an asynchronous action. The motivation for promises fundamentally is about creating a separation of concerns that allows one to achieve the same type of call patterns and logical data flow in asynchronous code as can be achieved in synchronous code. Promises allows one to be able to call a function purely with arguments needed for execution, without conflating the call with concerns of whether it is sync or async. One shouldn't need to alter a call's arguments if the implementation switches from sync to async (or vice versa). By having async functions return promises, the concerns of making the call are separated from the concerns of asynchronous interaction (which are handled by the promise).
The Deferred is a type of promise that provides methods for fulfilling the promise with a successful result or an error. The most important method for working with Dojo's promises is the then() method, which follows the CommonJS proposed promise API. An example of using a Dojo promise:
```
var resultingPromise = someAsyncOperation.then(function(result){
... handle result ...
},
function(error){
... handle error ...
});
```
The .then() call returns a new promise that represents the result of the execution of the callback. The callbacks will never affect the original promises value.
The Deferred instances also provide the following functions for backwards compatibility:
* addCallback(handler)
* addErrback(handler)
* callback(result)
* errback(result)
Callbacks are allowed to return promises themselves, so you can build complicated sequences of events with ease.
The creator of the Deferred may specify a canceller. The canceller is a function that will be called if Deferred.cancel is called before the Deferred fires. You can use this to implement clean aborting of an XMLHttpRequest, etc. Note that cancel will fire the deferred with a CancelledError (unless your canceller returns another kind of error), so the errbacks should be prepared to handle that error for cancellable Deferreds.
| Parameter | Type | Description |
| --- | --- | --- |
| canceller | Function | *Optional* |
Examples
--------
### Example 1
```
var deferred = new Deferred();
setTimeout(function(){ deferred.callback({success: true}); }, 1000);
return deferred;
```
### Example 2
Deferred objects are often used when making code asynchronous. It may be easiest to write functions in a synchronous manner and then split code using a deferred to trigger a response to a long-lived operation. For example, instead of register a callback function to denote when a rendering operation completes, the function can simply return a deferred:
```
// callback style:
function renderLotsOfData(data, callback){
var success = false
try{
for(var x in data){
renderDataitem(data[x]);
}
success = true;
}catch(e){ }
if(callback){
callback(success);
}
}
// using callback style
renderLotsOfData(someDataObj, function(success){
// handles success or failure
if(!success){
promptUserToRecover();
}
});
// NOTE: no way to add another callback here!!
```
### Example 3
Using a Deferred doesn't simplify the sending code any, but it provides a standard interface for callers and senders alike, providing both with a simple way to service multiple callbacks for an operation and freeing both sides from worrying about details such as "did this get called already?". With Deferreds, new callbacks can be added at any time.
```
// Deferred style:
function renderLotsOfData(data){
var d = new Deferred();
try{
for(var x in data){
renderDataitem(data[x]);
}
d.callback(true);
}catch(e){
d.errback(new Error("rendering failed"));
}
return d;
}
// using Deferred style
renderLotsOfData(someDataObj).then(null, function(){
promptUserToRecover();
});
// NOTE: addErrback and addCallback both return the Deferred
// again, so we could chain adding callbacks or save the
// deferred for later should we need to be notified again.
```
### Example 4
In this example, renderLotsOfData is synchronous and so both versions are pretty artificial. Putting the data display on a timeout helps show why Deferreds rock:
```
// Deferred style and async func
function renderLotsOfData(data){
var d = new Deferred();
setTimeout(function(){
try{
for(var x in data){
renderDataitem(data[x]);
}
d.callback(true);
}catch(e){
d.errback(new Error("rendering failed"));
}
}, 100);
return d;
}
// using Deferred style
renderLotsOfData(someDataObj).then(null, function(){
promptUserToRecover();
});
```
Note that the caller doesn't have to change his code at all to handle the asynchronous case.
###
`DeferredList``(list,fireOnOneCallback,fireOnOneErrback,consumeErrors,canceller)`
Defined by [dojo/DeferredList](deferredlist)
Deprecated, use dojo/promise/all instead. Provides event handling for a group of Deferred objects.
DeferredList takes an array of existing deferreds and returns a new deferred of its own this new deferred will typically have its callback fired when all of the deferreds in the given list have fired their own deferreds. The parameters `fireOnOneCallback` and fireOnOneErrback, will fire before all the deferreds as appropriate
| Parameter | Type | Description |
| --- | --- | --- |
| list | Array | The list of deferreds to be synchronizied with this DeferredList |
| fireOnOneCallback | Boolean | *Optional*
Will cause the DeferredLists callback to be fired as soon as any of the deferreds in its list have been fired instead of waiting until the entire list has finished |
| fireOnOneErrback | Boolean | *Optional* |
| consumeErrors | Boolean | *Optional* |
| canceller | Function | *Optional*
A deferred canceller function, see dojo.Deferred |
###
`deprecated``(behaviour,extra,removal)`
Defined by [dojo/\_base/kernel](_base/kernel)
Log a debug message to indicate that a behavior has been deprecated.
| Parameter | Type | Description |
| --- | --- | --- |
| behaviour | String | The API or behavior being deprecated. Usually in the form of "myApp.someFunction()". |
| extra | String | *Optional*
Text to append to the message. Often provides advice on a new function or facility to achieve the same goal during the deprecation period. |
| removal | String | *Optional*
Text to indicate when in the future the behavior will be removed. Usually a version number. |
Examples
--------
### Example 1
```
dojo.deprecated("myApp.getTemp()", "use myApp.getLocaleTemp() instead", "1.0");
```
###
`destroy``(node)`
Defined by [dojo/\_base/html](_base/html)
| Parameter | Type | Description |
| --- | --- | --- |
| node | undefined | |
###
`disconnect``(handle)`
Defined by [dojo/\_base/connect](_base/connect)
Remove a link created by dojo.connect.
Removes the connection between event and the method referenced by handle.
| Parameter | Type | Description |
| --- | --- | --- |
| handle | Handle | the return value of the dojo.connect call that created the connection. |
###
`docScroll``(doc)`
Defined by [dojo/dom-geometry](dom-geometry)
Returns an object with {node, x, y} with corresponding offsets.
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | *Optional*
Optional document to query. If unspecified, use win.doc. |
**Returns:** Object | undefined
###
`empty``(node)`
Defined by [dojo/\_base/html](_base/html)
| Parameter | Type | Description |
| --- | --- | --- |
| node | undefined | |
###
`eval``(scriptText)`
Defined by [dojo/\_base/kernel](_base/kernel)
A legacy method created for use exclusively by internal Dojo methods. Do not use this method directly unless you understand its possibly-different implications on the platforms your are targeting.
Makes an attempt to evaluate scriptText in the global scope. The function works correctly for browsers that support indirect eval.
As usual, IE does not. On IE, the only way to implement global eval is to use execScript. Unfortunately, execScript does not return a value and breaks some current usages of dojo.eval. This implementation uses the technique of executing eval in the scope of a function that is a single scope frame below the global scope; thereby coming close to the global scope. Note carefully that
dojo.eval("var pi = 3.14;");
will define global pi in non-IE environments, but define pi only in a temporary local scope for IE. If you want to define a global variable using dojo.eval, write something like
dojo.eval("window.pi = 3.14;")
| Parameter | Type | Description |
| --- | --- | --- |
| scriptText | undefined | The text to evaluation. |
**Returns:** any
The result of the evaluation. Often `undefined`
###
`every``(arr,callback,thisObject)`
Defined by [dojo/\_base/array](_base/array)
Determines whether or not every item in arr satisfies the condition implemented by callback.
This function corresponds to the JavaScript 1.6 Array.every() method, with one difference: when run over sparse arrays, this implementation passes the "holes" in the sparse array to the callback function with a value of undefined. JavaScript 1.6's every skips the holes in the sparse array. For more details, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/every>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | String | the array to iterate on. If a string, operates on individual characters. |
| callback | Function | String | a function is invoked with three arguments: item, index, and array and returns true if the condition is met. |
| thisObject | Object | *Optional*
may be used to scope the call to callback |
**Returns:** Boolean
Examples
--------
### Example 1
```
// returns false
array.every([1, 2, 3, 4], function(item){ return item>1; });
```
### Example 2
```
// returns true
array.every([1, 2, 3, 4], function(item){ return item>0; });
```
###
`exit``(exitcode)`
Defined by [dojo/\_base/configSpidermonkey](_base/configspidermonkey)
| Parameter | Type | Description |
| --- | --- | --- |
| exitcode | undefined | |
###
`experimental``(moduleName,extra)`
Defined by [dojo/\_base/kernel](_base/kernel)
Marks code as experimental.
This can be used to mark a function, file, or module as experimental. Experimental code is not ready to be used, and the APIs are subject to change without notice. Experimental code may be completed deleted without going through the normal deprecation process.
| Parameter | Type | Description |
| --- | --- | --- |
| moduleName | String | The name of a module, or the name of a module file or a specific function |
| extra | String | *Optional*
some additional message for the user |
Examples
--------
### Example 1
```
dojo.experimental("dojo.data.Result");
```
### Example 2
```
dojo.experimental("dojo.weather.toKelvin()", "PENDING approval from NOAA");
```
###
`fadeIn``(args)`
Defined by [dojo/\_base/fx](_base/fx)
Returns an animation that will fade node defined in 'args' from its current opacity to fully opaque.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* node (DOMNode|String): The node referenced in the animation
* duration (Integer, optional): Duration of the animation in milliseconds.
* easing (Function, optional): An easing function.
|
**Returns:** undefined
###
`fadeOut``(args)`
Defined by [dojo/\_base/fx](_base/fx)
Returns an animation that will fade node defined in 'args' from its current opacity to fully transparent.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* node (DOMNode|String): The node referenced in the animation
* duration (Integer, optional): Duration of the animation in milliseconds.
* easing (Function, optional): An easing function.
|
**Returns:** undefined
###
`fieldToObject``(inputNode)`
Defined by [dojo/dom-form](dom-form)
Serialize a form field to a JavaScript object.
Returns the value encoded in a form field as as a string or an array of strings. Disabled form elements and unchecked radio and checkboxes are skipped. Multi-select elements are returned as an array of string values.
| Parameter | Type | Description |
| --- | --- | --- |
| inputNode | DOMNode | String | |
**Returns:** Object | undefined
###
`filter``(arr,callback,thisObject)`
Defined by [dojo/\_base/array](_base/array)
Returns a new Array with those items from arr that match the condition implemented by callback.
This function corresponds to the JavaScript 1.6 Array.filter() method, with one difference: when run over sparse arrays, this implementation passes the "holes" in the sparse array to the callback function with a value of undefined. JavaScript 1.6's filter skips the holes in the sparse array. For more details, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | the array to iterate over. |
| callback | Function | String | a function that is invoked with three arguments (item, index, array). The return of this function is expected to be a boolean which determines whether the passed-in item will be included in the returned array. |
| thisObject | Object | *Optional*
may be used to scope the call to callback |
**Returns:** Array
Examples
--------
### Example 1
```
// returns [2, 3, 4]
array.filter([1, 2, 3, 4], function(item){ return item>1; });
```
###
`fixEvent``(evt,sender)`
Defined by [dojo/\_base/event](_base/event)
normalizes properties on the event object including event bubbling methods, keystroke normalization, and x/y positions
| Parameter | Type | Description |
| --- | --- | --- |
| evt | Event | native event object |
| sender | DOMNode | node to treat as "currentTarget" |
**Returns:** Event
native event object
###
`fixIeBiDiScrollLeft``(scrollLeft,doc)`
Defined by [dojo/dom-geometry](dom-geometry)
In RTL direction, scrollLeft should be a negative value, but IE returns a positive one. All codes using documentElement.scrollLeft must call this function to fix this error, otherwise the position will offset to right when there is a horizontal scrollbar.
| Parameter | Type | Description |
| --- | --- | --- |
| scrollLeft | Number | |
| doc | Document | *Optional*
Optional document to query. If unspecified, use win.doc. |
**Returns:** Number | number
###
`forEach``(arr,callback,thisObject)`
Defined by [dojo/\_base/array](_base/array)
for every item in arr, callback is invoked. Return values are ignored. If you want to break out of the loop, consider using array.every() or array.some(). forEach does not allow breaking out of the loop over the items in arr.
This function corresponds to the JavaScript 1.6 Array.forEach() method, with one difference: when run over sparse arrays, this implementation passes the "holes" in the sparse array to the callback function with a value of undefined. JavaScript 1.6's forEach skips the holes in the sparse array. For more details, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/forEach>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | String | |
| callback | Function | String | |
| thisObject | Object | *Optional* |
Examples
--------
### Example 1
```
// log out all members of the array:
array.forEach(
[ "thinger", "blah", "howdy", 10 ],
function(item){
console.log(item);
}
);
```
### Example 2
```
// log out the members and their indexes
array.forEach(
[ "thinger", "blah", "howdy", 10 ],
function(item, idx, arr){
console.log(item, "at index:", idx);
}
);
```
### Example 3
```
// use a scoped object member as the callback
var obj = {
prefix: "logged via obj.callback:",
callback: function(item){
console.log(this.prefix, item);
}
};
// specifying the scope function executes the callback in that scope
array.forEach(
[ "thinger", "blah", "howdy", 10 ],
obj.callback,
obj
);
// alternately, we can accomplish the same thing with lang.hitch()
array.forEach(
[ "thinger", "blah", "howdy", 10 ],
lang.hitch(obj, "callback")
);
```
###
`formToJson``(formNode,prettyPrint)`
Defined by [dojo/dom-form](dom-form)
Create a serialized JSON string from a form node or string ID identifying the form to serialize
| Parameter | Type | Description |
| --- | --- | --- |
| formNode | DOMNode | String | |
| prettyPrint | Boolean | *Optional* |
**Returns:** String | undefined
###
`formToObject``(formNode)`
Defined by [dojo/dom-form](dom-form)
Serialize a form node to a JavaScript object.
Returns the values encoded in an HTML form as string properties in an object which it then returns. Disabled form elements, buttons, and other non-value form elements are skipped. Multi-select elements are returned as an array of string values.
| Parameter | Type | Description |
| --- | --- | --- |
| formNode | DOMNode | String | |
**Returns:** object
Examples
--------
### Example 1
This form:
```
<form id="test_form">
<input type="text" name="blah" value="blah">
<input type="text" name="no_value" value="blah" disabled>
<input type="button" name="no_value2" value="blah">
<select type="select" multiple name="multi" size="5">
<option value="blah">blah</option>
<option value="thud" selected>thud</option>
<option value="thonk" selected>thonk</option>
</select>
</form>
```
yields this object structure as the result of a call to formToObject():
```
{
blah: "blah",
multi: [
"thud",
"thonk"
]
};
```
###
`formToQuery``(formNode)`
Defined by [dojo/dom-form](dom-form)
Returns a URL-encoded string representing the form passed as either a node or string ID identifying the form to serialize
| Parameter | Type | Description |
| --- | --- | --- |
| formNode | DOMNode | String | |
**Returns:** String | undefined
###
`fromJson``(js)`
Defined by [dojo/\_base/json](_base/json)
Parses a JavaScript expression and returns a JavaScript value.
Throws for invalid JavaScript expressions. It does not use a strict JSON parser. It always delegates to eval(). The content passed to this method must therefore come from a trusted source. It is recommend that you use [dojo/json](json)'s parse function for an implementation uses the (faster) native JSON parse when available.
| Parameter | Type | Description |
| --- | --- | --- |
| js | String | a string literal of a JavaScript expression, for instance: `'{ "foo": [ "bar", 1, { "baz": "thud" } ] }'` |
**Returns:** undefined
###
`getAttr``(node,name)`
Defined by [dojo/dom-attr](dom-attr)
Gets an attribute on an HTML element.
Handles normalized getting of attributes on DOM Nodes.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to get the attribute on |
| name | String | the name of the attribute to get. |
**Returns:** any | undefined | null
the value of the requested attribute or null if that attribute does not have a specified or default value;
Examples
--------
### Example 1
```
// get the current value of the "foo" attribute on a node
require(["dojo/dom-attr", "dojo/dom"], function(domAttr, dom){
domAttr.get(dom.byId("nodeId"), "foo");
// or we can just pass the id:
domAttr.get("nodeId", "foo");
});
```
###
`getBorderExtents``(node,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
returns an object with properties useful for noting the border dimensions.
* l/t/r/b = the sum of left/top/right/bottom border (respectively)
* w = the sum of the left and right border
* h = the sum of the top and bottom border
The w/h are used for calculating boxes. Normally application code will not need to invoke this directly, and will use the ...box... functions instead.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getComputedStyle``(node)`
Defined by [dojo/dom-style](dom-style)
Returns a "computed style" object.
Gets a "computed style" object which can be used to gather information about the current state of the rendered node.
Note that this may behave differently on different browsers. Values may have different formats and value encodings across browsers.
Note also that this method is expensive. Wherever possible, reuse the returned object.
Use the [dojo/dom-style.get()](dom-style#get) method for more consistent (pixelized) return values.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | A reference to a DOM node. Does NOT support taking an ID string for speed reasons. |
Examples
--------
### Example 1
```
require(["dojo/dom-style", "dojo/dom"], function(domStyle, dom){
domStyle.getComputedStyle(dom.byId('foo')).borderWidth;
});
```
### Example 2
Reusing the returned object, avoiding multiple lookups:
```
require(["dojo/dom-style", "dojo/dom"], function(domStyle, dom){
var cs = domStyle.getComputedStyle(dom.byId("someNode"));
var w = cs.width, h = cs.height;
});
```
###
`getContentBox``(node,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
Returns an object that encodes the width, height, left and top positions of the node's content box, irrespective of the current box model.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getIeDocumentElementOffset``(doc)`
Defined by [dojo/dom-geometry](dom-geometry)
returns the offset in x and y from the document body to the visual edge of the page for IE
The following values in IE contain an offset:
```
event.clientX
event.clientY
node.getBoundingClientRect().left
node.getBoundingClientRect().top
```
But other position related values do not contain this offset,
such as node.offsetLeft, node.offsetTop, node.style.left and node.style.top. The offset is always (2, 2) in LTR direction. When the body is in RTL direction, the offset counts the width of left scroll bar's width. This function computes the actual offset.
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | *Optional*
Optional document to query. If unspecified, use win.doc. |
**Returns:** object
###
`getL10nName``(moduleName,bundleName,locale)`
Defined by [dojo/i18n](i18n)
| Parameter | Type | Description |
| --- | --- | --- |
| moduleName | undefined | |
| bundleName | undefined | |
| locale | undefined | |
**Returns:** string
###
`getMarginBox``(node,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
returns an object that encodes the width, height, left and top positions of the node's margin box.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getMarginExtents``(node,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
returns object with properties useful for box fitting with regards to box margins (i.e., the outer-box).
* l/t = marginLeft, marginTop, respectively
* w = total width, margin inclusive
* h = total height, margin inclusive
The w/h are used for calculating boxes. Normally application code will not need to invoke this directly, and will use the ...box... functions instead.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getMarginSize``(node,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
returns an object that encodes the width and height of the node's margin box
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getNodeProp``(node,name)`
Defined by [dojo/dom-attr](dom-attr)
Returns an effective value of a property or an attribute.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to remove the attribute from |
| name | String | the name of the attribute |
**Returns:** any
the value of the attribute
###
`getPadBorderExtents``(node,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
Returns object with properties useful for box fitting with regards to padding.
* l/t/r/b = the sum of left/top/right/bottom padding and left/top/right/bottom border (respectively)
* w = the sum of the left and right padding and border
* h = the sum of the top and bottom padding and border
The w/h are used for calculating boxes. Normally application code will not need to invoke this directly, and will use the ...box... functions instead.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getPadExtents``(node,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
Returns object with special values specifically useful for node fitting.
Returns an object with `w`, `h`, `l`, `t` properties:
```
l/t/r/b = left/top/right/bottom padding (respectively)
w = the total of the left and right padding
h = the total of the top and bottom padding
```
If 'node' has position, l/t forms the origin for child nodes.
The w/h are used for calculating boxes. Normally application code will not need to invoke this directly, and will use the ...box... functions instead.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getProp``(node,name)`
Defined by [dojo/dom-prop](dom-prop)
Gets a property on an HTML element.
Handles normalized getting of properties on DOM nodes.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to get the property on |
| name | String | the name of the property to get. |
**Returns:** any | undefined
the value of the requested property or its default value
Examples
--------
### Example 1
```
// get the current value of the "foo" property on a node
require(["dojo/dom-prop", "dojo/dom"], function(domProp, dom){
domProp.get(dom.byId("nodeId"), "foo");
// or we can just pass the id:
domProp.get("nodeId", "foo");
});
```
###
`getStyle``(node,name)`
Defined by [dojo/dom-style](dom-style)
Accesses styles on a node.
Getting the style value uses the computed style for the node, so the value will be a calculated value, not just the immediate node.style value. Also when getting values, use specific style names, like "borderBottomWidth" instead of "border" since compound values like "border" are not necessarily reflected as expected. If you want to get node dimensions, use [dojo/dom-geometry.getMarginBox()](dom-geometry#getMarginBox), [dojo/dom-geometry.getContentBox()](dom-geometry#getContentBox) or [dojo/dom-geometry.getPosition()](dom-geometry#getPosition).
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to node to get style for |
| name | String | *Optional*
the style property to get |
**Returns:** undefined
Examples
--------
### Example 1
Passing only an ID or node returns the computed style object of the node:
```
require(["dojo/dom-style", "dojo/dom"], function(domStyle, dom){
domStyle.get("thinger");
});
```
### Example 2
Passing a node and a style property returns the current normalized, computed value for that property:
```
require(["dojo/dom-style", "dojo/dom"], function(domStyle, dom){
domStyle.get("thinger", "opacity"); // 1 by default
});
```
###
`hasAttr``(node,name)`
Defined by [dojo/dom-attr](dom-attr)
Returns true if the requested attribute is specified on the given element, and false otherwise.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to check |
| name | String | the name of the attribute |
**Returns:** Boolean | contentWindow.document isn't accessible within IE7/8
true if the requested attribute is specified on the given element, and false otherwise
###
`hasClass``(node,classStr)`
Defined by [dojo/dom-class](dom-class)
Returns whether or not the specified classes are a portion of the class list currently applied to the node.
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | String ID or DomNode reference to check the class for. |
| classStr | String | A string class name to look for. |
**Returns:** boolean
Examples
--------
### Example 1
Do something if a node with id="someNode" has class="aSillyClassName" present
```
if(dojo.hasClass("someNode","aSillyClassName")){ ... }
```
###
`hash``(hash,replace)`
Defined by [dojo/hash](hash)
Gets or sets the hash string in the browser URL.
Handles getting and setting of location.hash.
* If no arguments are passed, acts as a getter.
* If a string is passed, acts as a setter.
| Parameter | Type | Description |
| --- | --- | --- |
| hash | String | *Optional*
the hash is set - #string. |
| replace | Boolean | *Optional*
If true, updates the hash value in the current history state instead of creating a new history state. |
**Returns:** any | undefined
when used as a getter, returns the current hash string. when used as a setter, returns the new hash string.
Examples
--------
### Example 1
```
topic.subscribe("/dojo/hashchange", context, callback);
function callback (hashValue){
// do something based on the hash value.
}
```
###
`indexOf``(arr,value,fromIndex,findLast)`
Defined by [dojo/\_base/array](_base/array)
locates the first index of the provided value in the passed array. If the value is not found, -1 is returned.
This method corresponds to the JavaScript 1.6 Array.indexOf method, with two differences:
1. when run over sparse arrays, the Dojo function invokes the callback for every index whereas JavaScript 1.6's indexOf skips the holes in the sparse array.
2. uses equality (==) rather than strict equality (===)
For details on this method, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/indexOf>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | |
| value | Object | |
| fromIndex | Integer | *Optional* |
| findLast | Boolean | *Optional*
Makes indexOf() work like lastIndexOf(). Used internally; not meant for external usage. |
**Returns:** Number
###
`isBodyLtr``(doc)`
Defined by [dojo/dom-geometry](dom-geometry)
Returns true if the current language is left-to-right, and false otherwise.
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | *Optional*
Optional document to query. If unspecified, use win.doc. |
**Returns:** Boolean | boolean
###
`isDescendant``(node,ancestor)`
Defined by [dojo/dom](dom)
Returns true if node is a descendant of ancestor
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | string id or node reference to test |
| ancestor | DOMNode | String | string id or node reference of potential parent to test against |
**Returns:** boolean
Examples
--------
### Example 1
Test is node id="bar" is a descendant of node id="foo"
```
require(["dojo/dom"], function(dom){
if(dom.isDescendant("bar", "foo")){ ... }
});
```
###
`lastIndexOf``(arr,value,fromIndex)`
Defined by [dojo/\_base/array](_base/array)
locates the last index of the provided value in the passed array. If the value is not found, -1 is returned.
This method corresponds to the JavaScript 1.6 Array.lastIndexOf method, with two differences:
1. when run over sparse arrays, the Dojo function invokes the callback for every index whereas JavaScript 1.6's lasIndexOf skips the holes in the sparse array.
2. uses equality (==) rather than strict equality (===)
For details on this method, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/lastIndexOf>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | undefined | |
| value | undefined | |
| fromIndex | Integer | *Optional* |
**Returns:** Number
###
`loadInit``(f)`
Defined by [dojo/\_base/loader](_base/loader)
| Parameter | Type | Description |
| --- | --- | --- |
| f | undefined | |
###
`map``(arr,callback,thisObject,Ctr)`
Defined by [dojo/\_base/array](_base/array)
applies callback to each element of arr and returns an Array with the results
This function corresponds to the JavaScript 1.6 Array.map() method, with one difference: when run over sparse arrays, this implementation passes the "holes" in the sparse array to the callback function with a value of undefined. JavaScript 1.6's map skips the holes in the sparse array. For more details, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | String | the array to iterate on. If a string, operates on individual characters. |
| callback | Function | String | a function is invoked with three arguments, (item, index, array), and returns a value |
| thisObject | Object | *Optional*
may be used to scope the call to callback |
| Ctr | undefined | |
**Returns:** Array | instance
Examples
--------
### Example 1
```
// returns [2, 3, 4, 5]
array.map([1, 2, 3, 4], function(item){ return item+1 });
```
###
`marginBox``(node,box)`
Defined by [dojo/\_base/html](_base/html)
Getter/setter for the margin-box of node.
Getter/setter for the margin-box of node. Returns an object in the expected format of box (regardless if box is passed). The object might look like: `{ l: 50, t: 200, w: 300: h: 150 }` for a node offset from its parent 50px to the left, 200px from the top with a margin width of 300px and a margin-height of 150px.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DomNode | String | id or reference to DOM Node to get/set box for |
| box | Object | *Optional*
If passed, denotes that dojo.marginBox() should update/set the margin box for node. Box is an object in the above format. All properties are optional if passed. |
**Returns:** undefined
Examples
--------
### Example 1
Retrieve the margin box of a passed node
```
var box = dojo.marginBox("someNodeId");
console.dir(box);
```
### Example 2
Set a node's margin box to the size of another node
```
var box = dojo.marginBox("someNodeId");
dojo.marginBox("someOtherNode", box);
```
###
`moduleUrl``(module,url)`
Defined by [dojo/\_base/kernel](_base/kernel)
Returns a URL relative to a module.
| Parameter | Type | Description |
| --- | --- | --- |
| module | String | dojo/dom-class |
| url | String | *Optional* |
**Returns:** string
Examples
--------
### Example 1
```
var pngPath = dojo.moduleUrl("acme","images/small.png");
console.dir(pngPath); // list the object properties
// create an image and set it's source to pngPath's value:
var img = document.createElement("img");
img.src = pngPath;
// add our image to the document
dojo.body().appendChild(img);
```
### Example 2
you may de-reference as far as you like down the package hierarchy. This is sometimes handy to avoid lengthy relative urls or for building portable sub-packages. In this example, the `acme.widget` and `acme.util` directories may be located under different roots (see `dojo.registerModulePath`) but the the modules which reference them can be unaware of their relative locations on the filesystem:
```
// somewhere in a configuration block
dojo.registerModulePath("acme.widget", "../../acme/widget");
dojo.registerModulePath("acme.util", "../../util");
// ...
// code in a module using acme resources
var tmpltPath = dojo.moduleUrl("acme.widget","templates/template.html");
var dataPath = dojo.moduleUrl("acme.util","resources/data.json");
```
###
`NodeList``(array)`
Defined by [dojo/query](query)
Array-like object which adds syntactic sugar for chaining, common iteration operations, animation, and node manipulation. NodeLists are most often returned as the result of dojo/query() calls.
NodeList instances provide many utilities that reflect core Dojo APIs for Array iteration and manipulation, DOM manipulation, and event handling. Instead of needing to dig up functions in the dojo package, NodeLists generally make the full power of Dojo available for DOM manipulation tasks in a simple, chainable way.
| Parameter | Type | Description |
| --- | --- | --- |
| array | undefined | |
**Returns:** Array
Examples
--------
### Example 1
create a node list from a node
```
require(["dojo/query", "dojo/dom"
], function(query, dom){
query.NodeList(dom.byId("foo"));
});
```
### Example 2
get a NodeList from a CSS query and iterate on it
```
require(["dojo/on", "dojo/dom"
], function(on, dom){
var l = query(".thinger");
l.forEach(function(node, index, nodeList){
console.log(index, node.innerHTML);
});
});
```
### Example 3
use native and Dojo-provided array methods to manipulate a NodeList without needing to use dojo.\* functions explicitly:
```
require(["dojo/query", "dojo/dom-construct", "dojo/dom"
], function(query, domConstruct, dom){
var l = query(".thinger");
// since NodeLists are real arrays, they have a length
// property that is both readable and writable and
// push/pop/shift/unshift methods
console.log(l.length);
l.push(domConstruct.create("span"));
// dojo's normalized array methods work too:
console.log( l.indexOf(dom.byId("foo")) );
// ...including the special "function as string" shorthand
console.log( l.every("item.nodeType == 1") );
// NodeLists can be [..] indexed, or you can use the at()
// function to get specific items wrapped in a new NodeList:
var node = l[3]; // the 4th element
var newList = l.at(1, 3); // the 2nd and 4th elements
});
```
### Example 4
chainability is a key advantage of NodeLists:
```
require(["dojo/query", "dojo/NodeList-dom"
], function(query){
query(".thinger")
.onclick(function(e){ /* ... */ })
.at(1, 3, 8) // get a subset
.style("padding", "5px")
.forEach(console.log);
});
```
###
`objectToQuery``(map)`
Defined by [dojo/io-query](io-query)
takes a name/value mapping object and returns a string representing a URL-encoded version of that object.
| Parameter | Type | Description |
| --- | --- | --- |
| map | Object | |
**Returns:** undefined
Examples
--------
### Example 1
this object:
```
{
blah: "blah",
multi: [
"thud",
"thonk"
]
};
```
yields the following query string:
```
"blah=blah&multi=thud&multi=thonk"
```
###
`place``(node,refNode,position)`
Defined by [dojo/dom-construct](dom-construct)
Attempt to insert node into the DOM, choosing from various positioning options. Returns the first argument resolved to a DOM node.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | DocumentFragment | String | id or node reference, or HTML fragment starting with "<" to place relative to refNode |
| refNode | DOMNode | String | id or node reference to use as basis for placement |
| position | String | Number | *Optional*
string noting the position of node relative to refNode or a number indicating the location in the childNodes collection of refNode. Accepted string values are: * before
* after
* replace
* only
* first
* last
"first" and "last" indicate positions as children of refNode, "replace" replaces refNode, "only" replaces all children. position defaults to "last" if not specified |
**Returns:** DOMNode | undefined
Returned values is the first argument resolved to a DOM node.
.place() is also a method of `dojo/NodeList`, allowing `dojo/query` node lookups.
Examples
--------
### Example 1
Place a node by string id as the last child of another node by string id:
```
require(["dojo/dom-construct"], function(domConstruct){
domConstruct.place("someNode", "anotherNode");
});
```
### Example 2
Place a node by string id before another node by string id
```
require(["dojo/dom-construct"], function(domConstruct){
domConstruct.place("someNode", "anotherNode", "before");
});
```
### Example 3
Create a Node, and place it in the body element (last child):
```
require(["dojo/dom-construct", "dojo/_base/window"
], function(domConstruct, win){
domConstruct.place("<div></div>", win.body());
});
```
### Example 4
Put a new LI as the first child of a list by id:
```
require(["dojo/dom-construct"], function(domConstruct){
domConstruct.place("<li></li>", "someUl", "first");
});
```
###
`platformRequire``(modMap)`
Defined by [dojo/\_base/loader](_base/loader)
require one or more modules based on which host environment Dojo is currently operating in
This method takes a "map" of arrays which one can use to optionally load dojo modules. The map is indexed by the possible dojo.name *values, with two additional values: "default" and "common". The items in the "default" array will be loaded if none of the other items have been chosen based on dojo.name*, set by your host environment. The items in the "common" array will *always* be loaded, regardless of which list is chosen.
| Parameter | Type | Description |
| --- | --- | --- |
| modMap | Object | |
Examples
--------
### Example 1
```
dojo.platformRequire({
browser: [
"foo.sample", // simple module
"foo.test",
["foo.bar.baz", true] // skip object check in _loadModule (dojo.require)
],
default: [ "foo.sample._base" ],
common: [ "important.module.common" ]
});
```
###
`popContext``()`
Defined by [dojo/\_base/configFirefoxExtension](_base/configfirefoxextension)
If the context stack contains elements, ensure that subsequent code executes in the *previous* context to the current context. The current context set ([global, document]) is returned.
###
`position``(node,includeScroll)`
Defined by [dojo/dom-geometry](dom-geometry)
Gets the position and size of the passed element relative to the viewport (if includeScroll==false), or relative to the document root (if includeScroll==true).
Returns an object of the form: `{ x: 100, y: 300, w: 20, h: 15 }`. If includeScroll==true, the x and y values will include any document offsets that may affect the position relative to the viewport. Uses the border-box model (inclusive of border and padding but not margin). Does not act as a setter.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | |
| includeScroll | Boolean | *Optional* |
**Returns:** Object | object
###
`prop``(node,name,value)`
Defined by [dojo/\_base/html](_base/html)
Gets or sets a property on an HTML element.
Handles normalized getting and setting of properties on DOM Nodes. If 2 arguments are passed, and a the second argument is a string, acts as a getter.
If a third argument is passed, or if the second argument is a map of attributes, acts as a setter.
When passing functions as values, note that they will not be directly assigned to slots on the node, but rather the default behavior will be removed and the new behavior will be added using `dojo.connect()`, meaning that event handler properties will be normalized and that some caveats with regards to non-standard behaviors for onsubmit apply. Namely that you should cancel form submission using `dojo.stopEvent()` on the passed event object instead of returning a boolean value from the handler itself.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DomNode | String | id or reference to the element to get or set the property on |
| name | String | Object | the name of the property to get or set. |
| value | String | *Optional*
The value to set for the property |
**Returns:** any
when used as a getter, the value of the requested property or null if that attribute does not have a specified or default value;
when used as a setter, the DOM node
Examples
--------
### Example 1
```
// get the current value of the "foo" property on a node
dojo.prop(dojo.byId("nodeId"), "foo");
// or we can just pass the id:
dojo.prop("nodeId", "foo");
```
### Example 2
```
// use prop() to set the tab index
dojo.prop("nodeId", "tabIndex", 3);
```
### Example 3
Set multiple values at once, including event handlers:
```
dojo.prop("formId", {
"foo": "bar",
"tabIndex": -1,
"method": "POST",
"onsubmit": function(e){
// stop submitting the form. Note that the IE behavior
// of returning true or false will have no effect here
// since our handler is connect()ed to the built-in
// onsubmit behavior and so we need to use
// dojo.stopEvent() to ensure that the submission
// doesn't proceed.
dojo.stopEvent(e);
// submit the form with Ajax
dojo.xhrPost({ form: "formId" });
}
});
```
### Example 4
Style is s special case: Only set with an object hash of styles
```
dojo.prop("someNode",{
id:"bar",
style:{
width:"200px", height:"100px", color:"#000"
}
});
```
### Example 5
Again, only set style as an object hash of styles:
```
var obj = { color:"#fff", backgroundColor:"#000" };
dojo.prop("someNode", "style", obj);
// though shorter to use `dojo.style()` in this case:
dojo.style("someNode", obj);
```
###
`provide``(mid)`
Defined by [dojo/\_base/loader](_base/loader)
| Parameter | Type | Description |
| --- | --- | --- |
| mid | undefined | |
###
`pushContext``(g,d)`
Defined by [dojo/\_base/configFirefoxExtension](_base/configfirefoxextension)
causes subsequent calls to Dojo methods to assume the passed object and, optionally, document as the default scopes to use. A 2-element array of the previous global and document are returned.
dojo.pushContext treats contexts as a stack. The auto-detected contexts which are initially provided using dojo.setContext() require authors to keep state in order to "return" to a previous context, whereas the dojo.pushContext and dojo.popContext methods provide a more natural way to augment blocks of code to ensure that they execute in a different window or frame without issue. If called without any arguments, the default context (the context when Dojo is first loaded) is instead pushed into the stack. If only a single string is passed, a node in the intitial context's document is looked up and its contextWindow and contextDocument properties are used as the context to push. This means that iframes can be given an ID and code can be executed in the scope of the iframe's document in subsequent calls easily.
| Parameter | Type | Description |
| --- | --- | --- |
| g | Object | String | *Optional*
The global context. If a string, the id of the frame to search for a context and document. |
| d | MDocumentElement | *Optional*
The document element to execute subsequent code with. |
###
`queryToObject``(str)`
Defined by [dojo/io-query](io-query)
Create an object representing a de-serialized query section of a URL. Query keys with multiple values are returned in an array.
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | |
**Returns:** object
Examples
--------
### Example 1
This string:
```
"foo=bar&foo=baz&thinger=%20spaces%20=blah&zonk=blarg&"
```
results in this object structure:
```
{
foo: [ "bar", "baz" ],
thinger: " spaces =blah",
zonk: "blarg"
}
```
Note that spaces and other urlencoded entities are correctly handled.
###
`rawXhrPost``(args)`
Defined by [dojo/\_base/xhr](_base/xhr)
Sends an HTTP POST request to the server. In addition to the properties listed for the dojo.\_\_XhrArgs type, the following property is allowed:
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See `dojo/_base/xhr.contentHandlers`
* sync (Boolean, optional): false is default. Indicates whether the request should be a synchronous (blocking) request.
* headers (Object, optional): Additional HTTP headers to send in the request.
* failOk (Boolean, optional): false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
* contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
* load: This function will be called on a successful HTTP response code.
* error: This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
* handle: This function will be called at the end of every request, whether or not an error occurs.
* url (String): URL to server endpoint.
* content (Object, optional): Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
* timeout (Integer, optional): Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
* form (DOMNode, optional): DOM node for a form. Used to extract the form values and send to the server.
* preventCache (Boolean, optional): Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
* rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for dojo/\_base/xhr.rawXhrPost and dojo/\_base/xhr.rawXhrPut respectively.
* ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via dojo/topic.publish() for different phases of an IO operation. See dojo/main.\_\_IoPublish for a list of topics that are published.
|
**Returns:** undefined
###
`rawXhrPut``(args)`
Defined by [dojo/\_base/xhr](_base/xhr)
Sends an HTTP PUT request to the server. In addition to the properties listed for the dojo.\_\_XhrArgs type, the following property is allowed:
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See `dojo/_base/xhr.contentHandlers`
* sync (Boolean, optional): false is default. Indicates whether the request should be a synchronous (blocking) request.
* headers (Object, optional): Additional HTTP headers to send in the request.
* failOk (Boolean, optional): false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
* contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
* load: This function will be called on a successful HTTP response code.
* error: This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
* handle: This function will be called at the end of every request, whether or not an error occurs.
* url (String): URL to server endpoint.
* content (Object, optional): Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
* timeout (Integer, optional): Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
* form (DOMNode, optional): DOM node for a form. Used to extract the form values and send to the server.
* preventCache (Boolean, optional): Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
* rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for dojo/\_base/xhr.rawXhrPost and dojo/\_base/xhr.rawXhrPut respectively.
* ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via dojo/topic.publish() for different phases of an IO operation. See dojo/main.\_\_IoPublish for a list of topics that are published.
|
**Returns:** undefined
###
`ready``(priority,context,callback)`
Defined by [dojo/ready](ready)
Add a function to execute on DOM content loaded and all requested modules have arrived and been evaluated. In most cases, the `domReady` plug-in should suffice and this method should not be needed.
When called in a non-browser environment, just checks that all requested modules have arrived and been evaluated.
| Parameter | Type | Description |
| --- | --- | --- |
| priority | Integer | *Optional*
The order in which to exec this callback relative to other callbacks, defaults to 1000 |
| context | undefined | The context in which to run execute callback, or a callback if not using context |
| callback | Function | *Optional*
The function to execute. |
Examples
--------
### Example 1
Simple DOM and Modules ready syntax
```
require(["dojo/ready"], function(ready){
ready(function(){ alert("Dom ready!"); });
});
```
### Example 2
Using a priority
```
require(["dojo/ready"], function(ready){
ready(2, function(){ alert("low priority ready!"); })
});
```
### Example 3
Using context
```
require(["dojo/ready"], function(ready){
ready(foo, function(){
// in here, this == foo
});
});
```
### Example 4
Using dojo/hitch style args:
```
require(["dojo/ready"], function(ready){
var foo = { dojoReady: function(){ console.warn(this, "dojo dom and modules ready."); } };
ready(foo, "dojoReady");
});
```
###
`registerModulePath``(moduleName,prefix)`
Defined by [dojo/\_base/loader](_base/loader)
Maps a module name to a path
An unregistered module is given the default path of ../[module], relative to Dojo root. For example, module acme is mapped to ../acme. If you want to use a different module name, use dojo.registerModulePath.
| Parameter | Type | Description |
| --- | --- | --- |
| moduleName | String | |
| prefix | String | |
Examples
--------
### Example 1
If your dojo.js is located at this location in the web root:
```
/myapp/js/dojo/dojo/dojo.js
```
and your modules are located at:
```
/myapp/js/foo/bar.js
/myapp/js/foo/baz.js
/myapp/js/foo/thud/xyzzy.js
```
Your application can tell Dojo to locate the "foo" namespace by calling:
```
dojo.registerModulePath("foo", "../../foo");
```
At which point you can then use dojo.require() to load the
modules (assuming they provide() the same things which are required). The full code might be:
```
<script type="text/javascript"
src="/myapp/js/dojo/dojo/dojo.js"></script>
<script type="text/javascript">
dojo.registerModulePath("foo", "../../foo");
dojo.require("foo.bar");
dojo.require("foo.baz");
dojo.require("foo.thud.xyzzy");
</script>
```
###
`removeAttr``(node,name)`
Defined by [dojo/dom-attr](dom-attr)
Removes an attribute from an HTML element.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to remove the attribute from |
| name | String | the name of the attribute to remove |
###
`removeClass``(node,classStr)`
Defined by [dojo/dom-class](dom-class)
Removes the specified classes from node. No `contains()` check is required.
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | String ID or DomNode reference to remove the class from. |
| classStr | String | Array | *Optional*
An optional String class name to remove, or several space-separated class names, or an array of class names. If omitted, all class names will be deleted. |
Examples
--------
### Example 1
Remove a class from some node:
```
require(["dojo/dom-class"], function(domClass){
domClass.remove("someNode", "firstClass");
});
```
### Example 2
Remove two classes from some node:
```
require(["dojo/dom-class"], function(domClass){
domClass.remove("someNode", "firstClass secondClass");
});
```
### Example 3
Remove two classes from some node (using array):
```
require(["dojo/dom-class"], function(domClass){
domClass.remove("someNode", ["firstClass", "secondClass"]);
});
```
### Example 4
Remove all classes from some node:
```
require(["dojo/dom-class"], function(domClass){
domClass.remove("someNode");
});
```
### Example 5
Available in `dojo/NodeList` for multiple removal
```
require(["dojo/query"], function(query){
query("ul > li").removeClass("foo");
});
```
###
`replaceClass``(node,addClassStr,removeClassStr)`
Defined by [dojo/dom-class](dom-class)
Replaces one or more classes on a node if not present. Operates more quickly than calling dojo.removeClass and dojo.addClass
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | String ID or DomNode reference to remove the class from. |
| addClassStr | String | Array | A String class name to add, or several space-separated class names, or an array of class names. |
| removeClassStr | String | Array | *Optional*
A String class name to remove, or several space-separated class names, or an array of class names. |
Examples
--------
### Example 1
```
require(["dojo/dom-class"], function(domClass){
domClass.replace("someNode", "add1 add2", "remove1 remove2");
});
```
### Example 2
Replace all classes with addMe
```
require(["dojo/dom-class"], function(domClass){
domClass.replace("someNode", "addMe");
});
```
### Example 3
Available in `dojo/NodeList` for multiple toggles
```
require(["dojo/query"], function(query){
query(".findMe").replaceClass("addMe", "removeMe");
});
```
###
`require``(moduleName,omitModuleCheck)`
Defined by [dojo/\_base/loader](_base/loader)
loads a Javascript module from the appropriate URI
Modules are loaded via dojo.require by using one of two loaders: the normal loader and the xdomain loader. The xdomain loader is used when dojo was built with a custom build that specified loader=xdomain and the module lives on a modulePath that is a whole URL, with protocol and a domain. The versions of Dojo that are on the Google and AOL CDNs use the xdomain loader.
If the module is loaded via the xdomain loader, it is an asynchronous load, since the module is added via a dynamically created script tag. This means that dojo.require() can return before the module has loaded. However, this should only happen in the case where you do dojo.require calls in the top-level HTML page, or if you purposely avoid the loader checking for dojo.require dependencies in your module by using a syntax like dojo["require"] to load the module.
Sometimes it is useful to not have the loader detect the dojo.require calls in the module so that you can dynamically load the modules as a result of an action on the page, instead of right at module load time.
Also, for script blocks in an HTML page, the loader does not pre-process them, so it does not know to download the modules before the dojo.require calls occur.
So, in those two cases, when you want on-the-fly module loading or for script blocks in the HTML page, special care must be taken if the dojo.required code is loaded asynchronously. To make sure you can execute code that depends on the dojo.required modules, be sure to add the code that depends on the modules in a dojo.addOnLoad() callback. dojo.addOnLoad waits for all outstanding modules to finish loading before executing.
This type of syntax works with both xdomain and normal loaders, so it is good practice to always use this idiom for on-the-fly code loading and in HTML script blocks. If at some point you change loaders and where the code is loaded from, it will all still work.
More on how dojo.require `dojo.require("A.B")` first checks to see if symbol A.B is defined. If it is, it is simply returned (nothing to do).
If it is not defined, it will look for `A/B.js` in the script root directory.
`dojo.require` throws an exception if it cannot find a file to load, or if the symbol `A.B` is not defined after loading.
It returns the object `A.B`, but note the caveats above about on-the-fly loading and HTML script blocks when the xdomain loader is loading a module.
`dojo.require()` does nothing about importing symbols into the current namespace. It is presumed that the caller will take care of that.
| Parameter | Type | Description |
| --- | --- | --- |
| moduleName | String | module name to load, using periods for separators, e.g. "dojo.date.locale". Module paths are de-referenced by dojo's internal mapping of locations to names and are disambiguated by longest prefix. See `dojo.registerModulePath()` for details on registering new modules. |
| omitModuleCheck | Boolean | *Optional*
if `true`, omitModuleCheck skips the step of ensuring that the loaded file actually defines the symbol it is referenced by. For example if it called as `dojo.require("a.b.c")` and the file located at `a/b/c.js` does not define an object `a.b.c`, and exception will be throws whereas no exception is raised when called as `dojo.require("a.b.c", true)` |
**Returns:** any
the required namespace object
Examples
--------
### Example 1
To use dojo.require in conjunction with dojo.ready:
```
dojo.require("foo");
dojo.require("bar");
dojo.addOnLoad(function(){
//you can now safely do something with foo and bar
});
```
### Example 2
For example, to import all symbols into a local block, you might write:
```
with (dojo.require("A.B")) {
...
}
```
And to import just the leaf symbol to a local variable:
```
var B = dojo.require("A.B");
...
```
###
`requireAfterIf``(condition,moduleName,omitModuleCheck)`
Defined by [dojo/\_base/loader](_base/loader)
If the condition is true then call `dojo.require()` for the specified resource
| Parameter | Type | Description |
| --- | --- | --- |
| condition | Boolean | |
| moduleName | String | |
| omitModuleCheck | Boolean | *Optional* |
Examples
--------
### Example 1
```
dojo.requireIf(dojo.isBrowser, "my.special.Module");
```
###
`requireIf``(condition,moduleName,omitModuleCheck)`
Defined by [dojo/\_base/loader](_base/loader)
If the condition is true then call `dojo.require()` for the specified resource
| Parameter | Type | Description |
| --- | --- | --- |
| condition | Boolean | |
| moduleName | String | |
| omitModuleCheck | Boolean | *Optional* |
Examples
--------
### Example 1
```
dojo.requireIf(dojo.isBrowser, "my.special.Module");
```
###
`requireLocalization``(moduleName,bundleName,locale)`
Defined by [dojo/\_base/loader](_base/loader)
| Parameter | Type | Description |
| --- | --- | --- |
| moduleName | String | |
| bundleName | String | |
| locale | String | *Optional* |
###
`safeMixin``(target,source)`
Defined by [dojo/\_base/declare](_base/declare)
Mix in properties skipping a constructor and decorating functions like it is done by declare().
This function is used to mix in properties like lang.mixin does, but it skips a constructor property and decorates functions like declare() does.
It is meant to be used with classes and objects produced with declare. Functions mixed in with dojo.safeMixin can use this.inherited() like normal methods.
This function is used to implement extend() method of a constructor produced with declare().
| Parameter | Type | Description |
| --- | --- | --- |
| target | Object | Target object to accept new properties. |
| source | Object | Source object for new properties. |
**Returns:** Object
Target object to accept new properties.
Examples
--------
### Example 1
```
var A = declare(null, {
m1: function(){
console.log("A.m1");
},
m2: function(){
console.log("A.m2");
}
});
var B = declare(A, {
m1: function(){
this.inherited(arguments);
console.log("B.m1");
}
});
B.extend({
m2: function(){
this.inherited(arguments);
console.log("B.m2");
}
});
var x = new B();
dojo.safeMixin(x, {
m1: function(){
this.inherited(arguments);
console.log("X.m1");
},
m2: function(){
this.inherited(arguments);
console.log("X.m2");
}
});
x.m2();
// prints:
// A.m1
// B.m1
// X.m1
```
###
`setAttr``(node,name,value)`
Defined by [dojo/dom-attr](dom-attr)
Sets an attribute on an HTML element.
Handles normalized setting of attributes on DOM Nodes.
When passing functions as values, note that they will not be directly assigned to slots on the node, but rather the default behavior will be removed and the new behavior will be added using `dojo.connect()`, meaning that event handler properties will be normalized and that some caveats with regards to non-standard behaviors for onsubmit apply. Namely that you should cancel form submission using `dojo.stopEvent()` on the passed event object instead of returning a boolean value from the handler itself.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to set the attribute on |
| name | String | Object | the name of the attribute to set, or a hash of key-value pairs to set. |
| value | String | *Optional*
the value to set for the attribute, if the name is a string. |
**Returns:** any | undefined
the DOM node
Examples
--------
### Example 1
```
// use attr() to set the tab index
require(["dojo/dom-attr"], function(domAttr){
domAttr.set("nodeId", "tabIndex", 3);
});
```
### Example 2
Set multiple values at once, including event handlers:
```
require(["dojo/dom-attr"],
function(domAttr){
domAttr.set("formId", {
"foo": "bar",
"tabIndex": -1,
"method": "POST"
}
});
```
###
`setContentSize``(node,box,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
Sets the size of the node's contents, irrespective of margins, padding, or borders.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| box | Object | hash with optional "w", and "h" properties for "width", and "height" respectively. All specified properties should have numeric values in whole pixels. |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
###
`setContext``(globalObject,globalDocument)`
Defined by [dojo/\_base/window](_base/window)
changes the behavior of many core Dojo functions that deal with namespace and DOM lookup, changing them to work in a new global context (e.g., an iframe). The varibles dojo.global and dojo.doc are modified as a result of calling this function and the result of `dojo.body()` likewise differs.
| Parameter | Type | Description |
| --- | --- | --- |
| globalObject | Object | |
| globalDocument | DocumentElement | |
###
`setMarginBox``(node,box,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
sets the size of the node's margin box and placement (left/top), irrespective of box model. Think of it as a passthrough to setBox that handles box-model vagaries for you.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| box | Object | hash with optional "l", "t", "w", and "h" properties for "left", "right", "width", and "height" respectively. All specified properties should have numeric values in whole pixels. |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
###
`setProp``(node,name,value)`
Defined by [dojo/dom-prop](dom-prop)
Sets a property on an HTML element.
Handles normalized setting of properties on DOM nodes.
When passing functions as values, note that they will not be directly assigned to slots on the node, but rather the default behavior will be removed and the new behavior will be added using `dojo.connect()`, meaning that event handler properties will be normalized and that some caveats with regards to non-standard behaviors for onsubmit apply. Namely that you should cancel form submission using `dojo.stopEvent()` on the passed event object instead of returning a boolean value from the handler itself.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to set the property on |
| name | String | Object | the name of the property to set, or a hash object to set multiple properties at once. |
| value | String | *Optional*
The value to set for the property |
**Returns:** any | undefined
the DOM node
Examples
--------
### Example 1
```
// use prop() to set the tab index
require(["dojo/dom-prop"], function(domProp){
domProp.set("nodeId", "tabIndex", 3);
});
```
### Example 2
Set multiple values at once, including event handlers:
```
require(["dojo/dom-prop"], function(domProp){
domProp.set("formId", {
"foo": "bar",
"tabIndex": -1,
"method": "POST",
});
});
```
###
`setSelectable``(node,selectable)`
Defined by [dojo/dom](dom)
| Parameter | Type | Description |
| --- | --- | --- |
| node | undefined | |
| selectable | undefined | |
###
`setStyle``(node,name,value)`
Defined by [dojo/dom-style](dom-style)
Sets styles on a node.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to node to set style for |
| name | String | Object | the style property to set in DOM-accessor format ("borderWidth", not "border-width") or an object with key/value pairs suitable for setting each property. |
| value | String | *Optional*
If passed, sets value on the node for style, handling cross-browser concerns. When setting a pixel value, be sure to include "px" in the value. For instance, top: "200px". Otherwise, in some cases, some browsers will not apply the style. |
**Returns:** String | undefined
If passed, sets value on the node for style, handling cross-browser concerns. When setting a pixel value, be sure to include "px" in the value. For instance, top: "200px". Otherwise, in some cases, some browsers will not apply the style.
Examples
--------
### Example 1
Passing a node, a style property, and a value changes the current display of the node and returns the new computed value
```
require(["dojo/dom-style"], function(domStyle){
domStyle.set("thinger", "opacity", 0.5); // == 0.5
});
```
### Example 2
Passing a node, an object-style style property sets each of the values in turn and returns the computed style object of the node:
```
require(["dojo/dom-style"], function(domStyle){
domStyle.set("thinger", {
"opacity": 0.5,
"border": "3px solid black",
"height": "300px"
});
});
```
### Example 3
When the CSS style property is hyphenated, the JavaScript property is camelCased. font-size becomes fontSize, and so on.
```
require(["dojo/dom-style", "dojo/dom"], function(domStyle, dom){
domStyle.set("thinger",{
fontSize:"14pt",
letterSpacing:"1.2em"
});
});
```
### Example 4
dojo/NodeList implements .style() using the same syntax, omitting the "node" parameter, calling dojo/dom-style.get() on every element of the list. See: `dojo/query` and `dojo/NodeList`
```
require(["dojo/dom-style", "dojo/query", "dojo/NodeList-dom"],
function(domStyle, query){
query(".someClassName").style("visibility","hidden");
// or
query("#baz > div").style({
opacity:0.75,
fontSize:"13pt"
});
});
```
###
`some``(arr,callback,thisObject)`
Defined by [dojo/\_base/array](_base/array)
Determines whether or not any item in arr satisfies the condition implemented by callback.
This function corresponds to the JavaScript 1.6 Array.some() method, with one difference: when run over sparse arrays, this implementation passes the "holes" in the sparse array to the callback function with a value of undefined. JavaScript 1.6's some skips the holes in the sparse array. For more details, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/some>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | String | the array to iterate over. If a string, operates on individual characters. |
| callback | Function | String | a function is invoked with three arguments: item, index, and array and returns true if the condition is met. |
| thisObject | Object | *Optional*
may be used to scope the call to callback |
**Returns:** Boolean
Examples
--------
### Example 1
```
// is true
array.some([1, 2, 3, 4], function(item){ return item>1; });
```
### Example 2
```
// is false
array.some([1, 2, 3, 4], function(item){ return item<1; });
```
###
`Stateful``()`
Defined by [dojo/Stateful](stateful)
###
`stopEvent``(evt)`
Defined by [dojo/\_base/event](_base/event)
prevents propagation and clobbers the default action of the passed event
| Parameter | Type | Description |
| --- | --- | --- |
| evt | Event | The event object. If omitted, window.event is used on IE. |
###
`style``(node,name,value)`
Defined by [dojo/\_base/html](_base/html)
Accesses styles on a node. If 2 arguments are passed, acts as a getter. If 3 arguments are passed, acts as a setter.
Getting the style value uses the computed style for the node, so the value will be a calculated value, not just the immediate node.style value. Also when getting values, use specific style names, like "borderBottomWidth" instead of "border" since compound values like "border" are not necessarily reflected as expected. If you want to get node dimensions, use `dojo.marginBox()`, `dojo.contentBox()` or `dojo.position()`.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to node to get/set style for |
| name | String | Object | *Optional*
the style property to set in DOM-accessor format ("borderWidth", not "border-width") or an object with key/value pairs suitable for setting each property. |
| value | String | *Optional*
If passed, sets value on the node for style, handling cross-browser concerns. When setting a pixel value, be sure to include "px" in the value. For instance, top: "200px". Otherwise, in some cases, some browsers will not apply the style. |
**Returns:** any | undefined
when used as a getter, return the computed style of the node if passing in an ID or node, or return the normalized, computed value for the property when passing in a node and a style property
Examples
--------
### Example 1
Passing only an ID or node returns the computed style object of the node:
```
dojo.style("thinger");
```
### Example 2
Passing a node and a style property returns the current normalized, computed value for that property:
```
dojo.style("thinger", "opacity"); // 1 by default
```
### Example 3
Passing a node, a style property, and a value changes the current display of the node and returns the new computed value
```
dojo.style("thinger", "opacity", 0.5); // == 0.5
```
### Example 4
Passing a node, an object-style style property sets each of the values in turn and returns the computed style object of the node:
```
dojo.style("thinger", {
"opacity": 0.5,
"border": "3px solid black",
"height": "300px"
});
```
### Example 5
When the CSS style property is hyphenated, the JavaScript property is camelCased. font-size becomes fontSize, and so on.
```
dojo.style("thinger",{
fontSize:"14pt",
letterSpacing:"1.2em"
});
```
### Example 6
dojo/NodeList implements .style() using the same syntax, omitting the "node" parameter, calling dojo.style() on every element of the list. See: `dojo/query` and `dojo/NodeList`
```
dojo.query(".someClassName").style("visibility","hidden");
// or
dojo.query("#baz > div").style({
opacity:0.75,
fontSize:"13pt"
});
```
###
`toDom``(frag,doc)`
Defined by [dojo/dom-construct](dom-construct)
instantiates an HTML fragment returning the corresponding DOM.
| Parameter | Type | Description |
| --- | --- | --- |
| frag | String | the HTML fragment |
| doc | DocumentNode | *Optional*
optional document to use when creating DOM nodes, defaults to dojo/\_base/window.doc if not specified. |
**Returns:** any | undefined
Document fragment, unless it's a single node in which case it returns the node itself
Examples
--------
### Example 1
Create a table row:
```
require(["dojo/dom-construct"], function(domConstruct){
var tr = domConstruct.toDom("<tr><td>First!</td></tr>");
});
```
###
`toggleClass``(node,classStr,condition)`
Defined by [dojo/dom-class](dom-class)
Adds a class to node if not present, or removes if present. Pass a boolean condition if you want to explicitly add or remove. Returns the condition that was specified directly or indirectly.
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | String ID or DomNode reference to toggle a class string |
| classStr | String | Array | A String class name to toggle, or several space-separated class names, or an array of class names. |
| condition | Boolean | *Optional*
If passed, true means to add the class, false means to remove. Otherwise dojo.hasClass(node, classStr) is used to detect the class presence. |
**Returns:** Boolean
If passed, true means to add the class, false means to remove. Otherwise dojo.hasClass(node, classStr) is used to detect the class presence.
Examples
--------
### Example 1
```
require(["dojo/dom-class"], function(domClass){
domClass.toggle("someNode", "hovered");
});
```
### Example 2
Forcefully add a class
```
require(["dojo/dom-class"], function(domClass){
domClass.toggle("someNode", "hovered", true);
});
```
### Example 3
Available in `dojo/NodeList` for multiple toggles
```
require(["dojo/query"], function(query){
query(".toggleMe").toggleClass("toggleMe");
});
```
###
`toJson``(it,prettyPrint)`
Defined by [dojo/\_base/json](_base/json)
Returns a [JSON](http://json.org) serialization of an object.
Returns a [JSON](http://json.org) serialization of an object. Note that this doesn't check for infinite recursion, so don't do that! It is recommend that you use [dojo/json](json)'s stringify function for an lighter and faster implementation that matches the native JSON API and uses the native JSON serializer when available.
| Parameter | Type | Description |
| --- | --- | --- |
| it | Object | an object to be serialized. Objects may define their own serialization via a special "**json**" or "json" function property. If a specialized serializer has been defined, it will be used as a fallback. Note that in 1.6, toJson would serialize undefined, but this no longer supported since it is not supported by native JSON serializer. |
| prettyPrint | Boolean | *Optional*
if true, we indent objects and arrays to make the output prettier. The variable `dojo.toJsonIndentStr` is used as the indent string -- to use something other than the default (tab), change that variable before calling dojo.toJson(). Note that if native JSON support is available, it will be used for serialization, and native implementations vary on the exact spacing used in pretty printing. |
**Returns:** any | undefined
A JSON string serialization of the passed-in object.
Examples
--------
### Example 1
simple serialization of a trivial object
```
var jsonStr = dojo.toJson({ howdy: "stranger!", isStrange: true });
doh.is('{"howdy":"stranger!","isStrange":true}', jsonStr);
```
### Example 2
a custom serializer for an objects of a particular class:
```
dojo.declare("Furby", null, {
furbies: "are strange",
furbyCount: 10,
__json__: function(){
},
});
```
###
`toPixelValue``(node,value)`
Defined by [dojo/dom-style](dom-style)
converts style value to pixels on IE or return a numeric value.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| value | String | |
**Returns:** Number
###
`unsubscribe``(handle)`
Defined by [dojo/\_base/connect](_base/connect)
Remove a topic listener.
| Parameter | Type | Description |
| --- | --- | --- |
| handle | Handle | The handle returned from a call to subscribe. |
Examples
--------
### Example 1
```
var alerter = dojo.subscribe("alerts", null, function(caption, message){ alert(caption + "\n" + message); };
...
dojo.unsubscribe(alerter);
```
###
`when``(valueOrPromise,callback,errback,progback)`
Defined by [dojo/when](when)
Transparently applies callbacks to values and/or promises.
Accepts promises but also transparently handles non-promises. If no callbacks are provided returns a promise, regardless of the initial value. Foreign promises are converted.
If callbacks are provided and the initial value is not a promise, the callback is executed immediately with no error handling. Returns a promise if the initial value is a promise, or the result of the callback otherwise.
| Parameter | Type | Description |
| --- | --- | --- |
| valueOrPromise | undefined | Either a regular value or an object with a `then()` method that follows the Promises/A specification. |
| callback | Function | *Optional*
Callback to be invoked when the promise is resolved, or a non-promise is received. |
| errback | Function | *Optional*
Callback to be invoked when the promise is rejected. |
| progback | Function | *Optional*
Callback to be invoked when the promise emits a progress update. |
**Returns:** [dojo/promise/Promise](promise/promise) | summary: | name:
Promise, or if a callback is provided, the result of the callback.
###
`windowUnloaded``()`
Defined by [dojo/\_base/configFirefoxExtension](_base/configfirefoxextension)
signal fired by impending window destruction. You may use dojo.addOnWIndowUnload() or dojo.connect() to this method to perform page/application cleanup methods. See dojo.addOnWindowUnload for more info.
###
`withDoc``(documentObject,callback,thisObject,cbArguments)`
Defined by [dojo/\_base/window](_base/window)
Invoke callback with documentObject as dojo/\_base/window::doc.
Invoke callback with documentObject as [dojo/\_base/window](_base/window)::doc. If provided, callback will be executed in the context of object thisObject When callback() returns or throws an error, the [dojo/\_base/window](_base/window)::doc will be restored to its previous state.
| Parameter | Type | Description |
| --- | --- | --- |
| documentObject | DocumentElement | |
| callback | Function | |
| thisObject | Object | *Optional* |
| cbArguments | Array | *Optional* |
**Returns:** undefined
###
`withGlobal``(globalObject,callback,thisObject,cbArguments)`
Defined by [dojo/\_base/window](_base/window)
Invoke callback with globalObject as dojo.global and globalObject.document as dojo.doc.
Invoke callback with globalObject as dojo.global and globalObject.document as dojo.doc. If provided, globalObject will be executed in the context of object thisObject When callback() returns or throws an error, the dojo.global and dojo.doc will be restored to its previous state.
| Parameter | Type | Description |
| --- | --- | --- |
| globalObject | Object | |
| callback | Function | |
| thisObject | Object | *Optional* |
| cbArguments | Array | *Optional* |
**Returns:** undefined
###
`xhr``(method,args)`
Defined by [dojox/rpc/Client](http://dojotoolkit.org/api/1.10/dojox/rpc/Client)
| Parameter | Type | Description |
| --- | --- | --- |
| method | undefined | |
| args | undefined | |
**Returns:** undefined
###
`xhrDelete``(args)`
Defined by [dojo/\_base/xhr](_base/xhr)
Sends an HTTP DELETE request to the server.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See `dojo/_base/xhr.contentHandlers`
* sync (Boolean, optional): false is default. Indicates whether the request should be a synchronous (blocking) request.
* headers (Object, optional): Additional HTTP headers to send in the request.
* failOk (Boolean, optional): false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
* contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
* load: This function will be called on a successful HTTP response code.
* error: This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
* handle: This function will be called at the end of every request, whether or not an error occurs.
* url (String): URL to server endpoint.
* content (Object, optional): Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
* timeout (Integer, optional): Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
* form (DOMNode, optional): DOM node for a form. Used to extract the form values and send to the server.
* preventCache (Boolean, optional): Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
* rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for dojo/\_base/xhr.rawXhrPost and dojo/\_base/xhr.rawXhrPut respectively.
* ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via dojo/topic.publish() for different phases of an IO operation. See dojo/main.\_\_IoPublish for a list of topics that are published.
|
**Returns:** undefined
###
`xhrGet``(args)`
Defined by [dojo/\_base/xhr](_base/xhr)
Sends an HTTP GET request to the server.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See `dojo/_base/xhr.contentHandlers`
* sync (Boolean, optional): false is default. Indicates whether the request should be a synchronous (blocking) request.
* headers (Object, optional): Additional HTTP headers to send in the request.
* failOk (Boolean, optional): false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
* contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
* load: This function will be called on a successful HTTP response code.
* error: This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
* handle: This function will be called at the end of every request, whether or not an error occurs.
* url (String): URL to server endpoint.
* content (Object, optional): Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
* timeout (Integer, optional): Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
* form (DOMNode, optional): DOM node for a form. Used to extract the form values and send to the server.
* preventCache (Boolean, optional): Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
* rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for dojo/\_base/xhr.rawXhrPost and dojo/\_base/xhr.rawXhrPut respectively.
* ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via dojo/topic.publish() for different phases of an IO operation. See dojo/main.\_\_IoPublish for a list of topics that are published.
|
**Returns:** undefined
###
`xhrPost``(args)`
Defined by [dojo/\_base/xhr](_base/xhr)
Sends an HTTP POST request to the server. In addition to the properties listed for the dojo.\_\_XhrArgs type, the following property is allowed:
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See `dojo/_base/xhr.contentHandlers`
* sync (Boolean, optional): false is default. Indicates whether the request should be a synchronous (blocking) request.
* headers (Object, optional): Additional HTTP headers to send in the request.
* failOk (Boolean, optional): false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
* contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
* load: This function will be called on a successful HTTP response code.
* error: This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
* handle: This function will be called at the end of every request, whether or not an error occurs.
* url (String): URL to server endpoint.
* content (Object, optional): Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
* timeout (Integer, optional): Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
* form (DOMNode, optional): DOM node for a form. Used to extract the form values and send to the server.
* preventCache (Boolean, optional): Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
* rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for dojo/\_base/xhr.rawXhrPost and dojo/\_base/xhr.rawXhrPut respectively.
* ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via dojo/topic.publish() for different phases of an IO operation. See dojo/main.\_\_IoPublish for a list of topics that are published.
|
**Returns:** undefined
###
`xhrPut``(args)`
Defined by [dojo/\_base/xhr](_base/xhr)
Sends an HTTP PUT request to the server. In addition to the properties listed for the dojo.\_\_XhrArgs type, the following property is allowed:
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See `dojo/_base/xhr.contentHandlers`
* sync (Boolean, optional): false is default. Indicates whether the request should be a synchronous (blocking) request.
* headers (Object, optional): Additional HTTP headers to send in the request.
* failOk (Boolean, optional): false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
* contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
* load: This function will be called on a successful HTTP response code.
* error: This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
* handle: This function will be called at the end of every request, whether or not an error occurs.
* url (String): URL to server endpoint.
* content (Object, optional): Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
* timeout (Integer, optional): Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
* form (DOMNode, optional): DOM node for a form. Used to extract the form values and send to the server.
* preventCache (Boolean, optional): Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
* rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for dojo/\_base/xhr.rawXhrPost and dojo/\_base/xhr.rawXhrPut respectively.
* ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via dojo/topic.publish() for different phases of an IO operation. See dojo/main.\_\_IoPublish for a list of topics that are published.
|
**Returns:** undefined
| programming_docs |
dojo dojo/currency dojo/currency
=============
Summary
-------
localized formatting and parsing routines for currencies
extends dojo.number to provide culturally-appropriate formatting of values in various world currencies, including use of a currency symbol. The currencies are specified by a three-letter international symbol in all uppercase, and support for the currencies is provided by the data in `dojo.cldr`. The scripts generating dojo.cldr specify which currency support is included. A fixed number of decimal places is determined based on the currency type and is not determined by the 'pattern' argument. The fractional portion is optional, by default, and variable length decimals are not supported.
See the [dojo/currency reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/currency.html) for more information.
Methods
-------
###
`format``(value,options)`
Defined by [dojo/currency](currency)
Format a Number as a currency, using locale-specific settings
Create a string from a Number using a known, localized pattern. [Formatting patterns](http://www.unicode.org/reports/tr35/#Number_Elements) appropriate to the locale are chosen from the [CLDR](http://unicode.org/cldr) as well as the appropriate symbols and delimiters and number of decimal places.
| Parameter | Type | Description |
| --- | --- | --- |
| value | Number | the number to be formatted. |
| options | \_\_FormatOptions | *Optional* |
**Returns:** undefined
###
`parse``(expression,options)`
Defined by [dojo/currency](currency)
| Parameter | Type | Description |
| --- | --- | --- |
| expression | String | |
| options | Object | *Optional*
An object with the following properties:* type (String, optional): Should not be set. Value is assumed to be currency.
* currency (String, optional): an [ISO4217](http://en.wikipedia.org/wiki/ISO_4217) currency code, a three letter sequence like "USD". For use with dojo.currency only.
* symbol (String, optional): localized currency symbol. The default will be looked up in table of supported currencies in `dojo.cldr` A [ISO4217](http://en.wikipedia.org/wiki/ISO_4217) currency code will be used if not found.
* places (Number, optional): fixed number of decimal places to accept. The default is determined based on which currency is used.
* fractional (Boolean|Array, optional): Whether to include the fractional portion, where the number of decimal places are implied by the currency or explicit 'places' parameter. The value [true,false] makes the fractional portion optional. By default for currencies, it the fractional portion is optional.
* pattern (String, optional): override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization. Literal characters in patterns are not supported.
* locale (String, optional): override the locale used to determine formatting rules
* strict (Boolean, optional): strict parsing, false by default. Strict parsing requires input as produced by the format() method. Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
|
**Returns:** undefined
###
`regexp``(options)`
Defined by [dojo/currency](currency)
| Parameter | Type | Description |
| --- | --- | --- |
| options | Object | *Optional*
An object with the following properties:* pattern (String, optional): override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization.
* type (String, optional): choose a format type based on the locale from the following: decimal, scientific (not yet supported), percent, currency. decimal by default.
* locale (String, optional): override the locale used to determine formatting rules
* strict (Boolean, optional): strict parsing, false by default. Strict parsing requires input as produced by the format() method. Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
* places (Number|String, optional): number of decimal places to accept: Infinity, a positive number, or a range "n,m". Defined by pattern or Infinity if pattern not provided.
|
**Returns:** undefined
dojo dojo/request.__MethodOptions dojo/request.\_\_MethodOptions
==============================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new request.__MethodOptions()`
Properties
----------
### method
Defined by: [dojo/request](request)
The HTTP method to use to make the request. Must be uppercase.
dojo dojo/regexp dojo/regexp
===========
Summary
-------
Regular expressions and Builder resources
See the [dojo/regexp reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/regexp.html) for more information.
Methods
-------
###
`buildGroupRE``(arr,re,nonCapture)`
Defined by [dojo/regexp](regexp)
Builds a regular expression that groups subexpressions
A utility function used by some of the RE generators. The subexpressions are constructed by the function, re, in the second parameter. re builds one subexpression for each elem in the array a, in the first parameter. Returns a string for a regular expression that groups all the subexpressions.
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Object | Array | A single value or an array of values. |
| re | Function | A function. Takes one parameter and converts it to a regular expression. |
| nonCapture | Boolean | *Optional*
If true, uses non-capturing match, otherwise matches are retained by regular expression. Defaults to false |
**Returns:** undefined
###
`escapeString``(str,except)`
Defined by [dojo/regexp](regexp)
Adds escape sequences for special characters in regular expressions
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | |
| except | String | *Optional*
a String with special characters to be left unescaped |
**Returns:** undefined
###
`group``(expression,nonCapture)`
Defined by [dojo/regexp](regexp)
adds group match to expression
| Parameter | Type | Description |
| --- | --- | --- |
| expression | String | |
| nonCapture | Boolean | *Optional*
If true, uses non-capturing match, otherwise matches are retained by regular expression. |
**Returns:** string
dojo dojo/main.doc dojo/main.doc
=============
Summary
-------
Alias for the current document. 'doc' can be modified for temporary context shifting. See also withDoc().
Use this rather than referring to 'window.document' to ensure your code runs correctly in managed contexts.
Examples
--------
### Example 1
```
n.appendChild(dojo.doc.createElement('div'));
```
Properties
----------
### documentElement
Defined by: [dojox/gfx/\_base](http://dojotoolkit.org/api/1.10/dojox/gfx/_base)
### dojoClick
Defined by: [dojox/mobile/common](http://dojotoolkit.org/api/1.10/dojox/mobile/common)
dojo dojo/topic dojo/topic
==========
Summary
-------
Pubsub hub.
See the [dojo/topic reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/topic.html) for more information.
Examples
--------
### Example 1
```
topic.subscribe("some/topic", function(event){
... do something with event
});
topic.publish("some/topic", {name:"some event", ...});
```
Methods
-------
###
`publish``(topic,event)`
Defined by [dojo/topic](topic)
Publishes a message to a topic on the pub/sub hub. All arguments after the first will be passed to the subscribers, so any number of arguments can be provided (not just event).
| Parameter | Type | Description |
| --- | --- | --- |
| topic | String | The name of the topic to publish to |
| event | Object | An event to distribute to the topic listeners |
**Returns:** undefined
###
`subscribe``(topic,listener)`
Defined by [dojo/topic](topic)
Subscribes to a topic on the pub/sub hub
| Parameter | Type | Description |
| --- | --- | --- |
| topic | String | The topic to subscribe to |
| listener | Function | A function to call when a message is published to the given topic |
**Returns:** undefined
dojo dojo/main.regexp dojo/main.regexp
================
Summary
-------
Regular expressions and Builder resources
Methods
-------
###
`buildGroupRE``(arr,re,nonCapture)`
Defined by [dojo/regexp](regexp)
Builds a regular expression that groups subexpressions
A utility function used by some of the RE generators. The subexpressions are constructed by the function, re, in the second parameter. re builds one subexpression for each elem in the array a, in the first parameter. Returns a string for a regular expression that groups all the subexpressions.
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Object | Array | A single value or an array of values. |
| re | Function | A function. Takes one parameter and converts it to a regular expression. |
| nonCapture | Boolean | *Optional*
If true, uses non-capturing match, otherwise matches are retained by regular expression. Defaults to false |
**Returns:** undefined
###
`escapeString``(str,except)`
Defined by [dojo/regexp](regexp)
Adds escape sequences for special characters in regular expressions
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | |
| except | String | *Optional*
a String with special characters to be left unescaped |
**Returns:** undefined
###
`group``(expression,nonCapture)`
Defined by [dojo/regexp](regexp)
adds group match to expression
| Parameter | Type | Description |
| --- | --- | --- |
| expression | String | |
| nonCapture | Boolean | *Optional*
If true, uses non-capturing match, otherwise matches are retained by regular expression. |
**Returns:** string
dojo dojo/main.rpc dojo/main.rpc
=============
Methods
-------
###
`JsonpService``()`
Defined by [dojo/rpc/JsonpService](rpc/jsonpservice)
###
`JsonService``()`
Defined by [dojo/rpc/JsonService](rpc/jsonservice)
###
`RpcService``()`
Defined by [dojo/rpc/RpcService](rpc/rpcservice)
dojo dojo/main.scopeMap dojo/main.scopeMap
==================
Properties
----------
### dijit
Defined by: [dojo/\_base/kernel](_base/kernel)
### dojo
Defined by: [dojo/\_base/kernel](_base/kernel)
### dojox
Defined by: [dojo/\_base/kernel](_base/kernel)
dojo dojo/main.back dojo/main.back
==============
Summary
-------
Browser history management resources
Methods
-------
###
`addToHistory``(args)`
Defined by [dojo/back](back)
adds a state object (args) to the history list.
To support getting back button notifications, the object argument should implement a function called either "back", "backButton", or "handle". The string "back" will be passed as the first and only argument to this callback.
To support getting forward button notifications, the object argument should implement a function called either "forward", "forwardButton", or "handle". The string "forward" will be passed as the first and only argument to this callback.
If you want the browser location string to change, define "changeUrl" on the object. If the value of "changeUrl" is true, then a unique number will be appended to the URL as a fragment identifier (<http://some.domain.com/path#uniquenumber>). If it is any other value that does not evaluate to false, that value will be used as the fragment identifier. For example, if changeUrl: 'page1', then the URL will look like: <http://some.domain.com/path#page1>
There are problems with using [dojo/back](back) with semantically-named fragment identifiers ("hash values" on an URL). In most browsers it will be hard for [dojo/back](back) to know distinguish a back from a forward event in those cases. For back/forward support to work best, the fragment ID should always be a unique value (something using new Date().getTime() for example). If you want to detect hash changes using semantic fragment IDs, then consider using [dojo/hash](hash) instead (in Dojo 1.4+).
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | The state object that will be added to the history list. |
Examples
--------
### Example 1
```
back.addToHistory({
back: function(){ console.log('back pressed'); },
forward: function(){ console.log('forward pressed'); },
changeUrl: true
});
```
###
`getHash``()`
Defined by [dojo/back](back)
**Returns:** undefined
###
`goBack``()`
Defined by [dojo/back](back)
private method. Do not call this directly.
###
`goForward``()`
Defined by [dojo/back](back)
private method. Do not call this directly.
###
`init``()`
Defined by [dojo/back](back)
Initializes the undo stack. This must be called from a
dojo dojo/currency.__FormatOptions dojo/currency.\_\_FormatOptions
===============================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new currency.__FormatOptions()`
Properties
----------
### currency
Defined by: [dojo/currency](currency)
an [ISO4217](http://en.wikipedia.org/wiki/ISO_4217) currency code, a three letter sequence like "USD". For use with dojo.currency only.
### fractional
Defined by: [dojo/number](number)
If false, show no decimal places, overriding places and pattern settings.
### locale
Defined by: [dojo/number](number)
override the locale used to determine formatting rules
### pattern
Defined by: [dojo/number](number)
override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization. Literal characters in patterns are not supported.
### places
Defined by: [dojo/currency](currency)
number of decimal places to show. Default is defined based on which currency is used.
### round
Defined by: [dojo/number](number)
5 rounds to nearest .5; 0 rounds to nearest whole (default). -1 means do not round.
### symbol
Defined by: [dojo/currency](currency)
localized currency symbol. The default will be looked up in table of supported currencies in `dojo.cldr` A [ISO4217](http://en.wikipedia.org/wiki/ISO_4217) currency code will be used if not found.
### type
Defined by: [dojo/currency](currency)
Should not be set. Value is assumed to be "currency".
dojo dojo/main.keys dojo/main.keys
==============
Summary
-------
Definitions for common key values. Client code should test keyCode against these named constants, as the actual codes can vary by browser.
Properties
----------
### ALT
Defined by: [dojo/keys](keys)
### BACKSPACE
Defined by: [dojo/keys](keys)
### CAPS\_LOCK
Defined by: [dojo/keys](keys)
### CLEAR
Defined by: [dojo/keys](keys)
### copyKey
Defined by: [dojo/keys](keys)
### CTRL
Defined by: [dojo/keys](keys)
### DELETE
Defined by: [dojo/keys](keys)
### DOWN\_ARROW
Defined by: [dojo/keys](keys)
### DOWN\_DPAD
Defined by: [dojo/keys](keys)
### END
Defined by: [dojo/keys](keys)
### ENTER
Defined by: [dojo/keys](keys)
### ESCAPE
Defined by: [dojo/keys](keys)
### F1
Defined by: [dojo/keys](keys)
### F10
Defined by: [dojo/keys](keys)
### F11
Defined by: [dojo/keys](keys)
### F12
Defined by: [dojo/keys](keys)
### F13
Defined by: [dojo/keys](keys)
### F14
Defined by: [dojo/keys](keys)
### F15
Defined by: [dojo/keys](keys)
### F2
Defined by: [dojo/keys](keys)
### F3
Defined by: [dojo/keys](keys)
### F4
Defined by: [dojo/keys](keys)
### F5
Defined by: [dojo/keys](keys)
### F6
Defined by: [dojo/keys](keys)
### F7
Defined by: [dojo/keys](keys)
### F8
Defined by: [dojo/keys](keys)
### F9
Defined by: [dojo/keys](keys)
### HELP
Defined by: [dojo/keys](keys)
### HOME
Defined by: [dojo/keys](keys)
### INSERT
Defined by: [dojo/keys](keys)
### LEFT\_ARROW
Defined by: [dojo/keys](keys)
### LEFT\_DPAD
Defined by: [dojo/keys](keys)
### LEFT\_WINDOW
Defined by: [dojo/keys](keys)
### META
Defined by: [dojo/keys](keys)
### NUM\_LOCK
Defined by: [dojo/keys](keys)
### NUMPAD\_0
Defined by: [dojo/keys](keys)
### NUMPAD\_1
Defined by: [dojo/keys](keys)
### NUMPAD\_2
Defined by: [dojo/keys](keys)
### NUMPAD\_3
Defined by: [dojo/keys](keys)
### NUMPAD\_4
Defined by: [dojo/keys](keys)
### NUMPAD\_5
Defined by: [dojo/keys](keys)
### NUMPAD\_6
Defined by: [dojo/keys](keys)
### NUMPAD\_7
Defined by: [dojo/keys](keys)
### NUMPAD\_8
Defined by: [dojo/keys](keys)
### NUMPAD\_9
Defined by: [dojo/keys](keys)
### NUMPAD\_DIVIDE
Defined by: [dojo/keys](keys)
### NUMPAD\_ENTER
Defined by: [dojo/keys](keys)
### NUMPAD\_MINUS
Defined by: [dojo/keys](keys)
### NUMPAD\_MULTIPLY
Defined by: [dojo/keys](keys)
### NUMPAD\_PERIOD
Defined by: [dojo/keys](keys)
### NUMPAD\_PLUS
Defined by: [dojo/keys](keys)
### PAGE\_DOWN
Defined by: [dojo/keys](keys)
### PAGE\_UP
Defined by: [dojo/keys](keys)
### PAUSE
Defined by: [dojo/keys](keys)
### RIGHT\_ARROW
Defined by: [dojo/keys](keys)
### RIGHT\_DPAD
Defined by: [dojo/keys](keys)
### RIGHT\_WINDOW
Defined by: [dojo/keys](keys)
### SCROLL\_LOCK
Defined by: [dojo/keys](keys)
### SELECT
Defined by: [dojo/keys](keys)
### SHIFT
Defined by: [dojo/keys](keys)
### SPACE
Defined by: [dojo/keys](keys)
### TAB
Defined by: [dojo/keys](keys)
### UP\_ARROW
Defined by: [dojo/keys](keys)
### UP\_DPAD
Defined by: [dojo/keys](keys)
dojo dojo/NodeList-manipulate dojo/NodeList-manipulate
========================
Summary
-------
Adds chainable methods to dojo.query() / NodeList instances for manipulating HTML and DOM nodes and their properties.
Usage
-----
NodeList-manipulate`();` See the [dojo/NodeList-manipulate reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/NodeList-manipulate.html) for more information.
Methods
-------
dojo dojo/loadInit dojo/loadInit
=============
Properties
----------
### dynamic
Defined by: [dojo/loadInit](loadinit)
### load
Defined by: [dojo/loadInit](loadinit)
Methods
-------
###
`normalize``(id)`
Defined by [dojo/loadInit](loadinit)
| Parameter | Type | Description |
| --- | --- | --- |
| id | undefined | |
**Returns:** undefined
dojo dojo/io-query dojo/io-query
=============
Summary
-------
This module defines query string processing functions.
See the [dojo/io-query reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/io-query.html) for more information.
Methods
-------
###
`objectToQuery``(map)`
Defined by [dojo/io-query](io-query)
takes a name/value mapping object and returns a string representing a URL-encoded version of that object.
| Parameter | Type | Description |
| --- | --- | --- |
| map | Object | |
**Returns:** undefined
Examples
--------
### Example 1
this object:
```
{
blah: "blah",
multi: [
"thud",
"thonk"
]
};
```
yields the following query string:
```
"blah=blah&multi=thud&multi=thonk"
```
###
`queryToObject``(str)`
Defined by [dojo/io-query](io-query)
Create an object representing a de-serialized query section of a URL. Query keys with multiple values are returned in an array.
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | |
**Returns:** object
Examples
--------
### Example 1
This string:
```
"foo=bar&foo=baz&thinger=%20spaces%20=blah&zonk=blarg&"
```
results in this object structure:
```
{
foo: [ "bar", "baz" ],
thinger: " spaces =blah",
zonk: "blarg"
}
```
Note that spaces and other urlencoded entities are correctly handled.
| programming_docs |
dojo dojo/main.data dojo/main.data
==============
Properties
----------
### api
Defined by: [dojo/data/api/Read](data/api/read)
### util
Defined by: [dojo/data/util/filter](data/util/filter)
Methods
-------
###
`ItemFileReadStore``()`
Defined by [dojo/data/ItemFileReadStore](data/itemfilereadstore)
###
`ItemFileWriteStore``()`
Defined by [dojo/data/ItemFileWriteStore](data/itemfilewritestore)
###
`ObjectStore``()`
Defined by [dojo/data/ObjectStore](data/objectstore)
dojo dojo/main.touch dojo/main.touch
===============
Summary
-------
This module provides unified touch event handlers by exporting press, move, release and cancel which can also run well on desktop. Based on <http://dvcs.w3.org/hg/webevents/raw-file/tip/touchevents.html> Also, if the dojoClick property is set to truthy on a DOM node, [dojo/touch](touch) generates click events immediately for this node and its descendants (except for descendants that have a dojoClick property set to falsy), to avoid the delay before native browser click events, and regardless of whether evt.preventDefault() was called in a touch.press event listener.
Examples
--------
### Example 1
Used with dojo/on
```
define(["dojo/on", "dojo/touch"], function(on, touch){
on(node, touch.press, function(e){});
on(node, touch.move, function(e){});
on(node, touch.release, function(e){});
on(node, touch.cancel, function(e){});
```
### Example 2
Used with touch.\* directly
```
touch.press(node, function(e){});
touch.move(node, function(e){});
touch.release(node, function(e){});
touch.cancel(node, function(e){});
```
### Example 3
Have dojo/touch generate clicks without delay, with a default move threshold of 4 pixels
```
node.dojoClick = true;
```
### Example 4
Have dojo/touch generate clicks without delay, with a move threshold of 10 pixels horizontally and vertically
```
node.dojoClick = 10;
```
### Example 5
Have dojo/touch generate clicks without delay, with a move threshold of 50 pixels horizontally and 10 pixels vertically
```
node.dojoClick = {x:50, y:5};
```
### Example 6
Disable clicks without delay generated by dojo/touch on a node that has an ancestor with property dojoClick set to truthy
```
node.dojoClick = false;
```
Methods
-------
###
`cancel``(node,listener)`
Defined by [dojo/touch](touch)
Register a listener to 'touchcancel'|'mouseleave' for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`enter``(node,listener)`
Defined by [dojo/touch](touch)
Register a listener to mouse.enter or touch equivalent for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`leave``(node,listener)`
Defined by [dojo/touch](touch)
Register a listener to mouse.leave or touch equivalent for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`move``(node,listener)`
Defined by [dojo/touch](touch)
Register a listener that fires when the mouse cursor or a finger is dragged over the given node.
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`out``(node,listener)`
Defined by [dojo/touch](touch)
Register a listener to 'mouseout' or touch equivalent for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`over``(node,listener)`
Defined by [dojo/touch](touch)
Register a listener to 'mouseover' or touch equivalent for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`press``(node,listener)`
Defined by [dojo/touch](touch)
Register a listener to 'touchstart'|'mousedown' for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`release``(node,listener)`
Defined by [dojo/touch](touch)
Register a listener to releasing the mouse button while the cursor is over the given node (i.e. "mouseup") or for removing the finger from the screen while touching the given node.
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
dojo dojo/cookie dojo/cookie
===========
Summary
-------
Get or set a cookie.
If one argument is passed, returns the value of the cookie For two or more arguments, acts as a setter.
Usage
-----
cookie`(name,value,props);`
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | Name of the cookie |
| value | String | *Optional*
Value for the cookie |
| props | Object | *Optional*
Properties for the cookie |
**Returns:** undefined
See the [dojo/cookie reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/cookie.html) for more information.
Examples
--------
### Example 1
set a cookie with the JSON-serialized contents of an object which will expire 5 days from now:
```
require(["dojo/cookie", "dojo/json"], function(cookie, json){
cookie("configObj", json.stringify(config, {expires: 5 }));
});
```
### Example 2
de-serialize a cookie back into a JavaScript object:
```
require(["dojo/cookie", "dojo/json"], function(cookie, json){
config = json.parse(cookie("configObj"));
});
```
### Example 3
delete a cookie:
```
require(["dojo/cookie"], function(cookie){
cookie("configObj", null, {expires: -1});
});
```
Methods
-------
###
`isSupported``()`
Defined by [dojo/cookie](cookie)
Use to determine if the current browser supports cookies or not.
Returns true if user allows cookies. Returns false if user doesn't allow cookies.
dojo dojo/Stateful dojo/Stateful
=============
Summary
-------
Base class for objects that provide named properties with optional getter/setter control and the ability to watch for property changes
The class also provides the functionality to auto-magically manage getters and setters for object attributes/properties.
Getters and Setters should follow the format of \_xxxGetter or \_xxxSetter where the xxx is a name of the attribute to handle. So an attribute of "foo" would have a custom getter of \_fooGetter and a custom setter of \_fooSetter.
See the [dojo/Stateful reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/Stateful.html) for more information.
Examples
--------
### Example 1
```
require(["dojo/Stateful", function(Stateful) {
var obj = new Stateful();
obj.watch("foo", function(){
console.log("foo changed to " + this.get("foo"));
});
obj.set("foo","bar");
});
```
Properties
----------
Methods
-------
###
`get``(name)`
Defined by [dojo/Stateful](stateful)
Get a property on a Stateful instance.
Get a named property on a Stateful object. The property may potentially be retrieved via a getter method in subclasses. In the base class this just retrieves the object's property.
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | The property to get. |
**Returns:** any | undefined
The property value on this Stateful instance.
Examples
--------
### Example 1
```
require(["dojo/Stateful", function(Stateful) {
var stateful = new Stateful({foo: 3});
stateful.get("foo") // returns 3
stateful.foo // returns 3
});
```
###
`postscript``(params)`
Defined by [dojo/Stateful](stateful)
| Parameter | Type | Description |
| --- | --- | --- |
| params | Object | *Optional* |
###
`set``(name,value)`
Defined by [dojo/Stateful](stateful)
Set a property on a Stateful instance
Sets named properties on a stateful object and notifies any watchers of the property. A programmatic setter may be defined in subclasses.
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | The property to set. |
| value | Object | The value to set in the property. |
**Returns:** any | function
The function returns this dojo.Stateful instance.
Examples
--------
### Example 1
```
require(["dojo/Stateful", function(Stateful) {
var stateful = new Stateful();
stateful.watch(function(name, oldValue, value){
// this will be called on the set below
}
stateful.set(foo, 5);
```
set() may also be called with a hash of name/value pairs, ex:
```
stateful.set({
foo: "Howdy",
bar: 3
});
});
```
This is equivalent to calling set(foo, "Howdy") and set(bar, 3)
###
`watch``(name,callback)`
Defined by [dojo/Stateful](stateful)
Watches a property for changes
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | *Optional*
Indicates the property to watch. This is optional (the callback may be the only parameter), and if omitted, all the properties will be watched |
| callback | Function | The function to execute when the property changes. This will be called after the property has been changed. The callback will be called with the |this| set to the instance, the first argument as the name of the property, the second argument as the old value and the third argument as the new value. |
**Returns:** any | object
An object handle for the watch. The unwatch method of this object can be used to discontinue watching this property:
```
var watchHandle = obj.watch("foo", callback);
watchHandle.unwatch(); // callback won't be called now
```
dojo dojo/dom-geometry dojo/dom-geometry
=================
Summary
-------
This module defines the core dojo DOM geometry API.
See the [dojo/dom-geometry reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dom-geometry.html) for more information.
Properties
----------
### boxModel
Defined by: [dojo/dom-geometry](dom-geometry)
Methods
-------
###
`docScroll``(doc)`
Defined by [dojo/dom-geometry](dom-geometry)
Returns an object with {node, x, y} with corresponding offsets.
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | *Optional*
Optional document to query. If unspecified, use win.doc. |
**Returns:** Object | undefined
###
`fixIeBiDiScrollLeft``(scrollLeft,doc)`
Defined by [dojo/dom-geometry](dom-geometry)
In RTL direction, scrollLeft should be a negative value, but IE returns a positive one. All codes using documentElement.scrollLeft must call this function to fix this error, otherwise the position will offset to right when there is a horizontal scrollbar.
| Parameter | Type | Description |
| --- | --- | --- |
| scrollLeft | Number | |
| doc | Document | *Optional*
Optional document to query. If unspecified, use win.doc. |
**Returns:** Number | number
###
`getBorderExtents``(node,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
returns an object with properties useful for noting the border dimensions.
* l/t/r/b = the sum of left/top/right/bottom border (respectively)
* w = the sum of the left and right border
* h = the sum of the top and bottom border
The w/h are used for calculating boxes. Normally application code will not need to invoke this directly, and will use the ...box... functions instead.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getContentBox``(node,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
Returns an object that encodes the width, height, left and top positions of the node's content box, irrespective of the current box model.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getIeDocumentElementOffset``(doc)`
Defined by [dojo/dom-geometry](dom-geometry)
returns the offset in x and y from the document body to the visual edge of the page for IE
The following values in IE contain an offset:
```
event.clientX
event.clientY
node.getBoundingClientRect().left
node.getBoundingClientRect().top
```
But other position related values do not contain this offset,
such as node.offsetLeft, node.offsetTop, node.style.left and node.style.top. The offset is always (2, 2) in LTR direction. When the body is in RTL direction, the offset counts the width of left scroll bar's width. This function computes the actual offset.
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | *Optional*
Optional document to query. If unspecified, use win.doc. |
**Returns:** object
###
`getMarginBox``(node,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
returns an object that encodes the width, height, left and top positions of the node's margin box.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getMarginExtents``(node,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
returns object with properties useful for box fitting with regards to box margins (i.e., the outer-box).
* l/t = marginLeft, marginTop, respectively
* w = total width, margin inclusive
* h = total height, margin inclusive
The w/h are used for calculating boxes. Normally application code will not need to invoke this directly, and will use the ...box... functions instead.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getMarginSize``(node,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
returns an object that encodes the width and height of the node's margin box
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getPadBorderExtents``(node,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
Returns object with properties useful for box fitting with regards to padding.
* l/t/r/b = the sum of left/top/right/bottom padding and left/top/right/bottom border (respectively)
* w = the sum of the left and right padding and border
* h = the sum of the top and bottom padding and border
The w/h are used for calculating boxes. Normally application code will not need to invoke this directly, and will use the ...box... functions instead.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getPadExtents``(node,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
Returns object with special values specifically useful for node fitting.
Returns an object with `w`, `h`, `l`, `t` properties:
```
l/t/r/b = left/top/right/bottom padding (respectively)
w = the total of the left and right padding
h = the total of the top and bottom padding
```
If 'node' has position, l/t forms the origin for child nodes.
The w/h are used for calculating boxes. Normally application code will not need to invoke this directly, and will use the ...box... functions instead.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`isBodyLtr``(doc)`
Defined by [dojo/dom-geometry](dom-geometry)
Returns true if the current language is left-to-right, and false otherwise.
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | *Optional*
Optional document to query. If unspecified, use win.doc. |
**Returns:** Boolean | boolean
###
`normalizeEvent``(event)`
Defined by [dojo/dom-geometry](dom-geometry)
Normalizes the geometry of a DOM event, normalizing the pageX, pageY, offsetX, offsetY, layerX, and layerX properties
| Parameter | Type | Description |
| --- | --- | --- |
| event | Object | |
###
`position``(node,includeScroll)`
Defined by [dojo/dom-geometry](dom-geometry)
Gets the position and size of the passed element relative to the viewport (if includeScroll==false), or relative to the document root (if includeScroll==true).
Returns an object of the form: `{ x: 100, y: 300, w: 20, h: 15 }`. If includeScroll==true, the x and y values will include any document offsets that may affect the position relative to the viewport. Uses the border-box model (inclusive of border and padding but not margin). Does not act as a setter.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | |
| includeScroll | Boolean | *Optional* |
**Returns:** Object | object
###
`setContentSize``(node,box,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
Sets the size of the node's contents, irrespective of margins, padding, or borders.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| box | Object | hash with optional "w", and "h" properties for "width", and "height" respectively. All specified properties should have numeric values in whole pixels. |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
###
`setMarginBox``(node,box,computedStyle)`
Defined by [dojo/dom-geometry](dom-geometry)
sets the size of the node's margin box and placement (left/top), irrespective of box model. Think of it as a passthrough to setBox that handles box-model vagaries for you.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| box | Object | hash with optional "l", "t", "w", and "h" properties for "left", "right", "width", and "height" respectively. All specified properties should have numeric values in whole pixels. |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
| programming_docs |
dojo dojo/behavior dojo/behavior
=============
Summary
-------
Deprecated. [dojo/behavior](behavior)'s functionality can be achieved using event delegation using [dojo/on](on) and on.selector().
A very simple, lightweight mechanism for applying code to existing documents, based around [dojo/query](query) (CSS3 selectors) for node selection, and a simple two-command API: `add()` and `apply()`;
Behaviors apply to a given page, and are registered following the syntax options described by `add()` to match nodes to actions, or "behaviors".
Added behaviors are applied to the current DOM when .apply() is called, matching only new nodes found since .apply() was last called.
See the [dojo/behavior reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/behavior.html) for more information.
Properties
----------
Methods
-------
###
`add``(behaviorObj)`
Defined by [dojo/behavior](behavior)
Add the specified behavior to the list of behaviors, ignoring existing matches.
Add the specified behavior to the list of behaviors which will be applied the next time apply() is called. Calls to add() for an already existing behavior do not replace the previous rules, but are instead additive. New nodes which match the rule will have all add()-ed behaviors applied to them when matched.
The "found" method is a generalized handler that's called as soon as the node matches the selector. Rules for values that follow also apply to the "found" key.
The "on\*" handlers are attached with `dojo.connect()`, using the matching node
If the value corresponding to the ID key is a function and not a list, it's treated as though it was the value of "found".
[dojo/behavior.add()](behavior#add) can be called any number of times before the DOM is ready. [dojo/behavior.apply()](behavior#apply) is called automatically by `dojo.addOnLoad`, though can be called to re-apply previously added behaviors anytime the DOM changes.
There are a variety of formats permitted in the behaviorObject
| Parameter | Type | Description |
| --- | --- | --- |
| behaviorObj | Object | The behavior object that will be added to behaviors list. The behaviors in the list will be applied the next time apply() is called. |
Examples
--------
### Example 1
Simple list of properties. "found" is special. "Found" is assumed if no property object for a given selector, and property is a function.
```
behavior.add({
"#id": {
"found": function(element){
// node match found
},
"onclick": function(evt){
// register onclick handler for found node
}
},
"#otherid": function(element){
// assumes "found" with this syntax
}
});
```
### Example 2
If property is a string, a dojo.publish will be issued on the channel:
```
behavior.add({
// topic.publish() whenever class="noclick" found on anchors
"a.noclick": "/got/newAnchor",
"div.wrapper": {
"onclick": "/node/wasClicked"
}
});
topic.subscribe("/got/newAnchor", function(node){
// handle node finding when dojo/behavior.apply() is called,
// provided a newly matched node is found.
});
```
### Example 3
Scoping can be accomplished by passing an object as a property to a connection handle (on\*):
```
behavior.add({
"#id": {
// like calling dojo.hitch(foo,"bar"). execute foo.bar() in scope of foo
"onmouseenter": { targetObj: foo, targetFunc: "bar" },
"onmouseleave": { targetObj: foo, targetFunc: "baz" }
}
});
```
### Example 4
Behaviors match on CSS3 Selectors, powered by dojo/query. Example selectors:
```
behavior.add({
// match all direct descendants
"#id4 > *": function(element){
// ...
},
// match the first child node that's an element
"#id4 > :first-child": { ... },
// match the last child node that's an element
"#id4 > :last-child": { ... },
// all elements of type tagname
"tagname": {
// ...
},
"tagname1 tagname2 tagname3": {
// ...
},
".classname": {
// ...
},
"tagname.classname": {
// ...
}
});
```
###
`apply``()`
Defined by [dojo/behavior](behavior)
Applies all currently registered behaviors to the document.
Applies all currently registered behaviors to the document, taking care to ensure that only incremental updates are made since the last time add() or apply() were called.
If new matching nodes have been added, all rules in a behavior will be applied to that node. For previously matched nodes, only behaviors which have been added since the last call to apply() will be added to the nodes.
apply() is called once automatically by `dojo.addOnLoad`, so registering behaviors with [dojo/behavior.add()](behavior#add) before the DOM is ready is acceptable, provided the dojo.behavior module is ready.
Calling appy() manually after manipulating the DOM is required to rescan the DOM and apply newly .add()ed behaviors, or to match nodes that match existing behaviors when those nodes are added to the DOM.
dojo dojo/dom-attr dojo/dom-attr
=============
See the [dojo/dom-attr reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dom-attr.html) for more information.
Methods
-------
###
`get``(node,name)`
Defined by [dojo/dom-attr](dom-attr)
Gets an attribute on an HTML element.
Handles normalized getting of attributes on DOM Nodes.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to get the attribute on |
| name | String | the name of the attribute to get. |
**Returns:** any | undefined | null
the value of the requested attribute or null if that attribute does not have a specified or default value;
Examples
--------
### Example 1
```
// get the current value of the "foo" attribute on a node
require(["dojo/dom-attr", "dojo/dom"], function(domAttr, dom){
domAttr.get(dom.byId("nodeId"), "foo");
// or we can just pass the id:
domAttr.get("nodeId", "foo");
});
```
###
`getNodeProp``(node,name)`
Defined by [dojo/dom-attr](dom-attr)
Returns an effective value of a property or an attribute.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to remove the attribute from |
| name | String | the name of the attribute |
**Returns:** any
the value of the attribute
###
`has``(node,name)`
Defined by [dojo/dom-attr](dom-attr)
Returns true if the requested attribute is specified on the given element, and false otherwise.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to check |
| name | String | the name of the attribute |
**Returns:** Boolean | contentWindow.document isn't accessible within IE7/8
true if the requested attribute is specified on the given element, and false otherwise
###
`remove``(node,name)`
Defined by [dojo/dom-attr](dom-attr)
Removes an attribute from an HTML element.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to remove the attribute from |
| name | String | the name of the attribute to remove |
###
`set``(node,name,value)`
Defined by [dojo/dom-attr](dom-attr)
Sets an attribute on an HTML element.
Handles normalized setting of attributes on DOM Nodes.
When passing functions as values, note that they will not be directly assigned to slots on the node, but rather the default behavior will be removed and the new behavior will be added using `dojo.connect()`, meaning that event handler properties will be normalized and that some caveats with regards to non-standard behaviors for onsubmit apply. Namely that you should cancel form submission using `dojo.stopEvent()` on the passed event object instead of returning a boolean value from the handler itself.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to set the attribute on |
| name | String | Object | the name of the attribute to set, or a hash of key-value pairs to set. |
| value | String | *Optional*
the value to set for the attribute, if the name is a string. |
**Returns:** any | undefined
the DOM node
Examples
--------
### Example 1
```
// use attr() to set the tab index
require(["dojo/dom-attr"], function(domAttr){
domAttr.set("nodeId", "tabIndex", 3);
});
```
### Example 2
Set multiple values at once, including event handlers:
```
require(["dojo/dom-attr"],
function(domAttr){
domAttr.set("formId", {
"foo": "bar",
"tabIndex": -1,
"method": "POST"
}
});
```
dojo dojo/main.gears dojo/main.gears
===============
Summary
-------
TODOC
Properties
----------
### available
Defined by: [dojo/gears](gears)
True if client is using Google Gears
Methods
-------
dojo dojo/Deferred dojo/Deferred
=============
Summary
-------
Creates a new deferred. This API is preferred over [dojo/\_base/Deferred](_base/deferred).
Creates a new deferred, as an abstraction over (primarily) asynchronous operations. The deferred is the private interface that should not be returned to calling code. That's what the `promise` is for. See [dojo/promise/Promise](promise/promise).
Usage
-----
Deferred`(canceler);`
| Parameter | Type | Description |
| --- | --- | --- |
| canceler | Function | *Optional*
Will be invoked if the deferred is canceled. The canceler receives the reason the deferred was canceled as its argument. The deferred is rejected with its return value, or a new `dojo/errors/CancelError` instance. |
See the [dojo/Deferred reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/Deferred.html) for more information.
Properties
----------
### promise
Defined by: [dojo/Deferred](deferred)
Methods
-------
###
`cancel``(reason,strict)`
Defined by [dojo/Deferred](deferred)
Inform the deferred it may cancel its asynchronous operation.
Inform the deferred it may cancel its asynchronous operation. The deferred's (optional) canceler is invoked and the deferred will be left in a rejected state. Can affect other promises that originate with the same deferred.
| Parameter | Type | Description |
| --- | --- | --- |
| reason | any | A message that may be sent to the deferred's canceler, explaining why it's being canceled. |
| strict | Boolean | *Optional*
If strict, will throw an error if the deferred has already been fulfilled and consequently cannot be canceled. |
**Returns:** any
Returns the rejection reason if the deferred was canceled normally.
###
`isCanceled``()`
Defined by [dojo/Deferred](deferred)
Checks whether the deferred has been canceled.
**Returns:** Boolean
###
`isFulfilled``()`
Defined by [dojo/Deferred](deferred)
Checks whether the deferred has been resolved or rejected.
**Returns:** Boolean
###
`isRejected``()`
Defined by [dojo/Deferred](deferred)
Checks whether the deferred has been rejected.
**Returns:** Boolean
###
`isResolved``()`
Defined by [dojo/Deferred](deferred)
Checks whether the deferred has been resolved.
**Returns:** Boolean
###
`progress``(update,strict)`
Defined by [dojo/Deferred](deferred)
Emit a progress update on the deferred.
Emit a progress update on the deferred. Progress updates can be used to communicate updates about the asynchronous operation before it has finished.
| Parameter | Type | Description |
| --- | --- | --- |
| update | any | The progress update. Passed to progbacks. |
| strict | Boolean | *Optional*
If strict, will throw an error if the deferred has already been fulfilled and consequently no progress can be emitted. |
**Returns:** [dojo/promise/Promise](promise/promise)
Returns the original promise for the deferred.
###
`reject``(error,strict)`
Defined by [dojo/Deferred](deferred)
Reject the deferred.
Reject the deferred, putting it in an error state.
| Parameter | Type | Description |
| --- | --- | --- |
| error | any | The error result of the deferred. Passed to errbacks. |
| strict | Boolean | *Optional*
If strict, will throw an error if the deferred has already been fulfilled and consequently cannot be rejected. |
**Returns:** [dojo/promise/Promise](promise/promise) | instance
Returns the original promise for the deferred.
###
`resolve``(value,strict)`
Defined by [dojo/Deferred](deferred)
Resolve the deferred.
Resolve the deferred, putting it in a success state.
| Parameter | Type | Description |
| --- | --- | --- |
| value | any | The result of the deferred. Passed to callbacks. |
| strict | Boolean | *Optional*
If strict, will throw an error if the deferred has already been fulfilled and consequently cannot be resolved. |
**Returns:** [dojo/promise/Promise](promise/promise)
Returns the original promise for the deferred.
###
`then``(callback,errback,progback)`
Defined by [dojo/Deferred](deferred)
Add new callbacks to the deferred.
Add new callbacks to the deferred. Callbacks can be added before or after the deferred is fulfilled.
| Parameter | Type | Description |
| --- | --- | --- |
| callback | Function | *Optional*
Callback to be invoked when the promise is resolved. Receives the resolution value. |
| errback | Function | *Optional*
Callback to be invoked when the promise is rejected. Receives the rejection error. |
| progback | Function | *Optional*
Callback to be invoked when the promise emits a progress update. Receives the progress update. |
**Returns:** [dojo/promise/Promise](promise/promise)
Returns a new promise for the result of the callback(s). This can be used for chaining many asynchronous operations.
###
`toString``()`
Defined by [dojo/Deferred](deferred)
**Returns:** String
Returns `[object Deferred]`.
dojo dojo/dom-style dojo/dom-style
==============
Summary
-------
This module defines the core dojo DOM style API.
See the [dojo/dom-style reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dom-style.html) for more information.
Methods
-------
###
`get``(node,name)`
Defined by [dojox/html/ext-dojo/style](http://dojotoolkit.org/api/1.10/dojox/html/ext-dojo/style)
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | |
| name | String | Object | |
**Returns:** undefined
###
`getComputedStyle``(node)`
Defined by [dojo/dom-style](dom-style)
Returns a "computed style" object.
Gets a "computed style" object which can be used to gather information about the current state of the rendered node.
Note that this may behave differently on different browsers. Values may have different formats and value encodings across browsers.
Note also that this method is expensive. Wherever possible, reuse the returned object.
Use the [dojo/dom-style.get()](dom-style#get) method for more consistent (pixelized) return values.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | A reference to a DOM node. Does NOT support taking an ID string for speed reasons. |
Examples
--------
### Example 1
```
require(["dojo/dom-style", "dojo/dom"], function(domStyle, dom){
domStyle.getComputedStyle(dom.byId('foo')).borderWidth;
});
```
### Example 2
Reusing the returned object, avoiding multiple lookups:
```
require(["dojo/dom-style", "dojo/dom"], function(domStyle, dom){
var cs = domStyle.getComputedStyle(dom.byId("someNode"));
var w = cs.width, h = cs.height;
});
```
###
`set``(node,name,value)`
Defined by [dojox/html/ext-dojo/style](http://dojotoolkit.org/api/1.10/dojox/html/ext-dojo/style)
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | |
| name | String | Object | |
| value | String | *Optional* |
**Returns:** undefined | instance
###
`toPixelValue``(node,value)`
Defined by [dojo/dom-style](dom-style)
converts style value to pixels on IE or return a numeric value.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| value | String | |
**Returns:** Number
dojo dojo/number.__ParseOptions dojo/number.\_\_ParseOptions
============================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new number.__ParseOptions()`
Properties
----------
### fractional
Defined by: [dojo/number](number)
Whether to include the fractional portion, where the number of decimal places are implied by pattern or explicit 'places' parameter. The value [true,false] makes the fractional portion optional.
### locale
Defined by: [dojo/number](number)
override the locale used to determine formatting rules
### pattern
Defined by: [dojo/number](number)
override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization. Literal characters in patterns are not supported.
### strict
Defined by: [dojo/number](number)
strict parsing, false by default. Strict parsing requires input as produced by the format() method. Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
### type
Defined by: [dojo/number](number)
choose a format type based on the locale from the following: decimal, scientific (not yet supported), percent, currency. decimal by default.
dojo dojo/number.__IntegerRegexpFlags dojo/number.\_\_IntegerRegexpFlags
==================================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new number.__IntegerRegexpFlags()`
Properties
----------
### groupSize
Defined by: [dojo/number](number)
group size between separators
### groupSize2
Defined by: [dojo/number](number)
second grouping, where separators 2..n have a different interval than the first separator (for India)
### separator
Defined by: [dojo/number](number)
The character used as the thousands separator. Default is no separator. For more than one symbol use an array, e.g. `[",", ""]`, makes ',' optional.
### signed
Defined by: [dojo/number](number)
The leading plus-or-minus sign. Can be true, false, or `[true,false]`. Default is `[true, false]`, (i.e. will match if it is signed or unsigned).
dojo dojo/date dojo/date
=========
Summary
-------
Date manipulation utilities
See the [dojo/date reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/date.html) for more information.
Methods
-------
###
`add``(date,interval,amount)`
Defined by [dojo/date](date)
Add to a Date in intervals of different size, from milliseconds to years
| Parameter | Type | Description |
| --- | --- | --- |
| date | Date | Date object to start with |
| interval | String | A string representing the interval. One of the following: "year", "month", "day", "hour", "minute", "second", "millisecond", "quarter", "week", "weekday" |
| amount | int | How much to add to the date. |
**Returns:** instance
###
`compare``(date1,date2,portion)`
Defined by [dojo/date](date)
Compare two date objects by date, time, or both.
Returns 0 if equal, positive if a > b, else negative.
| Parameter | Type | Description |
| --- | --- | --- |
| date1 | Date | Date object |
| date2 | Date | *Optional*
Date object. If not specified, the current Date is used. |
| portion | String | *Optional*
A string indicating the "date" or "time" portion of a Date object. Compares both "date" and "time" by default. One of the following: "date", "time", "datetime" |
**Returns:** number
###
`difference``(date1,date2,interval)`
Defined by [dojo/date](date)
Get the difference in a specific unit of time (e.g., number of months, weeks, days, etc.) between two dates, rounded to the nearest integer.
| Parameter | Type | Description |
| --- | --- | --- |
| date1 | Date | Date object |
| date2 | Date | *Optional*
Date object. If not specified, the current Date is used. |
| interval | String | *Optional*
A string representing the interval. One of the following: "year", "month", "day", "hour", "minute", "second", "millisecond", "quarter", "week", "weekday" Defaults to "day". |
**Returns:** undefined
###
`getDaysInMonth``(dateObject)`
Defined by [dojo/date](date)
Returns the number of days in the month used by dateObject
| Parameter | Type | Description |
| --- | --- | --- |
| dateObject | Date | |
**Returns:** number | undefined
###
`getTimezoneName``(dateObject)`
Defined by [dojo/date](date)
Get the user's time zone as provided by the browser
Try to get time zone info from toString or toLocaleString method of the Date object -- UTC offset is not a time zone. See <http://www.twinsun.com/tz/tz-link.htm> Note: results may be inconsistent across browsers.
| Parameter | Type | Description |
| --- | --- | --- |
| dateObject | Date | Needed because the timezone may vary with time (daylight savings) |
**Returns:** undefined
###
`isLeapYear``(dateObject)`
Defined by [dojo/date](date)
Determines if the year of the dateObject is a leap year
Leap years are years with an additional day YYYY-02-29, where the year number is a multiple of four with the following exception: If a year is a multiple of 100, then it is only a leap year if it is also a multiple of 400. For example, 1900 was not a leap year, but 2000 is one.
| Parameter | Type | Description |
| --- | --- | --- |
| dateObject | Date | |
**Returns:** boolean
| programming_docs |
dojo dojo/gears dojo/gears
==========
Summary
-------
TODOC
See the [dojo/gears reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/gears.html) for more information.
Properties
----------
### available
Defined by: [dojo/gears](gears)
True if client is using Google Gears
Methods
-------
dojo dojo/touch dojo/touch
==========
Summary
-------
This module provides unified touch event handlers by exporting press, move, release and cancel which can also run well on desktop. Based on <http://dvcs.w3.org/hg/webevents/raw-file/tip/touchevents.html> Also, if the dojoClick property is set to truthy on a DOM node, [dojo/touch](touch) generates click events immediately for this node and its descendants (except for descendants that have a dojoClick property set to falsy), to avoid the delay before native browser click events, and regardless of whether evt.preventDefault() was called in a touch.press event listener.
See the [dojo/touch reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/touch.html) for more information.
Examples
--------
### Example 1
Used with dojo/on
```
define(["dojo/on", "dojo/touch"], function(on, touch){
on(node, touch.press, function(e){});
on(node, touch.move, function(e){});
on(node, touch.release, function(e){});
on(node, touch.cancel, function(e){});
```
### Example 2
Used with touch.\* directly
```
touch.press(node, function(e){});
touch.move(node, function(e){});
touch.release(node, function(e){});
touch.cancel(node, function(e){});
```
### Example 3
Have dojo/touch generate clicks without delay, with a default move threshold of 4 pixels
```
node.dojoClick = true;
```
### Example 4
Have dojo/touch generate clicks without delay, with a move threshold of 10 pixels horizontally and vertically
```
node.dojoClick = 10;
```
### Example 5
Have dojo/touch generate clicks without delay, with a move threshold of 50 pixels horizontally and 10 pixels vertically
```
node.dojoClick = {x:50, y:5};
```
### Example 6
Disable clicks without delay generated by dojo/touch on a node that has an ancestor with property dojoClick set to truthy
```
node.dojoClick = false;
```
Methods
-------
###
`cancel``(node,listener)`
Defined by [dojo/touch](touch)
Register a listener to 'touchcancel'|'mouseleave' for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`enter``(node,listener)`
Defined by [dojo/touch](touch)
Register a listener to mouse.enter or touch equivalent for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`leave``(node,listener)`
Defined by [dojo/touch](touch)
Register a listener to mouse.leave or touch equivalent for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`move``(node,listener)`
Defined by [dojo/touch](touch)
Register a listener that fires when the mouse cursor or a finger is dragged over the given node.
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`out``(node,listener)`
Defined by [dojo/touch](touch)
Register a listener to 'mouseout' or touch equivalent for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`over``(node,listener)`
Defined by [dojo/touch](touch)
Register a listener to 'mouseover' or touch equivalent for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`press``(node,listener)`
Defined by [dojo/touch](touch)
Register a listener to 'touchstart'|'mousedown' for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`release``(node,listener)`
Defined by [dojo/touch](touch)
Register a listener to releasing the mouse button while the cursor is over the given node (i.e. "mouseup") or for removing the finger from the screen while touching the given node.
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
dojo dojo/main.__IoCallbackArgs dojo/main.\_\_IoCallbackArgs
============================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new main.__IoCallbackArgs()`
Properties
----------
### args
Defined by: [dojo/\_base/xhr](_base/xhr)
the original object argument to the IO call.
### canDelete
Defined by: [dojo/\_base/xhr](_base/xhr)
For [dojo/io/script](io/script) calls only, indicates whether the script tag that represents the request can be deleted after callbacks have been called. Used internally to know when cleanup can happen on JSONP-type requests.
### handleAs
Defined by: [dojo/\_base/xhr](_base/xhr)
The final indicator on how the response will be handled.
### id
Defined by: [dojo/\_base/xhr](_base/xhr)
For [dojo/io/script](io/script) calls only, the internal script ID used for the request.
### json
Defined by: [dojo/\_base/xhr](_base/xhr)
For [dojo/io/script](io/script) calls only: holds the JSON response for JSONP-type requests. Used internally to hold on to the JSON responses. You should not need to access it directly -- the same object should be passed to the success callbacks directly.
### query
Defined by: [dojo/\_base/xhr](_base/xhr)
For non-GET requests, the name1=value1&name2=value2 parameters sent up in the request.
### url
Defined by: [dojo/\_base/xhr](_base/xhr)
The final URL used for the call. Many times it will be different than the original args.url value.
### xhr
Defined by: [dojo/\_base/xhr](_base/xhr)
For XMLHttpRequest calls only, the XMLHttpRequest object that was used for the request.
dojo dojo/hccss dojo/hccss
==========
Summary
-------
Test if computer is in high contrast mode (i.e. if browser is not displaying background images). Defines `has("highcontrast")` and sets `dj_a11y` CSS class on `<body>` if machine is in high contrast mode. Returns `has()` method;
Usage
-----
hccss`();` See the [dojo/hccss reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/hccss.html) for more information.
Methods
-------
dojo dojo/aspect dojo/aspect
===========
Summary
-------
provides aspect oriented programming functionality, allowing for one to add before, around, or after advice on existing methods.
See the [dojo/aspect reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/aspect.html) for more information.
Examples
--------
### Example 1
```
define(["dojo/aspect"], function(aspect){
var signal = aspect.after(targetObject, "methodName", function(someArgument){
this will be called when targetObject.methodName() is called, after the original function is called
});
```
### Example 2
The returned signal object can be used to cancel the advice.
```
signal.remove(); // this will stop the advice from being executed anymore
aspect.before(targetObject, "methodName", function(someArgument){
// this will be called when targetObject.methodName() is called, before the original function is called
});
```
Methods
-------
###
`after``(target,methodName,advice,receiveArguments)`
Defined by [dojo/aspect](aspect)
The "after" export of the aspect module is a function that can be used to attach "after" advice to a method. This function will be executed after the original method is executed. By default the function will be called with a single argument, the return value of the original method, or the the return value of the last executed advice (if a previous one exists). The fourth (optional) argument can be set to true to so the function receives the original arguments (from when the original method was called) rather than the return value. If there are multiple "after" advisors, they are executed in the order they were registered.
| Parameter | Type | Description |
| --- | --- | --- |
| target | Object | This is the target object |
| methodName | String | This is the name of the method to attach to. |
| advice | Function | This is function to be called after the original method |
| receiveArguments | Boolean | *Optional*
If this is set to true, the advice function receives the original arguments (from when the original mehtod was called) rather than the return value of the original/previous method. |
**Returns:** any
A signal object that can be used to cancel the advice. If remove() is called on this signal object, it will stop the advice function from being executed.
###
`around``(target,methodName,advice)`
Defined by [dojo/aspect](aspect)
The "around" export of the aspect module is a function that can be used to attach "around" advice to a method. The advisor function is immediately executed when the around() is called, is passed a single argument that is a function that can be called to continue execution of the original method (or the next around advisor). The advisor function should return a function, and this function will be called whenever the method is called. It will be called with the arguments used to call the method. Whatever this function returns will be returned as the result of the method call (unless after advise changes it).
| Parameter | Type | Description |
| --- | --- | --- |
| target | Object | This is the target object |
| methodName | String | This is the name of the method to attach to. |
| advice | Function | This is function to be called around the original method |
Examples
--------
### Example 1
If there are multiple "around" advisors, the most recent one is executed first, which can then delegate to the next one and so on. For example:
```
around(obj, "foo", function(originalFoo){
return function(){
var start = new Date().getTime();
var results = originalFoo.apply(this, arguments); // call the original
var end = new Date().getTime();
console.log("foo execution took " + (end - start) + " ms");
return results;
};
});
```
###
`before``(target,methodName,advice)`
Defined by [dojo/aspect](aspect)
The "before" export of the aspect module is a function that can be used to attach "before" advice to a method. This function will be executed before the original method is executed. This function will be called with the arguments used to call the method. This function may optionally return an array as the new arguments to use to call the original method (or the previous, next-to-execute before advice, if one exists). If the before method doesn't return anything (returns undefined) the original arguments will be preserved. If there are multiple "before" advisors, they are executed in the reverse order they were registered.
| Parameter | Type | Description |
| --- | --- | --- |
| target | Object | This is the target object |
| methodName | String | This is the name of the method to attach to. |
| advice | Function | This is function to be called before the original method |
dojo dojo/main.store dojo/main.store
===============
Properties
----------
### util
Defined by: [dojo/store/util/QueryResults](store/util/queryresults)
Methods
-------
###
`Cache``(masterStore,cachingStore,options)`
Defined by [dojo/store/Cache](store/cache)
| Parameter | Type | Description |
| --- | --- | --- |
| masterStore | undefined | |
| cachingStore | undefined | |
| options | undefined | |
**Returns:** undefined
###
`DataStore``()`
Defined by [dojo/store/DataStore](store/datastore)
###
`JsonRest``()`
Defined by [dojo/store/JsonRest](store/jsonrest)
###
`Memory``()`
Defined by [dojo/store/Memory](store/memory)
###
`Observable``(store)`
Defined by [dojo/store/Observable](store/observable)
The Observable store wrapper takes a store and sets an observe method on query() results that can be used to monitor results for changes.
Observable wraps an existing store so that notifications can be made when a query is performed.
| Parameter | Type | Description |
| --- | --- | --- |
| store | [dojo/store/api/Store](store/api/store) | |
**Returns:** undefined
Examples
--------
### Example 1
Create a Memory store that returns an observable query, and then log some information about that query.
```
var store = Observable(new Memory({
data: [
{id: 1, name: "one", prime: false},
{id: 2, name: "two", even: true, prime: true},
{id: 3, name: "three", prime: true},
{id: 4, name: "four", even: true, prime: false},
{id: 5, name: "five", prime: true}
]
}));
var changes = [], results = store.query({ prime: true });
var observer = results.observe(function(object, previousIndex, newIndex){
changes.push({previousIndex:previousIndex, newIndex:newIndex, object:object});
});
```
See the Observable tests for more information.
dojo dojo/main.currency dojo/main.currency
==================
Summary
-------
localized formatting and parsing routines for currencies
extends dojo.number to provide culturally-appropriate formatting of values in various world currencies, including use of a currency symbol. The currencies are specified by a three-letter international symbol in all uppercase, and support for the currencies is provided by the data in `dojo.cldr`. The scripts generating dojo.cldr specify which currency support is included. A fixed number of decimal places is determined based on the currency type and is not determined by the 'pattern' argument. The fractional portion is optional, by default, and variable length decimals are not supported.
Methods
-------
###
`format``(value,options)`
Defined by [dojo/currency](currency)
Format a Number as a currency, using locale-specific settings
Create a string from a Number using a known, localized pattern. [Formatting patterns](http://www.unicode.org/reports/tr35/#Number_Elements) appropriate to the locale are chosen from the [CLDR](http://unicode.org/cldr) as well as the appropriate symbols and delimiters and number of decimal places.
| Parameter | Type | Description |
| --- | --- | --- |
| value | Number | the number to be formatted. |
| options | \_\_FormatOptions | *Optional* |
**Returns:** undefined
###
`parse``(expression,options)`
Defined by [dojo/currency](currency)
| Parameter | Type | Description |
| --- | --- | --- |
| expression | String | |
| options | Object | *Optional*
An object with the following properties:* type (String, optional): Should not be set. Value is assumed to be currency.
* currency (String, optional): an [ISO4217](http://en.wikipedia.org/wiki/ISO_4217) currency code, a three letter sequence like "USD". For use with dojo.currency only.
* symbol (String, optional): localized currency symbol. The default will be looked up in table of supported currencies in `dojo.cldr` A [ISO4217](http://en.wikipedia.org/wiki/ISO_4217) currency code will be used if not found.
* places (Number, optional): fixed number of decimal places to accept. The default is determined based on which currency is used.
* fractional (Boolean|Array, optional): Whether to include the fractional portion, where the number of decimal places are implied by the currency or explicit 'places' parameter. The value [true,false] makes the fractional portion optional. By default for currencies, it the fractional portion is optional.
* pattern (String, optional): override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization. Literal characters in patterns are not supported.
* locale (String, optional): override the locale used to determine formatting rules
* strict (Boolean, optional): strict parsing, false by default. Strict parsing requires input as produced by the format() method. Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
|
**Returns:** undefined
###
`regexp``(options)`
Defined by [dojo/currency](currency)
| Parameter | Type | Description |
| --- | --- | --- |
| options | Object | *Optional*
An object with the following properties:* pattern (String, optional): override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization.
* type (String, optional): choose a format type based on the locale from the following: decimal, scientific (not yet supported), percent, currency. decimal by default.
* locale (String, optional): override the locale used to determine formatting rules
* strict (Boolean, optional): strict parsing, false by default. Strict parsing requires input as produced by the format() method. Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
* places (Number|String, optional): number of decimal places to accept: Infinity, a positive number, or a range "n,m". Defined by pattern or Infinity if pattern not provided.
|
**Returns:** undefined
dojo dojo/DeferredList dojo/DeferredList
=================
Summary
-------
Deprecated, use [dojo/promise/all](promise/all) instead. Provides event handling for a group of Deferred objects.
DeferredList takes an array of existing deferreds and returns a new deferred of its own this new deferred will typically have its callback fired when all of the deferreds in the given list have fired their own deferreds. The parameters `fireOnOneCallback` and fireOnOneErrback, will fire before all the deferreds as appropriate
| Parameter | Type | Description |
| --- | --- | --- |
| list | Array | The list of deferreds to be synchronizied with this DeferredList |
| fireOnOneCallback | Boolean | *Optional*
Will cause the DeferredLists callback to be fired as soon as any of the deferreds in its list have been fired instead of waiting until the entire list has finished |
| fireOnOneErrback | Boolean | *Optional* |
| consumeErrors | Boolean | *Optional* |
| canceller | Function | *Optional*
A deferred canceller function, see dojo.Deferred |
See the [dojo/DeferredList reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/DeferredList.html) for more information.
Methods
-------
###
`gatherResults``(deferredList)`
Defined by [dojo/DeferredList](deferredlist)
Gathers the results of the deferreds for packaging as the parameters to the Deferred Lists' callback
| Parameter | Type | Description |
| --- | --- | --- |
| deferredList | [dojo/DeferredList](deferredlist) | The deferred list from which this function gathers results. |
**Returns:** [dojo/DeferredList](deferredlist) | instance
The newly created deferred list which packs results as parameters to its callback.
| programming_docs |
dojo dojo/robotx._runsemaphore dojo/robotx.\_runsemaphore
==========================
Properties
----------
### lock
Defined by: [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
Methods
-------
###
`unlock``()`
Defined by [doh/robot](http://dojotoolkit.org/api/1.10/doh/robot)
**Returns:** undefined | null
dojo dojo/number.__RealNumberRegexpFlags dojo/number.\_\_RealNumberRegexpFlags
=====================================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new number.__RealNumberRegexpFlags()`
Properties
----------
### decimal
Defined by: [dojo/number](number)
A string for the character used as the decimal point. Default is ".".
### eSigned
Defined by: [dojo/number](number)
The leading plus-or-minus sign on the exponent. Can be true, false, or [true, false]. Default is [true, false], (i.e. will match if it is signed or unsigned). flags in regexp.integer can be applied.
### exponent
Defined by: [dojo/number](number)
Express in exponential notation. Can be true, false, or [true, false]. Default is [true, false], (i.e. will match if the exponential part is present are not).
### fractional
Defined by: [dojo/number](number)
Whether decimal places are used. Can be true, false, or [true, false]. Default is [true, false] which means optional.
### places
Defined by: [dojo/number](number)
The integer number of decimal places or a range given as "n,m". If not given, the decimal part is optional and the number of places is unlimited.
dojo dojo/request dojo/request
============
Summary
-------
Send a request using the default transport for the current platform.
Usage
-----
request`(url,options);`
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | The URL to request. |
| options | [dojo/request.\_\_Options](request.__options) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](request.__promise)
See the [dojo/request reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request.html) for more information.
Methods
-------
###
`del``(url,options)`
Defined by [dojo/request](request)
Send an HTTP DELETE request using the default transport for the current platform.
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request.\_\_BaseOptions](request.__baseoptions) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](request.__promise)
###
`get``(url,options)`
Defined by [dojo/request](request)
Send an HTTP GET request using the default transport for the current platform.
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request.\_\_BaseOptions](request.__baseoptions) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](request.__promise)
###
`post``(url,options)`
Defined by [dojo/request](request)
Send an HTTP POST request using the default transport for the current platform.
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request.\_\_BaseOptions](request.__baseoptions) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](request.__promise) | undefined
###
`put``(url,options)`
Defined by [dojo/request](request)
Send an HTTP POST request using the default transport for the current platform.
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request.\_\_BaseOptions](request.__baseoptions) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](request.__promise)
dojo dojo/selector/acme dojo/selector/acme
==================
Summary
-------
Returns nodes which match the given CSS3 selector, searching the entire document by default but optionally taking a node to scope the search by. Returns an array.
dojo.query() is the swiss army knife of DOM node manipulation in Dojo. Much like Prototype's "$$" (bling-bling) function or JQuery's "$" function, dojo.query provides robust, high-performance CSS-based node selector support with the option of scoping searches to a particular sub-tree of a document.
Supported Selectors:
--------------------
acme supports a rich set of CSS3 selectors, including:
* class selectors (e.g., `.foo`)
* node type selectors like `span`
* descendant selectors
* `>` child element selectors
* `#foo` style ID selectors
* `*` universal selector
* `~`, the preceded-by sibling selector
* `+`, the immediately preceded-by sibling selector
* attribute queries:
+ `[foo]` attribute presence selector
+ `[foo='bar']` attribute value exact match
+ `[foo~='bar']` attribute value list item match
+ `[foo^='bar']` attribute start match
+ `[foo$='bar']` attribute end match
+ `[foo*='bar']` attribute substring match
* `:first-child`, `:last-child`, and `:only-child` positional selectors
* `:empty` content emtpy selector
* `:checked` pseudo selector
* `:nth-child(n)`, `:nth-child(2n+1)` style positional calculations
* `:nth-child(even)`, `:nth-child(odd)` positional selectors
* `:not(...)` negation pseudo selectors
Any legal combination of these selectors will work with `dojo.query()`, including compound selectors ("," delimited). Very complex and useful searches can be constructed with this palette of selectors and when combined with functions for manipulation presented by [dojo/NodeList](../nodelist), many types of DOM manipulation operations become very straightforward.
Unsupported Selectors:
----------------------
While dojo.query handles many CSS3 selectors, some fall outside of what's reasonable for a programmatic node querying engine to handle. Currently unsupported selectors include:
* namespace-differentiated selectors of any form
* all `::` pseduo-element selectors
* certain pseudo-selectors which don't get a lot of day-to-day use:
+ `:root`, `:lang()`, `:target`, `:focus`
* all visual and state selectors:
+ `:root`, `:active`, `:hover`, `:visited`, `:link`,
```
`:enabled`, `:disabled`
```
+ `:*-of-type` pseudo selectors
dojo.query and XML Documents:
-----------------------------
`dojo.query` (as of dojo 1.2) supports searching XML documents in a case-sensitive manner. If an HTML document is served with a doctype that forces case-sensitivity (e.g., XHTML 1.1 Strict), dojo.query() will detect this and "do the right thing". Case sensitivity is dependent upon the document being searched and not the query used. It is therefore possible to use case-sensitive queries on strict sub-documents (iframes, etc.) or XML documents while still assuming case-insensitivity for a host/root document.
Non-selector Queries:
---------------------
If something other than a String is passed for the query, `dojo.query` will return a new [dojo/NodeList](../nodelist) instance constructed from that parameter alone and all further processing will stop. This means that if you have a reference to a node or NodeList, you can quickly construct a new NodeList from the original by calling `dojo.query(node)` or `dojo.query(list)`.
Usage
-----
acme`(query,root);`
| Parameter | Type | Description |
| --- | --- | --- |
| query | String | The CSS3 expression to match against. For details on the syntax of CSS3 selectors, see <http://www.w3.org/TR/css3-selectors/#selectors> |
| root | String | DOMNode | *Optional*
A DOMNode (or node id) to scope the search from. Optional. |
**Returns:** Array | undefined
See the [dojo/selector/acme reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/selector/acme.html) for more information.
Examples
--------
### Example 1
search the entire document for elements with the class "foo":
```
require(["dojo/query"], function(query) {
query(".foo").forEach(function(q) { console.log(q); });
});
```
these elements will match:
```
<span class="foo"></span>
<span class="foo bar"></span>
<p class="thud foo"></p>
```
### Example 2
search the entire document for elements with the classes "foo" *and* "bar":
```
require(["dojo/query"], function(query) {
query(".foo.bar").forEach(function(q) { console.log(q); });
});
```
Methods
-------
###
`filter``(nodeList,filter,root)`
Defined by [dojo/selector/acme](acme)
function for filtering a NodeList based on a selector, optimized for simple selectors
| Parameter | Type | Description |
| --- | --- | --- |
| nodeList | Node[] | |
| filter | String | |
| root | String | DOMNode | *Optional* |
dojo dojo/selector/_loader dojo/selector/\_loader
======================
Summary
-------
This module handles loading the appropriate selector engine for the given browser
See the [dojo/selector/\_loader reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/selector/_loader.html) for more information.
Methods
-------
###
`load``(id,parentRequire,loaded,config)`
Defined by [dojo/selector/\_loader](_loader)
| Parameter | Type | Description |
| --- | --- | --- |
| id | undefined | |
| parentRequire | undefined | |
| loaded | undefined | |
| config | undefined | |
**Returns:** undefined
dojo dojo/selector/lite dojo/selector/lite
==================
Summary
-------
A small lightweight query selector engine that implements CSS2.1 selectors minus pseudo-classes and the sibling combinator, plus CSS3 attribute selectors
Usage
-----
lite`(selector,root);`
| Parameter | Type | Description |
| --- | --- | --- |
| selector | undefined | |
| root | undefined | |
**Returns:** undefined | Array
See the [dojo/selector/lite reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/selector/lite.html) for more information.
Properties
----------
### match
Defined by: [dojo/selector/lite](lite)
Methods
-------
dojo dojo/fx/Toggler dojo/fx/Toggler
===============
Summary
-------
A simple `dojo.Animation` toggler API.
class constructor for an animation toggler. It accepts a packed set of arguments about what type of animation to use in each direction, duration, etc. All available members are mixed into these animations from the constructor (for example, `node`, `showDuration`, `hideDuration`).
Usage
-----
var foo = new Toggler`(args);` Defined by [dojo/fx/Toggler](toggler)
| Parameter | Type | Description |
| --- | --- | --- |
| args | undefined | |
See the [dojo/fx/Toggler reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/fx/Toggler.html) for more information.
Examples
--------
### Example 1
```
var t = new dojo/fx/Toggler({
node: "nodeId",
showDuration: 500,
// hideDuration will default to "200"
showFunc: dojo/fx/wipeIn,
// hideFunc will default to "fadeOut"
});
t.show(100); // delay showing for 100ms
// ...time passes...
t.hide();
```
Properties
----------
### hideDuration
Defined by: [dojo/fx/Toggler](toggler)
Time in milliseconds to run the hide Animation
### node
Defined by: [dojo/fx/Toggler](toggler)
the node to target for the showing and hiding animations
### showDuration
Defined by: [dojo/fx/Toggler](toggler)
Time in milliseconds to run the show Animation
Methods
-------
###
`hide``(delay)`
Defined by [dojo/fx/Toggler](toggler)
Toggle the node to hidden
| Parameter | Type | Description |
| --- | --- | --- |
| delay | Integer | *Optional*
Amount of time to stall playing the hide animation |
**Returns:** undefined
###
`hideFunc``(args)`
Defined by [dojo/fx/Toggler](toggler)
The function that returns the `dojo.Animation` to hide the node
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* node (DOMNode|String): The node referenced in the animation
* duration (Integer, optional): Duration of the animation in milliseconds.
* easing (Function, optional): An easing function.
|
**Returns:** undefined
###
`show``(delay)`
Defined by [dojo/fx/Toggler](toggler)
Toggle the node to showing
| Parameter | Type | Description |
| --- | --- | --- |
| delay | Integer | *Optional*
Amount of time to stall playing the show animation |
**Returns:** undefined
###
`showFunc``(args)`
Defined by [dojo/fx/Toggler](toggler)
The function that returns the `dojo.Animation` to show the node
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* node (DOMNode|String): The node referenced in the animation
* duration (Integer, optional): Duration of the animation in milliseconds.
* easing (Function, optional): An easing function.
|
**Returns:** undefined
dojo dojo/fx/easing dojo/fx/easing
==============
Summary
-------
Collection of easing functions to use beyond the default `dojo._defaultEasing` function.
Easing functions are used to manipulate the iteration through an `dojo.Animation`s \_Line. \_Line being the properties of an Animation, and the easing function progresses through that Line determining how quickly (or slowly) it should go. Or more accurately: modify the value of the \_Line based on the percentage of animation completed.
All functions follow a simple naming convention of "ease type" + "when". If the name of the function ends in Out, the easing described appears towards the end of the animation. "In" means during the beginning, and InOut means both ranges of the Animation will applied, both beginning and end.
One does not call the easing function directly, it must be passed to the `easing` property of an animation.
See the [dojo/fx/easing reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/fx/easing.html) for more information.
Examples
--------
### Example 1
```
dojo.require("dojo.fx.easing");
var anim = dojo.fadeOut({
node: 'node',
duration: 2000,
// note there is no ()
easing: dojo.fx.easing.quadIn
}).play();
```
Methods
-------
###
`backIn``(n)`
Defined by [dojo/fx/easing](easing)
An easing function that starts away from the target, and quickly accelerates towards the end value.
Use caution when the easing will cause values to become negative as some properties cannot be set to negative values.
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`backInOut``(n)`
Defined by [dojo/fx/easing](easing)
An easing function combining the effects of `backIn` and `backOut`
An easing function combining the effects of `backIn` and `backOut`. Use caution when the easing will cause values to become negative as some properties cannot be set to negative values.
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`backOut``(n)`
Defined by [dojo/fx/easing](easing)
An easing function that pops past the range briefly, and slowly comes back.
An easing function that pops past the range briefly, and slowly comes back.
Use caution when the easing will cause values to become negative as some properties cannot be set to negative values.
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`bounceIn``(n)`
Defined by [dojo/fx/easing](easing)
An easing function that 'bounces' near the beginning of an Animation
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`bounceInOut``(n)`
Defined by [dojo/fx/easing](easing)
An easing function that 'bounces' at the beginning and end of the Animation
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`bounceOut``(n)`
Defined by [dojo/fx/easing](easing)
An easing function that 'bounces' near the end of an Animation
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`circIn``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`circInOut``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`circOut``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** undefined
###
`cubicIn``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** undefined
###
`cubicInOut``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`cubicOut``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`elasticIn``(n)`
Defined by [dojo/fx/easing](easing)
An easing function the elastically snaps from the start value
An easing function the elastically snaps from the start value
Use caution when the elasticity will cause values to become negative as some properties cannot be set to negative values.
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** Decimal | number
###
`elasticInOut``(n)`
Defined by [dojo/fx/easing](easing)
An easing function that elasticly snaps around the value, near the beginning and end of the Animation.
An easing function that elasticly snaps around the value, near the beginning and end of the Animation.
Use caution when the elasticity will cause values to become negative as some properties cannot be set to negative values.
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`elasticOut``(n)`
Defined by [dojo/fx/easing](easing)
An easing function that elasticly snaps around the target value, near the end of the Animation
An easing function that elasticly snaps around the target value, near the end of the Animation
Use caution when the elasticity will cause values to become negative as some properties cannot be set to negative values.
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** Decimal | number
###
`expoIn``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** undefined
###
`expoInOut``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`expoOut``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`linear``(n)`
Defined by [dojo/fx/easing](easing)
A linear easing function
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** Decimal
###
`quadIn``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** undefined
###
`quadInOut``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`quadOut``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`quartIn``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** undefined
###
`quartInOut``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`quartOut``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`quintIn``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** undefined
###
`quintInOut``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`quintOut``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`sineIn``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`sineInOut``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** number
###
`sineOut``(n)`
Defined by [dojo/fx/easing](easing)
| Parameter | Type | Description |
| --- | --- | --- |
| n | Decimal | *Optional* |
**Returns:** undefined
| programming_docs |
dojo dojo/dnd/move.parentConstrainedMoveable dojo/dnd/move.parentConstrainedMoveable
=======================================
Extends[dojo/dnd/Moveable](moveable) Usage
-----
var foo = new move.parentConstrainedMoveable`(node,params);` Defined by [dojo/dnd/move](move)
| Parameter | Type | Description |
| --- | --- | --- |
| node | Node | a node (or node's id) to be moved |
| params | Object | *Optional*
an optional object with parameters |
See the [dojo/dnd/move.parentConstrainedMoveable reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
### area
Defined by: [dojo/dnd/move](move)
object attributes (for markup)
### delay
Defined by: [dojo/dnd/Moveable](moveable)
### handle
Defined by: [dojo/dnd/Moveable](moveable)
### skip
Defined by: [dojo/dnd/Moveable](moveable)
### within
Defined by: [dojo/dnd/move](move)
Methods
-------
###
`constraints``()`
Defined by [dojo/dnd/move](move)
###
`destroy``()`
Defined by [dojo/dnd/Moveable](moveable)
stops watching for possible move, deletes all references, so the object can be garbage-collected
###
`emit``(type,event)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| event | undefined | |
**Returns:** undefined
###
`markupFactory``(params,node,Ctor)`
Defined by [dojo/dnd/Moveable](moveable)
| Parameter | Type | Description |
| --- | --- | --- |
| params | undefined | |
| node | undefined | |
| Ctor | undefined | |
**Returns:** instance
###
`on``(type,listener)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| listener | undefined | |
**Returns:** undefined
Events
------
###
`onDragDetected``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
called when the drag is detected; responsible for creation of the mover
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | |
###
`onFirstMove``(mover)`
Defined by: [dojo/dnd/move](move)
called during the very first move notification; can be used to initialize coordinates, can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
###
`onMouseDown``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onmousedown/ontouchstart, creates a Mover for the node
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse/touch event |
###
`onMouseMove``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onmousemove/ontouchmove, used only for delayed drags
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse/touch event |
###
`onMouseUp``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onmouseup, used only for delayed drags
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMove``(mover,leftTop)`
Defined by: [dojo/dnd/move](move)
called during every move notification; should actually move the node; can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
| leftTop | Object | |
###
`onMoved``(mover,leftTop)`
Defined by: [dojo/dnd/Moveable](moveable)
called after every incremental move; can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
| leftTop | Object | |
###
`onMoveStart``(mover)`
Defined by: [dojo/dnd/Moveable](moveable)
called before every move operation
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
###
`onMoveStop``(mover)`
Defined by: [dojo/dnd/Moveable](moveable)
called after every move operation
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
###
`onMoving``(mover,leftTop)`
Defined by: [dojo/dnd/Moveable](moveable)
called before every incremental move; can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
| leftTop | Object | |
###
`onSelectStart``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onselectevent and ondragevent
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
dojo dojo/dnd/autoscroll._validOverflow dojo/dnd/autoscroll.\_validOverflow
===================================
See the [dojo/dnd/autoscroll.\_validOverflow reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
### auto
Defined by: [dojo/dnd/autoscroll](autoscroll)
### scroll
Defined by: [dojo/dnd/autoscroll](autoscroll)
dojo dojo/dnd/move.constrainedMoveable dojo/dnd/move.constrainedMoveable
=================================
Extends[dojo/dnd/Moveable](moveable) Usage
-----
var foo = new move.constrainedMoveable`(node,params);` Defined by [dojo/dnd/move](move)
| Parameter | Type | Description |
| --- | --- | --- |
| node | Node | a node (or node's id) to be moved |
| params | Object | *Optional*
an optional object with additional parameters; the rest is passed to the base class |
See the [dojo/dnd/move.constrainedMoveable reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
### delay
Defined by: [dojo/dnd/Moveable](moveable)
### handle
Defined by: [dojo/dnd/Moveable](moveable)
### skip
Defined by: [dojo/dnd/Moveable](moveable)
### within
Defined by: [dojo/dnd/move](move)
Methods
-------
###
`constraints``()`
Defined by [dojo/dnd/move](move)
###
`destroy``()`
Defined by [dojo/dnd/Moveable](moveable)
stops watching for possible move, deletes all references, so the object can be garbage-collected
###
`emit``(type,event)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| event | undefined | |
**Returns:** undefined
###
`markupFactory``(params,node,Ctor)`
Defined by [dojo/dnd/Moveable](moveable)
| Parameter | Type | Description |
| --- | --- | --- |
| params | undefined | |
| node | undefined | |
| Ctor | undefined | |
**Returns:** instance
###
`on``(type,listener)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| listener | undefined | |
**Returns:** undefined
Events
------
###
`onDragDetected``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
called when the drag is detected; responsible for creation of the mover
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | |
###
`onFirstMove``(mover)`
Defined by: [dojo/dnd/move](move)
called during the very first move notification; can be used to initialize coordinates, can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
###
`onMouseDown``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onmousedown/ontouchstart, creates a Mover for the node
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse/touch event |
###
`onMouseMove``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onmousemove/ontouchmove, used only for delayed drags
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse/touch event |
###
`onMouseUp``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onmouseup, used only for delayed drags
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMove``(mover,leftTop)`
Defined by: [dojo/dnd/move](move)
called during every move notification; should actually move the node; can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
| leftTop | Object | |
###
`onMoved``(mover,leftTop)`
Defined by: [dojo/dnd/Moveable](moveable)
called after every incremental move; can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
| leftTop | Object | |
###
`onMoveStart``(mover)`
Defined by: [dojo/dnd/Moveable](moveable)
called before every move operation
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
###
`onMoveStop``(mover)`
Defined by: [dojo/dnd/Moveable](moveable)
called after every move operation
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
###
`onMoving``(mover,leftTop)`
Defined by: [dojo/dnd/Moveable](moveable)
called before every incremental move; can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
| leftTop | Object | |
###
`onSelectStart``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onselectevent and ondragevent
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
dojo dojo/dnd/Moveable dojo/dnd/Moveable
=================
Extends[dojo/Evented](../evented) Summary
-------
an object, which makes a node movable
Usage
-----
var foo = new Moveable`(node,params);` Defined by [dojo/dnd/Moveable](moveable)
| Parameter | Type | Description |
| --- | --- | --- |
| node | Node | a node (or node's id) to be moved |
| params | Moveable.\_\_MoveableArgs | *Optional*
optional parameters |
See the [dojo/dnd/Moveable reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd/Moveable.html) for more information.
Properties
----------
### delay
Defined by: [dojo/dnd/Moveable](moveable)
### handle
Defined by: [dojo/dnd/Moveable](moveable)
### skip
Defined by: [dojo/dnd/Moveable](moveable)
Methods
-------
###
`destroy``()`
Defined by [dojo/dnd/Moveable](moveable)
stops watching for possible move, deletes all references, so the object can be garbage-collected
###
`emit``(type,event)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| event | undefined | |
**Returns:** undefined
###
`markupFactory``(params,node,Ctor)`
Defined by [dojo/dnd/Moveable](moveable)
| Parameter | Type | Description |
| --- | --- | --- |
| params | undefined | |
| node | undefined | |
| Ctor | undefined | |
**Returns:** instance
###
`on``(type,listener)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| listener | undefined | |
**Returns:** undefined
Events
------
###
`onDragDetected``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
called when the drag is detected; responsible for creation of the mover
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | |
###
`onFirstMove``(mover,e)`
Defined by: [dojo/dnd/Moveable](moveable)
called during the very first move notification; can be used to initialize coordinates, can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
| e | Event | |
###
`onMouseDown``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onmousedown/ontouchstart, creates a Mover for the node
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse/touch event |
###
`onMouseMove``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onmousemove/ontouchmove, used only for delayed drags
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse/touch event |
###
`onMouseUp``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onmouseup, used only for delayed drags
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMove``(mover,leftTop,e)`
Defined by: [dojo/dnd/Moveable](moveable)
called during every move notification; should actually move the node; can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
| leftTop | Object | |
| e | Event | |
###
`onMoved``(mover,leftTop)`
Defined by: [dojo/dnd/Moveable](moveable)
called after every incremental move; can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
| leftTop | Object | |
###
`onMoveStart``(mover)`
Defined by: [dojo/dnd/Moveable](moveable)
called before every move operation
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
###
`onMoveStop``(mover)`
Defined by: [dojo/dnd/Moveable](moveable)
called after every move operation
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
###
`onMoving``(mover,leftTop)`
Defined by: [dojo/dnd/Moveable](moveable)
called before every incremental move; can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
| leftTop | Object | |
###
`onSelectStart``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onselectevent and ondragevent
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
dojo dojo/dnd/common._empty dojo/dnd/common.\_empty
=======================
See the [dojo/dnd/common.\_empty reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
dojo dojo/dnd/Manager dojo/dnd/Manager
================
Extends[dojo/Evented](../evented) Summary
-------
the manager of DnD operations (usually a singleton)
Usage
-----
var foo = new Manager`();` Defined by [dojo/dnd/Manager](manager)
See the [dojo/dnd/Manager reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
### OFFSET\_X
Defined by: [dojo/dnd/Manager](manager)
### OFFSET\_Y
Defined by: [dojo/dnd/Manager](manager)
Methods
-------
###
`canDrop``(flag)`
Defined by [dojo/dnd/Manager](manager)
called to notify if the current target can accept items
| Parameter | Type | Description |
| --- | --- | --- |
| flag | undefined | |
###
`emit``(type,event)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| event | undefined | |
**Returns:** undefined
###
`makeAvatar``()`
Defined by [dojo/dnd/Manager](manager)
makes the avatar; it is separate to be overwritten dynamically, if needed
**Returns:** instance
###
`manager``()`
Defined by [dojo/dnd/Manager](manager)
Returns the current DnD manager. Creates one if it is not created yet.
**Returns:** instance
###
`on``(type,listener)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| listener | undefined | |
**Returns:** undefined
###
`outSource``(source)`
Defined by [dojo/dnd/Manager](manager)
called when a source detected a mouse-out condition
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the reporter |
###
`overSource``(source)`
Defined by [dojo/dnd/Manager](manager)
called when a source detected a mouse-over condition
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the reporter |
###
`startDrag``(source,nodes,copy)`
Defined by [dojo/dnd/Manager](manager)
called to initiate the DnD operation
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which provides items |
| nodes | Array | the list of transferred items |
| copy | Boolean | copy items, if true, move items otherwise |
###
`stopDrag``()`
Defined by [dojo/dnd/Manager](manager)
stop the DnD in progress
###
`updateAvatar``()`
Defined by [dojo/dnd/Manager](manager)
updates the avatar; it is separate to be overwritten dynamically, if needed
Events
------
###
`onKeyDown``(e)`
Defined by: [dojo/dnd/Manager](manager)
event processor for onkeydown: watching for CTRL for copy/move status, watching for ESCAPE to cancel the drag
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | keyboard event |
###
`onKeyUp``(e)`
Defined by: [dojo/dnd/Manager](manager)
event processor for onkeyup, watching for CTRL for copy/move status
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | keyboard event |
###
`onMouseMove``(e)`
Defined by: [dojo/dnd/Manager](manager)
event processor for onmousemove
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseUp``(e)`
Defined by: [dojo/dnd/Manager](manager)
event processor for onmouseup
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
dojo dojo/dnd/autoscroll._validNodes dojo/dnd/autoscroll.\_validNodes
================================
See the [dojo/dnd/autoscroll.\_validNodes reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
### div
Defined by: [dojo/dnd/autoscroll](autoscroll)
### p
Defined by: [dojo/dnd/autoscroll](autoscroll)
### td
Defined by: [dojo/dnd/autoscroll](autoscroll)
dojo dojo/dnd/Avatar dojo/dnd/Avatar
===============
Summary
-------
Object that represents transferred DnD items visually
Usage
-----
var foo = new Avatar`(manager);` Defined by [dojo/dnd/Avatar](avatar)
| Parameter | Type | Description |
| --- | --- | --- |
| manager | undefined | |
See the [dojo/dnd/Avatar reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
### manager
Defined by: [dojo/dnd/Avatar](avatar)
a DnD manager object
Methods
-------
###
`construct``()`
Defined by [dojo/dnd/Avatar](avatar)
constructor function; it is separate so it can be (dynamically) overwritten in case of need
###
`destroy``()`
Defined by [dojo/dnd/Avatar](avatar)
destructor for the avatar; called to remove all references so it can be garbage-collected
###
`update``()`
Defined by [dojo/dnd/Avatar](avatar)
updates the avatar to reflect the current DnD state
dojo dojo/dnd/move.boxConstrainedMoveable dojo/dnd/move.boxConstrainedMoveable
====================================
Extends[dojo/dnd/Moveable](moveable) Usage
-----
var foo = new move.boxConstrainedMoveable`(node,params);` Defined by [dojo/dnd/move](move)
| Parameter | Type | Description |
| --- | --- | --- |
| node | Node | a node (or node's id) to be moved |
| params | Object | *Optional*
an optional object with parameters |
See the [dojo/dnd/move.boxConstrainedMoveable reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
### box
Defined by: [dojo/dnd/move](move)
object attributes (for markup)
### delay
Defined by: [dojo/dnd/Moveable](moveable)
### handle
Defined by: [dojo/dnd/Moveable](moveable)
### skip
Defined by: [dojo/dnd/Moveable](moveable)
### within
Defined by: [dojo/dnd/move](move)
Methods
-------
###
`constraints``()`
Defined by [dojo/dnd/move](move)
###
`destroy``()`
Defined by [dojo/dnd/Moveable](moveable)
stops watching for possible move, deletes all references, so the object can be garbage-collected
###
`emit``(type,event)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| event | undefined | |
**Returns:** undefined
###
`markupFactory``(params,node,Ctor)`
Defined by [dojo/dnd/Moveable](moveable)
| Parameter | Type | Description |
| --- | --- | --- |
| params | undefined | |
| node | undefined | |
| Ctor | undefined | |
**Returns:** instance
###
`on``(type,listener)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| listener | undefined | |
**Returns:** undefined
Events
------
###
`onDragDetected``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
called when the drag is detected; responsible for creation of the mover
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | |
###
`onFirstMove``(mover)`
Defined by: [dojo/dnd/move](move)
called during the very first move notification; can be used to initialize coordinates, can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
###
`onMouseDown``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onmousedown/ontouchstart, creates a Mover for the node
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse/touch event |
###
`onMouseMove``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onmousemove/ontouchmove, used only for delayed drags
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse/touch event |
###
`onMouseUp``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onmouseup, used only for delayed drags
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMove``(mover,leftTop)`
Defined by: [dojo/dnd/move](move)
called during every move notification; should actually move the node; can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
| leftTop | Object | |
###
`onMoved``(mover,leftTop)`
Defined by: [dojo/dnd/Moveable](moveable)
called after every incremental move; can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
| leftTop | Object | |
###
`onMoveStart``(mover)`
Defined by: [dojo/dnd/Moveable](moveable)
called before every move operation
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
###
`onMoveStop``(mover)`
Defined by: [dojo/dnd/Moveable](moveable)
called after every move operation
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
###
`onMoving``(mover,leftTop)`
Defined by: [dojo/dnd/Moveable](moveable)
called before every incremental move; can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
| leftTop | Object | |
###
`onSelectStart``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onselectevent and ondragevent
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
| programming_docs |
dojo dojo/dnd/Container dojo/dnd/Container
==================
Extends[dojo/Evented](../evented) Summary
-------
a Container object, which knows when mouse hovers over it, and over which element it hovers
Usage
-----
var foo = new Container`(node,params);` Defined by [dojo/dnd/Container](container)
| Parameter | Type | Description |
| --- | --- | --- |
| node | Node | node or node's id to build the container on |
| params | Container.\_\_ContainerArgs | a dictionary of parameters |
See the [dojo/dnd/Container reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
### allowNested
Defined by: [dojo/dnd/Container](container)
Indicates whether to allow dnd item nodes to be nested within other elements. By default this is false, indicating that only direct children of the container can be draggable dnd item nodes
### current
Defined by: [dojo/dnd/Container](container)
The DOM node the mouse is currently hovered over
### map
Defined by: [dojo/dnd/Container](container)
Map from an item's id (which is also the DOMNode's id) to the [dojo/dnd/Container.Item](container#Item) itself.
### skipForm
Defined by: [dojo/dnd/Container](container)
Methods
-------
###
`clearItems``()`
Defined by [dojo/dnd/Container](container)
removes all data items from the map
###
`creator``()`
Defined by [dojo/dnd/Container](container)
creator function, dummy at the moment
###
`delItem``(key)`
Defined by [dojo/dnd/Container](container)
removes a data item from the map by its key (id)
| Parameter | Type | Description |
| --- | --- | --- |
| key | String | |
###
`destroy``()`
Defined by [dojo/dnd/Container](container)
prepares this object to be garbage-collected
###
`emit``(type,event)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| event | undefined | |
**Returns:** undefined
###
`forInItems``(f,o)`
Defined by [dojo/dnd/Container](container)
iterates over a data map skipping members that are present in the empty object (IE and/or 3rd-party libraries).
| Parameter | Type | Description |
| --- | --- | --- |
| f | Function | |
| o | Object | *Optional* |
**Returns:** string
###
`getAllNodes``()`
Defined by [dojo/dnd/Container](container)
returns a list (an array) of all valid child nodes
**Returns:** undefined
###
`getItem``(key)`
Defined by [dojo/dnd/Container](container)
returns a data item by its key (id)
| Parameter | Type | Description |
| --- | --- | --- |
| key | String | |
**Returns:** undefined
###
`insertNodes``(data,before,anchor)`
Defined by [dojo/dnd/Container](container)
inserts an array of new nodes before/after an anchor node
| Parameter | Type | Description |
| --- | --- | --- |
| data | Object | Logical representation of the object being dragged. If the drag object's type is "text" then data is a String, if it's another type then data could be a different Object, perhaps a name/value hash. |
| before | Boolean | insert before the anchor, if true, and after the anchor otherwise |
| anchor | Node | the anchor node to be used as a point of insertion |
**Returns:** function
inserts an array of new nodes before/after an anchor node
###
`Item``()`
Defined by [dojo/dnd/Container](container)
Represents (one of) the source node(s) being dragged. Contains (at least) the "type" and "data" attributes.
###
`markupFactory``(params,node,Ctor)`
Defined by [dojo/dnd/Container](container)
| Parameter | Type | Description |
| --- | --- | --- |
| params | undefined | |
| node | undefined | |
| Ctor | undefined | |
**Returns:** instance
###
`on``(type,listener)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| listener | undefined | |
**Returns:** undefined
###
`setItem``(key,data)`
Defined by [dojo/dnd/Container](container)
associates a data item with its key (id)
| Parameter | Type | Description |
| --- | --- | --- |
| key | String | |
| data | Container.Item | |
###
`startup``()`
Defined by [dojo/dnd/Container](container)
collects valid child items and populate the map
###
`sync``()`
Defined by [dojo/dnd/Container](container)
sync up the node list with the data map
**Returns:** function
sync up the node list with the data map
Events
------
###
`onMouseOut``(e)`
Defined by: [dojo/dnd/Container](container)
event processor for onmouseout
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseOver``(e)`
Defined by: [dojo/dnd/Container](container)
event processor for onmouseover or touch, to mark that element as the current element
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onOutEvent``()`
Defined by: [dojo/dnd/Container](container)
this function is called once, when mouse is out of our container
###
`onOverEvent``()`
Defined by: [dojo/dnd/Container](container)
this function is called once, when mouse is over our container
###
`onSelectStart``(e)`
Defined by: [dojo/dnd/Container](container)
event processor for onselectevent and ondragevent
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
dojo dojo/dnd/Container.__ContainerArgs dojo/dnd/Container.\_\_ContainerArgs
====================================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new Container.__ContainerArgs()`
See the [dojo/dnd/Container.\_\_ContainerArgs reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
### dropParent
Defined by: [dojo/dnd/Container](container)
node or node's id to use as the parent node for dropped items (must be underneath the 'node' parameter in the DOM)
### skipForm
Defined by: [dojo/dnd/Container](container)
don't start the drag operation, if clicked on form elements
Methods
-------
###
`creator``()`
Defined by [dojo/dnd/Container](container)
a creator function, which takes a data item, and returns an object like that: {node: newNode, data: usedData, type: arrayOfStrings}
dojo dojo/dnd/Moveable.__MoveableArgs dojo/dnd/Moveable.\_\_MoveableArgs
==================================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new Moveable.__MoveableArgs()`
See the [dojo/dnd/Moveable.\_\_MoveableArgs reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
### delay
Defined by: [dojo/dnd/Moveable](moveable)
delay move by this number of pixels
### handle
Defined by: [dojo/dnd/Moveable](moveable)
A node (or node's id), which is used as a mouse handle. If omitted, the node itself is used as a handle.
### mover
Defined by: [dojo/dnd/Moveable](moveable)
a constructor of custom Mover
### skip
Defined by: [dojo/dnd/Moveable](moveable)
skip move of form elements
dojo dojo/dnd/AutoSource dojo/dnd/AutoSource
===================
Extends[dojo/dnd/Source](source) Summary
-------
a source that syncs its DnD nodes by default
Usage
-----
var foo = new AutoSource`(node,params);` Defined by [dojo/dnd/AutoSource](autosource)
| Parameter | Type | Description |
| --- | --- | --- |
| node | undefined | |
| params | undefined | |
See the [dojo/dnd/AutoSource reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
### accept
Defined by: [dojo/dnd/Source](source)
### allowNested
Defined by: [dojo/dnd/Container](container)
Indicates whether to allow dnd item nodes to be nested within other elements. By default this is false, indicating that only direct children of the container can be draggable dnd item nodes
### autoSync
Defined by: [dojo/dnd/Source](source)
### copyOnly
Defined by: [dojo/dnd/Source](source)
### current
Defined by: [dojo/dnd/Container](container)
The DOM node the mouse is currently hovered over
### delay
Defined by: [dojo/dnd/Source](source)
### generateText
Defined by: [dojo/dnd/Source](source)
### horizontal
Defined by: [dojo/dnd/Source](source)
### isSource
Defined by: [dojo/dnd/Source](source)
### map
Defined by: [dojo/dnd/Container](container)
Map from an item's id (which is also the DOMNode's id) to the [dojo/dnd/Container.Item](container#Item) itself.
### selection
Defined by: [dojo/dnd/Selector](selector)
The set of id's that are currently selected, such that this.selection[id] == 1 if the node w/that id is selected. Can iterate over selected node's id's like:
```
for(var id in this.selection)
```
### selfAccept
Defined by: [dojo/dnd/Source](source)
### selfCopy
Defined by: [dojo/dnd/Source](source)
### singular
Defined by: [dojo/dnd/Selector](selector)
### skipForm
Defined by: [dojo/dnd/Source](source)
### withHandles
Defined by: [dojo/dnd/Source](source)
Methods
-------
###
`checkAcceptance``(source,nodes)`
Defined by [dojo/dnd/Source](source)
checks if the target can accept nodes from this source
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which provides items |
| nodes | Array | the list of transferred items |
**Returns:** boolean
###
`clearItems``()`
Defined by [dojo/dnd/Container](container)
removes all data items from the map
###
`copyState``(keyPressed,self)`
Defined by [dojo/dnd/Source](source)
Returns true if we need to copy items, false to move. It is separated to be overwritten dynamically, if needed.
| Parameter | Type | Description |
| --- | --- | --- |
| keyPressed | Boolean | the "copy" key was pressed |
| self | Boolean | *Optional*
optional flag that means that we are about to drop on itself |
**Returns:** boolean | undefined
###
`creator``()`
Defined by [dojo/dnd/Container](container)
creator function, dummy at the moment
###
`deleteSelectedNodes``()`
Defined by [dojo/dnd/Selector](selector)
deletes all selected items
**Returns:** function
deletes all selected items
###
`delItem``(key)`
Defined by [dojo/dnd/Container](container)
removes a data item from the map by its key (id)
| Parameter | Type | Description |
| --- | --- | --- |
| key | String | |
###
`destroy``()`
Defined by [dojo/dnd/Source](source)
prepares the object to be garbage-collected
###
`emit``(type,event)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| event | undefined | |
**Returns:** undefined
###
`forInItems``(f,o)`
Defined by [dojo/dnd/Container](container)
iterates over a data map skipping members that are present in the empty object (IE and/or 3rd-party libraries).
| Parameter | Type | Description |
| --- | --- | --- |
| f | Function | |
| o | Object | *Optional* |
**Returns:** string
###
`forInSelectedItems``(f,o)`
Defined by [dojo/dnd/Selector](selector)
iterates over selected items; see `dojo/dnd/Container.forInItems()` for details
| Parameter | Type | Description |
| --- | --- | --- |
| f | Function | |
| o | Object | *Optional* |
###
`getAllNodes``()`
Defined by [dojo/dnd/Container](container)
returns a list (an array) of all valid child nodes
**Returns:** undefined
###
`getItem``(key)`
Defined by [dojo/dnd/Container](container)
returns a data item by its key (id)
| Parameter | Type | Description |
| --- | --- | --- |
| key | String | |
**Returns:** undefined
###
`getSelectedNodes``()`
Defined by [dojo/dnd/Selector](selector)
returns a list (an array) of selected nodes
**Returns:** instance
###
`insertNodes``(addSelected,data,before,anchor)`
Defined by [dojo/dnd/Selector](selector)
inserts new data items (see `dojo/dnd/Container.insertNodes()` method for details)
| Parameter | Type | Description |
| --- | --- | --- |
| addSelected | Boolean | all new nodes will be added to selected items, if true, no selection change otherwise |
| data | Array | a list of data items, which should be processed by the creator function |
| before | Boolean | insert before the anchor, if true, and after the anchor otherwise |
| anchor | Node | the anchor node to be used as a point of insertion |
**Returns:** function
inserts new data items (see `dojo/dnd/Container.insertNodes()` method for details)
###
`markupFactory``(params,node,Ctor)`
Defined by [dojo/dnd/Container](container)
| Parameter | Type | Description |
| --- | --- | --- |
| params | undefined | |
| node | undefined | |
| Ctor | undefined | |
**Returns:** instance
###
`on``(type,listener)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| listener | undefined | |
**Returns:** undefined
###
`selectAll``()`
Defined by [dojo/dnd/Selector](selector)
selects all items
**Returns:** undefined
###
`selectNone``()`
Defined by [dojo/dnd/Selector](selector)
unselects all items
**Returns:** undefined
###
`setItem``(key,data)`
Defined by [dojo/dnd/Container](container)
associates a data item with its key (id)
| Parameter | Type | Description |
| --- | --- | --- |
| key | String | |
| data | Container.Item | |
###
`startup``()`
Defined by [dojo/dnd/Container](container)
collects valid child items and populate the map
###
`sync``()`
Defined by [dojo/dnd/Selector](selector)
sync up the node list with the data map
**Returns:** function
sync up the node list with the data map
Events
------
###
`onDndCancel``()`
Defined by: [dojo/dnd/Source](source)
topic event processor for /dnd/cancel, called to cancel the DnD operation
###
`onDndDrop``(source,nodes,copy,target)`
Defined by: [dojo/dnd/Source](source)
topic event processor for /dnd/drop, called to finish the DnD operation
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which provides items |
| nodes | Array | the list of transferred items |
| copy | Boolean | copy items, if true, move items otherwise |
| target | Object | the target which accepts items |
###
`onDndSourceOver``(source)`
Defined by: [dojo/dnd/Source](source)
topic event processor for /dnd/source/over, called when detected a current source
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which has the mouse over it |
###
`onDndStart``(source,nodes,copy)`
Defined by: [dojo/dnd/Source](source)
topic event processor for /dnd/start, called to initiate the DnD operation
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which provides items |
| nodes | Array | the list of transferred items |
| copy | Boolean | copy items, if true, move items otherwise |
###
`onDraggingOut``()`
Defined by: [dojo/dnd/Source](source)
called during the active DnD operation, when items are dragged away from this target, and it is not disabled
###
`onDraggingOver``()`
Defined by: [dojo/dnd/Source](source)
called during the active DnD operation, when items are dragged over this target, and it is not disabled
###
`onDrop``(source,nodes,copy)`
Defined by: [dojo/dnd/Source](source)
called only on the current target, when drop is performed
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which provides items |
| nodes | Array | the list of transferred items |
| copy | Boolean | copy items, if true, move items otherwise |
###
`onDropExternal``(source,nodes,copy)`
Defined by: [dojo/dnd/Source](source)
called only on the current target, when drop is performed from an external source
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which provides items |
| nodes | Array | the list of transferred items |
| copy | Boolean | copy items, if true, move items otherwise |
###
`onDropInternal``(nodes,copy)`
Defined by: [dojo/dnd/Source](source)
called only on the current target, when drop is performed from the same target/source
| Parameter | Type | Description |
| --- | --- | --- |
| nodes | Array | the list of transferred items |
| copy | Boolean | copy items, if true, move items otherwise |
###
`onMouseDown``(e)`
Defined by: [dojo/dnd/Source](source)
event processor for onmousedown
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseMove``(e)`
Defined by: [dojo/dnd/Source](source)
event processor for onmousemove
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseOut``(e)`
Defined by: [dojo/dnd/Container](container)
event processor for onmouseout
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseOver``(e)`
Defined by: [dojo/dnd/Container](container)
event processor for onmouseover or touch, to mark that element as the current element
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseUp``(e)`
Defined by: [dojo/dnd/Source](source)
event processor for onmouseup
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onOutEvent``()`
Defined by: [dojo/dnd/Source](source)
this function is called once, when mouse is out of our container
###
`onOverEvent``()`
Defined by: [dojo/dnd/Source](source)
this function is called once, when mouse is over our container
###
`onSelectStart``(e)`
Defined by: [dojo/dnd/Container](container)
event processor for onselectevent and ondragevent
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
dojo dojo/dnd/TimedMoveable dojo/dnd/TimedMoveable
======================
Extends[dojo/dnd/Moveable](moveable) Summary
-------
A specialized version of Moveable to support an FPS throttling. This class puts an upper restriction on FPS, which may reduce the CPU load. The additional parameter "timeout" regulates the delay before actually moving the moveable object.
Usage
-----
var foo = new TimedMoveable`(node,params);` Defined by [dojo/dnd/TimedMoveable](timedmoveable)
| Parameter | Type | Description |
| --- | --- | --- |
| node | Node | String | a node (or node's id) to be moved |
| params | Object | object with additional parameters. |
See the [dojo/dnd/TimedMoveable reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
### delay
Defined by: [dojo/dnd/Moveable](moveable)
### handle
Defined by: [dojo/dnd/Moveable](moveable)
### skip
Defined by: [dojo/dnd/Moveable](moveable)
### timeout
Defined by: [dojo/dnd/TimedMoveable](timedmoveable)
Methods
-------
###
`destroy``()`
Defined by [dojo/dnd/Moveable](moveable)
stops watching for possible move, deletes all references, so the object can be garbage-collected
###
`emit``(type,event)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| event | undefined | |
**Returns:** undefined
###
`markupFactory``(params,node,Ctor)`
Defined by [dojo/dnd/Moveable](moveable)
| Parameter | Type | Description |
| --- | --- | --- |
| params | undefined | |
| node | undefined | |
| Ctor | undefined | |
**Returns:** instance
###
`on``(type,listener)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| listener | undefined | |
**Returns:** undefined
Events
------
###
`onDragDetected``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
called when the drag is detected; responsible for creation of the mover
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | |
###
`onFirstMove``(mover,e)`
Defined by: [dojo/dnd/Moveable](moveable)
called during the very first move notification; can be used to initialize coordinates, can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
| e | Event | |
###
`onMouseDown``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onmousedown/ontouchstart, creates a Mover for the node
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse/touch event |
###
`onMouseMove``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onmousemove/ontouchmove, used only for delayed drags
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse/touch event |
###
`onMouseUp``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onmouseup, used only for delayed drags
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMove``(mover,leftTop)`
Defined by: [dojo/dnd/TimedMoveable](timedmoveable)
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
| leftTop | Object | |
###
`onMoved``(mover,leftTop)`
Defined by: [dojo/dnd/Moveable](moveable)
called after every incremental move; can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
| leftTop | Object | |
###
`onMoveStart``(mover)`
Defined by: [dojo/dnd/Moveable](moveable)
called before every move operation
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
###
`onMoveStop``(mover)`
Defined by: [dojo/dnd/TimedMoveable](timedmoveable)
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
###
`onMoving``(mover,leftTop)`
Defined by: [dojo/dnd/Moveable](moveable)
called before every incremental move; can be overwritten.
| Parameter | Type | Description |
| --- | --- | --- |
| mover | [dojo/dnd/Mover](mover) | |
| leftTop | Object | |
###
`onSelectStart``(e)`
Defined by: [dojo/dnd/Moveable](moveable)
event processor for onselectevent and ondragevent
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
| programming_docs |
dojo dojo/dnd/Selector dojo/dnd/Selector
=================
Extends[dojo/dnd/Container](container) Summary
-------
a Selector object, which knows how to select its children
Usage
-----
var foo = new Selector`(node,params);` Defined by [dojo/dnd/Selector](selector)
| Parameter | Type | Description |
| --- | --- | --- |
| node | Node | String | node or node's id to build the selector on |
| params | Object | *Optional*
a dictionary of parameters |
See the [dojo/dnd/Selector reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
### allowNested
Defined by: [dojo/dnd/Container](container)
Indicates whether to allow dnd item nodes to be nested within other elements. By default this is false, indicating that only direct children of the container can be draggable dnd item nodes
### current
Defined by: [dojo/dnd/Container](container)
The DOM node the mouse is currently hovered over
### map
Defined by: [dojo/dnd/Container](container)
Map from an item's id (which is also the DOMNode's id) to the [dojo/dnd/Container.Item](container#Item) itself.
### selection
Defined by: [dojo/dnd/Selector](selector)
The set of id's that are currently selected, such that this.selection[id] == 1 if the node w/that id is selected. Can iterate over selected node's id's like:
```
for(var id in this.selection)
```
### singular
Defined by: [dojo/dnd/Selector](selector)
### skipForm
Defined by: [dojo/dnd/Container](container)
Methods
-------
###
`clearItems``()`
Defined by [dojo/dnd/Container](container)
removes all data items from the map
###
`creator``()`
Defined by [dojo/dnd/Container](container)
creator function, dummy at the moment
###
`deleteSelectedNodes``()`
Defined by [dojo/dnd/Selector](selector)
deletes all selected items
**Returns:** function
deletes all selected items
###
`delItem``(key)`
Defined by [dojo/dnd/Container](container)
removes a data item from the map by its key (id)
| Parameter | Type | Description |
| --- | --- | --- |
| key | String | |
###
`destroy``()`
Defined by [dojo/dnd/Selector](selector)
prepares the object to be garbage-collected
###
`emit``(type,event)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| event | undefined | |
**Returns:** undefined
###
`forInItems``(f,o)`
Defined by [dojo/dnd/Container](container)
iterates over a data map skipping members that are present in the empty object (IE and/or 3rd-party libraries).
| Parameter | Type | Description |
| --- | --- | --- |
| f | Function | |
| o | Object | *Optional* |
**Returns:** string
###
`forInSelectedItems``(f,o)`
Defined by [dojo/dnd/Selector](selector)
iterates over selected items; see `dojo/dnd/Container.forInItems()` for details
| Parameter | Type | Description |
| --- | --- | --- |
| f | Function | |
| o | Object | *Optional* |
###
`getAllNodes``()`
Defined by [dojo/dnd/Container](container)
returns a list (an array) of all valid child nodes
**Returns:** undefined
###
`getItem``(key)`
Defined by [dojo/dnd/Container](container)
returns a data item by its key (id)
| Parameter | Type | Description |
| --- | --- | --- |
| key | String | |
**Returns:** undefined
###
`getSelectedNodes``()`
Defined by [dojo/dnd/Selector](selector)
returns a list (an array) of selected nodes
**Returns:** instance
###
`insertNodes``(addSelected,data,before,anchor)`
Defined by [dojo/dnd/Selector](selector)
inserts new data items (see `dojo/dnd/Container.insertNodes()` method for details)
| Parameter | Type | Description |
| --- | --- | --- |
| addSelected | Boolean | all new nodes will be added to selected items, if true, no selection change otherwise |
| data | Array | a list of data items, which should be processed by the creator function |
| before | Boolean | insert before the anchor, if true, and after the anchor otherwise |
| anchor | Node | the anchor node to be used as a point of insertion |
**Returns:** function
inserts new data items (see `dojo/dnd/Container.insertNodes()` method for details)
###
`markupFactory``(params,node,Ctor)`
Defined by [dojo/dnd/Container](container)
| Parameter | Type | Description |
| --- | --- | --- |
| params | undefined | |
| node | undefined | |
| Ctor | undefined | |
**Returns:** instance
###
`on``(type,listener)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| listener | undefined | |
**Returns:** undefined
###
`selectAll``()`
Defined by [dojo/dnd/Selector](selector)
selects all items
**Returns:** undefined
###
`selectNone``()`
Defined by [dojo/dnd/Selector](selector)
unselects all items
**Returns:** undefined
###
`setItem``(key,data)`
Defined by [dojo/dnd/Container](container)
associates a data item with its key (id)
| Parameter | Type | Description |
| --- | --- | --- |
| key | String | |
| data | Container.Item | |
###
`startup``()`
Defined by [dojo/dnd/Container](container)
collects valid child items and populate the map
###
`sync``()`
Defined by [dojo/dnd/Selector](selector)
sync up the node list with the data map
**Returns:** function
sync up the node list with the data map
Events
------
###
`onMouseDown``(e)`
Defined by: [dojo/dnd/Selector](selector)
event processor for onmousedown
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseMove``(e)`
Defined by: [dojo/dnd/Selector](selector)
event processor for onmousemove
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseOut``(e)`
Defined by: [dojo/dnd/Container](container)
event processor for onmouseout
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseOver``(e)`
Defined by: [dojo/dnd/Container](container)
event processor for onmouseover or touch, to mark that element as the current element
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseUp``(e)`
Defined by: [dojo/dnd/Selector](selector)
event processor for onmouseup
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onOutEvent``()`
Defined by: [dojo/dnd/Selector](selector)
this function is called once, when mouse is out of our container
###
`onOverEvent``()`
Defined by: [dojo/dnd/Selector](selector)
this function is called once, when mouse is over our container
###
`onSelectStart``(e)`
Defined by: [dojo/dnd/Container](container)
event processor for onselectevent and ondragevent
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
dojo dojo/dnd/common dojo/dnd/common
===============
Summary
-------
TODOC
See the [dojo/dnd/common reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
Methods
-------
###
`getCopyKeyState``(evt)`
Defined by [dojo/dnd/common](common)
| Parameter | Type | Description |
| --- | --- | --- |
| evt | undefined | |
**Returns:** undefined
###
`getUniqueId``()`
Defined by [dojo/dnd/common](common)
returns a unique string for use with any DOM element
**Returns:** string
###
`isFormElement``(e)`
Defined by [dojo/dnd/common](common)
returns true if user clicked on a form element
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | |
###
`manager``()`
Defined by [dojo/dnd/Manager](manager)
Returns the current DnD manager. Creates one if it is not created yet.
**Returns:** instance
dojo dojo/dnd/autoscroll dojo/dnd/autoscroll
===================
Summary
-------
Used by [dojo/dnd/Manager](manager) to scroll document or internal node when the user drags near the edge of the viewport or a scrollable node
See the [dojo/dnd/autoscroll reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
### H\_AUTOSCROLL\_VALUE
Defined by: [dojo/dnd/autoscroll](autoscroll)
### H\_TRIGGER\_AUTOSCROLL
Defined by: [dojo/dnd/autoscroll](autoscroll)
### V\_AUTOSCROLL\_VALUE
Defined by: [dojo/dnd/autoscroll](autoscroll)
### V\_TRIGGER\_AUTOSCROLL
Defined by: [dojo/dnd/autoscroll](autoscroll)
Methods
-------
###
`autoScroll``(e)`
Defined by [dojo/dnd/autoscroll](autoscroll)
a handler for mousemove and touchmove events, which scrolls the window, if necessary
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mousemove/touchmove event |
###
`autoScrollNodes``(e)`
Defined by [dojo/dnd/autoscroll](autoscroll)
a handler for mousemove and touchmove events, which scrolls the first available Dom element, it falls back to exports.autoScroll()
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mousemove/touchmove event |
###
`autoScrollStart``(d)`
Defined by [dojo/dnd/autoscroll](autoscroll)
Called at the start of a drag.
| Parameter | Type | Description |
| --- | --- | --- |
| d | Document | The document of the node being dragged. |
###
`getViewport``(doc)`
Defined by [dojo/window](../window)
Returns the dimensions and scroll position of the viewable area of a browser window
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | *Optional* |
**Returns:** object
dojo dojo/dnd/common._defaultCreatorNodes dojo/dnd/common.\_defaultCreatorNodes
=====================================
See the [dojo/dnd/common.\_defaultCreatorNodes reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
### div
Defined by: [dojo/dnd/Container](container)
### ol
Defined by: [dojo/dnd/Container](container)
### p
Defined by: [dojo/dnd/Container](container)
### ul
Defined by: [dojo/dnd/Container](container)
dojo dojo/dnd/Source dojo/dnd/Source
===============
Extends[dojo/dnd/Selector](selector) Summary
-------
a Source object, which can be used as a DnD source, or a DnD target
Usage
-----
var foo = new Source`(node,params);` Defined by [dojo/dnd/Source](source)
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | node or node's id to build the source on |
| params | Object | *Optional*
any property of this class may be configured via the params object which is mixed-in to the `dojo/dnd/Source` instance |
See the [dojo/dnd/Source reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
### accept
Defined by: [dojo/dnd/Source](source)
### allowNested
Defined by: [dojo/dnd/Container](container)
Indicates whether to allow dnd item nodes to be nested within other elements. By default this is false, indicating that only direct children of the container can be draggable dnd item nodes
### autoSync
Defined by: [dojo/dnd/Source](source)
### copyOnly
Defined by: [dojo/dnd/Source](source)
### current
Defined by: [dojo/dnd/Container](container)
The DOM node the mouse is currently hovered over
### delay
Defined by: [dojo/dnd/Source](source)
### generateText
Defined by: [dojo/dnd/Source](source)
### horizontal
Defined by: [dojo/dnd/Source](source)
### isSource
Defined by: [dojo/dnd/Source](source)
### map
Defined by: [dojo/dnd/Container](container)
Map from an item's id (which is also the DOMNode's id) to the [dojo/dnd/Container.Item](container#Item) itself.
### selection
Defined by: [dojo/dnd/Selector](selector)
The set of id's that are currently selected, such that this.selection[id] == 1 if the node w/that id is selected. Can iterate over selected node's id's like:
```
for(var id in this.selection)
```
### selfAccept
Defined by: [dojo/dnd/Source](source)
### selfCopy
Defined by: [dojo/dnd/Source](source)
### singular
Defined by: [dojo/dnd/Selector](selector)
### skipForm
Defined by: [dojo/dnd/Source](source)
### withHandles
Defined by: [dojo/dnd/Source](source)
Methods
-------
###
`checkAcceptance``(source,nodes)`
Defined by [dojo/dnd/Source](source)
checks if the target can accept nodes from this source
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which provides items |
| nodes | Array | the list of transferred items |
**Returns:** boolean
###
`clearItems``()`
Defined by [dojo/dnd/Container](container)
removes all data items from the map
###
`copyState``(keyPressed,self)`
Defined by [dojo/dnd/Source](source)
Returns true if we need to copy items, false to move. It is separated to be overwritten dynamically, if needed.
| Parameter | Type | Description |
| --- | --- | --- |
| keyPressed | Boolean | the "copy" key was pressed |
| self | Boolean | *Optional*
optional flag that means that we are about to drop on itself |
**Returns:** boolean | undefined
###
`creator``()`
Defined by [dojo/dnd/Container](container)
creator function, dummy at the moment
###
`deleteSelectedNodes``()`
Defined by [dojo/dnd/Selector](selector)
deletes all selected items
**Returns:** function
deletes all selected items
###
`delItem``(key)`
Defined by [dojo/dnd/Container](container)
removes a data item from the map by its key (id)
| Parameter | Type | Description |
| --- | --- | --- |
| key | String | |
###
`destroy``()`
Defined by [dojo/dnd/Source](source)
prepares the object to be garbage-collected
###
`emit``(type,event)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| event | undefined | |
**Returns:** undefined
###
`forInItems``(f,o)`
Defined by [dojo/dnd/Container](container)
iterates over a data map skipping members that are present in the empty object (IE and/or 3rd-party libraries).
| Parameter | Type | Description |
| --- | --- | --- |
| f | Function | |
| o | Object | *Optional* |
**Returns:** string
###
`forInSelectedItems``(f,o)`
Defined by [dojo/dnd/Selector](selector)
iterates over selected items; see `dojo/dnd/Container.forInItems()` for details
| Parameter | Type | Description |
| --- | --- | --- |
| f | Function | |
| o | Object | *Optional* |
###
`getAllNodes``()`
Defined by [dojo/dnd/Container](container)
returns a list (an array) of all valid child nodes
**Returns:** undefined
###
`getItem``(key)`
Defined by [dojo/dnd/Container](container)
returns a data item by its key (id)
| Parameter | Type | Description |
| --- | --- | --- |
| key | String | |
**Returns:** undefined
###
`getSelectedNodes``()`
Defined by [dojo/dnd/Selector](selector)
returns a list (an array) of selected nodes
**Returns:** instance
###
`insertNodes``(addSelected,data,before,anchor)`
Defined by [dojo/dnd/Selector](selector)
inserts new data items (see `dojo/dnd/Container.insertNodes()` method for details)
| Parameter | Type | Description |
| --- | --- | --- |
| addSelected | Boolean | all new nodes will be added to selected items, if true, no selection change otherwise |
| data | Array | a list of data items, which should be processed by the creator function |
| before | Boolean | insert before the anchor, if true, and after the anchor otherwise |
| anchor | Node | the anchor node to be used as a point of insertion |
**Returns:** function
inserts new data items (see `dojo/dnd/Container.insertNodes()` method for details)
###
`markupFactory``(params,node,Ctor)`
Defined by [dojo/dnd/Container](container)
| Parameter | Type | Description |
| --- | --- | --- |
| params | undefined | |
| node | undefined | |
| Ctor | undefined | |
**Returns:** instance
###
`on``(type,listener)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| listener | undefined | |
**Returns:** undefined
###
`selectAll``()`
Defined by [dojo/dnd/Selector](selector)
selects all items
**Returns:** undefined
###
`selectNone``()`
Defined by [dojo/dnd/Selector](selector)
unselects all items
**Returns:** undefined
###
`setItem``(key,data)`
Defined by [dojo/dnd/Container](container)
associates a data item with its key (id)
| Parameter | Type | Description |
| --- | --- | --- |
| key | String | |
| data | Container.Item | |
###
`startup``()`
Defined by [dojo/dnd/Container](container)
collects valid child items and populate the map
###
`sync``()`
Defined by [dojo/dnd/Selector](selector)
sync up the node list with the data map
**Returns:** function
sync up the node list with the data map
Events
------
###
`onDndCancel``()`
Defined by: [dojo/dnd/Source](source)
topic event processor for /dnd/cancel, called to cancel the DnD operation
###
`onDndDrop``(source,nodes,copy,target)`
Defined by: [dojo/dnd/Source](source)
topic event processor for /dnd/drop, called to finish the DnD operation
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which provides items |
| nodes | Array | the list of transferred items |
| copy | Boolean | copy items, if true, move items otherwise |
| target | Object | the target which accepts items |
###
`onDndSourceOver``(source)`
Defined by: [dojo/dnd/Source](source)
topic event processor for /dnd/source/over, called when detected a current source
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which has the mouse over it |
###
`onDndStart``(source,nodes,copy)`
Defined by: [dojo/dnd/Source](source)
topic event processor for /dnd/start, called to initiate the DnD operation
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which provides items |
| nodes | Array | the list of transferred items |
| copy | Boolean | copy items, if true, move items otherwise |
###
`onDraggingOut``()`
Defined by: [dojo/dnd/Source](source)
called during the active DnD operation, when items are dragged away from this target, and it is not disabled
###
`onDraggingOver``()`
Defined by: [dojo/dnd/Source](source)
called during the active DnD operation, when items are dragged over this target, and it is not disabled
###
`onDrop``(source,nodes,copy)`
Defined by: [dojo/dnd/Source](source)
called only on the current target, when drop is performed
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which provides items |
| nodes | Array | the list of transferred items |
| copy | Boolean | copy items, if true, move items otherwise |
###
`onDropExternal``(source,nodes,copy)`
Defined by: [dojo/dnd/Source](source)
called only on the current target, when drop is performed from an external source
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which provides items |
| nodes | Array | the list of transferred items |
| copy | Boolean | copy items, if true, move items otherwise |
###
`onDropInternal``(nodes,copy)`
Defined by: [dojo/dnd/Source](source)
called only on the current target, when drop is performed from the same target/source
| Parameter | Type | Description |
| --- | --- | --- |
| nodes | Array | the list of transferred items |
| copy | Boolean | copy items, if true, move items otherwise |
###
`onMouseDown``(e)`
Defined by: [dojo/dnd/Source](source)
event processor for onmousedown
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseMove``(e)`
Defined by: [dojo/dnd/Source](source)
event processor for onmousemove
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseOut``(e)`
Defined by: [dojo/dnd/Container](container)
event processor for onmouseout
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseOver``(e)`
Defined by: [dojo/dnd/Container](container)
event processor for onmouseover or touch, to mark that element as the current element
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseUp``(e)`
Defined by: [dojo/dnd/Source](source)
event processor for onmouseup
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onOutEvent``()`
Defined by: [dojo/dnd/Source](source)
this function is called once, when mouse is out of our container
###
`onOverEvent``()`
Defined by: [dojo/dnd/Source](source)
this function is called once, when mouse is over our container
###
`onSelectStart``(e)`
Defined by: [dojo/dnd/Container](container)
event processor for onselectevent and ondragevent
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
| programming_docs |
dojo dojo/dnd/Mover dojo/dnd/Mover
==============
Extends[dojo/Evented](../evented) Summary
-------
an object which makes a node follow the mouse, or touch-drag on touch devices. Used as a default mover, and as a base class for custom movers.
Usage
-----
var foo = new Mover`(node,e,host);` Defined by [dojo/dnd/Mover](mover)
| Parameter | Type | Description |
| --- | --- | --- |
| node | Node | a node (or node's id) to be moved |
| e | Event | a mouse event, which started the move; only pageX and pageY properties are used |
| host | Object | *Optional*
object which implements the functionality of the move, and defines proper events (onMoveStart and onMoveStop) |
See the [dojo/dnd/Mover reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Methods
-------
###
`destroy``()`
Defined by [dojo/dnd/Mover](mover)
stops the move, deletes all references, so the object can be garbage-collected
###
`emit``(type,event)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| event | undefined | |
**Returns:** undefined
###
`on``(type,listener)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| listener | undefined | |
**Returns:** undefined
Events
------
###
`onFirstMove``(e)`
Defined by: [dojo/dnd/Mover](mover)
makes the node absolute; it is meant to be called only once. relative and absolutely positioned nodes are assumed to use pixel units
| Parameter | Type | Description |
| --- | --- | --- |
| e | undefined | |
###
`onMouseMove``(e)`
Defined by: [dojo/dnd/Mover](mover)
event processor for onmousemove/ontouchmove
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse/touch event |
###
`onMouseUp``(e)`
Defined by: [dojo/dnd/Mover](mover)
| Parameter | Type | Description |
| --- | --- | --- |
| e | undefined | |
dojo dojo/dnd/Target dojo/dnd/Target
===============
Extends[dojo/dnd/Source](source) Summary
-------
a Target object, which can be used as a DnD target
Usage
-----
var foo = new Target`(node,params);` Defined by [dojo/dnd/Target](target)
| Parameter | Type | Description |
| --- | --- | --- |
| node | undefined | |
| params | undefined | |
See the [dojo/dnd/Target reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Properties
----------
### accept
Defined by: [dojo/dnd/Source](source)
### allowNested
Defined by: [dojo/dnd/Container](container)
Indicates whether to allow dnd item nodes to be nested within other elements. By default this is false, indicating that only direct children of the container can be draggable dnd item nodes
### autoSync
Defined by: [dojo/dnd/Source](source)
### copyOnly
Defined by: [dojo/dnd/Source](source)
### current
Defined by: [dojo/dnd/Container](container)
The DOM node the mouse is currently hovered over
### delay
Defined by: [dojo/dnd/Source](source)
### generateText
Defined by: [dojo/dnd/Source](source)
### horizontal
Defined by: [dojo/dnd/Source](source)
### isSource
Defined by: [dojo/dnd/Source](source)
### map
Defined by: [dojo/dnd/Container](container)
Map from an item's id (which is also the DOMNode's id) to the [dojo/dnd/Container.Item](container#Item) itself.
### selection
Defined by: [dojo/dnd/Selector](selector)
The set of id's that are currently selected, such that this.selection[id] == 1 if the node w/that id is selected. Can iterate over selected node's id's like:
```
for(var id in this.selection)
```
### selfAccept
Defined by: [dojo/dnd/Source](source)
### selfCopy
Defined by: [dojo/dnd/Source](source)
### singular
Defined by: [dojo/dnd/Selector](selector)
### skipForm
Defined by: [dojo/dnd/Source](source)
### withHandles
Defined by: [dojo/dnd/Source](source)
Methods
-------
###
`checkAcceptance``(source,nodes)`
Defined by [dojo/dnd/Source](source)
checks if the target can accept nodes from this source
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which provides items |
| nodes | Array | the list of transferred items |
**Returns:** boolean
###
`clearItems``()`
Defined by [dojo/dnd/Container](container)
removes all data items from the map
###
`copyState``(keyPressed,self)`
Defined by [dojo/dnd/Source](source)
Returns true if we need to copy items, false to move. It is separated to be overwritten dynamically, if needed.
| Parameter | Type | Description |
| --- | --- | --- |
| keyPressed | Boolean | the "copy" key was pressed |
| self | Boolean | *Optional*
optional flag that means that we are about to drop on itself |
**Returns:** boolean | undefined
###
`creator``()`
Defined by [dojo/dnd/Container](container)
creator function, dummy at the moment
###
`deleteSelectedNodes``()`
Defined by [dojo/dnd/Selector](selector)
deletes all selected items
**Returns:** function
deletes all selected items
###
`delItem``(key)`
Defined by [dojo/dnd/Container](container)
removes a data item from the map by its key (id)
| Parameter | Type | Description |
| --- | --- | --- |
| key | String | |
###
`destroy``()`
Defined by [dojo/dnd/Source](source)
prepares the object to be garbage-collected
###
`emit``(type,event)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| event | undefined | |
**Returns:** undefined
###
`forInItems``(f,o)`
Defined by [dojo/dnd/Container](container)
iterates over a data map skipping members that are present in the empty object (IE and/or 3rd-party libraries).
| Parameter | Type | Description |
| --- | --- | --- |
| f | Function | |
| o | Object | *Optional* |
**Returns:** string
###
`forInSelectedItems``(f,o)`
Defined by [dojo/dnd/Selector](selector)
iterates over selected items; see `dojo/dnd/Container.forInItems()` for details
| Parameter | Type | Description |
| --- | --- | --- |
| f | Function | |
| o | Object | *Optional* |
###
`getAllNodes``()`
Defined by [dojo/dnd/Container](container)
returns a list (an array) of all valid child nodes
**Returns:** undefined
###
`getItem``(key)`
Defined by [dojo/dnd/Container](container)
returns a data item by its key (id)
| Parameter | Type | Description |
| --- | --- | --- |
| key | String | |
**Returns:** undefined
###
`getSelectedNodes``()`
Defined by [dojo/dnd/Selector](selector)
returns a list (an array) of selected nodes
**Returns:** instance
###
`insertNodes``(addSelected,data,before,anchor)`
Defined by [dojo/dnd/Selector](selector)
inserts new data items (see `dojo/dnd/Container.insertNodes()` method for details)
| Parameter | Type | Description |
| --- | --- | --- |
| addSelected | Boolean | all new nodes will be added to selected items, if true, no selection change otherwise |
| data | Array | a list of data items, which should be processed by the creator function |
| before | Boolean | insert before the anchor, if true, and after the anchor otherwise |
| anchor | Node | the anchor node to be used as a point of insertion |
**Returns:** function
inserts new data items (see `dojo/dnd/Container.insertNodes()` method for details)
###
`markupFactory``(params,node,Ctor)`
Defined by [dojo/dnd/Container](container)
| Parameter | Type | Description |
| --- | --- | --- |
| params | undefined | |
| node | undefined | |
| Ctor | undefined | |
**Returns:** instance
###
`on``(type,listener)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| listener | undefined | |
**Returns:** undefined
###
`selectAll``()`
Defined by [dojo/dnd/Selector](selector)
selects all items
**Returns:** undefined
###
`selectNone``()`
Defined by [dojo/dnd/Selector](selector)
unselects all items
**Returns:** undefined
###
`setItem``(key,data)`
Defined by [dojo/dnd/Container](container)
associates a data item with its key (id)
| Parameter | Type | Description |
| --- | --- | --- |
| key | String | |
| data | Container.Item | |
###
`startup``()`
Defined by [dojo/dnd/Container](container)
collects valid child items and populate the map
###
`sync``()`
Defined by [dojo/dnd/Selector](selector)
sync up the node list with the data map
**Returns:** function
sync up the node list with the data map
Events
------
###
`onDndCancel``()`
Defined by: [dojo/dnd/Source](source)
topic event processor for /dnd/cancel, called to cancel the DnD operation
###
`onDndDrop``(source,nodes,copy,target)`
Defined by: [dojo/dnd/Source](source)
topic event processor for /dnd/drop, called to finish the DnD operation
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which provides items |
| nodes | Array | the list of transferred items |
| copy | Boolean | copy items, if true, move items otherwise |
| target | Object | the target which accepts items |
###
`onDndSourceOver``(source)`
Defined by: [dojo/dnd/Source](source)
topic event processor for /dnd/source/over, called when detected a current source
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which has the mouse over it |
###
`onDndStart``(source,nodes,copy)`
Defined by: [dojo/dnd/Source](source)
topic event processor for /dnd/start, called to initiate the DnD operation
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which provides items |
| nodes | Array | the list of transferred items |
| copy | Boolean | copy items, if true, move items otherwise |
###
`onDraggingOut``()`
Defined by: [dojo/dnd/Source](source)
called during the active DnD operation, when items are dragged away from this target, and it is not disabled
###
`onDraggingOver``()`
Defined by: [dojo/dnd/Source](source)
called during the active DnD operation, when items are dragged over this target, and it is not disabled
###
`onDrop``(source,nodes,copy)`
Defined by: [dojo/dnd/Source](source)
called only on the current target, when drop is performed
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which provides items |
| nodes | Array | the list of transferred items |
| copy | Boolean | copy items, if true, move items otherwise |
###
`onDropExternal``(source,nodes,copy)`
Defined by: [dojo/dnd/Source](source)
called only on the current target, when drop is performed from an external source
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | the source which provides items |
| nodes | Array | the list of transferred items |
| copy | Boolean | copy items, if true, move items otherwise |
###
`onDropInternal``(nodes,copy)`
Defined by: [dojo/dnd/Source](source)
called only on the current target, when drop is performed from the same target/source
| Parameter | Type | Description |
| --- | --- | --- |
| nodes | Array | the list of transferred items |
| copy | Boolean | copy items, if true, move items otherwise |
###
`onMouseDown``(e)`
Defined by: [dojo/dnd/Source](source)
event processor for onmousedown
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseMove``(e)`
Defined by: [dojo/dnd/Source](source)
event processor for onmousemove
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseOut``(e)`
Defined by: [dojo/dnd/Container](container)
event processor for onmouseout
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseOver``(e)`
Defined by: [dojo/dnd/Container](container)
event processor for onmouseover or touch, to mark that element as the current element
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onMouseUp``(e)`
Defined by: [dojo/dnd/Source](source)
event processor for onmouseup
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
###
`onOutEvent``()`
Defined by: [dojo/dnd/Source](source)
this function is called once, when mouse is out of our container
###
`onOverEvent``()`
Defined by: [dojo/dnd/Source](source)
this function is called once, when mouse is over our container
###
`onSelectStart``(e)`
Defined by: [dojo/dnd/Container](container)
event processor for onselectevent and ondragevent
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | mouse event |
dojo dojo/dnd/move dojo/dnd/move
=============
Summary
-------
TODOC
See the [dojo/dnd/move reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/dnd.html) for more information.
Methods
-------
###
`boxConstrainedMoveable``()`
Defined by [dojo/dnd/move](move)
###
`constrainedMoveable``()`
Defined by [dojo/dnd/move](move)
###
`parentConstrainedMoveable``()`
Defined by [dojo/dnd/move](move)
dojo dojo/date/locale.__FormatOptions dojo/date/locale.\_\_FormatOptions
==================================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new locale.__FormatOptions()`
See the [dojo/date/locale.\_\_FormatOptions reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/date.html) for more information.
Properties
----------
### am
Defined by: [dojo/date/locale](locale)
override strings for am in times
### datePattern
Defined by: [dojo/date/locale](locale)
override pattern with this string
### formatLength
Defined by: [dojo/date/locale](locale)
choice of long, short, medium or full (plus any custom additions). Defaults to 'short'
### fullYear
Defined by: [dojo/date/locale](locale)
(format only) use 4 digit years whenever 2 digit years are called for
### locale
Defined by: [dojo/date/locale](locale)
override the locale used to determine formatting rules
### pm
Defined by: [dojo/date/locale](locale)
override strings for pm in times
### selector
Defined by: [dojo/date/locale](locale)
choice of 'time','date' (default: date and time)
### strict
Defined by: [dojo/date/locale](locale)
(parse only) strict parsing, off by default
### timePattern
Defined by: [dojo/date/locale](locale)
override pattern with this string
dojo dojo/date/locale dojo/date/locale
================
Summary
-------
This modules defines [dojo/date/locale](locale), localization methods for Date.
See the [dojo/date/locale reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/date/locale.html) for more information.
Methods
-------
###
`addCustomFormats``(packageName,bundleName)`
Defined by [dojo/date/locale](locale)
Add a reference to a bundle containing localized custom formats to be used by date/time formatting and parsing routines.
The user may add custom localized formats where the bundle has properties following the same naming convention used by dojo.cldr: `dateFormat-xxxx` / `timeFormat-xxxx` The pattern string should match the format used by the CLDR. See [dojo/date/locale.format()](locale#format) for details. The resources must be loaded by dojo.requireLocalization() prior to use
| Parameter | Type | Description |
| --- | --- | --- |
| packageName | String | |
| bundleName | String | |
###
`format``(dateObject,options)`
Defined by [dojo/date/locale](locale)
Format a Date object as a String, using locale-specific settings.
Create a string from a Date object using a known localized pattern. By default, this method formats both date and time from dateObject. Formatting patterns are chosen appropriate to the locale. Different formatting lengths may be chosen, with "full" used by default. Custom patterns may be used or registered with translations using the [dojo/date/locale.addCustomFormats()](locale#addCustomFormats) method. Formatting patterns are implemented using [the syntax described at unicode.org](http://www.unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns)
| Parameter | Type | Description |
| --- | --- | --- |
| dateObject | Date | the date and/or time to be formatted. If a time only is formatted, the values in the year, month, and day fields are irrelevant. The opposite is true when formatting only dates. |
| options | Object | *Optional*
An object with the following properties:* selector (String): choice of 'time','date' (default: date and time)
* formatLength (String): choice of long, short, medium or full (plus any custom additions). Defaults to 'short'
* datePattern (String): override pattern with this string
* timePattern (String): override pattern with this string
* am (String): override strings for am in times
* pm (String): override strings for pm in times
* locale (String): override the locale used to determine formatting rules
* fullYear (Boolean): (format only) use 4 digit years whenever 2 digit years are called for
* strict (Boolean): (parse only) strict parsing, off by default
|
**Returns:** undefined
###
`getNames``(item,type,context,locale)`
Defined by [dojo/date/locale](locale)
Used to get localized strings from dojo.cldr for day or month names.
| Parameter | Type | Description |
| --- | --- | --- |
| item | String | 'months' || 'days' |
| type | String | 'wide' || 'abbr' || 'narrow' (e.g. "Monday", "Mon", or "M" respectively, in English) |
| context | String | *Optional*
'standAlone' || 'format' (default) |
| locale | String | *Optional*
override locale used to find the names |
**Returns:** undefined
###
`isWeekend``(dateObject,locale)`
Defined by [dojo/date/locale](locale)
Determines if the date falls on a weekend, according to local custom.
| Parameter | Type | Description |
| --- | --- | --- |
| dateObject | Date | *Optional* |
| locale | String | *Optional* |
**Returns:** boolean
###
`parse``(value,options)`
Defined by [dojo/date/locale](locale)
Convert a properly formatted string to a primitive Date object, using locale-specific settings.
Create a Date object from a string using a known localized pattern. By default, this method parses looking for both date and time in the string. Formatting patterns are chosen appropriate to the locale. Different formatting lengths may be chosen, with "full" used by default. Custom patterns may be used or registered with translations using the [dojo/date/locale.addCustomFormats()](locale#addCustomFormats) method.
Formatting patterns are implemented using [the syntax described at unicode.org](http://www.unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns) When two digit years are used, a century is chosen according to a sliding window of 80 years before and 20 years after present year, for both `yy` and `yyyy` patterns. year < 100CE requires strict mode.
| Parameter | Type | Description |
| --- | --- | --- |
| value | String | A string representation of a date |
| options | Object | *Optional*
An object with the following properties:* selector (String): choice of 'time','date' (default: date and time)
* formatLength (String): choice of long, short, medium or full (plus any custom additions). Defaults to 'short'
* datePattern (String): override pattern with this string
* timePattern (String): override pattern with this string
* am (String): override strings for am in times
* pm (String): override strings for pm in times
* locale (String): override the locale used to determine formatting rules
* fullYear (Boolean): (format only) use 4 digit years whenever 2 digit years are called for
* strict (Boolean): (parse only) strict parsing, off by default
|
**Returns:** null | undefined
###
`regexp``(options)`
Defined by [dojo/date/locale](locale)
Builds the regular needed to parse a localized date
| Parameter | Type | Description |
| --- | --- | --- |
| options | Object | *Optional*
An object with the following properties:* selector (String): choice of 'time','date' (default: date and time)
* formatLength (String): choice of long, short, medium or full (plus any custom additions). Defaults to 'short'
* datePattern (String): override pattern with this string
* timePattern (String): override pattern with this string
* am (String): override strings for am in times
* pm (String): override strings for pm in times
* locale (String): override the locale used to determine formatting rules
* fullYear (Boolean): (format only) use 4 digit years whenever 2 digit years are called for
* strict (Boolean): (parse only) strict parsing, off by default
|
**Returns:** undefined
| programming_docs |
dojo dojo/date/stamp dojo/date/stamp
===============
Summary
-------
TODOC
See the [dojo/date/stamp reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/date/stamp.html) for more information.
Properties
----------
Methods
-------
###
`fromISOString``(formattedString,defaultTime)`
Defined by [dojo/date/stamp](stamp)
Returns a Date object given a string formatted according to a subset of the ISO-8601 standard.
Accepts a string formatted according to a profile of ISO8601 as defined by [RFC3339](http://www.ietf.org/rfc/rfc3339.txt), except that partial input is allowed. Can also process dates as specified [by the W3C](http://www.w3.org/TR/NOTE-datetime) The following combinations are valid:
* dates only
+ yyyy
+ yyyy-MM
+ yyyy-MM-dd
* times only, with an optional time zone appended
+ THH:mm
+ THH:mm:ss
+ THH:mm:ss.SSS
* and "datetimes" which could be any combination of the above
timezones may be specified as Z (for UTC) or +/- followed by a time expression HH:mm Assumes the local time zone if not specified. Does not validate. Improperly formatted input may return null. Arguments which are out of bounds will be handled by the Date constructor (e.g. January 32nd typically gets resolved to February 1st) Only years between 100 and 9999 are supported.
| Parameter | Type | Description |
| --- | --- | --- |
| formattedString | String | A string such as 2005-06-30T08:05:00-07:00 or 2005-06-30 or T08:05:00 |
| defaultTime | Number | *Optional*
Used for defaults for fields omitted in the formattedString. Uses 1970-01-01T00:00:00.0Z by default. |
**Returns:** instance
###
`toISOString``(dateObject,options)`
Defined by [dojo/date/stamp](stamp)
Format a Date object as a string according a subset of the ISO-8601 standard
When options.selector is omitted, output follows [RFC3339](http://www.ietf.org/rfc/rfc3339.txt) The local time zone is included as an offset from GMT, except when selector=='time' (time without a date) Does not check bounds. Only years between 100 and 9999 are supported.
| Parameter | Type | Description |
| --- | --- | --- |
| dateObject | Date | A Date object |
| options | Object | *Optional*
An object with the following properties:* selector (String): "date" or "time" for partial formatting of the Date object. Both date and time will be formatted by default.
* zulu (Boolean): if true, UTC/GMT is used for a timezone
* milliseconds (Boolean): if true, output milliseconds
|
**Returns:** undefined
dojo dojo/io/iframe dojo/io/iframe
==============
Summary
-------
Deprecated, use [dojo/request/iframe](../request/iframe) instead. Sends an Ajax I/O call using and Iframe (for instance, to upload files)
See the [dojo/io/iframe reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/io/iframe.html) for more information.
Methods
-------
###
`create``(fname,onloadstr,uri)`
Defined by [dojo/io/iframe](iframe)
Creates a hidden iframe in the page. Used mostly for IO transports. You do not need to call this to start a dojo/io/iframe request. Just call send().
| Parameter | Type | Description |
| --- | --- | --- |
| fname | String | The name of the iframe. Used for the name attribute on the iframe. |
| onloadstr | String | A string of JavaScript that will be executed when the content in the iframe loads. |
| uri | String | The value of the src attribute on the iframe element. If a value is not given, then dojo/resources/blank.html will be used. |
###
`doc``(iframeNode)`
Defined by [dojo/io/iframe](iframe)
Returns the document object associated with the iframe DOM Node argument.
| Parameter | Type | Description |
| --- | --- | --- |
| iframeNode | undefined | |
###
`setSrc``(iframe,src,replace)`
Defined by [dojo/io/iframe](iframe)
Sets the URL that is loaded in an IFrame. The replace parameter indicates whether location.replace() should be used when changing the location of the iframe.
| Parameter | Type | Description |
| --- | --- | --- |
| iframe | undefined | |
| src | undefined | |
| replace | undefined | |
dojo dojo/io/script dojo/io/script
==============
Summary
-------
TODOC
See the [dojo/io/script reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/io/script.html) for more information.
Properties
----------
Methods
-------
###
`attach``(id,url,frameDocument)`
Defined by [dojo/io/script](script)
creates a new `<script>` tag pointing to the specified URL and adds it to the document.
Attaches the script element to the DOM. Use this method if you just want to attach a script to the DOM and do not care when or if it loads.
| Parameter | Type | Description |
| --- | --- | --- |
| id | undefined | |
| url | undefined | |
| frameDocument | undefined | |
###
`get``(args)`
Defined by [dojo/io/script](script)
sends a get request using a dynamically created script tag.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* callbackParamName (String): Deprecated as of Dojo 1.4 in favor of "jsonp", but still supported for legacy code. See notes for jsonp property.
* jsonp (String): The URL parameter name that indicates the JSONP callback string. For instance, when using Yahoo JSONP calls it is normally, jsonp: "callback". For AOL JSONP calls it is normally jsonp: "c".
* checkString (String): A string of JavaScript that when evaluated like so: "typeof(" + checkString + ") != 'undefined'" being true means that the script fetched has been loaded. Do not use this if doing a JSONP type of call (use callbackParamName instead).
* frameDoc (Document): The Document object for a child iframe. If this is passed in, the script will be attached to that document. This can be helpful in some comet long-polling scenarios with Firefox and Opera.
* load: This function will be called on a successful HTTP response code.
* error: This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
* handle: This function will be called at the end of every request, whether or not an error occurs.
* url (String): URL to server endpoint.
* content (Object, optional): Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
* timeout (Integer, optional): Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
* form (DOMNode, optional): DOM node for a form. Used to extract the form values and send to the server.
* preventCache (Boolean, optional): Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
* handleAs (String, optional): Acceptable values depend on the type of IO transport (see specific IO calls for more information).
* rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for dojo/\_base/xhr.rawXhrPost and dojo/\_base/xhr.rawXhrPut respectively.
* ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via dojo/topic.publish() for different phases of an IO operation. See dojo/main.\_\_IoPublish for a list of topics that are published.
|
**Returns:** undefined
###
`remove``(id,frameDocument)`
Defined by [dojo/io/script](script)
removes the script element with the given id, from the given frameDocument. If no frameDocument is passed, the current document is used.
| Parameter | Type | Description |
| --- | --- | --- |
| id | undefined | |
| frameDocument | undefined | |
dojo dojo/cldr/supplemental dojo/cldr/supplemental
======================
Summary
-------
TODOC
See the [dojo/cldr/supplemental reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/cldr/supplemental.html) for more information.
Methods
-------
###
`getFirstDayOfWeek``(locale)`
Defined by [dojo/cldr/supplemental](supplemental)
Returns a zero-based index for first day of the week
Returns a zero-based index for first day of the week, as used by the local (Gregorian) calendar. e.g. Sunday (returns 0), or Monday (returns 1)
| Parameter | Type | Description |
| --- | --- | --- |
| locale | String | *Optional* |
**Returns:** number
###
`getWeekend``(locale)`
Defined by [dojo/cldr/supplemental](supplemental)
Returns a hash containing the start and end days of the weekend
Returns a hash containing the start and end days of the weekend according to local custom using locale, or by default in the user's locale. e.g. {start:6, end:0}
| Parameter | Type | Description |
| --- | --- | --- |
| locale | String | *Optional* |
**Returns:** object
dojo dojo/cldr/monetary dojo/cldr/monetary
==================
Summary
-------
TODOC
See the [dojo/cldr/monetary reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/cldr/monetary.html) for more information.
Methods
-------
###
`getData``(code)`
Defined by [dojo/cldr/monetary](monetary)
A mapping of currency code to currency-specific formatting information. Returns a unique object with properties: places, round.
| Parameter | Type | Description |
| --- | --- | --- |
| code | String | an [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code |
**Returns:** object
dojo dojo/request/iframe.__MethodOptions dojo/request/iframe.\_\_MethodOptions
=====================================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new iframe.__MethodOptions()`
See the [dojo/request/iframe.\_\_MethodOptions reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request.html) for more information.
Properties
----------
### method
Defined by: [dojo/request/iframe](iframe)
The HTTP method to use to make the request. Must be uppercase. Only `"GET"` and `"POST"` are accepted. Default is `"POST"`.
dojo dojo/request/xhr.__MethodOptions dojo/request/xhr.\_\_MethodOptions
==================================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new xhr.__MethodOptions()`
See the [dojo/request/xhr.\_\_MethodOptions reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request.html) for more information.
Properties
----------
### method
Defined by: [dojo/request/xhr](xhr)
The HTTP method to use to make the request. Must be uppercase. Default is `"GET"`.
dojo dojo/request/node dojo/request/node
=================
Summary
-------
Sends a request using the included http or https interface from node.js with the given URL and options.
Usage
-----
node`(url,options);`
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request/node.\_\_Options](node.__options) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](../request.__promise)
See the [dojo/request/node reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request/node.html) for more information.
Methods
-------
###
`del``(url,options)`
Defined by [dojo/request/node](node)
Send an HTTP DELETE request using XMLHttpRequest with the given URL and options.
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request/node.\_\_BaseOptions](node.__baseoptions) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](../request.__promise)
###
`get``(url,options)`
Defined by [dojo/request/node](node)
Send an HTTP GET request using XMLHttpRequest with the given URL and options.
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request/node.\_\_BaseOptions](node.__baseoptions) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](../request.__promise)
###
`post``(url,options)`
Defined by [dojo/request/node](node)
Send an HTTP POST request using XMLHttpRequest with the given URL and options.
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request/node.\_\_BaseOptions](node.__baseoptions) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](../request.__promise)
###
`put``(url,options)`
Defined by [dojo/request/node](node)
Send an HTTP PUT request using XMLHttpRequest with the given URL and options.
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request/node.\_\_BaseOptions](node.__baseoptions) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](../request.__promise)
dojo dojo/request/iframe.__Options dojo/request/iframe.\_\_Options
===============================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new iframe.__Options()`
See the [dojo/request/iframe.\_\_Options reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request.html) for more information.
Properties
----------
### data
Defined by: [dojo/request/iframe](iframe)
Data to transfer. When making a GET request, this will be converted to key=value parameters and appended to the URL.
### form
Defined by: [dojo/request/iframe](iframe)
A form node to use to submit data to the server.
### handleAs
Defined by: [dojo/request](../request)
How to handle the response from the server. Default is 'text'. Other values are 'json', 'javascript', and 'xml'.
### method
Defined by: [dojo/request/iframe](iframe)
The HTTP method to use to make the request. Must be uppercase. Only `"GET"` and `"POST"` are accepted. Default is `"POST"`.
### preventCache
Defined by: [dojo/request](../request)
Whether to append a cache-busting parameter to the URL.
### query
Defined by: [dojo/request](../request)
Query parameters to append to the URL.
### timeout
Defined by: [dojo/request](../request)
Milliseconds to wait for the response. If this time passes, the then the promise is rejected.
dojo dojo/request/default dojo/request/default
====================
See the [dojo/request/default reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request/default.html) for more information.
Methods
-------
###
`getPlatformDefaultId``()`
Defined by [dojo/request/default](default)
###
`load``(id,parentRequire,loaded,config)`
Defined by [dojo/request/default](default)
| Parameter | Type | Description |
| --- | --- | --- |
| id | undefined | |
| parentRequire | undefined | |
| loaded | undefined | |
| config | undefined | |
dojo dojo/request/node.__Options dojo/request/node.\_\_Options
=============================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new node.__Options()`
See the [dojo/request/node.\_\_Options reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request.html) for more information.
Properties
----------
### data
Defined by: [dojo/request/node](node)
Data to transfer. This is ignored for GET and DELETE requests.
### handleAs
Defined by: [dojo/request](../request)
How to handle the response from the server. Default is 'text'. Other values are 'json', 'javascript', and 'xml'.
### headers
Defined by: [dojo/request/node](node)
Headers to use for the request.
### method
Defined by: [dojo/request/node](node)
The HTTP method to use to make the request. Must be uppercase. Default is `"GET"`.
### password
Defined by: [dojo/request/node](node)
Password to use during the request.
### preventCache
Defined by: [dojo/request](../request)
Whether to append a cache-busting parameter to the URL.
### query
Defined by: [dojo/request](../request)
Query parameters to append to the URL.
### timeout
Defined by: [dojo/request](../request)
Milliseconds to wait for the response. If this time passes, the then the promise is rejected.
### user
Defined by: [dojo/request/node](node)
Username to use during the request.
dojo dojo/request/util dojo/request/util
=================
See the [dojo/request/util reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request/util.html) for more information.
Methods
-------
###
`addCommonMethods``(provider,methods)`
Defined by [dojo/request/util](util)
| Parameter | Type | Description |
| --- | --- | --- |
| provider | undefined | |
| methods | undefined | |
###
`checkStatus``(stat)`
Defined by [dojo/request/util](util)
| Parameter | Type | Description |
| --- | --- | --- |
| stat | undefined | |
**Returns:** boolean
###
`deepCopy``(target,source)`
Defined by [dojo/request/util](util)
| Parameter | Type | Description |
| --- | --- | --- |
| target | undefined | |
| source | undefined | |
**Returns:** undefined
###
`deepCreate``(source,properties)`
Defined by [dojo/request/util](util)
| Parameter | Type | Description |
| --- | --- | --- |
| source | undefined | |
| properties | undefined | |
**Returns:** undefined
###
`deferred``(response,cancel,isValid,isReady,handleResponse,last)`
Defined by [dojo/request/util](util)
| Parameter | Type | Description |
| --- | --- | --- |
| response | Object | The object used as the value of the request promise. |
| cancel | undefined | |
| isValid | undefined | |
| isReady | undefined | |
| handleResponse | undefined | |
| last | undefined | |
**Returns:** instance
###
`notify``(type,listener)`
Defined by [dojo/request/notify](notify)
Register a listener to be notified when an event in dojo/request happens.
| Parameter | Type | Description |
| --- | --- | --- |
| type | String | *Optional*
The event to listen for. Events emitted: "start", "send", "load", "error", "done", "stop". |
| listener | Function | *Optional*
A callback to be run when an event happens. |
**Returns:** any | undefined
A signal object that can be used to cancel the listener. If remove() is called on this signal object, it will stop the listener from being executed.
###
`parseArgs``(url,options,skipData)`
Defined by [dojo/request/util](util)
| Parameter | Type | Description |
| --- | --- | --- |
| url | undefined | |
| options | undefined | |
| skipData | undefined | |
**Returns:** object
dojo dojo/request/watch dojo/request/watch
==================
Summary
-------
Watches the io request represented by dfd to see if it completes.
Usage
-----
watch`(dfd);`
| Parameter | Type | Description |
| --- | --- | --- |
| dfd | Deferred | The Deferred object to watch. |
See the [dojo/request/watch reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request/watch.html) for more information.
Properties
----------
###
`ioCheck`
Defined by: [dojo/request/watch](watch)
Function used to check if basic IO call worked. Gets the dfd object as its only argument.
###
`resHandle`
Defined by: [dojo/request/watch](watch)
Function used to process response. Gets the dfd object as its only argument.
###
`validCheck`
Defined by: [dojo/request/watch](watch)
Function used to check if the IO request is still valid. Gets the dfd object as its only argument.
Methods
-------
###
`cancelAll``()`
Defined by [dojo/request/watch](watch)
Cancels all pending IO requests, regardless of IO type
| programming_docs |
dojo dojo/request/iframe dojo/request/iframe
===================
Summary
-------
Sends a request using an iframe element with the given URL and options.
Usage
-----
iframe`(url,options);`
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request/iframe.\_\_Options](iframe.__options) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](../request.__promise)
See the [dojo/request/iframe reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request/iframe.html) for more information.
Properties
----------
Methods
-------
###
`create``(name,onloadstr,uri)`
Defined by [dojo/request/iframe](iframe)
| Parameter | Type | Description |
| --- | --- | --- |
| name | undefined | |
| onloadstr | undefined | |
| uri | undefined | |
**Returns:** undefined
###
`doc``(iframeNode)`
Defined by [dojo/request/iframe](iframe)
| Parameter | Type | Description |
| --- | --- | --- |
| iframeNode | undefined | |
**Returns:** undefined | null
###
`get``(url,options)`
Defined by [dojo/request/iframe](iframe)
Send an HTTP GET request using an iframe element with the given URL and options.
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request/iframe.\_\_BaseOptions](iframe.__baseoptions) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](../request.__promise)
###
`post``(url,options)`
Defined by [dojo/request/iframe](iframe)
Send an HTTP POST request using an iframe element with the given URL and options.
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request/iframe.\_\_BaseOptions](iframe.__baseoptions) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](../request.__promise)
###
`setSrc``(_iframe,src,replace)`
Defined by [dojo/request/iframe](iframe)
| Parameter | Type | Description |
| --- | --- | --- |
| \_iframe | undefined | |
| src | undefined | |
| replace | undefined | |
dojo dojo/request/node.__BaseOptions dojo/request/node.\_\_BaseOptions
=================================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new node.__BaseOptions()`
See the [dojo/request/node.\_\_BaseOptions reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request.html) for more information.
Properties
----------
### data
Defined by: [dojo/request/node](node)
Data to transfer. This is ignored for GET and DELETE requests.
### handleAs
Defined by: [dojo/request](../request)
How to handle the response from the server. Default is 'text'. Other values are 'json', 'javascript', and 'xml'.
### headers
Defined by: [dojo/request/node](node)
Headers to use for the request.
### password
Defined by: [dojo/request/node](node)
Password to use during the request.
### preventCache
Defined by: [dojo/request](../request)
Whether to append a cache-busting parameter to the URL.
### query
Defined by: [dojo/request](../request)
Query parameters to append to the URL.
### timeout
Defined by: [dojo/request](../request)
Milliseconds to wait for the response. If this time passes, the then the promise is rejected.
### user
Defined by: [dojo/request/node](node)
Username to use during the request.
dojo dojo/request/script.__Options dojo/request/script.\_\_Options
===============================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new script.__Options()`
See the [dojo/request/script.\_\_Options reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request.html) for more information.
Properties
----------
### checkString
Defined by: [dojo/request/script](script)
A string of JavaScript that when evaluated like so: "typeof(" + checkString + ") != 'undefined'" being true means that the script fetched has been loaded. Do not use this if doing a JSONP type of call (use `jsonp` instead).
### data
Defined by: [dojo/request](../request)
Data to transfer. This is ignored for GET and DELETE requests.
### frameDoc
Defined by: [dojo/request/script](script)
The Document object of a child iframe. If this is passed in, the script will be attached to that document. This can be helpful in some comet long-polling scenarios with Firefox and Opera.
### handleAs
Defined by: [dojo/request](../request)
How to handle the response from the server. Default is 'text'. Other values are 'json', 'javascript', and 'xml'.
### jsonp
Defined by: [dojo/request/script](script)
The URL parameter name that indicates the JSONP callback string. For instance, when using Yahoo JSONP calls it is normally, jsonp: "callback". For AOL JSONP calls it is normally jsonp: "c".
### method
Defined by: [dojo/request/script](script)
This option is ignored. All requests using this transport are GET requests.
### preventCache
Defined by: [dojo/request](../request)
Whether to append a cache-busting parameter to the URL.
### query
Defined by: [dojo/request](../request)
Query parameters to append to the URL.
### timeout
Defined by: [dojo/request](../request)
Milliseconds to wait for the response. If this time passes, the then the promise is rejected.
dojo dojo/request/iframe.__BaseOptions dojo/request/iframe.\_\_BaseOptions
===================================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new iframe.__BaseOptions()`
See the [dojo/request/iframe.\_\_BaseOptions reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request.html) for more information.
Properties
----------
### data
Defined by: [dojo/request/iframe](iframe)
Data to transfer. When making a GET request, this will be converted to key=value parameters and appended to the URL.
### form
Defined by: [dojo/request/iframe](iframe)
A form node to use to submit data to the server.
### handleAs
Defined by: [dojo/request](../request)
How to handle the response from the server. Default is 'text'. Other values are 'json', 'javascript', and 'xml'.
### preventCache
Defined by: [dojo/request](../request)
Whether to append a cache-busting parameter to the URL.
### query
Defined by: [dojo/request](../request)
Query parameters to append to the URL.
### timeout
Defined by: [dojo/request](../request)
Milliseconds to wait for the response. If this time passes, the then the promise is rejected.
dojo dojo/request/node.__MethodOptions dojo/request/node.\_\_MethodOptions
===================================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new node.__MethodOptions()`
See the [dojo/request/node.\_\_MethodOptions reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request.html) for more information.
Properties
----------
### method
Defined by: [dojo/request/node](node)
The HTTP method to use to make the request. Must be uppercase. Default is `"GET"`.
dojo dojo/request/notify dojo/request/notify
===================
Summary
-------
Register a listener to be notified when an event in [dojo/request](../request) happens.
Usage
-----
notify`(type,listener);`
| Parameter | Type | Description |
| --- | --- | --- |
| type | String | *Optional*
The event to listen for. Events emitted: "start", "send", "load", "error", "done", "stop". |
| listener | Function | *Optional*
A callback to be run when an event happens. |
**Returns:** any | undefined
A signal object that can be used to cancel the listener. If remove() is called on this signal object, it will stop the listener from being executed.
See the [dojo/request/notify reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request/notify.html) for more information.
Methods
-------
###
`emit``(type,event,cancel)`
Defined by [dojo/request/notify](notify)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| event | undefined | |
| cancel | undefined | |
dojo dojo/request/handlers dojo/request/handlers
=====================
Usage
-----
handlers`(response);`
| Parameter | Type | Description |
| --- | --- | --- |
| response | undefined | |
**Returns:** undefined
See the [dojo/request/handlers reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request/handlers.html) for more information.
Methods
-------
###
`register``(name,handler)`
Defined by [dojo/request/handlers](handlers)
| Parameter | Type | Description |
| --- | --- | --- |
| name | undefined | |
| handler | undefined | |
dojo dojo/request/xhr.__Options dojo/request/xhr.\_\_Options
============================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new xhr.__Options()`
See the [dojo/request/xhr.\_\_Options reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request.html) for more information.
Properties
----------
### data
Defined by: [dojo/request/xhr](xhr)
Data to transfer. This is ignored for GET and DELETE requests.
### handleAs
Defined by: [dojo/request](../request)
How to handle the response from the server. Default is 'text'. Other values are 'json', 'javascript', and 'xml'.
### headers
Defined by: [dojo/request/xhr](xhr)
Headers to use for the request.
### method
Defined by: [dojo/request/xhr](xhr)
The HTTP method to use to make the request. Must be uppercase. Default is `"GET"`.
### password
Defined by: [dojo/request/xhr](xhr)
Password to use during the request.
### preventCache
Defined by: [dojo/request](../request)
Whether to append a cache-busting parameter to the URL.
### query
Defined by: [dojo/request](../request)
Query parameters to append to the URL.
### sync
Defined by: [dojo/request/xhr](xhr)
Whether to make a synchronous request or not. Default is `false` (asynchronous).
### timeout
Defined by: [dojo/request](../request)
Milliseconds to wait for the response. If this time passes, the then the promise is rejected.
### user
Defined by: [dojo/request/xhr](xhr)
Username to use during the request.
### withCredentials
Defined by: [dojo/request/xhr](xhr)
For cross-site requests, whether to send credentials or not.
dojo dojo/request/script.__MethodOptions dojo/request/script.\_\_MethodOptions
=====================================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new script.__MethodOptions()`
See the [dojo/request/script.\_\_MethodOptions reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request.html) for more information.
Properties
----------
### method
Defined by: [dojo/request/script](script)
This option is ignored. All requests using this transport are GET requests.
dojo dojo/request/script.__BaseOptions dojo/request/script.\_\_BaseOptions
===================================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new script.__BaseOptions()`
See the [dojo/request/script.\_\_BaseOptions reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request.html) for more information.
Properties
----------
### checkString
Defined by: [dojo/request/script](script)
A string of JavaScript that when evaluated like so: "typeof(" + checkString + ") != 'undefined'" being true means that the script fetched has been loaded. Do not use this if doing a JSONP type of call (use `jsonp` instead).
### data
Defined by: [dojo/request](../request)
Data to transfer. This is ignored for GET and DELETE requests.
### frameDoc
Defined by: [dojo/request/script](script)
The Document object of a child iframe. If this is passed in, the script will be attached to that document. This can be helpful in some comet long-polling scenarios with Firefox and Opera.
### handleAs
Defined by: [dojo/request](../request)
How to handle the response from the server. Default is 'text'. Other values are 'json', 'javascript', and 'xml'.
### jsonp
Defined by: [dojo/request/script](script)
The URL parameter name that indicates the JSONP callback string. For instance, when using Yahoo JSONP calls it is normally, jsonp: "callback". For AOL JSONP calls it is normally jsonp: "c".
### preventCache
Defined by: [dojo/request](../request)
Whether to append a cache-busting parameter to the URL.
### query
Defined by: [dojo/request](../request)
Query parameters to append to the URL.
### timeout
Defined by: [dojo/request](../request)
Milliseconds to wait for the response. If this time passes, the then the promise is rejected.
dojo dojo/request/script dojo/request/script
===================
Summary
-------
Sends a request using a script element with the given URL and options.
Usage
-----
script`(url,options);`
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request/script.\_\_Options](script.__options) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](../request.__promise)
See the [dojo/request/script reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request/script.html) for more information.
Properties
----------
Methods
-------
###
`get``(url,options)`
Defined by [dojo/request/script](script)
Send an HTTP GET request using a script element with the given URL and options.
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request/script.\_\_BaseOptions](script.__baseoptions) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](../request.__promise)
dojo dojo/request/xhr dojo/request/xhr
================
Summary
-------
Sends a request using XMLHttpRequest with the given URL and options.
Usage
-----
xhr`(url,options);`
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request/xhr.\_\_Options](xhr.__options) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](../request.__promise)
See the [dojo/request/xhr reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request/xhr.html) for more information.
Methods
-------
###
`del``(url,options)`
Defined by [dojo/request/xhr](xhr)
Send an HTTP DELETE request using XMLHttpRequest with the given URL and options.
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request/xhr.\_\_BaseOptions](xhr.__baseoptions) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](../request.__promise)
###
`get``(url,options)`
Defined by [dojo/request/xhr](xhr)
Send an HTTP GET request using XMLHttpRequest with the given URL and options.
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request/xhr.\_\_BaseOptions](xhr.__baseoptions) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](../request.__promise)
###
`post``(url,options)`
Defined by [dojo/request/xhr](xhr)
Send an HTTP POST request using XMLHttpRequest with the given URL and options.
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request/xhr.\_\_BaseOptions](xhr.__baseoptions) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](../request.__promise)
###
`put``(url,options)`
Defined by [dojo/request/xhr](xhr)
Send an HTTP PUT request using XMLHttpRequest with the given URL and options.
| Parameter | Type | Description |
| --- | --- | --- |
| url | String | URL to request |
| options | [dojo/request/xhr.\_\_BaseOptions](xhr.__baseoptions) | *Optional*
Options for the request. |
**Returns:** [dojo/request.\_\_Promise](../request.__promise)
dojo dojo/request/registry dojo/request/registry
=====================
Usage
-----
registry`(url,options);`
| Parameter | Type | Description |
| --- | --- | --- |
| url | undefined | |
| options | undefined | |
**Returns:** undefined
See the [dojo/request/registry reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request/registry.html) for more information.
Methods
-------
###
`load``(id,parentRequire,loaded,config)`
Defined by [dojo/request/registry](registry)
| Parameter | Type | Description |
| --- | --- | --- |
| id | undefined | |
| parentRequire | undefined | |
| loaded | undefined | |
| config | undefined | |
###
`register``(url,provider,first)`
Defined by [dojo/request/registry](registry)
| Parameter | Type | Description |
| --- | --- | --- |
| url | undefined | |
| provider | undefined | |
| first | undefined | |
dojo dojo/request/xhr.__BaseOptions dojo/request/xhr.\_\_BaseOptions
================================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new xhr.__BaseOptions()`
See the [dojo/request/xhr.\_\_BaseOptions reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/request.html) for more information.
Properties
----------
### data
Defined by: [dojo/request/xhr](xhr)
Data to transfer. This is ignored for GET and DELETE requests.
### handleAs
Defined by: [dojo/request](../request)
How to handle the response from the server. Default is 'text'. Other values are 'json', 'javascript', and 'xml'.
### headers
Defined by: [dojo/request/xhr](xhr)
Headers to use for the request.
### password
Defined by: [dojo/request/xhr](xhr)
Password to use during the request.
### preventCache
Defined by: [dojo/request](../request)
Whether to append a cache-busting parameter to the URL.
### query
Defined by: [dojo/request](../request)
Query parameters to append to the URL.
### sync
Defined by: [dojo/request/xhr](xhr)
Whether to make a synchronous request or not. Default is `false` (asynchronous).
### timeout
Defined by: [dojo/request](../request)
Milliseconds to wait for the response. If this time passes, the then the promise is rejected.
### user
Defined by: [dojo/request/xhr](xhr)
Username to use during the request.
### withCredentials
Defined by: [dojo/request/xhr](xhr)
For cross-site requests, whether to send credentials or not.
| programming_docs |
dojo dojo/promise/all dojo/promise/all
================
Summary
-------
Takes multiple promises and returns a new promise that is fulfilled when all promises have been resolved or one has been rejected.
Takes multiple promises and returns a new promise that is fulfilled when all promises have been resolved or one has been rejected. If one of the promises is rejected, the returned promise is also rejected. Canceling the returned promise will *not* cancel any passed promises.
Usage
-----
all`(objectOrArray);`
| Parameter | Type | Description |
| --- | --- | --- |
| objectOrArray | Object | Array | *Optional*
The promise will be fulfilled with a list of results if invoked with an array, or an object of results when passed an object (using the same keys). If passed neither an object or array it is resolved with an undefined value. |
**Returns:** [dojo/promise/Promise](promise) | undefined
See the [dojo/promise/all reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/promise/all.html) for more information.
Methods
-------
dojo dojo/promise/tracer dojo/promise/tracer
===================
Summary
-------
Trace promise fulfillment.
Trace promise fulfillment. Calling `.trace()` or `.traceError()` on a promise enables tracing. Will emit `resolved`, `rejected` or `progress` events.
See the [dojo/promise/tracer reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/promise.html) for more information.
Methods
-------
###
`on``(type,listener)`
Defined by [dojo/promise/tracer](tracer)
Subscribe to traces.
See [dojo/Evented](../evented)#on().
| Parameter | Type | Description |
| --- | --- | --- |
| type | String | `resolved`, `rejected`, or `progress` |
| listener | Function | The listener is passed the traced value and any arguments that were used with the `.trace()` call. |
dojo dojo/promise/Promise dojo/promise/Promise
====================
Summary
-------
The public interface to a deferred.
The public interface to a deferred. All promises in Dojo are instances of this class.
Usage
-----
Promise`();` See the [dojo/promise/Promise reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/promise/Promise.html) for more information.
Methods
-------
###
`always``(callbackOrErrback)`
Defined by [dojo/promise/Promise](promise)
Add a callback to be invoked when the promise is resolved or rejected.
| Parameter | Type | Description |
| --- | --- | --- |
| callbackOrErrback | Function | *Optional*
A function that is used both as a callback and errback. |
**Returns:** [dojo/promise/Promise](promise) | undefined
Returns a new promise for the result of the callback/errback.
###
`cancel``(reason,strict)`
Defined by [dojo/promise/Promise](promise)
Inform the deferred it may cancel its asynchronous operation.
Inform the deferred it may cancel its asynchronous operation. The deferred's (optional) canceler is invoked and the deferred will be left in a rejected state. Can affect other promises that originate with the same deferred.
| Parameter | Type | Description |
| --- | --- | --- |
| reason | any | A message that may be sent to the deferred's canceler, explaining why it's being canceled. |
| strict | Boolean | *Optional*
If strict, will throw an error if the deferred has already been fulfilled and consequently cannot be canceled. |
**Returns:** any
Returns the rejection reason if the deferred was canceled normally.
###
`isCanceled``()`
Defined by [dojo/promise/Promise](promise)
Checks whether the promise has been canceled.
**Returns:** Boolean
###
`isFulfilled``()`
Defined by [dojo/promise/Promise](promise)
Checks whether the promise has been resolved or rejected.
**Returns:** Boolean
###
`isRejected``()`
Defined by [dojo/promise/Promise](promise)
Checks whether the promise has been rejected.
**Returns:** Boolean
###
`isResolved``()`
Defined by [dojo/promise/Promise](promise)
Checks whether the promise has been resolved.
**Returns:** Boolean
###
`otherwise``(errback)`
Defined by [dojo/promise/Promise](promise)
Add new errbacks to the promise.
| Parameter | Type | Description |
| --- | --- | --- |
| errback | Function | *Optional*
Callback to be invoked when the promise is rejected. |
**Returns:** [dojo/promise/Promise](promise) | undefined
Returns a new promise for the result of the errback.
###
`then``(callback,errback,progback)`
Defined by [dojo/promise/Promise](promise)
Add new callbacks to the promise.
Add new callbacks to the deferred. Callbacks can be added before or after the deferred is fulfilled.
| Parameter | Type | Description |
| --- | --- | --- |
| callback | Function | *Optional*
Callback to be invoked when the promise is resolved. Receives the resolution value. |
| errback | Function | *Optional*
Callback to be invoked when the promise is rejected. Receives the rejection error. |
| progback | Function | *Optional*
Callback to be invoked when the promise emits a progress update. Receives the progress update. |
**Returns:** [dojo/promise/Promise](promise)
Returns a new promise for the result of the callback(s). This can be used for chaining many asynchronous operations.
###
`toString``()`
Defined by [dojo/promise/Promise](promise)
**Returns:** string
Returns `[object Promise]`.
###
`trace``()`
Defined by [dojo/promise/tracer](tracer)
Trace the promise.
Tracing allows you to transparently log progress, resolution and rejection of promises, without affecting the promise itself. Any arguments passed to `trace()` are emitted in trace events. See [dojo/promise/tracer](tracer) on how to handle traces.
**Returns:** [dojo/promise/Promise](promise)
The promise instance `trace()` is called on.
###
`traceRejected``()`
Defined by [dojo/promise/tracer](tracer)
Trace rejection of the promise.
Tracing allows you to transparently log progress, resolution and rejection of promises, without affecting the promise itself. Any arguments passed to `trace()` are emitted in trace events. See [dojo/promise/tracer](tracer) on how to handle traces.
**Returns:** [dojo/promise/Promise](promise)
The promise instance `traceRejected()` is called on.
dojo dojo/promise/instrumentation dojo/promise/instrumentation
============================
Summary
-------
Initialize instrumentation for the Deferred class.
Initialize instrumentation for the Deferred class. Done automatically by [dojo/Deferred](../deferred) if the `deferredInstrumentation` and `useDeferredInstrumentation` config options are set.
Sets up [dojo/promise/tracer](tracer) to log to the console.
Sets up instrumentation of rejected deferreds so unhandled errors are logged to the console.
Usage
-----
instrumentation`(Deferred);`
| Parameter | Type | Description |
| --- | --- | --- |
| Deferred | undefined | |
See the [dojo/promise/instrumentation reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/promise.html) for more information.
Methods
-------
dojo dojo/promise/first dojo/promise/first
==================
Summary
-------
Takes multiple promises and returns a new promise that is fulfilled when the first of these promises is fulfilled.
Takes multiple promises and returns a new promise that is fulfilled when the first of these promises is fulfilled. Canceling the returned promise will *not* cancel any passed promises. The promise will be fulfilled with the value of the first fulfilled promise.
Usage
-----
first`(objectOrArray);`
| Parameter | Type | Description |
| --- | --- | --- |
| objectOrArray | Object | Array | *Optional*
The promises are taken from the array or object values. If no value is passed, the returned promise is resolved with an undefined value. |
**Returns:** [dojo/promise/Promise](promise)
See the [dojo/promise/first reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/promise/first.html) for more information.
Methods
-------
dojo dojo/errors/RequestError dojo/errors/RequestError
========================
Summary
-------
TODOC
Usage
-----
RequestError`();` Methods
-------
dojo dojo/errors/RequestTimeoutError dojo/errors/RequestTimeoutError
===============================
Summary
-------
TODOC
Usage
-----
RequestTimeoutError`();` Methods
-------
dojo dojo/errors/create dojo/errors/create
==================
Usage
-----
create`(name,ctor,base,props);`
| Parameter | Type | Description |
| --- | --- | --- |
| name | undefined | |
| ctor | undefined | |
| base | undefined | |
| props | undefined | |
**Returns:** function
Methods
-------
dojo dojo/errors/CancelError dojo/errors/CancelError
=======================
Summary
-------
Default error if a promise is canceled without a reason.
Usage
-----
CancelError`();` See the [dojo/errors/CancelError reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/errors/CancelError.html) for more information.
Methods
-------
dojo dojo/rpc/JsonpService dojo/rpc/JsonpService
=====================
Extends[dojo/rpc/RpcService](rpcservice) Summary
-------
Generic JSONP service. Minimally extends RpcService to allow easy definition of nearly any JSONP style service. Example SMD files exist in dojox.data
Usage
-----
var foo = new JsonpService`(args,requiredArgs);` Defined by [dojo/rpc/JsonpService](jsonpservice)
| Parameter | Type | Description |
| --- | --- | --- |
| args | undefined | |
| requiredArgs | undefined | |
See the [dojo/rpc/JsonpService reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/rpc/JsonpService.html) for more information.
Properties
----------
### serviceUrl
Defined by: [dojo/rpc/RpcService](rpcservice)
### strictArgChecks
Defined by: [dojo/rpc/JsonpService](jsonpservice)
Methods
-------
###
`bind``(method,parameters,deferredRequestHandler,url)`
Defined by [dojo/rpc/JsonpService](jsonpservice)
JSONP bind method. Takes remote method, parameters, deferred, and a url, calls createRequest to make a JSON-RPC envelope and passes that off with bind.
| Parameter | Type | Description |
| --- | --- | --- |
| method | string | The name of the method we are calling |
| parameters | [dojo/\_base/array](../_base/array) | The parameters we are passing off to the method |
| deferredRequestHandler | deferred | The Deferred object for this particular request |
| url | undefined | |
###
`createRequest``(parameters)`
Defined by [dojo/rpc/JsonpService](jsonpservice)
create a JSONP req
| Parameter | Type | Description |
| --- | --- | --- |
| parameters | undefined | |
**Returns:** object
###
`errorCallback``(deferredRequestHandler)`
Defined by [dojo/rpc/RpcService](rpcservice)
create callback that calls the Deferred errback method
| Parameter | Type | Description |
| --- | --- | --- |
| deferredRequestHandler | [dojo/\_base/Deferred](../_base/deferred) | The deferred object handling a request. |
**Returns:** function
###
`generateMethod``(method,parameters,url)`
Defined by [dojo/rpc/RpcService](rpcservice)
generate the local bind methods for the remote object
| Parameter | Type | Description |
| --- | --- | --- |
| method | string | The name of the method we are generating |
| parameters | [dojo/\_base/array](../_base/array) | the array of parameters for this call. |
| url | string | the service url for this call |
**Returns:** undefined
###
`parseResults``(obj)`
Defined by [dojo/rpc/RpcService](rpcservice)
parse the results coming back from an rpc request. this base implementation, just returns the full object subclasses should parse and only return the actual results
| Parameter | Type | Description |
| --- | --- | --- |
| obj | Object | Object that is the return results from an rpc request |
**Returns:** Object
Object that is the return results from an rpc request
###
`processSmd``(object)`
Defined by [dojo/rpc/RpcService](rpcservice)
callback method for receipt of a smd object. Parse the smd and generate functions based on the description
| Parameter | Type | Description |
| --- | --- | --- |
| object | undefined | smd object defining this service. |
###
`resultCallback``(deferredRequestHandler)`
Defined by [dojo/rpc/RpcService](rpcservice)
create callback that calls the Deferred's callback method
| Parameter | Type | Description |
| --- | --- | --- |
| deferredRequestHandler | [dojo/\_base/Deferred](../_base/deferred) | The deferred object handling a request. |
**Returns:** undefined
dojo dojo/rpc/JsonService dojo/rpc/JsonService
====================
Extends[dojo/rpc/RpcService](rpcservice) Summary
-------
TODOC
Usage
-----
var foo = new JsonService`(args);` Defined by [dojo/rpc/RpcService](rpcservice)
| Parameter | Type | Description |
| --- | --- | --- |
| args | object | Takes a number of properties as kwArgs for defining the service. It also accepts a string. When passed a string, it is treated as a url from which it should synchronously retrieve an smd file. Otherwise it is a kwArgs object. It accepts serviceUrl, to manually define a url for the rpc service allowing the rpc system to be used without an smd definition. strictArgChecks forces the system to verify that the # of arguments provided in a call matches those defined in the smd. smdString allows a developer to pass a jsonString directly, which will be converted into an object or alternatively smdObject is accepts an smdObject directly. |
See the [dojo/rpc/JsonService reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/rpc/JsonService.html) for more information.
Properties
----------
### bustCache
Defined by: [dojo/rpc/JsonService](jsonservice)
### contentType
Defined by: [dojo/rpc/JsonService](jsonservice)
### lastSubmissionId
Defined by: [dojo/rpc/JsonService](jsonservice)
### serviceUrl
Defined by: [dojo/rpc/RpcService](rpcservice)
### strictArgChecks
Defined by: [dojo/rpc/RpcService](rpcservice)
Methods
-------
###
`bind``(method,parameters,deferredRequestHandler,url)`
Defined by [dojo/rpc/JsonService](jsonservice)
JSON-RPC bind method. Takes remote method, parameters, deferred, and a url, calls createRequest to make a JSON-RPC envelope and passes that off with bind.
| Parameter | Type | Description |
| --- | --- | --- |
| method | string | The name of the method we are calling |
| parameters | array | The parameters we are passing off to the method |
| deferredRequestHandler | deferred | The Deferred object for this particular request |
| url | undefined | |
###
`callRemote``(method,params)`
Defined by [dojo/rpc/JsonService](jsonservice)
call an arbitrary remote method without requiring it to be predefined with SMD
| Parameter | Type | Description |
| --- | --- | --- |
| method | string | the name of the remote method you want to call. |
| params | array | array of parameters to pass to method |
**Returns:** instance
###
`createRequest``(method,params)`
Defined by [dojo/rpc/JsonService](jsonservice)
create a JSON-RPC envelope for the request
| Parameter | Type | Description |
| --- | --- | --- |
| method | string | The name of the method we are creating the request for |
| params | [dojo/\_base/array](../_base/array) | The array of parameters for this request; |
**Returns:** undefined
###
`errorCallback``(deferredRequestHandler)`
Defined by [dojo/rpc/RpcService](rpcservice)
create callback that calls the Deferred errback method
| Parameter | Type | Description |
| --- | --- | --- |
| deferredRequestHandler | [dojo/\_base/Deferred](../_base/deferred) | The deferred object handling a request. |
**Returns:** function
###
`generateMethod``(method,parameters,url)`
Defined by [dojo/rpc/RpcService](rpcservice)
generate the local bind methods for the remote object
| Parameter | Type | Description |
| --- | --- | --- |
| method | string | The name of the method we are generating |
| parameters | [dojo/\_base/array](../_base/array) | the array of parameters for this call. |
| url | string | the service url for this call |
**Returns:** undefined
###
`parseResults``(obj)`
Defined by [dojo/rpc/JsonService](jsonservice)
parse the result envelope and pass the results back to the callback function
| Parameter | Type | Description |
| --- | --- | --- |
| obj | Object | Object containing envelope of data we receive from the server |
**Returns:** undefined | Object
Object containing envelope of data we receive from the server
###
`processSmd``(object)`
Defined by [dojo/rpc/RpcService](rpcservice)
callback method for receipt of a smd object. Parse the smd and generate functions based on the description
| Parameter | Type | Description |
| --- | --- | --- |
| object | undefined | smd object defining this service. |
###
`resultCallback``(deferredRequestHandler)`
Defined by [dojo/rpc/RpcService](rpcservice)
create callback that calls the Deferred's callback method
| Parameter | Type | Description |
| --- | --- | --- |
| deferredRequestHandler | [dojo/\_base/Deferred](../_base/deferred) | The deferred object handling a request. |
**Returns:** undefined
dojo dojo/rpc/RpcService dojo/rpc/RpcService
===================
Summary
-------
TODOC
Usage
-----
var foo = new RpcService`(args);` Defined by [dojo/rpc/RpcService](rpcservice)
| Parameter | Type | Description |
| --- | --- | --- |
| args | object | Takes a number of properties as kwArgs for defining the service. It also accepts a string. When passed a string, it is treated as a url from which it should synchronously retrieve an smd file. Otherwise it is a kwArgs object. It accepts serviceUrl, to manually define a url for the rpc service allowing the rpc system to be used without an smd definition. strictArgChecks forces the system to verify that the # of arguments provided in a call matches those defined in the smd. smdString allows a developer to pass a jsonString directly, which will be converted into an object or alternatively smdObject is accepts an smdObject directly. |
See the [dojo/rpc/RpcService reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/rpc/RpcService.html) for more information.
Properties
----------
### serviceUrl
Defined by: [dojo/rpc/RpcService](rpcservice)
### strictArgChecks
Defined by: [dojo/rpc/RpcService](rpcservice)
Methods
-------
###
`errorCallback``(deferredRequestHandler)`
Defined by [dojo/rpc/RpcService](rpcservice)
create callback that calls the Deferred errback method
| Parameter | Type | Description |
| --- | --- | --- |
| deferredRequestHandler | [dojo/\_base/Deferred](../_base/deferred) | The deferred object handling a request. |
**Returns:** function
###
`generateMethod``(method,parameters,url)`
Defined by [dojo/rpc/RpcService](rpcservice)
generate the local bind methods for the remote object
| Parameter | Type | Description |
| --- | --- | --- |
| method | string | The name of the method we are generating |
| parameters | [dojo/\_base/array](../_base/array) | the array of parameters for this call. |
| url | string | the service url for this call |
**Returns:** undefined
###
`parseResults``(obj)`
Defined by [dojo/rpc/RpcService](rpcservice)
parse the results coming back from an rpc request. this base implementation, just returns the full object subclasses should parse and only return the actual results
| Parameter | Type | Description |
| --- | --- | --- |
| obj | Object | Object that is the return results from an rpc request |
**Returns:** Object
Object that is the return results from an rpc request
###
`processSmd``(object)`
Defined by [dojo/rpc/RpcService](rpcservice)
callback method for receipt of a smd object. Parse the smd and generate functions based on the description
| Parameter | Type | Description |
| --- | --- | --- |
| object | undefined | smd object defining this service. |
###
`resultCallback``(deferredRequestHandler)`
Defined by [dojo/rpc/RpcService](rpcservice)
create callback that calls the Deferred's callback method
| Parameter | Type | Description |
| --- | --- | --- |
| deferredRequestHandler | [dojo/\_base/Deferred](../_base/deferred) | The deferred object handling a request. |
**Returns:** undefined
| programming_docs |
dojo dojo/on/asyncEventListener dojo/on/asyncEventListener
==========================
Usage
-----
asyncEventListener`(listener);`
| Parameter | Type | Description |
| --- | --- | --- |
| listener | undefined | |
See the [dojo/on/asyncEventListener reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/on.html) for more information.
Methods
-------
dojo dojo/on/debounce dojo/on/debounce
================
Summary
-------
event parser for custom events
Usage
-----
debounce`(selector,delay);`
| Parameter | Type | Description |
| --- | --- | --- |
| selector | String | The selector to check against |
| delay | Interger | The amount of ms before testing the selector |
See the [dojo/on/debounce reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/on.html) for more information.
Methods
-------
dojo dojo/on/throttle dojo/on/throttle
================
Summary
-------
event parser for custom events
Usage
-----
throttle`(selector,delay);`
| Parameter | Type | Description |
| --- | --- | --- |
| selector | String | The selector to check against |
| delay | Interger | The amount of ms before testing the selector |
See the [dojo/on/throttle reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/on.html) for more information.
Methods
-------
dojo dojo/data/ItemFileReadStore dojo/data/ItemFileReadStore
===========================
Extends[dojo/Evented](../evented) Summary
-------
The ItemFileReadStore implements the [dojo/data/api/Read](api/read) API and reads data from JSON files that have contents in this format --
```
{ items: [
{ name:'Kermit', color:'green', age:12, friends:['Gonzo', {_reference:{name:'Fozzie Bear'}}]},
{ name:'Fozzie Bear', wears:['hat', 'tie']},
{ name:'Miss Piggy', pets:'Foo-Foo'}
]}
```
Note that it can also contain an 'identifier' property that specified which attribute on the items
in the array of items that acts as the unique identifier for that item.
Usage
-----
var foo = new ItemFileReadStore`(keywordParameters);` Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
| Parameter | Type | Description |
| --- | --- | --- |
| keywordParameters | Object | {url: String} {data: jsonObject} {typeMap: object} The structure of the typeMap object is as follows:
```
{
type0: function || object,
type1: function || object,
...
typeN: function || object
}
```
Where if it is a function, it is assumed to be an object constructor that takes the value of \_value as the initialization parameters. If it is an object, then it is assumed to be an object of general form:
```
{
type: function, //constructor.
deserialize: function(value) //The function that parses the value and constructs the object defined by type appropriately.
}
```
|
See the [dojo/data/ItemFileReadStore reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/data/ItemFileReadStore.html) for more information.
Properties
----------
### clearOnClose
Defined by: [dojo/data/ItemFileReadStore](itemfilereadstore)
Parameter to allow users to specify if a close call should force a reload or not. By default, it retains the old behavior of not clearing if close is called. But if set true, the store will be reset to default state. Note that by doing this, all item handles will become invalid and a new fetch must be issued.
### data
Defined by: [dojo/data/ItemFileReadStore](itemfilereadstore)
### failOk
Defined by: [dojo/data/ItemFileReadStore](itemfilereadstore)
Parameter for specifying that it is OK for the xhrGet call to fail silently.
### hierarchical
Defined by: [dojo/data/ItemFileReadStore](itemfilereadstore)
Parameter to indicate to process data from the url as hierarchical (data items can contain other data items in js form). Default is true for backwards compatibility. False means only root items are processed as items, all child objects outside of type-mapped objects and those in specific reference format, are left straight JS data objects.
### typeMap
Defined by: [dojo/data/ItemFileReadStore](itemfilereadstore)
### url
Defined by: [dojo/data/ItemFileReadStore](itemfilereadstore)
### urlPreventCache
Defined by: [dojo/data/ItemFileReadStore](itemfilereadstore)
Parameter to allow specifying if preventCache should be passed to the xhrGet call or not when loading data from a url. Note this does not mean the store calls the server on each fetch, only that the data load has preventCache set as an option. Added for tracker: #6072
Methods
-------
###
`close``(request)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.close()
| Parameter | Type | Description |
| --- | --- | --- |
| request | [dojo/data/api/Request](api/request) | Object | *Optional* |
###
`containsValue``(item,attribute,value)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.containsValue()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
| attribute | attribute-name-string | |
| value | anything | |
**Returns:** undefined
###
`emit``(type,event)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| event | undefined | |
**Returns:** undefined
###
`errorHandler``(errorData,requestObject)`
Defined by [dojo/data/util/simpleFetch](util/simplefetch)
The error handler when there is an error fetching items. This function should not be called directly and is used by simpleFetch.fetch().
| Parameter | Type | Description |
| --- | --- | --- |
| errorData | Object | |
| requestObject | Object | |
###
`fetch``(request)`
Defined by [dojo/data/util/simpleFetch](util/simplefetch)
The simpleFetch mixin is designed to serve as a set of function(s) that can be mixed into other datastore implementations to accelerate their development.
The simpleFetch mixin should work well for any datastore that can respond to a \_fetchItems() call by returning an array of all the found items that matched the query. The simpleFetch mixin is not designed to work for datastores that respond to a fetch() call by incrementally loading items, or sequentially loading partial batches of the result set. For datastores that mixin simpleFetch, simpleFetch implements a fetch method that automatically handles eight of the fetch() arguments -- onBegin, onItem, onComplete, onError, start, count, sort and scope The class mixing in simpleFetch should not implement fetch(), but should instead implement a \_fetchItems() method. The \_fetchItems() method takes three arguments, the keywordArgs object that was passed to fetch(), a callback function to be called when the result array is available, and an error callback to be called if something goes wrong. The \_fetchItems() method should ignore any keywordArgs parameters for start, count, onBegin, onItem, onComplete, onError, sort, and scope. The \_fetchItems() method needs to correctly handle any other keywordArgs parameters, including the query parameter and any optional parameters (such as includeChildren). The \_fetchItems() method should create an array of result items and pass it to the fetchHandler along with the original request object -- or, the \_fetchItems() method may, if it wants to, create an new request object with other specifics about the request that are specific to the datastore and pass that as the request object to the handler.
For more information on this specific function, see [dojo/data/api/Read.fetch()](api/read#fetch)
| Parameter | Type | Description |
| --- | --- | --- |
| request | Object | *Optional*
The keywordArgs parameter may either be an instance of conforming to dojo/data/api/Request or may be a simple anonymous object that may contain any of the following:
```
{
query: query-object or query-string,
queryOptions: object,
onBegin: Function,
onItem: Function,
onComplete: Function,
onError: Function,
scope: object,
start: int
count: int
sort: array
}
```
All implementations should accept keywordArgs objects with any of the 9 standard properties: query, onBegin, onItem, onComplete, onError scope, sort, start, and count. Some implementations may accept additional properties in the keywordArgs object as valid parameters, such as {includeOutliers:true}. The *query* parameter The query may be optional in some data store implementations. The dojo/data/api/Read API does not specify the syntax or semantics of the query itself -- each different data store implementation may have its own notion of what a query should look like. However, as of dojo 0.9, 1.0, and 1.1, all the provided datastores in dojo.data and dojox.data support an object structure query, where the object is a set of name/value parameters such as { attrFoo: valueBar, attrFoo1: valueBar1}. Most of the dijit widgets, such as ComboBox assume this to be the case when working with a datastore when they dynamically update the query. Therefore, for maximum compatibility with dijit widgets the recommended query parameter is a key/value object. That does not mean that the the datastore may not take alternative query forms, such as a simple string, a Date, a number, or a mix of such. Ultimately, The dojo/data/api/Read API is agnostic about what the query format. Further note: In general for query objects that accept strings as attribute value matches, the store should also support basic filtering capability, such as *(match any character) and ? (match single character). An example query that is a query object would be like: { attrFoo: "value*"}. Which generally means match all items where they have an attribute named attrFoo, with a value that starts with 'value'. The *queryOptions* parameter The queryOptions parameter is an optional parameter used to specify options that may modify the query in some fashion, such as doing a case insensitive search, or doing a deep search where all items in a hierarchical representation of data are scanned instead of just the root items. It currently defines two options that all datastores should attempt to honor if possible:
```
{
ignoreCase: boolean, // Whether or not the query should match case sensitively or not. Default behaviour is false.
deep: boolean // Whether or not a fetch should do a deep search of items and all child
// items instead of just root-level items in a datastore. Default is false.
}
```
The *onBegin* parameter. function(size, request); If an onBegin callback function is provided, the callback function will be called just once, before the first onItem callback is called. The onBegin callback function will be passed two arguments, the the total number of items identified and the Request object. If the total number is unknown, then size will be -1. Note that size is not necessarily the size of the collection of items returned from the query, as the request may have specified to return only a subset of the total set of items through the use of the start and count parameters. The *onItem* parameter. function(item, request); If an onItem callback function is provided, the callback function will be called as each item in the result is received. The callback function will be passed two arguments: the item itself, and the Request object. The *onComplete* parameter. function(items, request); If an onComplete callback function is provided, the callback function will be called just once, after the last onItem callback is called. Note that if the onItem callback is not present, then onComplete will be passed an array containing all items which matched the query and the request object. If the onItem callback is present, then onComplete is called as: onComplete(null, request). The *onError* parameter. function(errorData, request); If an onError callback function is provided, the callback function will be called if there is any sort of error while attempting to execute the query. The onError callback function will be passed two arguments: an Error object and the Request object. The *scope* parameter. If a scope object is provided, all of the callback functions (onItem, onComplete, onError, etc) will be invoked in the context of the scope object. In the body of the callback function, the value of the "this" keyword will be the scope object. If no scope object is provided, the callback functions will be called in the context of dojo.global(). For example, onItem.call(scope, item, request) vs. onItem.call(dojo.global(), item, request) The *start* parameter. If a start parameter is specified, this is a indication to the datastore to only start returning items once the start number of items have been located and skipped. When this parameter is paired with 'count', the store should be able to page across queries with millions of hits by only returning subsets of the hits for each query The *count* parameter. If a count parameter is specified, this is a indication to the datastore to only return up to that many items. This allows a fetch call that may have millions of item matches to be paired down to something reasonable. The *sort* parameter. If a sort parameter is specified, this is a indication to the datastore to sort the items in some manner before returning the items. The array is an array of javascript objects that must conform to the following format to be applied to the fetching of items:
```
{
attribute: attribute || attribute-name-string,
descending: true|false; // Optional. Default is false.
}
```
Note that when comparing attributes, if an item contains no value for the attribute (undefined), then it the default ascending sort logic should push it to the bottom of the list. In the descending order case, it such items should appear at the top of the list. |
###
`fetchHandler``(items,requestObject)`
Defined by [dojo/data/util/simpleFetch](util/simplefetch)
The handler when items are successfully fetched. This function should not be called directly and is used by simpleFetch.fetch().
| Parameter | Type | Description |
| --- | --- | --- |
| items | Array | |
| requestObject | Object | |
###
`fetchItemByIdentity``(keywordArgs)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Identity.fetchItemByIdentity()
| Parameter | Type | Description |
| --- | --- | --- |
| keywordArgs | Object | |
###
`filter``(requestArgs,arrayOfItems,findCallback)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
This method handles the basic filtering needs for ItemFile\* based stores.
| Parameter | Type | Description |
| --- | --- | --- |
| requestArgs | Object | |
| arrayOfItems | item[] | |
| findCallback | Function | |
###
`getAttributes``(item)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.getAttributes()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
**Returns:** Array
###
`getFeatures``()`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.getFeatures()
**Returns:** undefined
###
`getIdentity``(item)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Identity.getIdentity()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
**Returns:** undefined | null
###
`getIdentityAttributes``(item)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Identity.getIdentityAttributes()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
**Returns:** null | Array
###
`getLabel``(item)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.getLabel()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
**Returns:** undefined | number
###
`getLabelAttributes``(item)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.getLabelAttributes()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
**Returns:** Array | null
###
`getValue``(item,attribute,defaultValue)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.getValue()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
| attribute | attribute-name-string | |
| defaultValue | value | *Optional* |
**Returns:** value
###
`getValues``(item,attribute)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.getValues()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
| attribute | attribute-name-string | |
**Returns:** undefined
###
`hasAttribute``(item,attribute)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.hasAttribute()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
| attribute | attribute-name-string | |
**Returns:** boolean
###
`isItem``(something)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.isItem()
| Parameter | Type | Description |
| --- | --- | --- |
| something | anything | |
**Returns:** boolean
###
`isItemLoaded``(something)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.isItemLoaded()
| Parameter | Type | Description |
| --- | --- | --- |
| something | anything | |
**Returns:** undefined
###
`loadItem``(keywordArgs)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.loadItem()
| Parameter | Type | Description |
| --- | --- | --- |
| keywordArgs | object | |
###
`on``(type,listener)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| listener | undefined | |
**Returns:** undefined
dojo dojo/data/ObjectStore dojo/data/ObjectStore
=====================
Extends[dojo/Evented](../evented) Summary
-------
A Dojo Data implementation that wraps Dojo object stores for backwards compatibility.
Usage
-----
var foo = new ObjectStore`(options);` Defined by [dojo/data/ObjectStore](objectstore)
| Parameter | Type | Description |
| --- | --- | --- |
| options | undefined | The configuration information to pass into the data store. * options.objectStore:
The object store to use as the source provider for this data store |
See the [dojo/data/ObjectStore reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/data/ObjectStore.html) for more information.
Properties
----------
### labelProperty
Defined by: [dojo/data/ObjectStore](objectstore)
### objectStore
Defined by: [dojo/data/ObjectStore](objectstore)
Methods
-------
###
`changing``(object,_deleting)`
Defined by [dojo/data/ObjectStore](objectstore)
adds an object to the list of dirty objects. This object contains a reference to the object itself as well as a cloned and trimmed version of old object for use with revert.
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | Indicates that the given object is changing and should be marked as dirty for the next save |
| \_deleting | Boolean | |
###
`close``(request)`
Defined by [dojo/data/ObjectStore](objectstore)
See dojo/data/api/Read.close()
| Parameter | Type | Description |
| --- | --- | --- |
| request | undefined | |
**Returns:** undefined
###
`containsValue``(item,attribute,value)`
Defined by [dojo/data/ObjectStore](objectstore)
Checks to see if 'item' has 'value' at 'attribute'
| Parameter | Type | Description |
| --- | --- | --- |
| item | Object | The item to check |
| attribute | String | The attribute to check |
| value | Anything | The value to look for |
**Returns:** boolean
###
`deleteItem``(item)`
Defined by [dojo/data/ObjectStore](objectstore)
deletes item and any references to that item from the store.
| Parameter | Type | Description |
| --- | --- | --- |
| item | undefined | item to delete |
###
`emit``(type,event)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| event | undefined | |
**Returns:** undefined
###
`fetch``(args)`
Defined by [dojo/data/ObjectStore](objectstore)
See dojo/data/api/Read.fetch()
| Parameter | Type | Description |
| --- | --- | --- |
| args | undefined | |
**Returns:** undefined
###
`fetchItemByIdentity``(args)`
Defined by [dojo/data/ObjectStore](objectstore)
fetch an item by its identity, by looking in our index of what we have loaded
| Parameter | Type | Description |
| --- | --- | --- |
| args | undefined | |
**Returns:** undefined
###
`getAttributes``(item)`
Defined by [dojo/data/ObjectStore](objectstore)
Gets the available attributes of an item's 'property' and returns it as an array.
| Parameter | Type | Description |
| --- | --- | --- |
| item | Object | |
**Returns:** Array
###
`getFeatures``()`
Defined by [dojo/data/ObjectStore](objectstore)
return the store feature set
**Returns:** object
###
`getIdentity``(item)`
Defined by [dojo/data/ObjectStore](objectstore)
returns the identity of the given item See dojo/data/api/Read.getIdentity()
| Parameter | Type | Description |
| --- | --- | --- |
| item | undefined | |
**Returns:** undefined
###
`getIdentityAttributes``(item)`
Defined by [dojo/data/ObjectStore](objectstore)
returns the attributes which are used to make up the identity of an item. Basically returns this.objectStore.idProperty See dojo/data/api/Read.getIdentityAttributes()
| Parameter | Type | Description |
| --- | --- | --- |
| item | undefined | |
**Returns:** Array
###
`getLabel``(item)`
Defined by [dojo/data/ObjectStore](objectstore)
See dojo/data/api/Read.getLabel()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
**Returns:** undefined
###
`getLabelAttributes``(item)`
Defined by [dojo/data/ObjectStore](objectstore)
See dojo/data/api/Read.getLabelAttributes()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
**Returns:** Array
###
`getValue``(item,property,defaultValue)`
Defined by [dojo/data/ObjectStore](objectstore)
Gets the value of an item's 'property'
| Parameter | Type | Description |
| --- | --- | --- |
| item | Object | The item to get the value from |
| property | String | property to look up value for |
| defaultValue | value | *Optional*
the default value |
**Returns:** value
the default value
###
`getValues``(item,property)`
Defined by [dojo/data/ObjectStore](objectstore)
Gets the value of an item's 'property' and returns it. If this value is an array it is just returned, if not, the value is added to an array and that is returned.
| Parameter | Type | Description |
| --- | --- | --- |
| item | Object | |
| property | String | property to look up value for |
**Returns:** Array
###
`hasAttribute``(item,attribute)`
Defined by [dojo/data/ObjectStore](objectstore)
Checks to see if item has attribute
| Parameter | Type | Description |
| --- | --- | --- |
| item | Object | The item to check |
| attribute | String | The attribute to check |
**Returns:** boolean
###
`isDirty``(item)`
Defined by [dojo/data/ObjectStore](objectstore)
returns true if the item is marked as dirty or true if there are any dirty items
| Parameter | Type | Description |
| --- | --- | --- |
| item | Object | The item to check |
**Returns:** boolean | undefined
###
`isItem``(item)`
Defined by [dojo/data/ObjectStore](objectstore)
Checks to see if the argument is an item
| Parameter | Type | Description |
| --- | --- | --- |
| item | Object | The item to check |
**Returns:** boolean
###
`isItemLoaded``(item)`
Defined by [dojo/data/ObjectStore](objectstore)
Checks to see if the item is loaded.
| Parameter | Type | Description |
| --- | --- | --- |
| item | Object | The item to check |
**Returns:** undefined
###
`loadItem``(args)`
Defined by [dojo/data/ObjectStore](objectstore)
Loads an item and calls the callback handler. Note, that this will call the callback handler even if the item is loaded. Consequently, you can use loadItem to ensure that an item is loaded is situations when the item may or may not be loaded yet. If you access a value directly through property access, you can use this to load a lazy value as well (doesn't need to be an item).
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | See dojo/data/api/Read.fetch() |
**Returns:** undefined
Examples
--------
### Example 1
```
store.loadItem({
item: item, // this item may or may not be loaded
onItem: function(item){
// do something with the item
}
});
```
###
`newItem``(data,parentInfo)`
Defined by [dojo/data/ObjectStore](objectstore)
adds a new item to the store at the specified point. Takes two parameters, data, and options.
| Parameter | Type | Description |
| --- | --- | --- |
| data | Object | See dojo/data/api/Write.newItem() |
| parentInfo | undefined | |
**Returns:** Object
See dojo/data/api/Write.newItem()
###
`on``(type,listener)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| listener | undefined | |
**Returns:** undefined
###
`revert``()`
Defined by [dojo/data/ObjectStore](objectstore)
returns any modified data to its original state prior to a save();
###
`save``(kwArgs)`
Defined by [dojo/data/ObjectStore](objectstore)
Saves the dirty data using object store provider. See dojo/data/api/Write for API.
| Parameter | Type | Description |
| --- | --- | --- |
| kwArgs | undefined | * kwArgs.global: This will cause the save to commit the dirty data for all ObjectStores as a single transaction.
* kwArgs.revertOnError: This will cause the changes to be reverted if there is an error on the save. By default a revert is executed unless a value of false is provide for this parameter.
* kwArgs.onError: Called when an error occurs in the commit
* kwArgs.onComplete: Called when an the save/commit is completed
|
###
`setValue``(item,attribute,value)`
Defined by [dojo/data/ObjectStore](objectstore)
sets 'attribute' on 'item' to 'value' See dojo/data/api/Write.setValue()
| Parameter | Type | Description |
| --- | --- | --- |
| item | undefined | |
| attribute | undefined | |
| value | undefined | |
###
`setValues``(item,attribute,values)`
Defined by [dojo/data/ObjectStore](objectstore)
sets 'attribute' on 'item' to 'value' value must be an array. See dojo/data/api/Write.setValues()
| Parameter | Type | Description |
| --- | --- | --- |
| item | undefined | |
| attribute | undefined | |
| values | undefined | |
###
`unsetAttribute``(item,attribute)`
Defined by [dojo/data/ObjectStore](objectstore)
unsets 'attribute' on 'item' See dojo/data/api/Write.unsetAttribute()
| Parameter | Type | Description |
| --- | --- | --- |
| item | undefined | |
| attribute | undefined | |
Events
------
###
`onDelete``()`
Defined by: [dojo/data/ObjectStore](objectstore)
See [dojo/data/api/Notification.onDelete()](api/notification#onDelete)
Examples
--------
### Example 1
```
store.loadItem({
item: item, // this item may or may not be loaded
onItem: function(item){
// do something with the item
}
});
```
###
`onFetch``(results)`
Defined by: [dojo/data/ObjectStore](objectstore)
Called when a fetch occurs
| Parameter | Type | Description |
| --- | --- | --- |
| results | undefined | |
Examples
--------
### Example 1
```
store.loadItem({
item: item, // this item may or may not be loaded
onItem: function(item){
// do something with the item
}
});
```
###
`onNew``()`
Defined by: [dojo/data/ObjectStore](objectstore)
See [dojo/data/api/Notification.onNew()](api/notification#onNew)
Examples
--------
### Example 1
```
store.loadItem({
item: item, // this item may or may not be loaded
onItem: function(item){
// do something with the item
}
});
```
###
`onSet``()`
Defined by: [dojo/data/ObjectStore](objectstore)
See [dojo/data/api/Notification.onSet()](api/notification#onSet)
Examples
--------
### Example 1
```
store.loadItem({
item: item, // this item may or may not be loaded
onItem: function(item){
// do something with the item
}
});
```
| programming_docs |
dojo dojo/data/ItemFileWriteStore dojo/data/ItemFileWriteStore
============================
Extends[dojo/data/ItemFileReadStore](itemfilereadstore) Summary
-------
TODOC
Usage
-----
var foo = new ItemFileWriteStore`(keywordParameters);` Defined by [dojo/data/ItemFileWriteStore](itemfilewritestore)
| Parameter | Type | Description |
| --- | --- | --- |
| keywordParameters | object | The structure of the typeMap object is as follows:
```
{
type0: function || object,
type1: function || object,
...
typeN: function || object
}
```
Where if it is a function, it is assumed to be an object constructor that takes the value of \_value as the initialization parameters. It is serialized assuming object.toString() serialization. If it is an object, then it is assumed to be an object of general form:
```
{
type: function, //constructor.
deserialize: function(value) //The function that parses the value and constructs the object defined by type appropriately.
serialize: function(object) //The function that converts the object back into the proper file format form.
}
```
|
See the [dojo/data/ItemFileWriteStore reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/data/ItemFileWriteStore.html) for more information.
Properties
----------
### clearOnClose
Defined by: [dojo/data/ItemFileReadStore](itemfilereadstore)
Parameter to allow users to specify if a close call should force a reload or not. By default, it retains the old behavior of not clearing if close is called. But if set true, the store will be reset to default state. Note that by doing this, all item handles will become invalid and a new fetch must be issued.
### data
Defined by: [dojo/data/ItemFileReadStore](itemfilereadstore)
### failOk
Defined by: [dojo/data/ItemFileReadStore](itemfilereadstore)
Parameter for specifying that it is OK for the xhrGet call to fail silently.
### hierarchical
Defined by: [dojo/data/ItemFileReadStore](itemfilereadstore)
Parameter to indicate to process data from the url as hierarchical (data items can contain other data items in js form). Default is true for backwards compatibility. False means only root items are processed as items, all child objects outside of type-mapped objects and those in specific reference format, are left straight JS data objects.
### referenceIntegrity
Defined by: [dojo/data/ItemFileWriteStore](itemfilewritestore)
### typeMap
Defined by: [dojo/data/ItemFileReadStore](itemfilereadstore)
### url
Defined by: [dojo/data/ItemFileReadStore](itemfilereadstore)
### urlPreventCache
Defined by: [dojo/data/ItemFileReadStore](itemfilereadstore)
Parameter to allow specifying if preventCache should be passed to the xhrGet call or not when loading data from a url. Note this does not mean the store calls the server on each fetch, only that the data load has preventCache set as an option. Added for tracker: #6072
Methods
-------
###
`close``(request)`
Defined by [dojo/data/ItemFileWriteStore](itemfilewritestore)
Over-ride of base close function of ItemFileReadStore to add in check for store state.
Over-ride of base close function of ItemFileReadStore to add in check for store state. If the store is still dirty (unsaved changes), then an error will be thrown instead of clearing the internal state for reload from the url.
| Parameter | Type | Description |
| --- | --- | --- |
| request | object | *Optional* |
###
`containsValue``(item,attribute,value)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.containsValue()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
| attribute | attribute-name-string | |
| value | anything | |
**Returns:** undefined
###
`deleteItem``(item)`
Defined by [dojo/data/ItemFileWriteStore](itemfilewritestore)
See dojo/data/api/Write.deleteItem()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
**Returns:** boolean
###
`emit``(type,event)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| event | undefined | |
**Returns:** undefined
###
`errorHandler``(errorData,requestObject)`
Defined by [dojo/data/util/simpleFetch](util/simplefetch)
The error handler when there is an error fetching items. This function should not be called directly and is used by simpleFetch.fetch().
| Parameter | Type | Description |
| --- | --- | --- |
| errorData | Object | |
| requestObject | Object | |
###
`fetch``(request)`
Defined by [dojo/data/util/simpleFetch](util/simplefetch)
The simpleFetch mixin is designed to serve as a set of function(s) that can be mixed into other datastore implementations to accelerate their development.
The simpleFetch mixin should work well for any datastore that can respond to a \_fetchItems() call by returning an array of all the found items that matched the query. The simpleFetch mixin is not designed to work for datastores that respond to a fetch() call by incrementally loading items, or sequentially loading partial batches of the result set. For datastores that mixin simpleFetch, simpleFetch implements a fetch method that automatically handles eight of the fetch() arguments -- onBegin, onItem, onComplete, onError, start, count, sort and scope The class mixing in simpleFetch should not implement fetch(), but should instead implement a \_fetchItems() method. The \_fetchItems() method takes three arguments, the keywordArgs object that was passed to fetch(), a callback function to be called when the result array is available, and an error callback to be called if something goes wrong. The \_fetchItems() method should ignore any keywordArgs parameters for start, count, onBegin, onItem, onComplete, onError, sort, and scope. The \_fetchItems() method needs to correctly handle any other keywordArgs parameters, including the query parameter and any optional parameters (such as includeChildren). The \_fetchItems() method should create an array of result items and pass it to the fetchHandler along with the original request object -- or, the \_fetchItems() method may, if it wants to, create an new request object with other specifics about the request that are specific to the datastore and pass that as the request object to the handler.
For more information on this specific function, see [dojo/data/api/Read.fetch()](api/read#fetch)
| Parameter | Type | Description |
| --- | --- | --- |
| request | Object | *Optional*
The keywordArgs parameter may either be an instance of conforming to dojo/data/api/Request or may be a simple anonymous object that may contain any of the following:
```
{
query: query-object or query-string,
queryOptions: object,
onBegin: Function,
onItem: Function,
onComplete: Function,
onError: Function,
scope: object,
start: int
count: int
sort: array
}
```
All implementations should accept keywordArgs objects with any of the 9 standard properties: query, onBegin, onItem, onComplete, onError scope, sort, start, and count. Some implementations may accept additional properties in the keywordArgs object as valid parameters, such as {includeOutliers:true}. The *query* parameter The query may be optional in some data store implementations. The dojo/data/api/Read API does not specify the syntax or semantics of the query itself -- each different data store implementation may have its own notion of what a query should look like. However, as of dojo 0.9, 1.0, and 1.1, all the provided datastores in dojo.data and dojox.data support an object structure query, where the object is a set of name/value parameters such as { attrFoo: valueBar, attrFoo1: valueBar1}. Most of the dijit widgets, such as ComboBox assume this to be the case when working with a datastore when they dynamically update the query. Therefore, for maximum compatibility with dijit widgets the recommended query parameter is a key/value object. That does not mean that the the datastore may not take alternative query forms, such as a simple string, a Date, a number, or a mix of such. Ultimately, The dojo/data/api/Read API is agnostic about what the query format. Further note: In general for query objects that accept strings as attribute value matches, the store should also support basic filtering capability, such as *(match any character) and ? (match single character). An example query that is a query object would be like: { attrFoo: "value*"}. Which generally means match all items where they have an attribute named attrFoo, with a value that starts with 'value'. The *queryOptions* parameter The queryOptions parameter is an optional parameter used to specify options that may modify the query in some fashion, such as doing a case insensitive search, or doing a deep search where all items in a hierarchical representation of data are scanned instead of just the root items. It currently defines two options that all datastores should attempt to honor if possible:
```
{
ignoreCase: boolean, // Whether or not the query should match case sensitively or not. Default behaviour is false.
deep: boolean // Whether or not a fetch should do a deep search of items and all child
// items instead of just root-level items in a datastore. Default is false.
}
```
The *onBegin* parameter. function(size, request); If an onBegin callback function is provided, the callback function will be called just once, before the first onItem callback is called. The onBegin callback function will be passed two arguments, the the total number of items identified and the Request object. If the total number is unknown, then size will be -1. Note that size is not necessarily the size of the collection of items returned from the query, as the request may have specified to return only a subset of the total set of items through the use of the start and count parameters. The *onItem* parameter. function(item, request); If an onItem callback function is provided, the callback function will be called as each item in the result is received. The callback function will be passed two arguments: the item itself, and the Request object. The *onComplete* parameter. function(items, request); If an onComplete callback function is provided, the callback function will be called just once, after the last onItem callback is called. Note that if the onItem callback is not present, then onComplete will be passed an array containing all items which matched the query and the request object. If the onItem callback is present, then onComplete is called as: onComplete(null, request). The *onError* parameter. function(errorData, request); If an onError callback function is provided, the callback function will be called if there is any sort of error while attempting to execute the query. The onError callback function will be passed two arguments: an Error object and the Request object. The *scope* parameter. If a scope object is provided, all of the callback functions (onItem, onComplete, onError, etc) will be invoked in the context of the scope object. In the body of the callback function, the value of the "this" keyword will be the scope object. If no scope object is provided, the callback functions will be called in the context of dojo.global(). For example, onItem.call(scope, item, request) vs. onItem.call(dojo.global(), item, request) The *start* parameter. If a start parameter is specified, this is a indication to the datastore to only start returning items once the start number of items have been located and skipped. When this parameter is paired with 'count', the store should be able to page across queries with millions of hits by only returning subsets of the hits for each query The *count* parameter. If a count parameter is specified, this is a indication to the datastore to only return up to that many items. This allows a fetch call that may have millions of item matches to be paired down to something reasonable. The *sort* parameter. If a sort parameter is specified, this is a indication to the datastore to sort the items in some manner before returning the items. The array is an array of javascript objects that must conform to the following format to be applied to the fetching of items:
```
{
attribute: attribute || attribute-name-string,
descending: true|false; // Optional. Default is false.
}
```
Note that when comparing attributes, if an item contains no value for the attribute (undefined), then it the default ascending sort logic should push it to the bottom of the list. In the descending order case, it such items should appear at the top of the list. |
###
`fetchHandler``(items,requestObject)`
Defined by [dojo/data/util/simpleFetch](util/simplefetch)
The handler when items are successfully fetched. This function should not be called directly and is used by simpleFetch.fetch().
| Parameter | Type | Description |
| --- | --- | --- |
| items | Array | |
| requestObject | Object | |
###
`fetchItemByIdentity``(keywordArgs)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Identity.fetchItemByIdentity()
| Parameter | Type | Description |
| --- | --- | --- |
| keywordArgs | Object | |
###
`filter``(requestArgs,arrayOfItems,findCallback)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
This method handles the basic filtering needs for ItemFile\* based stores.
| Parameter | Type | Description |
| --- | --- | --- |
| requestArgs | Object | |
| arrayOfItems | item[] | |
| findCallback | Function | |
###
`getAttributes``(item)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.getAttributes()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
**Returns:** Array
###
`getFeatures``()`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.getFeatures()
**Returns:** undefined
###
`getIdentity``(item)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Identity.getIdentity()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
**Returns:** undefined | null
###
`getIdentityAttributes``(item)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Identity.getIdentityAttributes()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
**Returns:** null | Array
###
`getLabel``(item)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.getLabel()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
**Returns:** undefined | number
###
`getLabelAttributes``(item)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.getLabelAttributes()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
**Returns:** Array | null
###
`getValue``(item,attribute,defaultValue)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.getValue()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
| attribute | attribute-name-string | |
| defaultValue | value | *Optional* |
**Returns:** value
###
`getValues``(item,attribute)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.getValues()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
| attribute | attribute-name-string | |
**Returns:** undefined
###
`hasAttribute``(item,attribute)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.hasAttribute()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
| attribute | attribute-name-string | |
**Returns:** boolean
###
`isDirty``(item)`
Defined by [dojo/data/ItemFileWriteStore](itemfilewritestore)
See dojo/data/api/Write.isDirty()
| Parameter | Type | Description |
| --- | --- | --- |
| item | item | *Optional* |
**Returns:** undefined | boolean
###
`isItem``(something)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.isItem()
| Parameter | Type | Description |
| --- | --- | --- |
| something | anything | |
**Returns:** boolean
###
`isItemLoaded``(something)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.isItemLoaded()
| Parameter | Type | Description |
| --- | --- | --- |
| something | anything | |
**Returns:** undefined
###
`loadItem``(keywordArgs)`
Defined by [dojo/data/ItemFileReadStore](itemfilereadstore)
See dojo/data/api/Read.loadItem()
| Parameter | Type | Description |
| --- | --- | --- |
| keywordArgs | object | |
###
`newItem``(keywordArgs,parentInfo)`
Defined by [dojo/data/ItemFileWriteStore](itemfilewritestore)
See dojo/data/api/Write.newItem()
| Parameter | Type | Description |
| --- | --- | --- |
| keywordArgs | Object | *Optional* |
| parentInfo | Object | *Optional* |
**Returns:** object
###
`on``(type,listener)`
Defined by [dojo/Evented](../evented)
| Parameter | Type | Description |
| --- | --- | --- |
| type | undefined | |
| listener | undefined | |
**Returns:** undefined
###
`revert``()`
Defined by [dojo/data/ItemFileWriteStore](itemfilewritestore)
See dojo/data/api/Write.revert()
**Returns:** boolean
###
`save``(keywordArgs)`
Defined by [dojo/data/ItemFileWriteStore](itemfilewritestore)
See dojo/data/api/Write.save()
| Parameter | Type | Description |
| --- | --- | --- |
| keywordArgs | object | |
###
`setValue``(item,attribute,value)`
Defined by [dojo/data/ItemFileWriteStore](itemfilewritestore)
See dojo/data/api/Write.set()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
| attribute | attribute-name-string | |
| value | almost anything | |
**Returns:** undefined
###
`setValues``(item,attribute,values)`
Defined by [dojo/data/ItemFileWriteStore](itemfilewritestore)
See dojo/data/api/Write.setValues()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
| attribute | attribute-name-string | |
| values | array | |
**Returns:** undefined
###
`unsetAttribute``(item,attribute)`
Defined by [dojo/data/ItemFileWriteStore](itemfilewritestore)
See dojo/data/api/Write.unsetAttribute()
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
| attribute | attribute-name-string | |
**Returns:** undefined
Events
------
###
`onDelete``(deletedItem)`
Defined by: [dojo/data/ItemFileWriteStore](itemfilewritestore)
See [dojo/data/api/Notification.onDelete()](api/notification#onDelete)
| Parameter | Type | Description |
| --- | --- | --- |
| deletedItem | [dojo/data/api/Item](api/item) | |
###
`onNew``(newItem,parentInfo)`
Defined by: [dojo/data/ItemFileWriteStore](itemfilewritestore)
See [dojo/data/api/Notification.onNew()](api/notification#onNew)
| Parameter | Type | Description |
| --- | --- | --- |
| newItem | [dojo/data/api/Item](api/item) | |
| parentInfo | object | *Optional* |
###
`onSet``(item,attribute,oldValue,newValue)`
Defined by: [dojo/data/ItemFileWriteStore](itemfilewritestore)
See [dojo/data/api/Notification.onSet()](api/notification#onSet)
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](api/item) | |
| attribute | attribute-name-string | |
| oldValue | object | array | |
| newValue | object | array | |
| programming_docs |
dojo dojo/data/util/simpleFetch dojo/data/util/simpleFetch
==========================
Methods
-------
###
`errorHandler``(errorData,requestObject)`
Defined by [dojo/data/util/simpleFetch](simplefetch)
The error handler when there is an error fetching items. This function should not be called directly and is used by simpleFetch.fetch().
| Parameter | Type | Description |
| --- | --- | --- |
| errorData | Object | |
| requestObject | Object | |
###
`fetch``(request)`
Defined by [dojo/data/util/simpleFetch](simplefetch)
The simpleFetch mixin is designed to serve as a set of function(s) that can be mixed into other datastore implementations to accelerate their development.
The simpleFetch mixin should work well for any datastore that can respond to a \_fetchItems() call by returning an array of all the found items that matched the query. The simpleFetch mixin is not designed to work for datastores that respond to a fetch() call by incrementally loading items, or sequentially loading partial batches of the result set. For datastores that mixin simpleFetch, simpleFetch implements a fetch method that automatically handles eight of the fetch() arguments -- onBegin, onItem, onComplete, onError, start, count, sort and scope The class mixing in simpleFetch should not implement fetch(), but should instead implement a \_fetchItems() method. The \_fetchItems() method takes three arguments, the keywordArgs object that was passed to fetch(), a callback function to be called when the result array is available, and an error callback to be called if something goes wrong. The \_fetchItems() method should ignore any keywordArgs parameters for start, count, onBegin, onItem, onComplete, onError, sort, and scope. The \_fetchItems() method needs to correctly handle any other keywordArgs parameters, including the query parameter and any optional parameters (such as includeChildren). The \_fetchItems() method should create an array of result items and pass it to the fetchHandler along with the original request object -- or, the \_fetchItems() method may, if it wants to, create an new request object with other specifics about the request that are specific to the datastore and pass that as the request object to the handler.
For more information on this specific function, see [dojo/data/api/Read.fetch()](../api/read#fetch)
| Parameter | Type | Description |
| --- | --- | --- |
| request | Object | *Optional*
The keywordArgs parameter may either be an instance of conforming to dojo/data/api/Request or may be a simple anonymous object that may contain any of the following:
```
{
query: query-object or query-string,
queryOptions: object,
onBegin: Function,
onItem: Function,
onComplete: Function,
onError: Function,
scope: object,
start: int
count: int
sort: array
}
```
All implementations should accept keywordArgs objects with any of the 9 standard properties: query, onBegin, onItem, onComplete, onError scope, sort, start, and count. Some implementations may accept additional properties in the keywordArgs object as valid parameters, such as {includeOutliers:true}. The *query* parameter The query may be optional in some data store implementations. The dojo/data/api/Read API does not specify the syntax or semantics of the query itself -- each different data store implementation may have its own notion of what a query should look like. However, as of dojo 0.9, 1.0, and 1.1, all the provided datastores in dojo.data and dojox.data support an object structure query, where the object is a set of name/value parameters such as { attrFoo: valueBar, attrFoo1: valueBar1}. Most of the dijit widgets, such as ComboBox assume this to be the case when working with a datastore when they dynamically update the query. Therefore, for maximum compatibility with dijit widgets the recommended query parameter is a key/value object. That does not mean that the the datastore may not take alternative query forms, such as a simple string, a Date, a number, or a mix of such. Ultimately, The dojo/data/api/Read API is agnostic about what the query format. Further note: In general for query objects that accept strings as attribute value matches, the store should also support basic filtering capability, such as *(match any character) and ? (match single character). An example query that is a query object would be like: { attrFoo: "value*"}. Which generally means match all items where they have an attribute named attrFoo, with a value that starts with 'value'. The *queryOptions* parameter The queryOptions parameter is an optional parameter used to specify options that may modify the query in some fashion, such as doing a case insensitive search, or doing a deep search where all items in a hierarchical representation of data are scanned instead of just the root items. It currently defines two options that all datastores should attempt to honor if possible:
```
{
ignoreCase: boolean, // Whether or not the query should match case sensitively or not. Default behaviour is false.
deep: boolean // Whether or not a fetch should do a deep search of items and all child
// items instead of just root-level items in a datastore. Default is false.
}
```
The *onBegin* parameter. function(size, request); If an onBegin callback function is provided, the callback function will be called just once, before the first onItem callback is called. The onBegin callback function will be passed two arguments, the the total number of items identified and the Request object. If the total number is unknown, then size will be -1. Note that size is not necessarily the size of the collection of items returned from the query, as the request may have specified to return only a subset of the total set of items through the use of the start and count parameters. The *onItem* parameter. function(item, request); If an onItem callback function is provided, the callback function will be called as each item in the result is received. The callback function will be passed two arguments: the item itself, and the Request object. The *onComplete* parameter. function(items, request); If an onComplete callback function is provided, the callback function will be called just once, after the last onItem callback is called. Note that if the onItem callback is not present, then onComplete will be passed an array containing all items which matched the query and the request object. If the onItem callback is present, then onComplete is called as: onComplete(null, request). The *onError* parameter. function(errorData, request); If an onError callback function is provided, the callback function will be called if there is any sort of error while attempting to execute the query. The onError callback function will be passed two arguments: an Error object and the Request object. The *scope* parameter. If a scope object is provided, all of the callback functions (onItem, onComplete, onError, etc) will be invoked in the context of the scope object. In the body of the callback function, the value of the "this" keyword will be the scope object. If no scope object is provided, the callback functions will be called in the context of dojo.global(). For example, onItem.call(scope, item, request) vs. onItem.call(dojo.global(), item, request) The *start* parameter. If a start parameter is specified, this is a indication to the datastore to only start returning items once the start number of items have been located and skipped. When this parameter is paired with 'count', the store should be able to page across queries with millions of hits by only returning subsets of the hits for each query The *count* parameter. If a count parameter is specified, this is a indication to the datastore to only return up to that many items. This allows a fetch call that may have millions of item matches to be paired down to something reasonable. The *sort* parameter. If a sort parameter is specified, this is a indication to the datastore to sort the items in some manner before returning the items. The array is an array of javascript objects that must conform to the following format to be applied to the fetching of items:
```
{
attribute: attribute || attribute-name-string,
descending: true|false; // Optional. Default is false.
}
```
Note that when comparing attributes, if an item contains no value for the attribute (undefined), then it the default ascending sort logic should push it to the bottom of the list. In the descending order case, it such items should appear at the top of the list. |
###
`fetchHandler``(items,requestObject)`
Defined by [dojo/data/util/simpleFetch](simplefetch)
The handler when items are successfully fetched. This function should not be called directly and is used by simpleFetch.fetch().
| Parameter | Type | Description |
| --- | --- | --- |
| items | Array | |
| requestObject | Object | |
dojo dojo/data/util/sorter dojo/data/util/sorter
=====================
Methods
-------
###
`basicComparator``(a,b)`
Defined by [dojo/data/util/sorter](sorter)
Basic comparison function that compares if an item is greater or less than another item
returns 1 if a > b, -1 if a < b, 0 if equal. 'null' values (null, undefined) are treated as larger values so that they're pushed to the end of the list. And compared to each other, null is equivalent to undefined.
| Parameter | Type | Description |
| --- | --- | --- |
| a | anything | |
| b | anything | |
**Returns:** number
###
`createSortFunction``(sortSpec,store)`
Defined by [dojo/data/util/sorter](sorter)
Helper function to generate the sorting function based off the list of sort attributes.
The sort function creation will look for a property on the store called 'comparatorMap'. If it exists it will look in the mapping for comparisons function for the attributes. If one is found, it will use it instead of the basic comparator, which is typically used for strings, ints, booleans, and dates. Returns the sorting function for this particular list of attributes and sorting directions.
| Parameter | Type | Description |
| --- | --- | --- |
| sortSpec | attributes[] | A JS object that array that defines out what attribute names to sort on and whether it should be descenting or asending. The objects should be formatted as follows:
```
{
attribute: "attributeName-string" || attribute,
descending: true|false; // Default is false.
}
```
|
| store | [dojo/data/api/Read](../api/read) | The datastore object to look up item values from. |
**Returns:** Return an array of property names
dojo dojo/data/util/filter dojo/data/util/filter
=====================
Methods
-------
###
`patternToRegExp``(pattern,ignoreCase)`
Defined by [dojo/data/util/filter](filter)
Helper function to convert a simple pattern to a regular expression for matching.
Returns a regular expression object that conforms to the defined conversion rules. For example:
* ca *-> /^ca.*$/
* *ca* -> /^.*ca.*$/
* *c\*a *-> /^.*c\*a.\*$/
* *c\*a? *-> /^.*c\*a..\*$/
and so on.
| Parameter | Type | Description |
| --- | --- | --- |
| pattern | string | A simple matching pattern to convert that follows basic rules: * + Means match anything, so ca\* means match anything starting with ca
* ? Means match single character. So, b?b will match to bob and bab, and so on.
* \ is an escape character. So for example, \* means do not treat *as a match, but literal character* .
To use a \ as a character in the string, it must be escaped. So in the pattern it should be represented by \ to be treated as an ordinary \ character instead of an escape. |
| ignoreCase | boolean | *Optional*
An optional flag to indicate if the pattern matching should be treated as case-sensitive or not when comparing By default, it is assumed case sensitive. |
**Returns:** instance
dojo dojo/data/api/Read dojo/data/api/Read
==================
Summary
-------
This is an abstract API that data provider implementations conform to. This file defines methods signatures and intentionally leaves all the methods unimplemented. For more information on the dojo.data APIs, please visit: <http://www.dojotoolkit.org/node/98>
See the [dojo/data/api/Read reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/data/api/Read.html) for more information.
Methods
-------
###
`close``(request)`
Defined by [dojo/data/api/Read](read)
The close() method is intended for instructing the store to 'close' out any information associated with a particular request.
The close() method is intended for instructing the store to 'close' out any information associated with a particular request. In general, this API expects to receive as a parameter a request object returned from a fetch. It will then close out anything associated with that request, such as clearing any internal datastore caches and closing any 'open' connections. For some store implementations, this call may be a no-op.
| Parameter | Type | Description |
| --- | --- | --- |
| request | [dojo/data/api/Request](request) | Object | *Optional*
An instance of a request for the store to use to identify what to close out. If no request is passed, then the store should clear all internal caches (if any) and close out all 'open' connections. It does not render the store unusable from there on, it merely cleans out any current data and resets the store to initial state. |
Examples
--------
### Example 1
```
var request = store.fetch({onComplete: doSomething});
...
store.close(request);
```
###
`containsValue``(item,attribute,value)`
Defined by [dojo/data/api/Read](read)
Returns true if the given *value* is one of the values that getValues() would return.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access values on. |
| attribute | attribute-name-string | The attribute to access represented as a string. |
| value | anything | The value to match as a value for the attribute. |
Examples
--------
### Example 1
```
var trueOrFalse = store.containsValue(kermit, "color", "green");
```
###
`fetch``(keywordArgs)`
Defined by [dojo/data/api/Read](read)
Given a query and set of defined options, such as a start and count of items to return, this method executes the query and makes the results available as data items. The format and expectations of stores is that they operate in a generally asynchronous manner, therefore callbacks are always used to return items located by the fetch parameters.
A Request object will always be returned and is returned immediately. The basic request is nothing more than the keyword args passed to fetch and an additional function attached, abort(). The returned request object may then be used to cancel a fetch. All data items returns are passed through the callbacks defined in the fetch parameters and are not present on the 'request' object.
This does not mean that custom stores can not add methods and properties to the request object returned, only that the API does not require it. For more info about the Request API, see [dojo/data/api/Request](request)
| Parameter | Type | Description |
| --- | --- | --- |
| keywordArgs | Object | The keywordArgs parameter may either be an instance of conforming to dojo/data/api/Request or may be a simple anonymous object that may contain any of the following:
```
{
query: query-object or query-string,
queryOptions: object,
onBegin: Function,
onItem: Function,
onComplete: Function,
onError: Function,
scope: object,
start: int
count: int
sort: array
}
```
All implementations should accept keywordArgs objects with any of the 9 standard properties: query, onBegin, onItem, onComplete, onError scope, sort, start, and count. Some implementations may accept additional properties in the keywordArgs object as valid parameters, such as {includeOutliers:true}. The *query* parameter The query may be optional in some data store implementations. The dojo/data/api/Read API does not specify the syntax or semantics of the query itself -- each different data store implementation may have its own notion of what a query should look like. However, as of dojo 0.9, 1.0, and 1.1, all the provided datastores in dojo.data and dojox.data support an object structure query, where the object is a set of name/value parameters such as { attrFoo: valueBar, attrFoo1: valueBar1}. Most of the dijit widgets, such as ComboBox assume this to be the case when working with a datastore when they dynamically update the query. Therefore, for maximum compatibility with dijit widgets the recommended query parameter is a key/value object. That does not mean that the the datastore may not take alternative query forms, such as a simple string, a Date, a number, or a mix of such. Ultimately, The dojo/data/api/Read API is agnostic about what the query format. Further note: In general for query objects that accept strings as attribute value matches, the store should also support basic filtering capability, such as *(match any character) and ? (match single character). An example query that is a query object would be like: { attrFoo: "value*"}. Which generally means match all items where they have an attribute named attrFoo, with a value that starts with 'value'. The *queryOptions* parameter The queryOptions parameter is an optional parameter used to specify options that may modify the query in some fashion, such as doing a case insensitive search, or doing a deep search where all items in a hierarchical representation of data are scanned instead of just the root items. It currently defines two options that all datastores should attempt to honor if possible:
```
{
ignoreCase: boolean, // Whether or not the query should match case sensitively or not. Default behaviour is false.
deep: boolean // Whether or not a fetch should do a deep search of items and all child
// items instead of just root-level items in a datastore. Default is false.
}
```
The *onBegin* parameter. function(size, request); If an onBegin callback function is provided, the callback function will be called just once, before the first onItem callback is called. The onBegin callback function will be passed two arguments, the the total number of items identified and the Request object. If the total number is unknown, then size will be -1. Note that size is not necessarily the size of the collection of items returned from the query, as the request may have specified to return only a subset of the total set of items through the use of the start and count parameters. The *onItem* parameter. function(item, request); If an onItem callback function is provided, the callback function will be called as each item in the result is received. The callback function will be passed two arguments: the item itself, and the Request object. The *onComplete* parameter. function(items, request); If an onComplete callback function is provided, the callback function will be called just once, after the last onItem callback is called. Note that if the onItem callback is not present, then onComplete will be passed an array containing all items which matched the query and the request object. If the onItem callback is present, then onComplete is called as: onComplete(null, request). The *onError* parameter. function(errorData, request); If an onError callback function is provided, the callback function will be called if there is any sort of error while attempting to execute the query. The onError callback function will be passed two arguments: an Error object and the Request object. The *scope* parameter. If a scope object is provided, all of the callback functions (onItem, onComplete, onError, etc) will be invoked in the context of the scope object. In the body of the callback function, the value of the "this" keyword will be the scope object. If no scope object is provided, the callback functions will be called in the context of dojo.global(). For example, onItem.call(scope, item, request) vs. onItem.call(dojo.global(), item, request) The *start* parameter. If a start parameter is specified, this is a indication to the datastore to only start returning items once the start number of items have been located and skipped. When this parameter is paired with 'count', the store should be able to page across queries with millions of hits by only returning subsets of the hits for each query The *count* parameter. If a count parameter is specified, this is a indication to the datastore to only return up to that many items. This allows a fetch call that may have millions of item matches to be paired down to something reasonable. The *sort* parameter. If a sort parameter is specified, this is a indication to the datastore to sort the items in some manner before returning the items. The array is an array of javascript objects that must conform to the following format to be applied to the fetching of items:
```
{
attribute: attribute || attribute-name-string,
descending: true|false; // Optional. Default is false.
}
```
Note that when comparing attributes, if an item contains no value for the attribute (undefined), then it the default ascending sort logic should push it to the bottom of the list. In the descending order case, it such items should appear at the top of the list. |
**Returns:** any
The fetch() method will return a javascript object conforming to the API defined in dojo/data/api/Request. In general, it will be the keywordArgs object returned with the required functions in Request.js attached. Its general purpose is to provide a convenient way for a caller to abort an ongoing fetch.
The Request object may also have additional properties when it is returned such as request.store property, which is a pointer to the datastore object that fetch() is a method of.
Examples
--------
### Example 1
Fetch all books identified by the query and call 'showBooks' when complete
```
var request = store.fetch({query:"all books", onComplete: showBooks});
```
### Example 2
Fetch all items in the story and call 'showEverything' when complete.
```
var request = store.fetch(onComplete: showEverything);
```
### Example 3
Fetch only 10 books that match the query 'all books', starting at the fifth book found during the search. This demonstrates how paging can be done for specific queries.
```
var request = store.fetch({query:"all books", start: 4, count: 10, onComplete: showBooks});
```
### Example 4
Fetch all items that match the query, calling 'callback' each time an item is located.
```
var request = store.fetch({query:"foo/bar", onItem:callback});
```
### Example 5
Fetch the first 100 books by author King, call showKing when up to 100 items have been located.
```
var request = store.fetch({query:{author:"King"}, start: 0, count:100, onComplete: showKing});
```
### Example 6
Locate the books written by Author King, sort it on title and publisher, then return the first 100 items from the sorted items.
```
var request = store.fetch({query:{author:"King"}, sort: [{ attribute: "title", descending: true}, {attribute: "publisher"}], ,start: 0, count:100, onComplete: 'showKing'});
```
### Example 7
Fetch the first 100 books by authors starting with the name King, then call showKing when up to 100 items have been located.
```
var request = store.fetch({query:{author:"King*"}, start: 0, count:100, onComplete: showKing});
```
### Example 8
Fetch the first 100 books by authors ending with 'ing', but only have one character before it (King, Bing, Ling, Sing, etc.), then call showBooks when up to 100 items have been located.
```
var request = store.fetch({query:{author:"?ing"}, start: 0, count:100, onComplete: showBooks});
```
### Example 9
Fetch the first 100 books by author King, where the name may appear as King, king, KING, kInG, and so on, then call showKing when up to 100 items have been located.
```
var request = store.fetch({query:{author:"King"}, queryOptions:(ignoreCase: true}, start: 0, count:100, onComplete: showKing});
```
### Example 10
Paging
```
var store = new LargeRdbmsStore({url:"jdbc:odbc:foobar"});
var fetchArgs = {
query: {type:"employees", name:"Hillary *"}, // string matching
sort: [{attribute:"department", descending:true}],
start: 0,
count: 20,
scope: displayer,
onBegin: showThrobber,
onItem: displayItem,
onComplete: stopThrobber,
onError: handleFetchError,
};
store.fetch(fetchArgs);
...
```
and then when the user presses the "Next Page" button...
```
fetchArgs.start += 20;
store.fetch(fetchArgs); // get the next 20 items
```
###
`getAttributes``(item)`
Defined by [dojo/data/api/Read](read)
Returns an array with all the attributes that this item has. This method will always return an array; if the item has no attributes at all, getAttributes() will return an empty array: [].
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access attributes on. |
Examples
--------
### Example 1
```
var array = store.getAttributes(kermit);
```
###
`getFeatures``()`
Defined by [dojo/data/api/Read](read)
The getFeatures() method returns an simple keyword values object that specifies what interface features the datastore implements. A simple CsvStore may be read-only, and the only feature it implements will be the 'dojo/data/api/Read' interface, so the getFeatures() method will return an object like this one: {'dojo.data.api.Read': true}. A more sophisticated datastore might implement a variety of interface features, like 'dojo.data.api.Read', 'dojo/data/api/Write', 'dojo.data.api.Identity', and 'dojo/data/api/Attribution'.
**Returns:** object
###
`getLabel``(item)`
Defined by [dojo/data/api/Read](read)
Method to inspect the item and return a user-readable 'label' for the item that provides a general/adequate description of what the item is.
Method to inspect the item and return a user-readable 'label' for the item that provides a general/adequate description of what the item is. In general most labels will be a specific attribute value or collection of the attribute values that combine to label the item in some manner. For example for an item that represents a person it may return the label as: "firstname lastlame" where the firstname and lastname are attributes on the item. If the store is unable to determine an adequate human readable label, it should return undefined. Users that wish to customize how a store instance labels items should replace the getLabel() function on their instance of the store, or extend the store and replace the function in the extension class.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to return the label for. |
**Returns:** any
A user-readable string representing the item or undefined if no user-readable label can be generated.
###
`getLabelAttributes``(item)`
Defined by [dojo/data/api/Read](read)
Method to inspect the item and return an array of what attributes of the item were used to generate its label, if any.
Method to inspect the item and return an array of what attributes of the item were used to generate its label, if any. This function is to assist UI developers in knowing what attributes can be ignored out of the attributes an item has when displaying it, in cases where the UI is using the label as an overall identifer should they wish to hide redundant information.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to return the list of label attributes for. |
**Returns:** any
An array of attribute names that were used to generate the label, or null if public attributes were not used to generate the label.
###
`getValue``(item,attribute,defaultValue)`
Defined by [dojo/data/api/Read](read)
Returns a single attribute value. Returns defaultValue if and only if *item* does not have a value for *attribute*. Returns null if and only if null was explicitly set as the attribute value. Returns undefined if and only if the item does not have a value for the given attribute (which is the same as saying the item does not have the attribute).
Saying that an "item x does not have a value for an attribute y" is identical to saying that an "item x does not have attribute y". It is an oxymoron to say "that attribute is present but has no values" or "the item has that attribute but does not have any attribute values". If store.hasAttribute(item, attribute) returns false, then store.getValue(item, attribute) will return undefined.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access values on. |
| attribute | attribute-name-string | The attribute to access represented as a string. |
| defaultValue | value | *Optional*
Optional. A default value to use for the getValue return in the attribute does not exist or has no value. |
**Returns:** any
a literal, an item, null, or undefined (never an array)
Examples
--------
### Example 1
```
var darthVader = store.getValue(lukeSkywalker, "father");
```
###
`getValues``(item,attribute)`
Defined by [dojo/data/api/Read](read)
This getValues() method works just like the getValue() method, but getValues() always returns an array rather than a single attribute value. The array may be empty, may contain a single attribute value, or may contain many attribute values. If the item does not have a value for the given attribute, then getValues() will return an empty array: []. (So, if store.hasAttribute(item, attribute) has a return of false, then store.getValues(item, attribute) will return [].)
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access values on. |
| attribute | attribute-name-string | The attribute to access represented as a string. |
**Returns:** any
an array that may contain literals and items
Examples
--------
### Example 1
```
var friendsOfLuke = store.getValues(lukeSkywalker, "friends");
```
###
`hasAttribute``(item,attribute)`
Defined by [dojo/data/api/Read](read)
Returns true if the given *item* has a value for the given *attribute*.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access attributes on. |
| attribute | attribute-name-string | The attribute to access represented as a string. |
Examples
--------
### Example 1
```
var trueOrFalse = store.hasAttribute(kermit, "color");
```
###
`isItem``(something)`
Defined by [dojo/data/api/Read](read)
Returns true if *something* is an item and came from the store instance. Returns false if *something* is a literal, an item from another store instance, or is any object other than an item.
| Parameter | Type | Description |
| --- | --- | --- |
| something | anything | Can be anything. |
Examples
--------
### Example 1
```
var yes = store.isItem(store.newItem());
var no = store.isItem("green");
```
###
`isItemLoaded``(something)`
Defined by [dojo/data/api/Read](read)
Returns false if isItem(something) is false. Returns false if if isItem(something) is true but the the item is not yet loaded in local memory (for example, if the item has not yet been read from the server).
| Parameter | Type | Description |
| --- | --- | --- |
| something | anything | Can be anything. |
Examples
--------
### Example 1
```
var yes = store.isItemLoaded(store.newItem());
var no = store.isItemLoaded("green");
```
###
`loadItem``(keywordArgs)`
Defined by [dojo/data/api/Read](read)
Given an item, this method loads the item so that a subsequent call to store.isItemLoaded(item) will return true. If a call to isItemLoaded() returns true before loadItem() is even called, then loadItem() need not do any work at all and will not even invoke the callback handlers. So, before invoking this method, check that the item has not already been loaded.
| Parameter | Type | Description |
| --- | --- | --- |
| keywordArgs | Object | An anonymous object that defines the item to load and callbacks to invoke when the load has completed. The format of the object is as follows:
```
{
item: object,
onItem: Function,
onError: Function,
scope: object
}
```
The *item* parameter The item parameter is an object that represents the item in question that should be contained by the store. This attribute is required. The *onItem* parameter Function(item) The onItem parameter is the callback to invoke when the item has been loaded. It takes only one parameter, the fully loaded item. The *onError* parameter Function(error) The onError parameter is the callback to invoke when the item load encountered an error. It takes only one parameter, the error object The *scope* parameter If a scope object is provided, all of the callback functions (onItem, onError, etc) will be invoked in the context of the scope object. In the body of the callback function, the value of the "this" keyword will be the scope object. If no scope object is provided, the callback functions will be called in the context of dojo.global(). For example, onItem.call(scope, item, request) vs. onItem.call(dojo.global(), item, request) |
| programming_docs |
dojo dojo/data/api/Notification dojo/data/api/Notification
==========================
Extends[dojo/data/api/Read](read) Summary
-------
This is an abstract API that data provider implementations conform to. This file defines functions signatures and intentionally leaves all the functions unimplemented.
This API defines a set of APIs that all datastores that conform to the Notifications API must implement. In general, most stores will implement these APIs as no-op functions for users who wish to monitor them to be able to connect to then via dojo.connect(). For non-users of dojo.connect, they should be able to just replace the function on the store to obtain notifications. Both read-only and read-write stores may implement this feature. In the case of a read-only store, this feature makes sense if the store itself does internal polling to a back-end server and periodically updates its cache of items (deletes, adds, and updates).
See the [dojo/data/api/Notification reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/data/api/Notification.html) for more information.
Examples
--------
### Example 1
```
function onSet(item, attribute, oldValue, newValue){
//Do something with the information...
};
var store = new some.newStore();
dojo.connect(store, "onSet", onSet);
```
Methods
-------
###
`close``(request)`
Defined by [dojo/data/api/Read](read)
The close() method is intended for instructing the store to 'close' out any information associated with a particular request.
The close() method is intended for instructing the store to 'close' out any information associated with a particular request. In general, this API expects to receive as a parameter a request object returned from a fetch. It will then close out anything associated with that request, such as clearing any internal datastore caches and closing any 'open' connections. For some store implementations, this call may be a no-op.
| Parameter | Type | Description |
| --- | --- | --- |
| request | [dojo/data/api/Request](request) | Object | *Optional*
An instance of a request for the store to use to identify what to close out. If no request is passed, then the store should clear all internal caches (if any) and close out all 'open' connections. It does not render the store unusable from there on, it merely cleans out any current data and resets the store to initial state. |
Examples
--------
### Example 1
```
var request = store.fetch({onComplete: doSomething});
...
store.close(request);
```
###
`containsValue``(item,attribute,value)`
Defined by [dojo/data/api/Read](read)
Returns true if the given *value* is one of the values that getValues() would return.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access values on. |
| attribute | attribute-name-string | The attribute to access represented as a string. |
| value | anything | The value to match as a value for the attribute. |
Examples
--------
### Example 1
```
var trueOrFalse = store.containsValue(kermit, "color", "green");
```
###
`fetch``(keywordArgs)`
Defined by [dojo/data/api/Read](read)
Given a query and set of defined options, such as a start and count of items to return, this method executes the query and makes the results available as data items. The format and expectations of stores is that they operate in a generally asynchronous manner, therefore callbacks are always used to return items located by the fetch parameters.
A Request object will always be returned and is returned immediately. The basic request is nothing more than the keyword args passed to fetch and an additional function attached, abort(). The returned request object may then be used to cancel a fetch. All data items returns are passed through the callbacks defined in the fetch parameters and are not present on the 'request' object.
This does not mean that custom stores can not add methods and properties to the request object returned, only that the API does not require it. For more info about the Request API, see [dojo/data/api/Request](request)
| Parameter | Type | Description |
| --- | --- | --- |
| keywordArgs | Object | The keywordArgs parameter may either be an instance of conforming to dojo/data/api/Request or may be a simple anonymous object that may contain any of the following:
```
{
query: query-object or query-string,
queryOptions: object,
onBegin: Function,
onItem: Function,
onComplete: Function,
onError: Function,
scope: object,
start: int
count: int
sort: array
}
```
All implementations should accept keywordArgs objects with any of the 9 standard properties: query, onBegin, onItem, onComplete, onError scope, sort, start, and count. Some implementations may accept additional properties in the keywordArgs object as valid parameters, such as {includeOutliers:true}. The *query* parameter The query may be optional in some data store implementations. The dojo/data/api/Read API does not specify the syntax or semantics of the query itself -- each different data store implementation may have its own notion of what a query should look like. However, as of dojo 0.9, 1.0, and 1.1, all the provided datastores in dojo.data and dojox.data support an object structure query, where the object is a set of name/value parameters such as { attrFoo: valueBar, attrFoo1: valueBar1}. Most of the dijit widgets, such as ComboBox assume this to be the case when working with a datastore when they dynamically update the query. Therefore, for maximum compatibility with dijit widgets the recommended query parameter is a key/value object. That does not mean that the the datastore may not take alternative query forms, such as a simple string, a Date, a number, or a mix of such. Ultimately, The dojo/data/api/Read API is agnostic about what the query format. Further note: In general for query objects that accept strings as attribute value matches, the store should also support basic filtering capability, such as *(match any character) and ? (match single character). An example query that is a query object would be like: { attrFoo: "value*"}. Which generally means match all items where they have an attribute named attrFoo, with a value that starts with 'value'. The *queryOptions* parameter The queryOptions parameter is an optional parameter used to specify options that may modify the query in some fashion, such as doing a case insensitive search, or doing a deep search where all items in a hierarchical representation of data are scanned instead of just the root items. It currently defines two options that all datastores should attempt to honor if possible:
```
{
ignoreCase: boolean, // Whether or not the query should match case sensitively or not. Default behaviour is false.
deep: boolean // Whether or not a fetch should do a deep search of items and all child
// items instead of just root-level items in a datastore. Default is false.
}
```
The *onBegin* parameter. function(size, request); If an onBegin callback function is provided, the callback function will be called just once, before the first onItem callback is called. The onBegin callback function will be passed two arguments, the the total number of items identified and the Request object. If the total number is unknown, then size will be -1. Note that size is not necessarily the size of the collection of items returned from the query, as the request may have specified to return only a subset of the total set of items through the use of the start and count parameters. The *onItem* parameter. function(item, request); If an onItem callback function is provided, the callback function will be called as each item in the result is received. The callback function will be passed two arguments: the item itself, and the Request object. The *onComplete* parameter. function(items, request); If an onComplete callback function is provided, the callback function will be called just once, after the last onItem callback is called. Note that if the onItem callback is not present, then onComplete will be passed an array containing all items which matched the query and the request object. If the onItem callback is present, then onComplete is called as: onComplete(null, request). The *onError* parameter. function(errorData, request); If an onError callback function is provided, the callback function will be called if there is any sort of error while attempting to execute the query. The onError callback function will be passed two arguments: an Error object and the Request object. The *scope* parameter. If a scope object is provided, all of the callback functions (onItem, onComplete, onError, etc) will be invoked in the context of the scope object. In the body of the callback function, the value of the "this" keyword will be the scope object. If no scope object is provided, the callback functions will be called in the context of dojo.global(). For example, onItem.call(scope, item, request) vs. onItem.call(dojo.global(), item, request) The *start* parameter. If a start parameter is specified, this is a indication to the datastore to only start returning items once the start number of items have been located and skipped. When this parameter is paired with 'count', the store should be able to page across queries with millions of hits by only returning subsets of the hits for each query The *count* parameter. If a count parameter is specified, this is a indication to the datastore to only return up to that many items. This allows a fetch call that may have millions of item matches to be paired down to something reasonable. The *sort* parameter. If a sort parameter is specified, this is a indication to the datastore to sort the items in some manner before returning the items. The array is an array of javascript objects that must conform to the following format to be applied to the fetching of items:
```
{
attribute: attribute || attribute-name-string,
descending: true|false; // Optional. Default is false.
}
```
Note that when comparing attributes, if an item contains no value for the attribute (undefined), then it the default ascending sort logic should push it to the bottom of the list. In the descending order case, it such items should appear at the top of the list. |
**Returns:** any
The fetch() method will return a javascript object conforming to the API defined in dojo/data/api/Request. In general, it will be the keywordArgs object returned with the required functions in Request.js attached. Its general purpose is to provide a convenient way for a caller to abort an ongoing fetch.
The Request object may also have additional properties when it is returned such as request.store property, which is a pointer to the datastore object that fetch() is a method of.
Examples
--------
### Example 1
Fetch all books identified by the query and call 'showBooks' when complete
```
var request = store.fetch({query:"all books", onComplete: showBooks});
```
### Example 2
Fetch all items in the story and call 'showEverything' when complete.
```
var request = store.fetch(onComplete: showEverything);
```
### Example 3
Fetch only 10 books that match the query 'all books', starting at the fifth book found during the search. This demonstrates how paging can be done for specific queries.
```
var request = store.fetch({query:"all books", start: 4, count: 10, onComplete: showBooks});
```
### Example 4
Fetch all items that match the query, calling 'callback' each time an item is located.
```
var request = store.fetch({query:"foo/bar", onItem:callback});
```
### Example 5
Fetch the first 100 books by author King, call showKing when up to 100 items have been located.
```
var request = store.fetch({query:{author:"King"}, start: 0, count:100, onComplete: showKing});
```
### Example 6
Locate the books written by Author King, sort it on title and publisher, then return the first 100 items from the sorted items.
```
var request = store.fetch({query:{author:"King"}, sort: [{ attribute: "title", descending: true}, {attribute: "publisher"}], ,start: 0, count:100, onComplete: 'showKing'});
```
### Example 7
Fetch the first 100 books by authors starting with the name King, then call showKing when up to 100 items have been located.
```
var request = store.fetch({query:{author:"King*"}, start: 0, count:100, onComplete: showKing});
```
### Example 8
Fetch the first 100 books by authors ending with 'ing', but only have one character before it (King, Bing, Ling, Sing, etc.), then call showBooks when up to 100 items have been located.
```
var request = store.fetch({query:{author:"?ing"}, start: 0, count:100, onComplete: showBooks});
```
### Example 9
Fetch the first 100 books by author King, where the name may appear as King, king, KING, kInG, and so on, then call showKing when up to 100 items have been located.
```
var request = store.fetch({query:{author:"King"}, queryOptions:(ignoreCase: true}, start: 0, count:100, onComplete: showKing});
```
### Example 10
Paging
```
var store = new LargeRdbmsStore({url:"jdbc:odbc:foobar"});
var fetchArgs = {
query: {type:"employees", name:"Hillary *"}, // string matching
sort: [{attribute:"department", descending:true}],
start: 0,
count: 20,
scope: displayer,
onBegin: showThrobber,
onItem: displayItem,
onComplete: stopThrobber,
onError: handleFetchError,
};
store.fetch(fetchArgs);
...
```
and then when the user presses the "Next Page" button...
```
fetchArgs.start += 20;
store.fetch(fetchArgs); // get the next 20 items
```
###
`getAttributes``(item)`
Defined by [dojo/data/api/Read](read)
Returns an array with all the attributes that this item has. This method will always return an array; if the item has no attributes at all, getAttributes() will return an empty array: [].
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access attributes on. |
Examples
--------
### Example 1
```
var array = store.getAttributes(kermit);
```
###
`getFeatures``()`
Defined by [dojo/data/api/Notification](notification)
See dojo/data/api/Read.getFeatures()
**Returns:** object
###
`getLabel``(item)`
Defined by [dojo/data/api/Read](read)
Method to inspect the item and return a user-readable 'label' for the item that provides a general/adequate description of what the item is.
Method to inspect the item and return a user-readable 'label' for the item that provides a general/adequate description of what the item is. In general most labels will be a specific attribute value or collection of the attribute values that combine to label the item in some manner. For example for an item that represents a person it may return the label as: "firstname lastlame" where the firstname and lastname are attributes on the item. If the store is unable to determine an adequate human readable label, it should return undefined. Users that wish to customize how a store instance labels items should replace the getLabel() function on their instance of the store, or extend the store and replace the function in the extension class.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to return the label for. |
**Returns:** any
A user-readable string representing the item or undefined if no user-readable label can be generated.
###
`getLabelAttributes``(item)`
Defined by [dojo/data/api/Read](read)
Method to inspect the item and return an array of what attributes of the item were used to generate its label, if any.
Method to inspect the item and return an array of what attributes of the item were used to generate its label, if any. This function is to assist UI developers in knowing what attributes can be ignored out of the attributes an item has when displaying it, in cases where the UI is using the label as an overall identifer should they wish to hide redundant information.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to return the list of label attributes for. |
**Returns:** any
An array of attribute names that were used to generate the label, or null if public attributes were not used to generate the label.
###
`getValue``(item,attribute,defaultValue)`
Defined by [dojo/data/api/Read](read)
Returns a single attribute value. Returns defaultValue if and only if *item* does not have a value for *attribute*. Returns null if and only if null was explicitly set as the attribute value. Returns undefined if and only if the item does not have a value for the given attribute (which is the same as saying the item does not have the attribute).
Saying that an "item x does not have a value for an attribute y" is identical to saying that an "item x does not have attribute y". It is an oxymoron to say "that attribute is present but has no values" or "the item has that attribute but does not have any attribute values". If store.hasAttribute(item, attribute) returns false, then store.getValue(item, attribute) will return undefined.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access values on. |
| attribute | attribute-name-string | The attribute to access represented as a string. |
| defaultValue | value | *Optional*
Optional. A default value to use for the getValue return in the attribute does not exist or has no value. |
**Returns:** any
a literal, an item, null, or undefined (never an array)
Examples
--------
### Example 1
```
var darthVader = store.getValue(lukeSkywalker, "father");
```
###
`getValues``(item,attribute)`
Defined by [dojo/data/api/Read](read)
This getValues() method works just like the getValue() method, but getValues() always returns an array rather than a single attribute value. The array may be empty, may contain a single attribute value, or may contain many attribute values. If the item does not have a value for the given attribute, then getValues() will return an empty array: []. (So, if store.hasAttribute(item, attribute) has a return of false, then store.getValues(item, attribute) will return [].)
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access values on. |
| attribute | attribute-name-string | The attribute to access represented as a string. |
**Returns:** any
an array that may contain literals and items
Examples
--------
### Example 1
```
var friendsOfLuke = store.getValues(lukeSkywalker, "friends");
```
###
`hasAttribute``(item,attribute)`
Defined by [dojo/data/api/Read](read)
Returns true if the given *item* has a value for the given *attribute*.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access attributes on. |
| attribute | attribute-name-string | The attribute to access represented as a string. |
Examples
--------
### Example 1
```
var trueOrFalse = store.hasAttribute(kermit, "color");
```
###
`isItem``(something)`
Defined by [dojo/data/api/Read](read)
Returns true if *something* is an item and came from the store instance. Returns false if *something* is a literal, an item from another store instance, or is any object other than an item.
| Parameter | Type | Description |
| --- | --- | --- |
| something | anything | Can be anything. |
Examples
--------
### Example 1
```
var yes = store.isItem(store.newItem());
var no = store.isItem("green");
```
###
`isItemLoaded``(something)`
Defined by [dojo/data/api/Read](read)
Returns false if isItem(something) is false. Returns false if if isItem(something) is true but the the item is not yet loaded in local memory (for example, if the item has not yet been read from the server).
| Parameter | Type | Description |
| --- | --- | --- |
| something | anything | Can be anything. |
Examples
--------
### Example 1
```
var yes = store.isItemLoaded(store.newItem());
var no = store.isItemLoaded("green");
```
###
`loadItem``(keywordArgs)`
Defined by [dojo/data/api/Read](read)
Given an item, this method loads the item so that a subsequent call to store.isItemLoaded(item) will return true. If a call to isItemLoaded() returns true before loadItem() is even called, then loadItem() need not do any work at all and will not even invoke the callback handlers. So, before invoking this method, check that the item has not already been loaded.
| Parameter | Type | Description |
| --- | --- | --- |
| keywordArgs | Object | An anonymous object that defines the item to load and callbacks to invoke when the load has completed. The format of the object is as follows:
```
{
item: object,
onItem: Function,
onError: Function,
scope: object
}
```
The *item* parameter The item parameter is an object that represents the item in question that should be contained by the store. This attribute is required. The *onItem* parameter Function(item) The onItem parameter is the callback to invoke when the item has been loaded. It takes only one parameter, the fully loaded item. The *onError* parameter Function(error) The onError parameter is the callback to invoke when the item load encountered an error. It takes only one parameter, the error object The *scope* parameter If a scope object is provided, all of the callback functions (onItem, onError, etc) will be invoked in the context of the scope object. In the body of the callback function, the value of the "this" keyword will be the scope object. If no scope object is provided, the callback functions will be called in the context of dojo.global(). For example, onItem.call(scope, item, request) vs. onItem.call(dojo.global(), item, request) |
Events
------
###
`onDelete``(deletedItem)`
Defined by: [dojo/data/api/Notification](notification)
This function is called any time an item is deleted from the store. It is called immediately after the store deleteItem processing has completed.
This function is called any time an item is deleted from the store. It is called immediately after the store deleteItem processing has completed.
| Parameter | Type | Description |
| --- | --- | --- |
| deletedItem | [dojo/data/api/Item](item) | The item deleted. |
**Returns:** any
Nothing.
Examples
--------
### Example 1
```
var yes = store.isItemLoaded(store.newItem());
var no = store.isItemLoaded("green");
```
###
`onNew``(newItem,parentInfo)`
Defined by: [dojo/data/api/Notification](notification)
This function is called any time a new item is created in the store. It is called immediately after the store newItem processing has completed.
This function is called any time a new item is created in the store. It is called immediately after the store newItem processing has completed.
| Parameter | Type | Description |
| --- | --- | --- |
| newItem | [dojo/data/api/Item](item) | The item created. |
| parentInfo | object | *Optional*
An optional javascript object that is passed when the item created was placed in the store hierarchy as a value f another item's attribute, instead of a root level item. Note that if this function is invoked with a value for parentInfo, then onSet is not invoked stating the attribute of the parent item was modified. This is to avoid getting two notification events occurring when a new item with a parent is created. The structure passed in is as follows:
```
{
item: someItem, //The parent item
attribute: "attribute-name-string", //The attribute the new item was assigned to.
oldValue: something //Whatever was the previous value for the attribute.
//If it is a single-value attribute only, then this value will be a single value.
//If it was a multi-valued attribute, then this will be an array of all the values minus the new one.
newValue: something //The new value of the attribute. In the case of single value calls, such as setValue, this value will be
//generally be an atomic value of some sort (string, int, etc, object). In the case of multi-valued attributes,
//it will be an array.
}
```
|
**Returns:** any
Nothing.
Examples
--------
### Example 1
```
var yes = store.isItemLoaded(store.newItem());
var no = store.isItemLoaded("green");
```
###
`onSet``(item,attribute,oldValue,newValue)`
Defined by: [dojo/data/api/Notification](notification)
This function is called any time an item is modified via setValue, setValues, unsetAttribute, etc.
This function is called any time an item is modified via setValue, setValues, unsetAttribute, etc. Its purpose is to provide a hook point for those who wish to monitor actions on items in the store in a simple manner. The general expected usage is to dojo.connect() to the store's implementation and be called after the store function is called.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item being modified. |
| attribute | attribute-name-string | The attribute being changed represented as a string name. |
| oldValue | object | array | The old value of the attribute. In the case of single value calls, such as setValue, unsetAttribute, etc, this value will be generally be an atomic value of some sort (string, int, etc, object). In the case of multi-valued attributes, it will be an array. |
| newValue | object | array | The new value of the attribute. In the case of single value calls, such as setValue, this value will be generally be an atomic value of some sort (string, int, etc, object). In the case of multi-valued attributes, it will be an array. In the case of unsetAttribute, the new value will be 'undefined'. |
**Returns:** any
Nothing.
Examples
--------
### Example 1
```
var yes = store.isItemLoaded(store.newItem());
var no = store.isItemLoaded("green");
```
| programming_docs |
dojo dojo/data/api/Identity dojo/data/api/Identity
======================
Extends[dojo/data/api/Read](read) Summary
-------
This is an abstract API that data provider implementations conform to. This file defines methods signatures and intentionally leaves all the methods unimplemented.
See the [dojo/data/api/Identity reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/data/api/Identity.html) for more information.
Methods
-------
###
`close``(request)`
Defined by [dojo/data/api/Read](read)
The close() method is intended for instructing the store to 'close' out any information associated with a particular request.
The close() method is intended for instructing the store to 'close' out any information associated with a particular request. In general, this API expects to receive as a parameter a request object returned from a fetch. It will then close out anything associated with that request, such as clearing any internal datastore caches and closing any 'open' connections. For some store implementations, this call may be a no-op.
| Parameter | Type | Description |
| --- | --- | --- |
| request | [dojo/data/api/Request](request) | Object | *Optional*
An instance of a request for the store to use to identify what to close out. If no request is passed, then the store should clear all internal caches (if any) and close out all 'open' connections. It does not render the store unusable from there on, it merely cleans out any current data and resets the store to initial state. |
Examples
--------
### Example 1
```
var request = store.fetch({onComplete: doSomething});
...
store.close(request);
```
###
`containsValue``(item,attribute,value)`
Defined by [dojo/data/api/Read](read)
Returns true if the given *value* is one of the values that getValues() would return.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access values on. |
| attribute | attribute-name-string | The attribute to access represented as a string. |
| value | anything | The value to match as a value for the attribute. |
Examples
--------
### Example 1
```
var trueOrFalse = store.containsValue(kermit, "color", "green");
```
###
`fetch``(keywordArgs)`
Defined by [dojo/data/api/Read](read)
Given a query and set of defined options, such as a start and count of items to return, this method executes the query and makes the results available as data items. The format and expectations of stores is that they operate in a generally asynchronous manner, therefore callbacks are always used to return items located by the fetch parameters.
A Request object will always be returned and is returned immediately. The basic request is nothing more than the keyword args passed to fetch and an additional function attached, abort(). The returned request object may then be used to cancel a fetch. All data items returns are passed through the callbacks defined in the fetch parameters and are not present on the 'request' object.
This does not mean that custom stores can not add methods and properties to the request object returned, only that the API does not require it. For more info about the Request API, see [dojo/data/api/Request](request)
| Parameter | Type | Description |
| --- | --- | --- |
| keywordArgs | Object | The keywordArgs parameter may either be an instance of conforming to dojo/data/api/Request or may be a simple anonymous object that may contain any of the following:
```
{
query: query-object or query-string,
queryOptions: object,
onBegin: Function,
onItem: Function,
onComplete: Function,
onError: Function,
scope: object,
start: int
count: int
sort: array
}
```
All implementations should accept keywordArgs objects with any of the 9 standard properties: query, onBegin, onItem, onComplete, onError scope, sort, start, and count. Some implementations may accept additional properties in the keywordArgs object as valid parameters, such as {includeOutliers:true}. The *query* parameter The query may be optional in some data store implementations. The dojo/data/api/Read API does not specify the syntax or semantics of the query itself -- each different data store implementation may have its own notion of what a query should look like. However, as of dojo 0.9, 1.0, and 1.1, all the provided datastores in dojo.data and dojox.data support an object structure query, where the object is a set of name/value parameters such as { attrFoo: valueBar, attrFoo1: valueBar1}. Most of the dijit widgets, such as ComboBox assume this to be the case when working with a datastore when they dynamically update the query. Therefore, for maximum compatibility with dijit widgets the recommended query parameter is a key/value object. That does not mean that the the datastore may not take alternative query forms, such as a simple string, a Date, a number, or a mix of such. Ultimately, The dojo/data/api/Read API is agnostic about what the query format. Further note: In general for query objects that accept strings as attribute value matches, the store should also support basic filtering capability, such as *(match any character) and ? (match single character). An example query that is a query object would be like: { attrFoo: "value*"}. Which generally means match all items where they have an attribute named attrFoo, with a value that starts with 'value'. The *queryOptions* parameter The queryOptions parameter is an optional parameter used to specify options that may modify the query in some fashion, such as doing a case insensitive search, or doing a deep search where all items in a hierarchical representation of data are scanned instead of just the root items. It currently defines two options that all datastores should attempt to honor if possible:
```
{
ignoreCase: boolean, // Whether or not the query should match case sensitively or not. Default behaviour is false.
deep: boolean // Whether or not a fetch should do a deep search of items and all child
// items instead of just root-level items in a datastore. Default is false.
}
```
The *onBegin* parameter. function(size, request); If an onBegin callback function is provided, the callback function will be called just once, before the first onItem callback is called. The onBegin callback function will be passed two arguments, the the total number of items identified and the Request object. If the total number is unknown, then size will be -1. Note that size is not necessarily the size of the collection of items returned from the query, as the request may have specified to return only a subset of the total set of items through the use of the start and count parameters. The *onItem* parameter. function(item, request); If an onItem callback function is provided, the callback function will be called as each item in the result is received. The callback function will be passed two arguments: the item itself, and the Request object. The *onComplete* parameter. function(items, request); If an onComplete callback function is provided, the callback function will be called just once, after the last onItem callback is called. Note that if the onItem callback is not present, then onComplete will be passed an array containing all items which matched the query and the request object. If the onItem callback is present, then onComplete is called as: onComplete(null, request). The *onError* parameter. function(errorData, request); If an onError callback function is provided, the callback function will be called if there is any sort of error while attempting to execute the query. The onError callback function will be passed two arguments: an Error object and the Request object. The *scope* parameter. If a scope object is provided, all of the callback functions (onItem, onComplete, onError, etc) will be invoked in the context of the scope object. In the body of the callback function, the value of the "this" keyword will be the scope object. If no scope object is provided, the callback functions will be called in the context of dojo.global(). For example, onItem.call(scope, item, request) vs. onItem.call(dojo.global(), item, request) The *start* parameter. If a start parameter is specified, this is a indication to the datastore to only start returning items once the start number of items have been located and skipped. When this parameter is paired with 'count', the store should be able to page across queries with millions of hits by only returning subsets of the hits for each query The *count* parameter. If a count parameter is specified, this is a indication to the datastore to only return up to that many items. This allows a fetch call that may have millions of item matches to be paired down to something reasonable. The *sort* parameter. If a sort parameter is specified, this is a indication to the datastore to sort the items in some manner before returning the items. The array is an array of javascript objects that must conform to the following format to be applied to the fetching of items:
```
{
attribute: attribute || attribute-name-string,
descending: true|false; // Optional. Default is false.
}
```
Note that when comparing attributes, if an item contains no value for the attribute (undefined), then it the default ascending sort logic should push it to the bottom of the list. In the descending order case, it such items should appear at the top of the list. |
**Returns:** any
The fetch() method will return a javascript object conforming to the API defined in dojo/data/api/Request. In general, it will be the keywordArgs object returned with the required functions in Request.js attached. Its general purpose is to provide a convenient way for a caller to abort an ongoing fetch.
The Request object may also have additional properties when it is returned such as request.store property, which is a pointer to the datastore object that fetch() is a method of.
Examples
--------
### Example 1
Fetch all books identified by the query and call 'showBooks' when complete
```
var request = store.fetch({query:"all books", onComplete: showBooks});
```
### Example 2
Fetch all items in the story and call 'showEverything' when complete.
```
var request = store.fetch(onComplete: showEverything);
```
### Example 3
Fetch only 10 books that match the query 'all books', starting at the fifth book found during the search. This demonstrates how paging can be done for specific queries.
```
var request = store.fetch({query:"all books", start: 4, count: 10, onComplete: showBooks});
```
### Example 4
Fetch all items that match the query, calling 'callback' each time an item is located.
```
var request = store.fetch({query:"foo/bar", onItem:callback});
```
### Example 5
Fetch the first 100 books by author King, call showKing when up to 100 items have been located.
```
var request = store.fetch({query:{author:"King"}, start: 0, count:100, onComplete: showKing});
```
### Example 6
Locate the books written by Author King, sort it on title and publisher, then return the first 100 items from the sorted items.
```
var request = store.fetch({query:{author:"King"}, sort: [{ attribute: "title", descending: true}, {attribute: "publisher"}], ,start: 0, count:100, onComplete: 'showKing'});
```
### Example 7
Fetch the first 100 books by authors starting with the name King, then call showKing when up to 100 items have been located.
```
var request = store.fetch({query:{author:"King*"}, start: 0, count:100, onComplete: showKing});
```
### Example 8
Fetch the first 100 books by authors ending with 'ing', but only have one character before it (King, Bing, Ling, Sing, etc.), then call showBooks when up to 100 items have been located.
```
var request = store.fetch({query:{author:"?ing"}, start: 0, count:100, onComplete: showBooks});
```
### Example 9
Fetch the first 100 books by author King, where the name may appear as King, king, KING, kInG, and so on, then call showKing when up to 100 items have been located.
```
var request = store.fetch({query:{author:"King"}, queryOptions:(ignoreCase: true}, start: 0, count:100, onComplete: showKing});
```
### Example 10
Paging
```
var store = new LargeRdbmsStore({url:"jdbc:odbc:foobar"});
var fetchArgs = {
query: {type:"employees", name:"Hillary *"}, // string matching
sort: [{attribute:"department", descending:true}],
start: 0,
count: 20,
scope: displayer,
onBegin: showThrobber,
onItem: displayItem,
onComplete: stopThrobber,
onError: handleFetchError,
};
store.fetch(fetchArgs);
...
```
and then when the user presses the "Next Page" button...
```
fetchArgs.start += 20;
store.fetch(fetchArgs); // get the next 20 items
```
###
`fetchItemByIdentity``(keywordArgs)`
Defined by [dojo/data/api/Identity](identity)
Given the identity of an item, this method returns the item that has that identity through the onItem callback. Conforming implementations should return null if there is no item with the given identity. Implementations of fetchItemByIdentity() may sometimes return an item from a local cache and may sometimes fetch an item from a remote server,
| Parameter | Type | Description |
| --- | --- | --- |
| keywordArgs | object | An anonymous object that defines the item to locate and callbacks to invoke when the item has been located and load has completed. The format of the object is as follows:
```
{
identity: string|object,
onItem: Function,
onError: Function,
scope: object
}
```
The *identity* parameter The identity parameter is the identity of the item you wish to locate and load This attribute is required. It should be a string or an object that toString() can be called on. The *onItem* parameter Function(item) The onItem parameter is the callback to invoke when the item has been loaded. It takes only one parameter, the item located, or null if none found. The *onError* parameter Function(error) The onError parameter is the callback to invoke when the item load encountered an error. It takes only one parameter, the error object The *scope* parameter If a scope object is provided, all of the callback functions (onItem, onError, etc) will be invoked in the context of the scope object. In the body of the callback function, the value of the "this" keyword will be the scope object. If no scope object is provided, the callback functions will be called in the context of dojo.global. For example, onItem.call(scope, item, request) vs. onItem.call(dojo.global, item, request) |
###
`getAttributes``(item)`
Defined by [dojo/data/api/Read](read)
Returns an array with all the attributes that this item has. This method will always return an array; if the item has no attributes at all, getAttributes() will return an empty array: [].
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access attributes on. |
Examples
--------
### Example 1
```
var array = store.getAttributes(kermit);
```
###
`getFeatures``()`
Defined by [dojo/data/api/Identity](identity)
See dojo/data/api/Read.getFeatures()
**Returns:** object
###
`getIdentity``(item)`
Defined by [dojo/data/api/Identity](identity)
Returns a unique identifier for an item. The return value will be either a string or something that has a toString() method (such as, for example, a dojox/uuid object).
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item from the store from which to obtain its identifier. |
Examples
--------
### Example 1
```
var itemId = store.getIdentity(kermit);
assert(kermit === store.findByIdentity(store.getIdentity(kermit)));
```
###
`getIdentityAttributes``(item)`
Defined by [dojo/data/api/Identity](identity)
Returns an array of attribute names that are used to generate the identity. For most stores, this is a single attribute, but for some complex stores such as RDB backed stores that use compound (multi-attribute) identifiers it can be more than one. If the identity is not composed of attributes on the item, it will return null. This function is intended to identify the attributes that comprise the identity so that so that during a render of all attributes, the UI can hide the the identity information if it chooses.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item from the store from which to obtain the array of public attributes that compose the identifier, if any. |
Examples
--------
### Example 1
```
var itemId = store.getIdentity(kermit);
var identifiers = store.getIdentityAttributes(itemId);
assert(typeof identifiers === "array" || identifiers === null);
```
###
`getLabel``(item)`
Defined by [dojo/data/api/Read](read)
Method to inspect the item and return a user-readable 'label' for the item that provides a general/adequate description of what the item is.
Method to inspect the item and return a user-readable 'label' for the item that provides a general/adequate description of what the item is. In general most labels will be a specific attribute value or collection of the attribute values that combine to label the item in some manner. For example for an item that represents a person it may return the label as: "firstname lastlame" where the firstname and lastname are attributes on the item. If the store is unable to determine an adequate human readable label, it should return undefined. Users that wish to customize how a store instance labels items should replace the getLabel() function on their instance of the store, or extend the store and replace the function in the extension class.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to return the label for. |
**Returns:** any
A user-readable string representing the item or undefined if no user-readable label can be generated.
###
`getLabelAttributes``(item)`
Defined by [dojo/data/api/Read](read)
Method to inspect the item and return an array of what attributes of the item were used to generate its label, if any.
Method to inspect the item and return an array of what attributes of the item were used to generate its label, if any. This function is to assist UI developers in knowing what attributes can be ignored out of the attributes an item has when displaying it, in cases where the UI is using the label as an overall identifer should they wish to hide redundant information.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to return the list of label attributes for. |
**Returns:** any
An array of attribute names that were used to generate the label, or null if public attributes were not used to generate the label.
###
`getValue``(item,attribute,defaultValue)`
Defined by [dojo/data/api/Read](read)
Returns a single attribute value. Returns defaultValue if and only if *item* does not have a value for *attribute*. Returns null if and only if null was explicitly set as the attribute value. Returns undefined if and only if the item does not have a value for the given attribute (which is the same as saying the item does not have the attribute).
Saying that an "item x does not have a value for an attribute y" is identical to saying that an "item x does not have attribute y". It is an oxymoron to say "that attribute is present but has no values" or "the item has that attribute but does not have any attribute values". If store.hasAttribute(item, attribute) returns false, then store.getValue(item, attribute) will return undefined.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access values on. |
| attribute | attribute-name-string | The attribute to access represented as a string. |
| defaultValue | value | *Optional*
Optional. A default value to use for the getValue return in the attribute does not exist or has no value. |
**Returns:** any
a literal, an item, null, or undefined (never an array)
Examples
--------
### Example 1
```
var darthVader = store.getValue(lukeSkywalker, "father");
```
###
`getValues``(item,attribute)`
Defined by [dojo/data/api/Read](read)
This getValues() method works just like the getValue() method, but getValues() always returns an array rather than a single attribute value. The array may be empty, may contain a single attribute value, or may contain many attribute values. If the item does not have a value for the given attribute, then getValues() will return an empty array: []. (So, if store.hasAttribute(item, attribute) has a return of false, then store.getValues(item, attribute) will return [].)
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access values on. |
| attribute | attribute-name-string | The attribute to access represented as a string. |
**Returns:** any
an array that may contain literals and items
Examples
--------
### Example 1
```
var friendsOfLuke = store.getValues(lukeSkywalker, "friends");
```
###
`hasAttribute``(item,attribute)`
Defined by [dojo/data/api/Read](read)
Returns true if the given *item* has a value for the given *attribute*.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access attributes on. |
| attribute | attribute-name-string | The attribute to access represented as a string. |
Examples
--------
### Example 1
```
var trueOrFalse = store.hasAttribute(kermit, "color");
```
###
`isItem``(something)`
Defined by [dojo/data/api/Read](read)
Returns true if *something* is an item and came from the store instance. Returns false if *something* is a literal, an item from another store instance, or is any object other than an item.
| Parameter | Type | Description |
| --- | --- | --- |
| something | anything | Can be anything. |
Examples
--------
### Example 1
```
var yes = store.isItem(store.newItem());
var no = store.isItem("green");
```
###
`isItemLoaded``(something)`
Defined by [dojo/data/api/Read](read)
Returns false if isItem(something) is false. Returns false if if isItem(something) is true but the the item is not yet loaded in local memory (for example, if the item has not yet been read from the server).
| Parameter | Type | Description |
| --- | --- | --- |
| something | anything | Can be anything. |
Examples
--------
### Example 1
```
var yes = store.isItemLoaded(store.newItem());
var no = store.isItemLoaded("green");
```
###
`loadItem``(keywordArgs)`
Defined by [dojo/data/api/Read](read)
Given an item, this method loads the item so that a subsequent call to store.isItemLoaded(item) will return true. If a call to isItemLoaded() returns true before loadItem() is even called, then loadItem() need not do any work at all and will not even invoke the callback handlers. So, before invoking this method, check that the item has not already been loaded.
| Parameter | Type | Description |
| --- | --- | --- |
| keywordArgs | Object | An anonymous object that defines the item to load and callbacks to invoke when the load has completed. The format of the object is as follows:
```
{
item: object,
onItem: Function,
onError: Function,
scope: object
}
```
The *item* parameter The item parameter is an object that represents the item in question that should be contained by the store. This attribute is required. The *onItem* parameter Function(item) The onItem parameter is the callback to invoke when the item has been loaded. It takes only one parameter, the fully loaded item. The *onError* parameter Function(error) The onError parameter is the callback to invoke when the item load encountered an error. It takes only one parameter, the error object The *scope* parameter If a scope object is provided, all of the callback functions (onItem, onError, etc) will be invoked in the context of the scope object. In the body of the callback function, the value of the "this" keyword will be the scope object. If no scope object is provided, the callback functions will be called in the context of dojo.global(). For example, onItem.call(scope, item, request) vs. onItem.call(dojo.global(), item, request) |
| programming_docs |
dojo dojo/data/api/Write dojo/data/api/Write
===================
Extends[dojo/data/api/Read](read) Summary
-------
This is an abstract API that data provider implementations conform to. This file defines function signatures and intentionally leaves all the functions unimplemented.
See the [dojo/data/api/Write reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/data/api/Write.html) for more information.
Methods
-------
###
`close``(request)`
Defined by [dojo/data/api/Read](read)
The close() method is intended for instructing the store to 'close' out any information associated with a particular request.
The close() method is intended for instructing the store to 'close' out any information associated with a particular request. In general, this API expects to receive as a parameter a request object returned from a fetch. It will then close out anything associated with that request, such as clearing any internal datastore caches and closing any 'open' connections. For some store implementations, this call may be a no-op.
| Parameter | Type | Description |
| --- | --- | --- |
| request | [dojo/data/api/Request](request) | Object | *Optional*
An instance of a request for the store to use to identify what to close out. If no request is passed, then the store should clear all internal caches (if any) and close out all 'open' connections. It does not render the store unusable from there on, it merely cleans out any current data and resets the store to initial state. |
Examples
--------
### Example 1
```
var request = store.fetch({onComplete: doSomething});
...
store.close(request);
```
###
`containsValue``(item,attribute,value)`
Defined by [dojo/data/api/Read](read)
Returns true if the given *value* is one of the values that getValues() would return.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access values on. |
| attribute | attribute-name-string | The attribute to access represented as a string. |
| value | anything | The value to match as a value for the attribute. |
Examples
--------
### Example 1
```
var trueOrFalse = store.containsValue(kermit, "color", "green");
```
###
`deleteItem``(item)`
Defined by [dojo/data/api/Write](write)
Deletes an item from the store.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to delete. |
Examples
--------
### Example 1
```
var success = store.deleteItem(kermit);
```
###
`fetch``(keywordArgs)`
Defined by [dojo/data/api/Read](read)
Given a query and set of defined options, such as a start and count of items to return, this method executes the query and makes the results available as data items. The format and expectations of stores is that they operate in a generally asynchronous manner, therefore callbacks are always used to return items located by the fetch parameters.
A Request object will always be returned and is returned immediately. The basic request is nothing more than the keyword args passed to fetch and an additional function attached, abort(). The returned request object may then be used to cancel a fetch. All data items returns are passed through the callbacks defined in the fetch parameters and are not present on the 'request' object.
This does not mean that custom stores can not add methods and properties to the request object returned, only that the API does not require it. For more info about the Request API, see [dojo/data/api/Request](request)
| Parameter | Type | Description |
| --- | --- | --- |
| keywordArgs | Object | The keywordArgs parameter may either be an instance of conforming to dojo/data/api/Request or may be a simple anonymous object that may contain any of the following:
```
{
query: query-object or query-string,
queryOptions: object,
onBegin: Function,
onItem: Function,
onComplete: Function,
onError: Function,
scope: object,
start: int
count: int
sort: array
}
```
All implementations should accept keywordArgs objects with any of the 9 standard properties: query, onBegin, onItem, onComplete, onError scope, sort, start, and count. Some implementations may accept additional properties in the keywordArgs object as valid parameters, such as {includeOutliers:true}. The *query* parameter The query may be optional in some data store implementations. The dojo/data/api/Read API does not specify the syntax or semantics of the query itself -- each different data store implementation may have its own notion of what a query should look like. However, as of dojo 0.9, 1.0, and 1.1, all the provided datastores in dojo.data and dojox.data support an object structure query, where the object is a set of name/value parameters such as { attrFoo: valueBar, attrFoo1: valueBar1}. Most of the dijit widgets, such as ComboBox assume this to be the case when working with a datastore when they dynamically update the query. Therefore, for maximum compatibility with dijit widgets the recommended query parameter is a key/value object. That does not mean that the the datastore may not take alternative query forms, such as a simple string, a Date, a number, or a mix of such. Ultimately, The dojo/data/api/Read API is agnostic about what the query format. Further note: In general for query objects that accept strings as attribute value matches, the store should also support basic filtering capability, such as *(match any character) and ? (match single character). An example query that is a query object would be like: { attrFoo: "value*"}. Which generally means match all items where they have an attribute named attrFoo, with a value that starts with 'value'. The *queryOptions* parameter The queryOptions parameter is an optional parameter used to specify options that may modify the query in some fashion, such as doing a case insensitive search, or doing a deep search where all items in a hierarchical representation of data are scanned instead of just the root items. It currently defines two options that all datastores should attempt to honor if possible:
```
{
ignoreCase: boolean, // Whether or not the query should match case sensitively or not. Default behaviour is false.
deep: boolean // Whether or not a fetch should do a deep search of items and all child
// items instead of just root-level items in a datastore. Default is false.
}
```
The *onBegin* parameter. function(size, request); If an onBegin callback function is provided, the callback function will be called just once, before the first onItem callback is called. The onBegin callback function will be passed two arguments, the the total number of items identified and the Request object. If the total number is unknown, then size will be -1. Note that size is not necessarily the size of the collection of items returned from the query, as the request may have specified to return only a subset of the total set of items through the use of the start and count parameters. The *onItem* parameter. function(item, request); If an onItem callback function is provided, the callback function will be called as each item in the result is received. The callback function will be passed two arguments: the item itself, and the Request object. The *onComplete* parameter. function(items, request); If an onComplete callback function is provided, the callback function will be called just once, after the last onItem callback is called. Note that if the onItem callback is not present, then onComplete will be passed an array containing all items which matched the query and the request object. If the onItem callback is present, then onComplete is called as: onComplete(null, request). The *onError* parameter. function(errorData, request); If an onError callback function is provided, the callback function will be called if there is any sort of error while attempting to execute the query. The onError callback function will be passed two arguments: an Error object and the Request object. The *scope* parameter. If a scope object is provided, all of the callback functions (onItem, onComplete, onError, etc) will be invoked in the context of the scope object. In the body of the callback function, the value of the "this" keyword will be the scope object. If no scope object is provided, the callback functions will be called in the context of dojo.global(). For example, onItem.call(scope, item, request) vs. onItem.call(dojo.global(), item, request) The *start* parameter. If a start parameter is specified, this is a indication to the datastore to only start returning items once the start number of items have been located and skipped. When this parameter is paired with 'count', the store should be able to page across queries with millions of hits by only returning subsets of the hits for each query The *count* parameter. If a count parameter is specified, this is a indication to the datastore to only return up to that many items. This allows a fetch call that may have millions of item matches to be paired down to something reasonable. The *sort* parameter. If a sort parameter is specified, this is a indication to the datastore to sort the items in some manner before returning the items. The array is an array of javascript objects that must conform to the following format to be applied to the fetching of items:
```
{
attribute: attribute || attribute-name-string,
descending: true|false; // Optional. Default is false.
}
```
Note that when comparing attributes, if an item contains no value for the attribute (undefined), then it the default ascending sort logic should push it to the bottom of the list. In the descending order case, it such items should appear at the top of the list. |
**Returns:** any
The fetch() method will return a javascript object conforming to the API defined in dojo/data/api/Request. In general, it will be the keywordArgs object returned with the required functions in Request.js attached. Its general purpose is to provide a convenient way for a caller to abort an ongoing fetch.
The Request object may also have additional properties when it is returned such as request.store property, which is a pointer to the datastore object that fetch() is a method of.
Examples
--------
### Example 1
Fetch all books identified by the query and call 'showBooks' when complete
```
var request = store.fetch({query:"all books", onComplete: showBooks});
```
### Example 2
Fetch all items in the story and call 'showEverything' when complete.
```
var request = store.fetch(onComplete: showEverything);
```
### Example 3
Fetch only 10 books that match the query 'all books', starting at the fifth book found during the search. This demonstrates how paging can be done for specific queries.
```
var request = store.fetch({query:"all books", start: 4, count: 10, onComplete: showBooks});
```
### Example 4
Fetch all items that match the query, calling 'callback' each time an item is located.
```
var request = store.fetch({query:"foo/bar", onItem:callback});
```
### Example 5
Fetch the first 100 books by author King, call showKing when up to 100 items have been located.
```
var request = store.fetch({query:{author:"King"}, start: 0, count:100, onComplete: showKing});
```
### Example 6
Locate the books written by Author King, sort it on title and publisher, then return the first 100 items from the sorted items.
```
var request = store.fetch({query:{author:"King"}, sort: [{ attribute: "title", descending: true}, {attribute: "publisher"}], ,start: 0, count:100, onComplete: 'showKing'});
```
### Example 7
Fetch the first 100 books by authors starting with the name King, then call showKing when up to 100 items have been located.
```
var request = store.fetch({query:{author:"King*"}, start: 0, count:100, onComplete: showKing});
```
### Example 8
Fetch the first 100 books by authors ending with 'ing', but only have one character before it (King, Bing, Ling, Sing, etc.), then call showBooks when up to 100 items have been located.
```
var request = store.fetch({query:{author:"?ing"}, start: 0, count:100, onComplete: showBooks});
```
### Example 9
Fetch the first 100 books by author King, where the name may appear as King, king, KING, kInG, and so on, then call showKing when up to 100 items have been located.
```
var request = store.fetch({query:{author:"King"}, queryOptions:(ignoreCase: true}, start: 0, count:100, onComplete: showKing});
```
### Example 10
Paging
```
var store = new LargeRdbmsStore({url:"jdbc:odbc:foobar"});
var fetchArgs = {
query: {type:"employees", name:"Hillary *"}, // string matching
sort: [{attribute:"department", descending:true}],
start: 0,
count: 20,
scope: displayer,
onBegin: showThrobber,
onItem: displayItem,
onComplete: stopThrobber,
onError: handleFetchError,
};
store.fetch(fetchArgs);
...
```
and then when the user presses the "Next Page" button...
```
fetchArgs.start += 20;
store.fetch(fetchArgs); // get the next 20 items
```
###
`getAttributes``(item)`
Defined by [dojo/data/api/Read](read)
Returns an array with all the attributes that this item has. This method will always return an array; if the item has no attributes at all, getAttributes() will return an empty array: [].
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access attributes on. |
Examples
--------
### Example 1
```
var array = store.getAttributes(kermit);
```
###
`getFeatures``()`
Defined by [dojo/data/api/Write](write)
See dojo/data/api/Read.getFeatures()
**Returns:** object
###
`getLabel``(item)`
Defined by [dojo/data/api/Read](read)
Method to inspect the item and return a user-readable 'label' for the item that provides a general/adequate description of what the item is.
Method to inspect the item and return a user-readable 'label' for the item that provides a general/adequate description of what the item is. In general most labels will be a specific attribute value or collection of the attribute values that combine to label the item in some manner. For example for an item that represents a person it may return the label as: "firstname lastlame" where the firstname and lastname are attributes on the item. If the store is unable to determine an adequate human readable label, it should return undefined. Users that wish to customize how a store instance labels items should replace the getLabel() function on their instance of the store, or extend the store and replace the function in the extension class.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to return the label for. |
**Returns:** any
A user-readable string representing the item or undefined if no user-readable label can be generated.
###
`getLabelAttributes``(item)`
Defined by [dojo/data/api/Read](read)
Method to inspect the item and return an array of what attributes of the item were used to generate its label, if any.
Method to inspect the item and return an array of what attributes of the item were used to generate its label, if any. This function is to assist UI developers in knowing what attributes can be ignored out of the attributes an item has when displaying it, in cases where the UI is using the label as an overall identifer should they wish to hide redundant information.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to return the list of label attributes for. |
**Returns:** any
An array of attribute names that were used to generate the label, or null if public attributes were not used to generate the label.
###
`getValue``(item,attribute,defaultValue)`
Defined by [dojo/data/api/Read](read)
Returns a single attribute value. Returns defaultValue if and only if *item* does not have a value for *attribute*. Returns null if and only if null was explicitly set as the attribute value. Returns undefined if and only if the item does not have a value for the given attribute (which is the same as saying the item does not have the attribute).
Saying that an "item x does not have a value for an attribute y" is identical to saying that an "item x does not have attribute y". It is an oxymoron to say "that attribute is present but has no values" or "the item has that attribute but does not have any attribute values". If store.hasAttribute(item, attribute) returns false, then store.getValue(item, attribute) will return undefined.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access values on. |
| attribute | attribute-name-string | The attribute to access represented as a string. |
| defaultValue | value | *Optional*
Optional. A default value to use for the getValue return in the attribute does not exist or has no value. |
**Returns:** any
a literal, an item, null, or undefined (never an array)
Examples
--------
### Example 1
```
var darthVader = store.getValue(lukeSkywalker, "father");
```
###
`getValues``(item,attribute)`
Defined by [dojo/data/api/Read](read)
This getValues() method works just like the getValue() method, but getValues() always returns an array rather than a single attribute value. The array may be empty, may contain a single attribute value, or may contain many attribute values. If the item does not have a value for the given attribute, then getValues() will return an empty array: []. (So, if store.hasAttribute(item, attribute) has a return of false, then store.getValues(item, attribute) will return [].)
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access values on. |
| attribute | attribute-name-string | The attribute to access represented as a string. |
**Returns:** any
an array that may contain literals and items
Examples
--------
### Example 1
```
var friendsOfLuke = store.getValues(lukeSkywalker, "friends");
```
###
`hasAttribute``(item,attribute)`
Defined by [dojo/data/api/Read](read)
Returns true if the given *item* has a value for the given *attribute*.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to access attributes on. |
| attribute | attribute-name-string | The attribute to access represented as a string. |
Examples
--------
### Example 1
```
var trueOrFalse = store.hasAttribute(kermit, "color");
```
###
`isDirty``(item)`
Defined by [dojo/data/api/Write](write)
Given an item, isDirty() returns true if the item has been modified since the last save(). If isDirty() is called with no *item* argument, then this function returns true if any item has been modified since the last save().
| Parameter | Type | Description |
| --- | --- | --- |
| item | item | *Optional*
The item to check. |
Examples
--------
### Example 1
```
var trueOrFalse = store.isDirty(kermit); // true if kermit is dirty
var trueOrFalse = store.isDirty(); // true if any item is dirty
```
###
`isItem``(something)`
Defined by [dojo/data/api/Read](read)
Returns true if *something* is an item and came from the store instance. Returns false if *something* is a literal, an item from another store instance, or is any object other than an item.
| Parameter | Type | Description |
| --- | --- | --- |
| something | anything | Can be anything. |
Examples
--------
### Example 1
```
var yes = store.isItem(store.newItem());
var no = store.isItem("green");
```
###
`isItemLoaded``(something)`
Defined by [dojo/data/api/Read](read)
Returns false if isItem(something) is false. Returns false if if isItem(something) is true but the the item is not yet loaded in local memory (for example, if the item has not yet been read from the server).
| Parameter | Type | Description |
| --- | --- | --- |
| something | anything | Can be anything. |
Examples
--------
### Example 1
```
var yes = store.isItemLoaded(store.newItem());
var no = store.isItemLoaded("green");
```
###
`loadItem``(keywordArgs)`
Defined by [dojo/data/api/Read](read)
Given an item, this method loads the item so that a subsequent call to store.isItemLoaded(item) will return true. If a call to isItemLoaded() returns true before loadItem() is even called, then loadItem() need not do any work at all and will not even invoke the callback handlers. So, before invoking this method, check that the item has not already been loaded.
| Parameter | Type | Description |
| --- | --- | --- |
| keywordArgs | Object | An anonymous object that defines the item to load and callbacks to invoke when the load has completed. The format of the object is as follows:
```
{
item: object,
onItem: Function,
onError: Function,
scope: object
}
```
The *item* parameter The item parameter is an object that represents the item in question that should be contained by the store. This attribute is required. The *onItem* parameter Function(item) The onItem parameter is the callback to invoke when the item has been loaded. It takes only one parameter, the fully loaded item. The *onError* parameter Function(error) The onError parameter is the callback to invoke when the item load encountered an error. It takes only one parameter, the error object The *scope* parameter If a scope object is provided, all of the callback functions (onItem, onError, etc) will be invoked in the context of the scope object. In the body of the callback function, the value of the "this" keyword will be the scope object. If no scope object is provided, the callback functions will be called in the context of dojo.global(). For example, onItem.call(scope, item, request) vs. onItem.call(dojo.global(), item, request) |
###
`newItem``(keywordArgs,parentInfo)`
Defined by [dojo/data/api/Write](write)
Returns a newly created item. Sets the attributes of the new item based on the *keywordArgs* provided. In general, the attribute names in the keywords become the attributes in the new item and as for the attribute values in keywordArgs, they become the values of the attributes in the new item. In addition, for stores that support hierarchical item creation, an optional second parameter is accepted that defines what item is the parent of the new item and what attribute of that item should the new item be assigned to. In general, this will assume that the attribute targeted is multi-valued and a new item is appended onto the list of values for that attribute.
| Parameter | Type | Description |
| --- | --- | --- |
| keywordArgs | Object | *Optional*
A javascript object defining the initial content of the item as a set of JavaScript 'property name: value' pairs. |
| parentInfo | Object | *Optional*
An optional javascript object defining what item is the parent of this item (in a hierarchical store. Not all stores do hierarchical items), and what attribute of that parent to assign the new item to. If this is present, and the attribute specified is a multi-valued attribute, it will append this item into the array of values for that attribute. The structure of the object is as follows:
```
{
parent: someItem,
attribute: "attribute-name-string"
}
```
|
Examples
--------
### Example 1
```
var kermit = store.newItem({name: "Kermit", color:[blue, green]});
```
###
`revert``()`
Defined by [dojo/data/api/Write](write)
Discards any unsaved changes.
Discards any unsaved changes.
Examples
--------
### Example 1
```
var success = store.revert();
```
###
`save``(keywordArgs)`
Defined by [dojo/data/api/Write](write)
Saves to the server all the changes that have been made locally. The save operation may take some time and is generally performed in an asynchronous fashion. The outcome of the save action is is passed into the set of supported callbacks for the save.
| Parameter | Type | Description |
| --- | --- | --- |
| keywordArgs | object |
```
{
onComplete: function
onError: function
scope: object
}
####The *onComplete* parameter.
function();
If an onComplete callback function is provided, the callback function
will be called just once, after the save has completed. No parameters
are generally passed to the onComplete.
####The *onError* parameter.
function(errorData);
If an onError callback function is provided, the callback function
will be called if there is any sort of error while attempting to
execute the save. The onError function will be based one parameter, the
error.
####The *scope* parameter.
If a scope object is provided, all of the callback function (
onComplete, onError, etc) will be invoked in the context of the scope
object. In the body of the callback function, the value of the "this"
keyword will be the scope object. If no scope object is provided,
the callback functions will be called in the context of dojo.global.
For example, onComplete.call(scope) vs.
onComplete.call(dojo.global)
```
|
**Returns:** any
Nothing. Since the saves are generally asynchronous, there is no need to return anything. All results are passed via callbacks.
Examples
--------
### Example 1
```
store.save({onComplete: onSave});
store.save({scope: fooObj, onComplete: onSave, onError: saveFailed});
```
###
`setValue``(item,attribute,value)`
Defined by [dojo/data/api/Write](write)
Sets the value of an attribute on an item. Replaces any previous value or values.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to modify. |
| attribute | string | The attribute of the item to change represented as a string name. |
| value | almost anything | The value to assign to the item. |
Examples
--------
### Example 1
```
var success = store.set(kermit, "color", "green");
```
###
`setValues``(item,attribute,values)`
Defined by [dojo/data/api/Write](write)
Adds each value in the *values* array as a value of the given attribute on the given item. Replaces any previous value or values. Calling store.setValues(x, y, []) (with *values* as an empty array) has the same effect as calling store.unsetAttribute(x, y).
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to modify. |
| attribute | string | The attribute of the item to change represented as a string name. |
| values | array | An array of values to assign to the attribute.. |
Examples
--------
### Example 1
```
var success = store.setValues(kermit, "color", ["green", "aqua"]);
success = store.setValues(kermit, "color", []);
if (success){assert(!store.hasAttribute(kermit, "color"));}
```
###
`unsetAttribute``(item,attribute)`
Defined by [dojo/data/api/Write](write)
Deletes all the values of an attribute on an item.
| Parameter | Type | Description |
| --- | --- | --- |
| item | [dojo/data/api/Item](item) | The item to modify. |
| attribute | string | The attribute of the item to unset represented as a string. |
Examples
--------
### Example 1
```
var success = store.unsetAttribute(kermit, "color");
if (success){assert(!store.hasAttribute(kermit, "color"));}
```
| programming_docs |
dojo dojo/data/api/Item dojo/data/api/Item
==================
Summary
-------
An item in a dojo/data store Class for documentation purposes only. An item can take any form, so no properties or methods are defined here.
See the [dojo/data/api/Item reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/data/api.html) for more information.
dojo dojo/data/api/Request dojo/data/api/Request
=====================
Summary
-------
This class defines out the semantics of what a 'Request' object looks like when returned from a fetch() method. In general, a request object is nothing more than the original keywordArgs from fetch with an abort function attached to it to allow users to abort a particular request if they so choose. No other functions are required on a general Request object return. That does not inhibit other store implementations from adding extensions to it, of course.
This is an abstract API that data provider implementations conform to. This file defines methods signatures and intentionally leaves all the methods unimplemented.
For more details on fetch, see [dojo/data/api/Read.fetch()](read#fetch).
See the [dojo/data/api/Request reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/data/api.html) for more information.
Methods
-------
###
`abort``()`
Defined by [dojo/data/api/Request](request)
This function is a hook point for stores to provide as a way for a fetch to be halted mid-processing.
This function is a hook point for stores to provide as a way for a fetch to be halted mid-processing. For more details on the fetch() api, please see [dojo/data/api/Read.fetch()](read#fetch).
dojo dojo/_base/kernel.cldr dojo/\_base/kernel.cldr
=======================
Properties
----------
### monetary
Defined by: [dojo/cldr/monetary](../cldr/monetary)
TODOC
### supplemental
Defined by: [dojo/cldr/supplemental](../cldr/supplemental)
TODOC
dojo dojo/_base/kernel.i18n dojo/\_base/kernel.i18n
=======================
Summary
-------
This module implements the [dojo/i18n](../i18n)! plugin and the v1.6- i18n API
We choose to include our own plugin to leverage functionality already contained in dojo and thereby reduce the size of the plugin compared to various loader implementations. Also, this allows foreign AMD loaders to be used without their plugins.
Properties
----------
### cache
Defined by: [dojo/i18n](../i18n)
### dynamic
Defined by: [dojo/i18n](../i18n)
### unitTests
Defined by: [dojo/i18n](../i18n)
Methods
-------
###
`getL10nName``(moduleName,bundleName,locale)`
Defined by [dojo/i18n](../i18n)
| Parameter | Type | Description |
| --- | --- | --- |
| moduleName | undefined | |
| bundleName | undefined | |
| locale | undefined | |
**Returns:** string
###
`getLocalization``(moduleName,bundleName,locale)`
Defined by [dojo/i18n](../i18n)
| Parameter | Type | Description |
| --- | --- | --- |
| moduleName | undefined | |
| bundleName | undefined | |
| locale | undefined | |
**Returns:** undefined
###
`load``(id,require,load)`
Defined by [dojo/i18n](../i18n)
id is in one of the following formats
1. /nls/ => load the bundle, localized to config.locale; load all bundles localized to config.extraLocale (if any); return the loaded bundle localized to config.locale.
2. /nls// => load then return the bundle localized to
3. *preload*/nls/\* => for config.locale and all config.extraLocale, load all bundles found in the best-matching bundle rollup. A value of 1 is returned, which is meaningless other than to say the plugin is executing the requested preloads
In cases 1 and 2, is always normalized to an absolute module id upon entry; see normalize. In case 3, it is assumed to be absolute; this is arranged by the builder.
To load a bundle means to insert the bundle into the plugin's cache and publish the bundle value to the loader. Given , , and a particular , the cache key
```
<path>/nls/<bundle>/<locale>
```
will hold the value. Similarly, then plugin will publish this value to the loader by
```
define("<path>/nls/<bundle>/<locale>", <bundle-value>);
```
Given this algorithm, other machinery can provide fast load paths be preplacing values in the plugin's cache, which is public. When a load is demanded the cache is inspected before starting any loading. Explicitly placing values in the plugin cache is an advanced/experimental feature that should not be needed; use at your own risk.
For the normal AMD algorithm, the root bundle is loaded first, which instructs the plugin what additional localized bundles are required for a particular locale. These additional locales are loaded and a mix of the root and each progressively-specific locale is returned. For example:
1. The client demands "dojo/i18n!some/path/nls/someBundle
2. The loader demands load(some/path/nls/someBundle)
3. This plugin require's "some/path/nls/someBundle", which is the root bundle.
4. Assuming config.locale is "ab-cd-ef" and the root bundle indicates that localizations are available for "ab" and "ab-cd-ef" (note the missing "ab-cd", then the plugin requires "some/path/nls/ab/someBundle" and "some/path/nls/ab-cd-ef/someBundle"
5. Upon receiving all required bundles, the plugin constructs the value of the bundle ab-cd-ef as...
```
mixin(mixin(mixin({}, require("some/path/nls/someBundle"),
require("some/path/nls/ab/someBundle")),
require("some/path/nls/ab-cd-ef/someBundle"));
```
This value is inserted into the cache and published to the loader at the key/module-id some/path/nls/someBundle/ab-cd-ef.
The special preload signature (case 3) instructs the plugin to stop servicing all normal requests (further preload requests will be serviced) until all ongoing preloading has completed.
The preload signature instructs the plugin that a special rollup module is available that contains one or more flattened, localized bundles. The JSON array of available locales indicates which locales are available. Here is an example:
```
*preload*some/path/nls/someModule*["root", "ab", "ab-cd-ef"]
```
This indicates the following rollup modules are available:
```
some/path/nls/someModule_ROOT
some/path/nls/someModule_ab
some/path/nls/someModule_ab-cd-ef
```
Each of these modules is a normal AMD module that contains one or more flattened bundles in a hash. For example, assume someModule contained the bundles some/bundle/path/someBundle and some/bundle/path/someOtherBundle, then some/path/nls/someModule\_ab would be expressed as follows:
```
define({
some/bundle/path/someBundle:<value of someBundle, flattened with respect to locale ab>,
some/bundle/path/someOtherBundle:<value of someOtherBundle, flattened with respect to locale ab>,
});
```
E.g., given this design, preloading for locale=="ab" can execute the following algorithm:
```
require(["some/path/nls/someModule_ab"], function(rollup){
for(var p in rollup){
var id = p + "/ab",
cache[id] = rollup[p];
define(id, rollup[p]);
}
});
```
Similarly, if "ab-cd" is requested, the algorithm can determine that "ab" is the best available and load accordingly.
The builder will write such rollups for every layer if a non-empty localeList profile property is provided. Further, the builder will include the following cache entry in the cache associated with any layer.
```
"*now":function(r){r(['dojo/i18n!*preload*<path>/nls/<module>*<JSON array of available locales>']);}
```
The \*now special cache module instructs the loader to apply the provided function to context-require with respect to the particular layer being defined. This causes the plugin to hold all normal service requests until all preloading is complete.
Notice that this algorithm is rarely better than the standard AMD load algorithm. Consider the normal case where the target locale has a single segment and a layer depends on a single bundle:
Without Preloads:
1. Layer loads root bundle.
2. bundle is demanded; plugin loads single localized bundle.
With Preloads:
1. Layer causes preloading of target bundle.
2. bundle is demanded; service is delayed until preloading complete; bundle is returned.
In each case a single transaction is required to load the target bundle. In cases where multiple bundles are required and/or the locale has multiple segments, preloads still requires a single transaction whereas the normal path requires an additional transaction for each additional bundle/locale-segment. However all of these additional transactions can be done concurrently. Owing to this analysis, the entire preloading algorithm can be discard during a build by setting the has feature dojo-preload-i18n-Api to false.
| Parameter | Type | Description |
| --- | --- | --- |
| id | undefined | |
| require | undefined | |
| load | undefined | |
###
`normalize``(id,toAbsMid)`
Defined by [dojo/i18n](../i18n)
id may be relative. preload has form `*preload*<path>/nls/<module>*<flattened locales>` and therefore never looks like a relative
| Parameter | Type | Description |
| --- | --- | --- |
| id | undefined | |
| toAbsMid | undefined | |
**Returns:** undefined
###
`normalizeLocale``(locale)`
Defined by [dojo/i18n](../i18n)
| Parameter | Type | Description |
| --- | --- | --- |
| locale | undefined | |
**Returns:** undefined
dojo dojo/_base/kernel.__IoPublish dojo/\_base/kernel.\_\_IoPublish
================================
Summary
-------
This is a list of IO topics that can be published if djConfig.ioPublish is set to true. IO topics can be published for any Input/Output, network operation. So, dojo.xhr, dojo.io.script and dojo.io.iframe can all trigger these topics to be published.
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new kernel.__IoPublish()`
Properties
----------
### done
Defined by: [dojo/\_base/xhr](xhr)
"/dojo/io/done" is sent whenever an IO request has completed, either by loading or by erroring. It passes the error and the dojo.Deferred for the request with the topic.
### error
Defined by: [dojo/\_base/xhr](xhr)
"/dojo/io/error" is sent whenever an IO request has errored. It passes the error and the dojo.Deferred for the request with the topic.
### load
Defined by: [dojo/\_base/xhr](xhr)
"/dojo/io/load" is sent whenever an IO request has loaded successfully. It passes the response and the dojo.Deferred for the request with the topic.
### send
Defined by: [dojo/\_base/xhr](xhr)
"/dojo/io/send" is sent whenever a new IO request is started. It passes the dojo.Deferred for the request with the topic.
### start
Defined by: [dojo/\_base/xhr](xhr)
"/dojo/io/start" is sent when there are no outstanding IO requests, and a new IO request is started. No arguments are passed with this topic.
### stop
Defined by: [dojo/\_base/xhr](xhr)
"/dojo/io/stop" is sent when all outstanding IO requests have finished. No arguments are passed with this topic.
dojo dojo/_base/config.modulePaths dojo/\_base/config.modulePaths
==============================
Summary
-------
A map of module names to paths relative to `dojo.baseUrl`. The key/value pairs correspond directly to the arguments which `dojo.registerModulePath` accepts. Specifying `djConfig.modulePaths = { "foo": "../../bar" }` is the equivalent of calling `dojo.registerModulePath("foo", "../../bar");`. Multiple modules may be configured via `djConfig.modulePaths`.
dojo dojo/_base/browser dojo/\_base/browser
===================
Summary
-------
This module causes the browser-only base modules to be loaded.
dojo dojo/_base/kernel.dnd dojo/\_base/kernel.dnd
======================
Properties
----------
### autoscroll
Defined by: [dojo/dnd/autoscroll](../dnd/autoscroll)
Used by [dojo/dnd/Manager](../dnd/manager) to scroll document or internal node when the user drags near the edge of the viewport or a scrollable node
### move
Defined by: [dojo/dnd/move](../dnd/move)
Methods
-------
###
`AutoSource``()`
Defined by [dojo/dnd/AutoSource](../dnd/autosource)
###
`Avatar``()`
Defined by [dojo/dnd/Avatar](../dnd/avatar)
###
`Container``()`
Defined by [dojo/dnd/Container](../dnd/container)
###
`Manager``()`
Defined by [dojo/dnd/Manager](../dnd/manager)
###
`Moveable``()`
Defined by [dojo/dnd/Moveable](../dnd/moveable)
###
`Mover``()`
Defined by [dojo/dnd/Mover](../dnd/mover)
###
`Selector``()`
Defined by [dojo/dnd/Selector](../dnd/selector)
###
`Source``()`
Defined by [dojo/dnd/Source](../dnd/source)
###
`Target``()`
Defined by [dojo/dnd/Target](../dnd/target)
###
`TimedMoveable``()`
Defined by [dojo/dnd/TimedMoveable](../dnd/timedmoveable)
dojo dojo/_base/kernel.version dojo/\_base/kernel.version
==========================
Summary
-------
Version number of the Dojo Toolkit
Hash about the version, including
* major: Integer: Major version. If total version is "1.2.0beta1", will be 1
* minor: Integer: Minor version. If total version is "1.2.0beta1", will be 2
* patch: Integer: Patch version. If total version is "1.2.0beta1", will be 0
* flag: String: Descriptor flag. If total version is "1.2.0beta1", will be "beta1"
* revision: Number: The Git rev from which dojo was pulled
Properties
----------
### flag
Defined by: [dojo/\_base/kernel](kernel)
### major
Defined by: [dojo/\_base/kernel](kernel)
### minor
Defined by: [dojo/\_base/kernel](kernel)
### patch
Defined by: [dojo/\_base/kernel](kernel)
### revision
Defined by: [dojo/\_base/kernel](kernel)
Methods
-------
###
`toString``()`
Defined by [dojo/\_base/kernel](kernel)
**Returns:** string
dojo dojo/_base/kernel.rpc dojo/\_base/kernel.rpc
======================
Methods
-------
###
`JsonpService``()`
Defined by [dojo/rpc/JsonpService](../rpc/jsonpservice)
###
`JsonService``()`
Defined by [dojo/rpc/JsonService](../rpc/jsonservice)
###
`RpcService``()`
Defined by [dojo/rpc/RpcService](../rpc/rpcservice)
dojo dojo/_base/window dojo/\_base/window
==================
Summary
-------
API to save/set/restore the global/document scope.
See the [dojo/\_base/window reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/window.html) for more information.
Properties
----------
### doc
Defined by: [dojo/\_base/window](window)
Alias for the current document. 'doc' can be modified for temporary context shifting. See also withDoc().
### global
Defined by: [dojo/\_base/window](window)
Alias for the current window. 'global' can be modified for temporary context shifting. See also withGlobal().
Methods
-------
###
`body``(doc)`
Defined by [dojo/\_base/window](window)
Return the body element of the specified document or of dojo/\_base/window::doc.
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | *Optional* |
**Returns:** undefined
Examples
--------
### Example 1
```
win.body().appendChild(dojo.doc.createElement('div'));
```
###
`setContext``(globalObject,globalDocument)`
Defined by [dojo/\_base/window](window)
changes the behavior of many core Dojo functions that deal with namespace and DOM lookup, changing them to work in a new global context (e.g., an iframe). The varibles dojo.global and dojo.doc are modified as a result of calling this function and the result of `dojo.body()` likewise differs.
| Parameter | Type | Description |
| --- | --- | --- |
| globalObject | Object | |
| globalDocument | DocumentElement | |
###
`withDoc``(documentObject,callback,thisObject,cbArguments)`
Defined by [dojo/\_base/window](window)
Invoke callback with documentObject as dojo/\_base/window::doc.
Invoke callback with documentObject as [dojo/\_base/window](window)::doc. If provided, callback will be executed in the context of object thisObject When callback() returns or throws an error, the [dojo/\_base/window](window)::doc will be restored to its previous state.
| Parameter | Type | Description |
| --- | --- | --- |
| documentObject | DocumentElement | |
| callback | Function | |
| thisObject | Object | *Optional* |
| cbArguments | Array | *Optional* |
**Returns:** undefined
###
`withGlobal``(globalObject,callback,thisObject,cbArguments)`
Defined by [dojo/\_base/window](window)
Invoke callback with globalObject as dojo.global and globalObject.document as dojo.doc.
Invoke callback with globalObject as dojo.global and globalObject.document as dojo.doc. If provided, globalObject will be executed in the context of object thisObject When callback() returns or throws an error, the dojo.global and dojo.doc will be restored to its previous state.
| Parameter | Type | Description |
| --- | --- | --- |
| globalObject | Object | |
| callback | Function | |
| thisObject | Object | *Optional* |
| cbArguments | Array | *Optional* |
**Returns:** undefined
dojo dojo/_base/fx dojo/\_base/fx
==============
Summary
-------
This module defines the base [dojo/\_base/fx](fx) implementation.
See the [dojo/\_base/fx reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/fx.html) for more information.
Methods
-------
###
`anim``(node,properties,duration,easing,onEnd,delay)`
Defined by [dojo/\_base/fx](fx)
A simpler interface to `animateProperty()`, also returns an instance of `Animation` but begins the animation immediately, unlike nearly every other Dojo animation API.
Simpler (but somewhat less powerful) version of `animateProperty`. It uses defaults for many basic properties and allows for positional parameters to be used in place of the packed "property bag" which is used for other Dojo animation methods.
The `Animation` object returned will be already playing, so calling play() on it again is (usually) a no-op.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | a DOM node or the id of a node to animate CSS properties on |
| properties | Object | |
| duration | Integer | *Optional*
The number of milliseconds over which the animation should run. Defaults to the global animation default duration (350ms). |
| easing | Function | *Optional*
An easing function over which to calculate acceleration and deceleration of the animation through its duration. A default easing algorithm is provided, but you may plug in any you wish. A large selection of easing algorithms are available in `dojo/fx/easing`. |
| onEnd | Function | *Optional*
A function to be called when the animation finishes running. |
| delay | Integer | *Optional*
The number of milliseconds to delay beginning the animation by. The default is 0. |
**Returns:** undefined
Examples
--------
### Example 1
Fade out a node
```
basefx.anim("id", { opacity: 0 });
```
### Example 2
Fade out a node over a full second
```
basefx.anim("id", { opacity: 0 }, 1000);
```
###
`animateProperty``(args)`
Defined by [dojo/\_base/fx](fx)
Returns an animation that will transition the properties of node defined in `args` depending how they are defined in `args.properties`
Foundation of most [dojo/\_base/fx](fx) animations. It takes an object of "properties" corresponding to style properties, and animates them in parallel over a set duration.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* properties (Object, optional): A hash map of style properties to Objects describing the transition, such as the properties of \_Line with an additional 'units' property
* node (DOMNode|String): The node referenced in the animation
* duration (Integer, optional): Duration of the animation in milliseconds.
* easing (Function, optional): An easing function.
|
**Returns:** instance
Examples
--------
### Example 1
A simple animation that changes the width of the specified node.
```
basefx.animateProperty({
node: "nodeId",
properties: { width: 400 },
}).play();
```
Dojo figures out the start value for the width and converts the
integer specified for the width to the more expressive but verbose form `{ width: { end: '400', units: 'px' } }` which you can also specify directly. Defaults to 'px' if omitted.
### Example 2
Animate width, height, and padding over 2 seconds... the pedantic way:
```
basefx.animateProperty({ node: node, duration:2000,
properties: {
width: { start: '200', end: '400', units:"px" },
height: { start:'200', end: '400', units:"px" },
paddingTop: { start:'5', end:'50', units:"px" }
}
}).play();
```
Note 'paddingTop' is used over 'padding-top'. Multi-name CSS properties
are written using "mixed case", as the hyphen is illegal as an object key.
### Example 3
Plug in a different easing function and register a callback for when the animation ends. Easing functions accept values between zero and one and return a value on that basis. In this case, an exponential-in curve.
```
basefx.animateProperty({
node: "nodeId",
// dojo figures out the start value
properties: { width: { end: 400 } },
easing: function(n){
return (n==0) ? 0 : Math.pow(2, 10 * (n - 1));
},
onEnd: function(node){
// called when the animation finishes. The animation
// target is passed to this function
}
}).play(500); // delay playing half a second
```
### Example 4
Like all `Animation`s, animateProperty returns a handle to the Animation instance, which fires the events common to Dojo FX. Use `aspect.after` to access these events outside of the Animation definition:
```
var anim = basefx.animateProperty({
node:"someId",
properties:{
width:400, height:500
}
});
aspect.after(anim, "onEnd", function(){
console.log("animation ended");
}, true);
// play the animation now:
anim.play();
```
### Example 5
Each property can be a function whose return value is substituted along. Additionally, each measurement (eg: start, end) can be a function. The node reference is passed directly to callbacks.
```
basefx.animateProperty({
node:"mine",
properties:{
height:function(node){
// shrink this node by 50%
return domGeom.position(node).h / 2
},
width:{
start:function(node){ return 100; },
end:function(node){ return 200; }
}
}
}).play();
```
###
`Animation``(args)`
Defined by [dojo/\_base/fx](fx)
A generic animation class that fires callbacks into its handlers object at various states.
A generic animation class that fires callbacks into its handlers object at various states. Nearly all dojo animation functions return an instance of this method, usually without calling the .play() method beforehand. Therefore, you will likely need to call .play() on instances of `Animation` when one is returned.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | The 'magic argument', mixing all the properties into this animation instance. |
###
`fadeIn``(args)`
Defined by [dojo/\_base/fx](fx)
Returns an animation that will fade node defined in 'args' from its current opacity to fully opaque.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* node (DOMNode|String): The node referenced in the animation
* duration (Integer, optional): Duration of the animation in milliseconds.
* easing (Function, optional): An easing function.
|
**Returns:** undefined
###
`fadeOut``(args)`
Defined by [dojo/\_base/fx](fx)
Returns an animation that will fade node defined in 'args' from its current opacity to fully transparent.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* node (DOMNode|String): The node referenced in the animation
* duration (Integer, optional): Duration of the animation in milliseconds.
* easing (Function, optional): An easing function.
|
**Returns:** undefined
| programming_docs |
dojo dojo/_base/kernel.Stateful dojo/\_base/kernel.Stateful
===========================
Summary
-------
Base class for objects that provide named properties with optional getter/setter control and the ability to watch for property changes
The class also provides the functionality to auto-magically manage getters and setters for object attributes/properties.
Getters and Setters should follow the format of \_xxxGetter or \_xxxSetter where the xxx is a name of the attribute to handle. So an attribute of "foo" would have a custom getter of \_fooGetter and a custom setter of \_fooSetter.
Examples
--------
### Example 1
```
require(["dojo/Stateful", function(Stateful) {
var obj = new Stateful();
obj.watch("foo", function(){
console.log("foo changed to " + this.get("foo"));
});
obj.set("foo","bar");
});
```
Properties
----------
Methods
-------
###
`get``(name)`
Defined by [dojo/Stateful](../stateful)
Get a property on a Stateful instance.
Get a named property on a Stateful object. The property may potentially be retrieved via a getter method in subclasses. In the base class this just retrieves the object's property.
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | The property to get. |
**Returns:** any | undefined
The property value on this Stateful instance.
Examples
--------
### Example 1
```
require(["dojo/Stateful", function(Stateful) {
var stateful = new Stateful({foo: 3});
stateful.get("foo") // returns 3
stateful.foo // returns 3
});
```
###
`postscript``(params)`
Defined by [dojo/Stateful](../stateful)
| Parameter | Type | Description |
| --- | --- | --- |
| params | Object | *Optional* |
###
`set``(name,value)`
Defined by [dojo/Stateful](../stateful)
Set a property on a Stateful instance
Sets named properties on a stateful object and notifies any watchers of the property. A programmatic setter may be defined in subclasses.
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | The property to set. |
| value | Object | The value to set in the property. |
**Returns:** any | function
The function returns this dojo.Stateful instance.
Examples
--------
### Example 1
```
require(["dojo/Stateful", function(Stateful) {
var stateful = new Stateful();
stateful.watch(function(name, oldValue, value){
// this will be called on the set below
}
stateful.set(foo, 5);
```
set() may also be called with a hash of name/value pairs, ex:
```
stateful.set({
foo: "Howdy",
bar: 3
});
});
```
This is equivalent to calling set(foo, "Howdy") and set(bar, 3)
###
`watch``(name,callback)`
Defined by [dojo/Stateful](../stateful)
Watches a property for changes
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | *Optional*
Indicates the property to watch. This is optional (the callback may be the only parameter), and if omitted, all the properties will be watched |
| callback | Function | The function to execute when the property changes. This will be called after the property has been changed. The callback will be called with the |this| set to the instance, the first argument as the name of the property, the second argument as the old value and the third argument as the new value. |
**Returns:** any | object
An object handle for the watch. The unwatch method of this object can be used to discontinue watching this property:
```
var watchHandle = obj.watch("foo", callback);
watchHandle.unwatch(); // callback won't be called now
```
dojo dojo/_base/kernel.doc dojo/\_base/kernel.doc
======================
Summary
-------
Alias for the current document. 'doc' can be modified for temporary context shifting. See also withDoc().
Use this rather than referring to 'window.document' to ensure your code runs correctly in managed contexts.
Examples
--------
### Example 1
```
n.appendChild(dojo.doc.createElement('div'));
```
Properties
----------
### documentElement
Defined by: [dojox/gfx/\_base](http://dojotoolkit.org/api/1.10/dojox/gfx/_base)
### dojoClick
Defined by: [dojox/mobile/common](http://dojotoolkit.org/api/1.10/dojox/mobile/common)
dojo dojo/_base/kernel.__IoArgs dojo/\_base/kernel.\_\_IoArgs
=============================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new kernel.__IoArgs()`
Properties
----------
### content
Defined by: [dojo/\_base/xhr](xhr)
Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
### form
Defined by: [dojo/\_base/xhr](xhr)
DOM node for a form. Used to extract the form values and send to the server.
### handleAs
Defined by: [dojo/\_base/xhr](xhr)
Acceptable values depend on the type of IO transport (see specific IO calls for more information).
### ioPublish
Defined by: [dojo/\_base/xhr](xhr)
Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via [dojo/topic.publish()](../topic#publish) for different phases of an IO operation. See [dojo/main.\_\_IoPublish](../main.__iopublish) for a list of topics that are published.
### preventCache
Defined by: [dojo/\_base/xhr](xhr)
Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
### rawBody
Defined by: [dojo/\_base/xhr](xhr)
Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for [dojo/\_base/xhr.rawXhrPost](xhr#rawXhrPost) and [dojo/\_base/xhr.rawXhrPut](xhr#rawXhrPut) respectively.
### timeout
Defined by: [dojo/\_base/xhr](xhr)
Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
### url
Defined by: [dojo/\_base/xhr](xhr)
URL to server endpoint.
Methods
-------
###
`error``(response,ioArgs)`
Defined by [dojo/\_base/xhr](xhr)
This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
| Parameter | Type | Description |
| --- | --- | --- |
| response | Object | The response in the format as defined with handleAs. |
| ioArgs | [dojo/main.\_\_IoCallbackArgs](../main.__iocallbackargs) | Provides additional information about the request. |
###
`handle``(loadOrError,response,ioArgs)`
Defined by [dojo/\_base/xhr](xhr)
This function will be called at the end of every request, whether or not an error occurs.
| Parameter | Type | Description |
| --- | --- | --- |
| loadOrError | String | Provides a string that tells you whether this function was called because of success (load) or failure (error). |
| response | Object | The response in the format as defined with handleAs. |
| ioArgs | [dojo/main.\_\_IoCallbackArgs](../main.__iocallbackargs) | Provides additional information about the request. |
###
`load``(response,ioArgs)`
Defined by [dojo/\_base/xhr](xhr)
This function will be called on a successful HTTP response code.
| Parameter | Type | Description |
| --- | --- | --- |
| response | Object | The response in the format as defined with handleAs. |
| ioArgs | [dojo/main.\_\_IoCallbackArgs](../main.__iocallbackargs) | Provides additional information about the request. |
dojo dojo/_base/html dojo/\_base/html
================
Summary
-------
This module is a stub for the core dojo DOM API.
See the [dojo/\_base/html reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/html.html) for more information.
dojo dojo/_base/Color.named dojo/\_base/Color.named
=======================
Summary
-------
Dictionary list of all CSS named colors, by name. Values are 3-item arrays with corresponding RG and B values.
Properties
----------
### aliceblue
Defined by: [dojo/colors](../colors)
### antiquewhite
Defined by: [dojo/colors](../colors)
### aqua
Defined by: [dojo/\_base/Color](color)
### aquamarine
Defined by: [dojo/colors](../colors)
### azure
Defined by: [dojo/colors](../colors)
### beige
Defined by: [dojo/colors](../colors)
### bisque
Defined by: [dojo/colors](../colors)
### black
Defined by: [dojo/\_base/Color](color)
### blanchedalmond
Defined by: [dojo/colors](../colors)
### blue
Defined by: [dojo/\_base/Color](color)
### blueviolet
Defined by: [dojo/colors](../colors)
### brown
Defined by: [dojo/colors](../colors)
### burlywood
Defined by: [dojo/colors](../colors)
### cadetblue
Defined by: [dojo/colors](../colors)
### chartreuse
Defined by: [dojo/colors](../colors)
### chocolate
Defined by: [dojo/colors](../colors)
### coral
Defined by: [dojo/colors](../colors)
### cornflowerblue
Defined by: [dojo/colors](../colors)
### cornsilk
Defined by: [dojo/colors](../colors)
### crimson
Defined by: [dojo/colors](../colors)
### cyan
Defined by: [dojo/colors](../colors)
### darkblue
Defined by: [dojo/colors](../colors)
### darkcyan
Defined by: [dojo/colors](../colors)
### darkgoldenrod
Defined by: [dojo/colors](../colors)
### darkgray
Defined by: [dojo/colors](../colors)
### darkgreen
Defined by: [dojo/colors](../colors)
### darkgrey
Defined by: [dojo/colors](../colors)
### darkkhaki
Defined by: [dojo/colors](../colors)
### darkmagenta
Defined by: [dojo/colors](../colors)
### darkolivegreen
Defined by: [dojo/colors](../colors)
### darkorange
Defined by: [dojo/colors](../colors)
### darkorchid
Defined by: [dojo/colors](../colors)
### darkred
Defined by: [dojo/colors](../colors)
### darksalmon
Defined by: [dojo/colors](../colors)
### darkseagreen
Defined by: [dojo/colors](../colors)
### darkslateblue
Defined by: [dojo/colors](../colors)
### darkslategray
Defined by: [dojo/colors](../colors)
### darkslategrey
Defined by: [dojo/colors](../colors)
### darkturquoise
Defined by: [dojo/colors](../colors)
### darkviolet
Defined by: [dojo/colors](../colors)
### deeppink
Defined by: [dojo/colors](../colors)
### deepskyblue
Defined by: [dojo/colors](../colors)
### dimgray
Defined by: [dojo/colors](../colors)
### dimgrey
Defined by: [dojo/colors](../colors)
### dodgerblue
Defined by: [dojo/colors](../colors)
### firebrick
Defined by: [dojo/colors](../colors)
### floralwhite
Defined by: [dojo/colors](../colors)
### forestgreen
Defined by: [dojo/colors](../colors)
### fuchsia
Defined by: [dojo/\_base/Color](color)
### gainsboro
Defined by: [dojo/colors](../colors)
### ghostwhite
Defined by: [dojo/colors](../colors)
### gold
Defined by: [dojo/colors](../colors)
### goldenrod
Defined by: [dojo/colors](../colors)
### gray
Defined by: [dojo/\_base/Color](color)
### green
Defined by: [dojo/\_base/Color](color)
### greenyellow
Defined by: [dojo/colors](../colors)
### grey
Defined by: [dojo/colors](../colors)
### honeydew
Defined by: [dojo/colors](../colors)
### hotpink
Defined by: [dojo/colors](../colors)
### indianred
Defined by: [dojo/colors](../colors)
### indigo
Defined by: [dojo/colors](../colors)
### ivory
Defined by: [dojo/colors](../colors)
### khaki
Defined by: [dojo/colors](../colors)
### lavender
Defined by: [dojo/colors](../colors)
### lavenderblush
Defined by: [dojo/colors](../colors)
### lawngreen
Defined by: [dojo/colors](../colors)
### lemonchiffon
Defined by: [dojo/colors](../colors)
### lightblue
Defined by: [dojo/colors](../colors)
### lightcoral
Defined by: [dojo/colors](../colors)
### lightcyan
Defined by: [dojo/colors](../colors)
### lightgoldenrodyellow
Defined by: [dojo/colors](../colors)
### lightgray
Defined by: [dojo/colors](../colors)
### lightgreen
Defined by: [dojo/colors](../colors)
### lightgrey
Defined by: [dojo/colors](../colors)
### lightpink
Defined by: [dojo/colors](../colors)
### lightsalmon
Defined by: [dojo/colors](../colors)
### lightseagreen
Defined by: [dojo/colors](../colors)
### lightskyblue
Defined by: [dojo/colors](../colors)
### lightslategray
Defined by: [dojo/colors](../colors)
### lightslategrey
Defined by: [dojo/colors](../colors)
### lightsteelblue
Defined by: [dojo/colors](../colors)
### lightyellow
Defined by: [dojo/colors](../colors)
### lime
Defined by: [dojo/\_base/Color](color)
### limegreen
Defined by: [dojo/colors](../colors)
### linen
Defined by: [dojo/colors](../colors)
### magenta
Defined by: [dojo/colors](../colors)
### maroon
Defined by: [dojo/\_base/Color](color)
### mediumaquamarine
Defined by: [dojo/colors](../colors)
### mediumblue
Defined by: [dojo/colors](../colors)
### mediumorchid
Defined by: [dojo/colors](../colors)
### mediumpurple
Defined by: [dojo/colors](../colors)
### mediumseagreen
Defined by: [dojo/colors](../colors)
### mediumslateblue
Defined by: [dojo/colors](../colors)
### mediumspringgreen
Defined by: [dojo/colors](../colors)
### mediumturquoise
Defined by: [dojo/colors](../colors)
### mediumvioletred
Defined by: [dojo/colors](../colors)
### midnightblue
Defined by: [dojo/colors](../colors)
### mintcream
Defined by: [dojo/colors](../colors)
### mistyrose
Defined by: [dojo/colors](../colors)
### moccasin
Defined by: [dojo/colors](../colors)
### navajowhite
Defined by: [dojo/colors](../colors)
### navy
Defined by: [dojo/\_base/Color](color)
### oldlace
Defined by: [dojo/colors](../colors)
### olive
Defined by: [dojo/\_base/Color](color)
### olivedrab
Defined by: [dojo/colors](../colors)
### orange
Defined by: [dojo/colors](../colors)
### orangered
Defined by: [dojo/colors](../colors)
### orchid
Defined by: [dojo/colors](../colors)
### palegoldenrod
Defined by: [dojo/colors](../colors)
### palegreen
Defined by: [dojo/colors](../colors)
### paleturquoise
Defined by: [dojo/colors](../colors)
### palevioletred
Defined by: [dojo/colors](../colors)
### papayawhip
Defined by: [dojo/colors](../colors)
### peachpuff
Defined by: [dojo/colors](../colors)
### peru
Defined by: [dojo/colors](../colors)
### pink
Defined by: [dojo/colors](../colors)
### plum
Defined by: [dojo/colors](../colors)
### powderblue
Defined by: [dojo/colors](../colors)
### purple
Defined by: [dojo/\_base/Color](color)
### red
Defined by: [dojo/\_base/Color](color)
### rosybrown
Defined by: [dojo/colors](../colors)
### royalblue
Defined by: [dojo/colors](../colors)
### saddlebrown
Defined by: [dojo/colors](../colors)
### salmon
Defined by: [dojo/colors](../colors)
### sandybrown
Defined by: [dojo/colors](../colors)
### seagreen
Defined by: [dojo/colors](../colors)
### seashell
Defined by: [dojo/colors](../colors)
### sienna
Defined by: [dojo/colors](../colors)
### silver
Defined by: [dojo/\_base/Color](color)
### skyblue
Defined by: [dojo/colors](../colors)
### slateblue
Defined by: [dojo/colors](../colors)
### slategray
Defined by: [dojo/colors](../colors)
### slategrey
Defined by: [dojo/colors](../colors)
### snow
Defined by: [dojo/colors](../colors)
### springgreen
Defined by: [dojo/colors](../colors)
### steelblue
Defined by: [dojo/colors](../colors)
### tan
Defined by: [dojo/colors](../colors)
### teal
Defined by: [dojo/\_base/Color](color)
### thistle
Defined by: [dojo/colors](../colors)
### tomato
Defined by: [dojo/colors](../colors)
### transparent
Defined by: [dojo/\_base/Color](color)
### turquoise
Defined by: [dojo/colors](../colors)
### violet
Defined by: [dojo/colors](../colors)
### wheat
Defined by: [dojo/colors](../colors)
### white
Defined by: [dojo/\_base/Color](color)
### whitesmoke
Defined by: [dojo/colors](../colors)
### yellow
Defined by: [dojo/\_base/Color](color)
### yellowgreen
Defined by: [dojo/colors](../colors)
dojo dojo/_base/kernel.fx dojo/\_base/kernel.fx
=====================
Summary
-------
Effects library on top of Base animations
Properties
----------
### easing
Defined by: [dojo/fx/easing](../fx/easing)
Collection of easing functions to use beyond the default `dojo._defaultEasing` function.
Methods
-------
###
`chain``(animations)`
Defined by [dojo/fx](../fx)
Chain a list of `dojo/_base/fx.Animation`s to run in sequence
Return a [dojo/\_base/fx.Animation](fx#Animation) which will play all passed [dojo/\_base/fx.Animation](fx#Animation) instances in sequence, firing its own synthesized events simulating a single animation. (eg: onEnd of this animation means the end of the chain, not the individual animations within)
| Parameter | Type | Description |
| --- | --- | --- |
| animations | [dojo/\_base/fx.Animation](fx#Animation)[] | |
**Returns:** instance
Examples
--------
### Example 1
Once `node` is faded out, fade in `otherNode`
```
require(["dojo/fx"], function(fx){
fx.chain([
fx.fadeIn({ node:node }),
fx.fadeOut({ node:otherNode })
]).play();
});
```
###
`combine``(animations)`
Defined by [dojo/fx](../fx)
Combine a list of `dojo/_base/fx.Animation`s to run in parallel
Combine an array of [dojo/\_base/fx.Animation](fx#Animation)s to run in parallel, providing a new [dojo/\_base/fx.Animation](fx#Animation) instance encompasing each animation, firing standard animation events.
| Parameter | Type | Description |
| --- | --- | --- |
| animations | [dojo/\_base/fx.Animation](fx#Animation)[] | |
**Returns:** instance
Examples
--------
### Example 1
Fade out `node` while fading in `otherNode` simultaneously
```
require(["dojo/fx"], function(fx){
fx.combine([
fx.fadeIn({ node:node }),
fx.fadeOut({ node:otherNode })
]).play();
});
```
### Example 2
When the longest animation ends, execute a function:
```
require(["dojo/fx"], function(fx){
var anim = fx.combine([
fx.fadeIn({ node: n, duration:700 }),
fx.fadeOut({ node: otherNode, duration: 300 })
]);
aspect.after(anim, "onEnd", function(){
// overall animation is done.
}, true);
anim.play(); // play the animation
});
```
###
`slideTo``(args)`
Defined by [dojo/fx](../fx)
Slide a node to a new top/left position
Returns an animation that will slide "node" defined in args Object from its current position to the position defined by (args.left, args.top).
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | A hash-map of standard `dojo/_base/fx.Animation` constructor properties (such as easing: node: duration: and so on). Special args members are `top` and `left`, which indicate the new position to slide to. |
**Returns:** undefined
Examples
--------
### Example 1
```
.slideTo({ node: node, left:"40", top:"50", units:"px" }).play()
```
###
`Toggler``()`
Defined by [dojo/fx/Toggler](../fx/toggler)
###
`wipeIn``(args)`
Defined by [dojo/fx](../fx)
Expand a node to it's natural height.
Returns an animation that will expand the node defined in 'args' object from it's current height to it's natural height (with no scrollbar). Node must have no margin/border/padding.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | A hash-map of standard `dojo/_base/fx.Animation` constructor properties (such as easing: node: duration: and so on) |
**Returns:** undefined
Examples
--------
### Example 1
```
require(["dojo/fx"], function(fx){
fx.wipeIn({
node:"someId"
}).play()
});
```
###
`wipeOut``(args)`
Defined by [dojo/fx](../fx)
Shrink a node to nothing and hide it.
Returns an animation that will shrink node defined in "args" from it's current height to 1px, and then hide it.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | A hash-map of standard `dojo/_base/fx.Animation` constructor properties (such as easing: node: duration: and so on) |
**Returns:** undefined
Examples
--------
### Example 1
```
require(["dojo/fx"], function(fx){
fx.wipeOut({ node:"someId" }).play()
});
```
| programming_docs |
dojo dojo/_base/kernel.number dojo/\_base/kernel.number
=========================
Summary
-------
localized formatting and parsing routines for Number
Properties
----------
Methods
-------
###
`format``(value,options)`
Defined by [dojo/number](../number)
Format a Number as a String, using locale-specific settings
Create a string from a Number using a known localized pattern. Formatting patterns appropriate to the locale are chosen from the [Common Locale Data Repository](http://unicode.org/cldr) as well as the appropriate symbols and delimiters. If value is Infinity, -Infinity, or is not a valid JavaScript number, return null.
| Parameter | Type | Description |
| --- | --- | --- |
| value | Number | the number to be formatted |
| options | Object | *Optional*
An object with the following properties:* pattern (String, optional): override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization. Literal characters in patterns are not supported.
* type (String, optional): choose a format type based on the locale from the following: decimal, scientific (not yet supported), percent, currency. decimal by default.
* places (Number, optional): fixed number of decimal places to show. This overrides any information in the provided pattern.
* round (Number, optional): 5 rounds to nearest .5; 0 rounds to nearest whole (default). -1 means do not round.
* locale (String, optional): override the locale used to determine formatting rules
* fractional (Boolean, optional): If false, show no decimal places, overriding places and pattern settings.
|
**Returns:** null | undefined
###
`parse``(expression,options)`
Defined by [dojo/number](../number)
Convert a properly formatted string to a primitive Number, using locale-specific settings.
Create a Number from a string using a known localized pattern. Formatting patterns are chosen appropriate to the locale and follow the syntax described by [unicode.org TR35](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) Note that literal characters in patterns are not supported.
| Parameter | Type | Description |
| --- | --- | --- |
| expression | String | A string representation of a Number |
| options | Object | *Optional*
An object with the following properties:* pattern (String, optional): override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization. Literal characters in patterns are not supported.
* type (String, optional): choose a format type based on the locale from the following: decimal, scientific (not yet supported), percent, currency. decimal by default.
* locale (String, optional): override the locale used to determine formatting rules
* strict (Boolean, optional): strict parsing, false by default. Strict parsing requires input as produced by the format() method. Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
* fractional (Boolean|Array, optional): Whether to include the fractional portion, where the number of decimal places are implied by pattern or explicit 'places' parameter. The value [true,false] makes the fractional portion optional.
|
**Returns:** number
###
`regexp``(options)`
Defined by [dojo/number](../number)
Builds the regular needed to parse a number
Returns regular expression with positive and negative match, group and decimal separators
| Parameter | Type | Description |
| --- | --- | --- |
| options | Object | *Optional*
An object with the following properties:* pattern (String, optional): override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization.
* type (String, optional): choose a format type based on the locale from the following: decimal, scientific (not yet supported), percent, currency. decimal by default.
* locale (String, optional): override the locale used to determine formatting rules
* strict (Boolean, optional): strict parsing, false by default. Strict parsing requires input as produced by the format() method. Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
* places (Number|String, optional): number of decimal places to accept: Infinity, a positive number, or a range "n,m". Defined by pattern or Infinity if pattern not provided.
|
**Returns:** undefined
###
`round``(value,places,increment)`
Defined by [dojo/number](../number)
Rounds to the nearest value with the given number of decimal places, away from zero
Rounds to the nearest value with the given number of decimal places, away from zero if equal. Similar to Number.toFixed(), but compensates for browser quirks. Rounding can be done by fractional increments also, such as the nearest quarter. NOTE: Subject to floating point errors. See [dojox/math/round](http://dojotoolkit.org/api/1.10/dojox/math/round) for experimental workaround.
| Parameter | Type | Description |
| --- | --- | --- |
| value | Number | The number to round |
| places | Number | *Optional*
The number of decimal places where rounding takes place. Defaults to 0 for whole rounding. Must be non-negative. |
| increment | Number | *Optional*
Rounds next place to nearest value of increment/10. 10 by default. |
**Returns:** number
Examples
--------
### Example 1
```
>>> number.round(-0.5)
-1
>>> number.round(162.295, 2)
162.29 // note floating point error. Should be 162.3
>>> number.round(10.71, 0, 2.5)
10.75
```
dojo dojo/_base/kernel.io dojo/\_base/kernel.io
=====================
Properties
----------
### iframe
Defined by: [dojo/io/iframe](../io/iframe)
### script
Defined by: [dojo/io/script](../io/script)
TODOC
dojo dojo/_base/json dojo/\_base/json
================
Summary
-------
This module defines the dojo JSON API.
See the [dojo/\_base/json reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/json.html) for more information.
dojo dojo/_base/kernel.date dojo/\_base/kernel.date
=======================
Properties
----------
### stamp
Defined by: [dojo/date/stamp](../date/stamp)
TODOC
Methods
-------
###
`add``(date,interval,amount)`
Defined by [dojo/date](../date)
Add to a Date in intervals of different size, from milliseconds to years
| Parameter | Type | Description |
| --- | --- | --- |
| date | Date | Date object to start with |
| interval | String | A string representing the interval. One of the following: "year", "month", "day", "hour", "minute", "second", "millisecond", "quarter", "week", "weekday" |
| amount | int | How much to add to the date. |
**Returns:** instance
###
`compare``(date1,date2,portion)`
Defined by [dojo/date](../date)
Compare two date objects by date, time, or both.
Returns 0 if equal, positive if a > b, else negative.
| Parameter | Type | Description |
| --- | --- | --- |
| date1 | Date | Date object |
| date2 | Date | *Optional*
Date object. If not specified, the current Date is used. |
| portion | String | *Optional*
A string indicating the "date" or "time" portion of a Date object. Compares both "date" and "time" by default. One of the following: "date", "time", "datetime" |
**Returns:** number
###
`difference``(date1,date2,interval)`
Defined by [dojo/date](../date)
Get the difference in a specific unit of time (e.g., number of months, weeks, days, etc.) between two dates, rounded to the nearest integer.
| Parameter | Type | Description |
| --- | --- | --- |
| date1 | Date | Date object |
| date2 | Date | *Optional*
Date object. If not specified, the current Date is used. |
| interval | String | *Optional*
A string representing the interval. One of the following: "year", "month", "day", "hour", "minute", "second", "millisecond", "quarter", "week", "weekday" Defaults to "day". |
**Returns:** undefined
###
`getDaysInMonth``(dateObject)`
Defined by [dojo/date](../date)
Returns the number of days in the month used by dateObject
| Parameter | Type | Description |
| --- | --- | --- |
| dateObject | Date | |
**Returns:** number | undefined
###
`getTimezoneName``(dateObject)`
Defined by [dojo/date](../date)
Get the user's time zone as provided by the browser
Try to get time zone info from toString or toLocaleString method of the Date object -- UTC offset is not a time zone. See <http://www.twinsun.com/tz/tz-link.htm> Note: results may be inconsistent across browsers.
| Parameter | Type | Description |
| --- | --- | --- |
| dateObject | Date | Needed because the timezone may vary with time (daylight savings) |
**Returns:** undefined
###
`isLeapYear``(dateObject)`
Defined by [dojo/date](../date)
Determines if the year of the dateObject is a leap year
Leap years are years with an additional day YYYY-02-29, where the year number is a multiple of four with the following exception: If a year is a multiple of 100, then it is only a leap year if it is also a multiple of 400. For example, 1900 was not a leap year, but 2000 is one.
| Parameter | Type | Description |
| --- | --- | --- |
| dateObject | Date | |
**Returns:** boolean
dojo dojo/_base/kernel.__IoCallbackArgs dojo/\_base/kernel.\_\_IoCallbackArgs
=====================================
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new kernel.__IoCallbackArgs()`
Properties
----------
### args
Defined by: [dojo/\_base/xhr](xhr)
the original object argument to the IO call.
### canDelete
Defined by: [dojo/\_base/xhr](xhr)
For [dojo/io/script](../io/script) calls only, indicates whether the script tag that represents the request can be deleted after callbacks have been called. Used internally to know when cleanup can happen on JSONP-type requests.
### handleAs
Defined by: [dojo/\_base/xhr](xhr)
The final indicator on how the response will be handled.
### id
Defined by: [dojo/\_base/xhr](xhr)
For [dojo/io/script](../io/script) calls only, the internal script ID used for the request.
### json
Defined by: [dojo/\_base/xhr](xhr)
For [dojo/io/script](../io/script) calls only: holds the JSON response for JSONP-type requests. Used internally to hold on to the JSON responses. You should not need to access it directly -- the same object should be passed to the success callbacks directly.
### query
Defined by: [dojo/\_base/xhr](xhr)
For non-GET requests, the name1=value1&name2=value2 parameters sent up in the request.
### url
Defined by: [dojo/\_base/xhr](xhr)
The final URL used for the call. Many times it will be different than the original args.url value.
### xhr
Defined by: [dojo/\_base/xhr](xhr)
For XMLHttpRequest calls only, the XMLHttpRequest object that was used for the request.
dojo dojo/_base/loader dojo/\_base/loader
==================
See the [dojo/\_base/loader reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/loader.html) for more information.
dojo dojo/_base/lang dojo/\_base/lang
================
Summary
-------
This module defines Javascript language extensions.
See the [dojo/\_base/lang reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/lang.html) for more information.
Properties
----------
Methods
-------
###
`clone``(src)`
Defined by [dojo/\_base/lang](lang)
Clones objects (including DOM nodes) and all children. Warning: do not clone cyclic structures.
| Parameter | Type | Description |
| --- | --- | --- |
| src | anything | The object to clone |
**Returns:** anything | undefined | instance
The object to clone
###
`delegate``(obj,props)`
Defined by [dojo/\_base/lang](lang)
Returns a new object which "looks" to obj for properties which it does not have a value for. Optionally takes a bag of properties to seed the returned object with initially.
This is a small implementation of the Boodman/Crockford delegation pattern in JavaScript. An intermediate object constructor mediates the prototype chain for the returned object, using it to delegate down to obj for property lookup when object-local lookup fails. This can be thought of similarly to ES4's "wrap", save that it does not act on types but rather on pure objects.
| Parameter | Type | Description |
| --- | --- | --- |
| obj | Object | The object to delegate to for properties not found directly on the return object or in props. |
| props | Object... | an object containing properties to assign to the returned object |
**Returns:** any
an Object of anonymous type
Examples
--------
### Example 1
```
var foo = { bar: "baz" };
var thinger = lang.delegate(foo, { thud: "xyzzy"});
thinger.bar == "baz"; // delegated to foo
foo.thud == undefined; // by definition
thinger.thud == "xyzzy"; // mixed in from props
foo.bar = "thonk";
thinger.bar == "thonk"; // still delegated to foo's bar
```
###
`exists``(name,obj)`
Defined by [dojo/\_base/lang](lang)
determine if an object supports a given method
useful for longer api chains where you have to test each object in the chain. Useful for object and method detection.
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | Path to an object, in the form "A.B.C". |
| obj | Object | *Optional*
Object to use as root of path. Defaults to 'dojo.global'. Null may be passed. |
**Returns:** boolean
Examples
--------
### Example 1
```
// define an object
var foo = {
bar: { }
};
// search the global scope
lang.exists("foo.bar"); // true
lang.exists("foo.bar.baz"); // false
// search from a particular scope
lang.exists("bar", foo); // true
lang.exists("bar.baz", foo); // false
```
###
`extend``(ctor,props)`
Defined by [dojo/\_base/lang](lang)
Adds all properties and methods of props to constructor's prototype, making them available to all instances created with constructor.
| Parameter | Type | Description |
| --- | --- | --- |
| ctor | Object | Target constructor to extend. |
| props | Object | One or more objects to mix into ctor.prototype |
**Returns:** Object
Target constructor to extend.
###
`getObject``(name,create,context)`
Defined by [dojo/\_base/lang](lang)
Get a property from a dot-separated string, such as "A.B.C"
Useful for longer api chains where you have to test each object in the chain, or when you have an object reference in string format.
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | Path to an property, in the form "A.B.C". |
| create | Boolean | *Optional*
Optional. Defaults to `false`. If `true`, Objects will be created at any point along the 'path' that is undefined. |
| context | Object | *Optional*
Optional. Object to use as root of path. Defaults to 'dojo.global'. Null may be passed. |
**Returns:** undefined
###
`hitch``(scope,method)`
Defined by [dojo/\_base/lang](lang)
Returns a function that will only ever execute in the given scope. This allows for easy use of object member functions in callbacks and other places in which the "this" keyword may otherwise not reference the expected scope. Any number of default positional arguments may be passed as parameters beyond "method". Each of these values will be used to "placehold" (similar to curry) for the hitched function.
| Parameter | Type | Description |
| --- | --- | --- |
| scope | Object | The scope to use when method executes. If method is a string, scope is also the object containing method. |
| method | Function | String... | A function to be hitched to scope, or the name of the method in scope to be hitched. |
**Returns:** undefined | function
Examples
--------
### Example 1
```
lang.hitch(foo, "bar")();
```
runs foo.bar() in the scope of foo
### Example 2
```
lang.hitch(foo, myFunction);
```
returns a function that runs myFunction in the scope of foo
### Example 3
Expansion on the default positional arguments passed along from hitch. Passed args are mixed first, additional args after.
```
var foo = { bar: function(a, b, c){ console.log(a, b, c); } };
var fn = lang.hitch(foo, "bar", 1, 2);
fn(3); // logs "1, 2, 3"
```
### Example 4
```
var foo = { bar: 2 };
lang.hitch(foo, function(){ this.bar = 10; })();
```
execute an anonymous function in scope of foo
###
`isAlien``(it)`
Defined by [dojo/\_base/lang](lang)
Returns true if it is a built-in function or some other kind of oddball that *should* report as a function but doesn't
| Parameter | Type | Description |
| --- | --- | --- |
| it | undefined | |
**Returns:** undefined
###
`isArray``(it)`
Defined by [dojo/\_base/lang](lang)
Return true if it is an Array. Does not work on Arrays created in other windows.
| Parameter | Type | Description |
| --- | --- | --- |
| it | anything | Item to test. |
**Returns:** undefined
###
`isArrayLike``(it)`
Defined by [dojo/\_base/lang](lang)
similar to isArray() but more permissive
Doesn't strongly test for "arrayness". Instead, settles for "isn't a string or number and has a length property". Arguments objects and DOM collections will return true when passed to isArrayLike(), but will return false when passed to isArray().
| Parameter | Type | Description |
| --- | --- | --- |
| it | anything | Item to test. |
**Returns:** any | Boolean
If it walks like a duck and quacks like a duck, return `true`
###
`isFunction``(it)`
Defined by [dojo/\_base/lang](lang)
Return true if it is a Function
| Parameter | Type | Description |
| --- | --- | --- |
| it | anything | Item to test. |
**Returns:** boolean
###
`isObject``(it)`
Defined by [dojo/\_base/lang](lang)
Returns true if it is a JavaScript object (or an Array, a Function or null)
| Parameter | Type | Description |
| --- | --- | --- |
| it | anything | Item to test. |
**Returns:** boolean
###
`isString``(it)`
Defined by [dojo/\_base/lang](lang)
Return true if it is a String
| Parameter | Type | Description |
| --- | --- | --- |
| it | anything | Item to test. |
**Returns:** boolean
###
`mixin``(dest,sources)`
Defined by [dojo/\_base/lang](lang)
Copies/adds all properties of one or more sources to dest; returns dest.
All properties, including functions (sometimes termed "methods"), excluding any non-standard extensions found in Object.prototype, are copied/added from sources to dest. sources are processed left to right. The Javascript assignment operator is used to copy/add each property; therefore, by default, mixin executes a so-called "shallow copy" and aggregate types are copied/added by reference.
| Parameter | Type | Description |
| --- | --- | --- |
| dest | Object | The object to which to copy/add all properties contained in source. If dest is falsy, then a new object is manufactured before copying/adding properties begins. |
| sources | Object... | One of more objects from which to draw all properties to copy into dest. sources are processed left-to-right and if more than one of these objects contain the same property name, the right-most value "wins". |
**Returns:** Object | object
dest, as modified
Examples
--------
### Example 1
make a shallow copy of an object
```
var copy = lang.mixin({}, source);
```
### Example 2
many class constructors often take an object which specifies values to be configured on the object. In this case, it is often simplest to call `lang.mixin` on the `this` object:
```
declare("acme.Base", null, {
constructor: function(properties){
// property configuration:
lang.mixin(this, properties);
console.log(this.quip);
// ...
},
quip: "I wasn't born yesterday, you know - I've seen movies.",
// ...
});
// create an instance of the class and configure it
var b = new acme.Base({quip: "That's what it does!" });
```
### Example 3
copy in properties from multiple objects
```
var flattened = lang.mixin(
{
name: "Frylock",
braces: true
},
{
name: "Carl Brutanananadilewski"
}
);
// will print "Carl Brutanananadilewski"
console.log(flattened.name);
// will print "true"
console.log(flattened.braces);
```
###
`partial``(method)`
Defined by [dojo/\_base/lang](lang)
similar to hitch() except that the scope object is left to be whatever the execution context eventually becomes.
Calling lang.partial is the functional equivalent of calling:
```
lang.hitch(null, funcName, ...);
```
| Parameter | Type | Description |
| --- | --- | --- |
| method | Function | String | The function to "wrap" |
**Returns:** undefined
###
`replace``(tmpl,map,pattern)`
Defined by [dojo/\_base/lang](lang)
Performs parameterized substitutions on a string. Throws an exception if any parameter is unmatched.
| Parameter | Type | Description |
| --- | --- | --- |
| tmpl | String | String to be used as a template. |
| map | Object | Function | If an object, it is used as a dictionary to look up substitutions. If a function, it is called for every substitution with following parameters: a whole match, a name, an offset, and the whole template string (see <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/replace> for more details). |
| pattern | RegEx | *Optional*
Optional regular expression objects that overrides the default pattern. Must be global and match one item. The default is: /{([^}]+)}/g, which matches patterns like that: "{xxx}", where "xxx" is any sequence of characters, which doesn't include "}". |
**Returns:** String | undefined
Returns the substituted string.
Examples
--------
### Example 1
```
// uses a dictionary for substitutions:
lang.replace("Hello, {name.first} {name.last} AKA {nick}!",
{
nick: "Bob",
name: {
first: "Robert",
middle: "X",
last: "Cringely"
}
});
// returns: Hello, Robert Cringely AKA Bob!
```
### Example 2
```
// uses an array for substitutions:
lang.replace("Hello, {0} {2}!",
["Robert", "X", "Cringely"]);
// returns: Hello, Robert Cringely!
```
### Example 3
```
// uses a function for substitutions:
function sum(a){
var t = 0;
arrayforEach(a, function(x){ t += x; });
return t;
}
lang.replace(
"{count} payments averaging {avg} USD per payment.",
lang.hitch(
{ payments: [11, 16, 12] },
function(_, key){
switch(key){
case "count": return this.payments.length;
case "min": return Math.min.apply(Math, this.payments);
case "max": return Math.max.apply(Math, this.payments);
case "sum": return sum(this.payments);
case "avg": return sum(this.payments) / this.payments.length;
}
}
)
);
// prints: 3 payments averaging 13 USD per payment.
```
### Example 4
```
// uses an alternative PHP-like pattern for substitutions:
lang.replace("Hello, ${0} ${2}!",
["Robert", "X", "Cringely"], /\$\{([^\}]+)\}/g);
// returns: Hello, Robert Cringely!
```
###
`setObject``(name,value,context)`
Defined by [dojo/\_base/lang](lang)
Set a property from a dot-separated string, such as "A.B.C"
Useful for longer api chains where you have to test each object in the chain, or when you have an object reference in string format. Objects are created as needed along `path`. Returns the passed value if setting is successful or `undefined` if not.
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | Path to a property, in the form "A.B.C". |
| value | anything | value or object to place at location given by name |
| context | Object | *Optional*
Optional. Object to use as root of path. Defaults to `dojo.global`. |
**Returns:** undefined
Examples
--------
### Example 1
set the value of `foo.bar.baz`, regardless of whether intermediate objects already exist:
```
lang.setObject("foo.bar.baz", value);
```
### Example 2
without `lang.setObject`, we often see code like this:
```
// ensure that intermediate objects are available
if(!obj["parent"]){ obj.parent = {}; }
if(!obj.parent["child"]){ obj.parent.child = {}; }
// now we can safely set the property
obj.parent.child.prop = "some value";
```
whereas with `lang.setObject`, we can shorten that to:
```
lang.setObject("parent.child.prop", "some value", obj);
```
###
`trim``(str)`
Defined by [dojo/\_base/lang](lang)
Trims whitespace from both sides of the string
This version of trim() was selected for inclusion into the base due to its compact size and relatively good performance (see [Steven Levithan's blog](http://blog.stevenlevithan.com/archives/faster-trim-javascript) Uses String.prototype.trim instead, if available. The fastest but longest version of this function is located at lang.string.trim()
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | String to be trimmed |
**Returns:** String
Returns the trimmed string
| programming_docs |
dojo dojo/_base/kernel.currency dojo/\_base/kernel.currency
===========================
Summary
-------
localized formatting and parsing routines for currencies
extends dojo.number to provide culturally-appropriate formatting of values in various world currencies, including use of a currency symbol. The currencies are specified by a three-letter international symbol in all uppercase, and support for the currencies is provided by the data in `dojo.cldr`. The scripts generating dojo.cldr specify which currency support is included. A fixed number of decimal places is determined based on the currency type and is not determined by the 'pattern' argument. The fractional portion is optional, by default, and variable length decimals are not supported.
Methods
-------
###
`format``(value,options)`
Defined by [dojo/currency](../currency)
Format a Number as a currency, using locale-specific settings
Create a string from a Number using a known, localized pattern. [Formatting patterns](http://www.unicode.org/reports/tr35/#Number_Elements) appropriate to the locale are chosen from the [CLDR](http://unicode.org/cldr) as well as the appropriate symbols and delimiters and number of decimal places.
| Parameter | Type | Description |
| --- | --- | --- |
| value | Number | the number to be formatted. |
| options | \_\_FormatOptions | *Optional* |
**Returns:** undefined
###
`parse``(expression,options)`
Defined by [dojo/currency](../currency)
| Parameter | Type | Description |
| --- | --- | --- |
| expression | String | |
| options | Object | *Optional*
An object with the following properties:* type (String, optional): Should not be set. Value is assumed to be currency.
* currency (String, optional): an [ISO4217](http://en.wikipedia.org/wiki/ISO_4217) currency code, a three letter sequence like "USD". For use with dojo.currency only.
* symbol (String, optional): localized currency symbol. The default will be looked up in table of supported currencies in `dojo.cldr` A [ISO4217](http://en.wikipedia.org/wiki/ISO_4217) currency code will be used if not found.
* places (Number, optional): fixed number of decimal places to accept. The default is determined based on which currency is used.
* fractional (Boolean|Array, optional): Whether to include the fractional portion, where the number of decimal places are implied by the currency or explicit 'places' parameter. The value [true,false] makes the fractional portion optional. By default for currencies, it the fractional portion is optional.
* pattern (String, optional): override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization. Literal characters in patterns are not supported.
* locale (String, optional): override the locale used to determine formatting rules
* strict (Boolean, optional): strict parsing, false by default. Strict parsing requires input as produced by the format() method. Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
|
**Returns:** undefined
###
`regexp``(options)`
Defined by [dojo/currency](../currency)
| Parameter | Type | Description |
| --- | --- | --- |
| options | Object | *Optional*
An object with the following properties:* pattern (String, optional): override [formatting pattern](http://www.unicode.org/reports/tr35/#Number_Format_Patterns) with this string. Default value is based on locale. Overriding this property will defeat localization.
* type (String, optional): choose a format type based on the locale from the following: decimal, scientific (not yet supported), percent, currency. decimal by default.
* locale (String, optional): override the locale used to determine formatting rules
* strict (Boolean, optional): strict parsing, false by default. Strict parsing requires input as produced by the format() method. Non-strict is more permissive, e.g. flexible on white space, omitting thousands separators
* places (Number|String, optional): number of decimal places to accept: Infinity, a positive number, or a range "n,m". Defined by pattern or Infinity if pattern not provided.
|
**Returns:** undefined
dojo dojo/_base/url dojo/\_base/url
===============
Usage
-----
url`();` See the [dojo/\_base/url reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/url.html) for more information.
Properties
----------
### authority
Defined by: [dojo/\_base/url](url)
### fragment
Defined by: [dojo/\_base/url](url)
### host
Defined by: [dojo/\_base/url](url)
### password
Defined by: [dojo/\_base/url](url)
### path
Defined by: [dojo/\_base/url](url)
### port
Defined by: [dojo/\_base/url](url)
### query
Defined by: [dojo/\_base/url](url)
### scheme
Defined by: [dojo/\_base/url](url)
### uri
Defined by: [dojo/\_base/url](url)
### user
Defined by: [dojo/\_base/url](url)
Methods
-------
###
`toString``()`
Defined by [dojo/\_base/url](url)
dojo dojo/_base/sniff dojo/\_base/sniff
=================
Summary
-------
Deprecated. New code should use [dojo/sniff](../sniff). This module populates the dojo browser version sniffing properties like dojo.isIE.
See the [dojo/\_base/sniff reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/sniff.html) for more information.
dojo dojo/_base/kernel.regexp dojo/\_base/kernel.regexp
=========================
Summary
-------
Regular expressions and Builder resources
Methods
-------
###
`buildGroupRE``(arr,re,nonCapture)`
Defined by [dojo/regexp](../regexp)
Builds a regular expression that groups subexpressions
A utility function used by some of the RE generators. The subexpressions are constructed by the function, re, in the second parameter. re builds one subexpression for each elem in the array a, in the first parameter. Returns a string for a regular expression that groups all the subexpressions.
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Object | Array | A single value or an array of values. |
| re | Function | A function. Takes one parameter and converts it to a regular expression. |
| nonCapture | Boolean | *Optional*
If true, uses non-capturing match, otherwise matches are retained by regular expression. Defaults to false |
**Returns:** undefined
###
`escapeString``(str,except)`
Defined by [dojo/regexp](../regexp)
Adds escape sequences for special characters in regular expressions
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | |
| except | String | *Optional*
a String with special characters to be left unescaped |
**Returns:** undefined
###
`group``(expression,nonCapture)`
Defined by [dojo/regexp](../regexp)
adds group match to expression
| Parameter | Type | Description |
| --- | --- | --- |
| expression | String | |
| nonCapture | Boolean | *Optional*
If true, uses non-capturing match, otherwise matches are retained by regular expression. |
**Returns:** string
dojo dojo/_base/kernel.scopeMap dojo/\_base/kernel.scopeMap
===========================
Properties
----------
### dijit
Defined by: [dojo/\_base/kernel](kernel)
### dojo
Defined by: [dojo/\_base/kernel](kernel)
### dojox
Defined by: [dojo/\_base/kernel](kernel)
dojo dojo/_base/kernel.config dojo/\_base/kernel.config
=========================
Summary
-------
This module defines the user configuration during bootstrap.
By defining user configuration as a module value, an entire configuration can be specified in a build, thereby eliminating the need for sniffing and or explicitly setting in the global variable dojoConfig. Also, when multiple instances of dojo exist in a single application, each will necessarily be located at an unique absolute module identifier as given by the package configuration. Implementing configuration as a module allows for specifying unique, per-instance configurations.
Examples
--------
### Example 1
Create a second instance of dojo with a different, instance-unique configuration (assume the loader and dojo.js are already loaded).
```
// specify a configuration that creates a new instance of dojo at the absolute module identifier "myDojo"
require({
packages:[{
name:"myDojo",
location:".", //assume baseUrl points to dojo.js
}]
});
// specify a configuration for the myDojo instance
define("myDojo/config", {
// normal configuration variables go here, e.g.,
locale:"fr-ca"
});
// load and use the new instance of dojo
require(["myDojo"], function(dojo){
// dojo is the new instance of dojo
// use as required
});
```
Properties
----------
###
`addOnLoad`
Defined by: [dojo/\_base/config](config)
Adds a callback via [dojo/ready](../ready). Useful when Dojo is added after the page loads and djConfig.afterOnLoad is true. Supports the same arguments as [dojo/ready](../ready). When using a function reference, use `djConfig.addOnLoad = function(){};`. For object with function name use `djConfig.addOnLoad = [myObject, "functionName"];` and for object with function reference use `djConfig.addOnLoad = [myObject, function(){}];`
### afterOnLoad
Defined by: [dojo/ready](../ready)
### baseUrl
Defined by: [dojo/\_base/kernel](kernel)
###
`callback`
Defined by: [dojo/\_base/config](config)
Defines a callback to be used when dependencies are defined before the loader has been loaded. When provided, they cause the loader to execute require(deps, callback) once it has finished loading. Should be used with deps.
### debugContainerId
Defined by: [dojo/\_firebug/firebug](../_firebug/firebug)
### debugHeight
Defined by: [dojo/robotx](../robotx)
### defaultDuration
Defined by: [dojo/\_base/config](config)
Default duration, in milliseconds, for wipe and fade animations within dijits. Assigned to dijit.defaultDuration.
### deferredInstrumentation
Defined by: [dojo/\_base/config](config)
Whether deferred instrumentation should be loaded or included in builds.
###
`deps`
Defined by: [dojo/\_base/config](config)
Defines dependencies to be used before the loader has been loaded. When provided, they cause the loader to execute require(deps, callback) once it has finished loading. Should be used with callback.
### dojoBlankHtmlUrl
Defined by: [dojo/\_base/config](config)
Used by some modules to configure an empty iframe. Used by [dojo/io/iframe](../io/iframe) and [dojo/back](../back), and [dijit/popup](http://dojotoolkit.org/api/1.10/dijit/popup) support in IE where an iframe is needed to make sure native controls do not bleed through the popups. Normally this configuration variable does not need to be set, except when using cross-domain/CDN Dojo builds. Save dojo/resources/blank.html to your domain and set `djConfig.dojoBlankHtmlUrl` to the path on your domain your copy of blank.html.
### extraLocale
Defined by: [dojo/\_base/config](config)
No default value. Specifies additional locales whose resources should also be loaded alongside the default locale when calls to `dojo.requireLocalization()` are processed.
### ioPublish
Defined by: [dojo/\_base/config](config)
Set this to true to enable publishing of topics for the different phases of IO operations. Publishing is done via [dojo/topic.publish()](../topic#publish). See [dojo/main.\_\_IoPublish](../main.__iopublish) for a list of topics that are published.
### isDebug
Defined by: [dojo/\_base/config](config)
Defaults to `false`. If set to `true`, ensures that Dojo provides extended debugging feedback via Firebug. If Firebug is not available on your platform, setting `isDebug` to `true` will force Dojo to pull in (and display) the version of Firebug Lite which is integrated into the Dojo distribution, thereby always providing a debugging/logging console when `isDebug` is enabled. Note that Firebug's `console.*` methods are ALWAYS defined by Dojo. If `isDebug` is false and you are on a platform without Firebug, these methods will be defined as no-ops.
### locale
Defined by: [dojo/\_base/config](config)
The locale to assume for loading localized resources in this page, specified according to [RFC 3066](http://www.ietf.org/rfc/rfc3066.txt). Must be specified entirely in lowercase, e.g. `en-us` and `zh-cn`. See the documentation for `dojo.i18n` and `dojo.requireLocalization` for details on loading localized resources. If no locale is specified, Dojo assumes the locale of the user agent, according to `navigator.userLanguage` or `navigator.language` properties.
### modulePaths
Defined by: [dojo/\_base/config](config)
A map of module names to paths relative to `dojo.baseUrl`. The key/value pairs correspond directly to the arguments which `dojo.registerModulePath` accepts. Specifying `djConfig.modulePaths = { "foo": "../../bar" }` is the equivalent of calling `dojo.registerModulePath("foo", "../../bar");`. Multiple modules may be configured via `djConfig.modulePaths`.
### parseOnLoad
Defined by: [dojo/\_base/config](config)
Run the parser after the page is loaded
### require
Defined by: [dojo/\_base/config](config)
An array of module names to be loaded immediately after dojo.js has been included in a page.
### transparentColor
Defined by: [dojo/\_base/config](config)
Array containing the r, g, b components used as transparent color in dojo.Color; if undefined, [255,255,255] (white) will be used.
### urchin
Defined by: [dojox/analytics/Urchin](http://dojotoolkit.org/api/1.10/dojox/analytics/Urchin)
Used by `dojox.analytics.Urchin` as the default UA-123456-7 account number used when being created. Alternately, you can pass an acct:"" parameter to the constructor a la: new dojox.analytics.Urchin({ acct:"UA-123456-7" });
### useCustomLogger
Defined by: [dojo/\_base/config](config)
If set to a value that evaluates to true such as a string or array and isDebug is true and Firebug is not available or running, then it bypasses the creation of Firebug Lite allowing you to define your own console object.
### useDeferredInstrumentation
Defined by: [dojo/\_base/config](config)
Whether the deferred instrumentation should be used.
* `"report-rejections"`: report each rejection as it occurs.
* `true` or `1` or `"report-unhandled-rejections"`: wait 1 second in an attempt to detect unhandled rejections.
dojo dojo/_base/NodeList dojo/\_base/NodeList
====================
Summary
-------
This module extends [dojo/NodeList](../nodelist) with the legacy connect(), coords(), blur(), focus(), change(), click(), error(), keydown(), keypress(), keyup(), load(), mousedown(), mouseenter(), mouseleave(), mousemove(), mouseout(), mouseover(), mouseup(), and submit() methods.
See the [dojo/\_base/NodeList reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/NodeList.html) for more information.
dojo dojo/_base/kernel.mouseButtons dojo/\_base/kernel.mouseButtons
===============================
Properties
----------
### LEFT
Defined by: [dojo/mouse](../mouse)
Numeric value of the left mouse button for the platform.
### MIDDLE
Defined by: [dojo/mouse](../mouse)
Numeric value of the middle mouse button for the platform.
### RIGHT
Defined by: [dojo/mouse](../mouse)
Numeric value of the right mouse button for the platform.
Methods
-------
###
`isButton``(e,button)`
Defined by [dojo/mouse](../mouse)
Checks an event object for a pressed button
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | Event object to examine |
| button | Number | The button value (example: dojo.mouseButton.LEFT) |
**Returns:** boolean
###
`isLeft``(e)`
Defined by [dojo/mouse](../mouse)
Checks an event object for the pressed left button
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | Event object to examine |
**Returns:** boolean
###
`isMiddle``(e)`
Defined by [dojo/mouse](../mouse)
Checks an event object for the pressed middle button
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | Event object to examine |
**Returns:** boolean
###
`isRight``(e)`
Defined by [dojo/mouse](../mouse)
Checks an event object for the pressed right button
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | Event object to examine |
**Returns:** boolean
dojo dojo/_base/kernel.global dojo/\_base/kernel.global
=========================
Summary
-------
Alias for the current window. 'global' can be modified for temporary context shifting. See also withGlobal().
Use this rather than referring to 'window' to ensure your code runs correctly in managed contexts.
Methods
-------
###
`$``()`
Defined by [dojox/jq](http://dojotoolkit.org/api/1.10/dojox/jq)
**Returns:** undefined
###
`GoogleSearchStoreCallback_undefined_NaN``(start,data,responseCode,errorMsg)`
Defined by [dojox/data/GoogleSearchStore](http://dojotoolkit.org/api/1.10/dojox/data/GoogleSearchStore)
| Parameter | Type | Description |
| --- | --- | --- |
| start | undefined | |
| data | undefined | |
| responseCode | undefined | |
| errorMsg | undefined | |
###
`jQuery``()`
Defined by [dojox/jq](http://dojotoolkit.org/api/1.10/dojox/jq)
**Returns:** undefined
###
`swfIsInHTML``()`
Defined by [dojox/av/FLVideo](http://dojotoolkit.org/api/1.10/dojox/av/FLVideo)
###
`undefined_onload``()`
Defined by [dojo/request/iframe](../request/iframe)
dojo dojo/_base/window.global dojo/\_base/window.global
=========================
Summary
-------
Alias for the current window. 'global' can be modified for temporary context shifting. See also withGlobal().
Use this rather than referring to 'window' to ensure your code runs correctly in managed contexts.
Methods
-------
###
`$``()`
Defined by [dojox/jq](http://dojotoolkit.org/api/1.10/dojox/jq)
**Returns:** undefined
###
`GoogleSearchStoreCallback_undefined_NaN``(start,data,responseCode,errorMsg)`
Defined by [dojox/data/GoogleSearchStore](http://dojotoolkit.org/api/1.10/dojox/data/GoogleSearchStore)
| Parameter | Type | Description |
| --- | --- | --- |
| start | undefined | |
| data | undefined | |
| responseCode | undefined | |
| errorMsg | undefined | |
###
`jQuery``()`
Defined by [dojox/jq](http://dojotoolkit.org/api/1.10/dojox/jq)
**Returns:** undefined
###
`swfIsInHTML``()`
Defined by [dojox/av/FLVideo](http://dojotoolkit.org/api/1.10/dojox/av/FLVideo)
###
`undefined_onload``()`
Defined by [dojo/request/iframe](../request/iframe)
dojo dojo/_base/event dojo/\_base/event
=================
Summary
-------
This module defines dojo DOM event API. Usually you should use [dojo/on](../on), and evt.stopPropagation() + evt.preventDefault(), rather than this module.
See the [dojo/\_base/event reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/event.html) for more information.
Methods
-------
###
`fix``(evt,sender)`
Defined by [dojo/\_base/event](event)
normalizes properties on the event object including event bubbling methods, keystroke normalization, and x/y positions
| Parameter | Type | Description |
| --- | --- | --- |
| evt | Event | native event object |
| sender | DOMNode | node to treat as "currentTarget" |
**Returns:** Event
native event object
###
`stop``(evt)`
Defined by [dojo/\_base/event](event)
prevents propagation and clobbers the default action of the passed event
| Parameter | Type | Description |
| --- | --- | --- |
| evt | Event | The event object. If omitted, window.event is used on IE. |
dojo dojo/_base/kernel.touch dojo/\_base/kernel.touch
========================
Summary
-------
This module provides unified touch event handlers by exporting press, move, release and cancel which can also run well on desktop. Based on <http://dvcs.w3.org/hg/webevents/raw-file/tip/touchevents.html> Also, if the dojoClick property is set to truthy on a DOM node, [dojo/touch](../touch) generates click events immediately for this node and its descendants (except for descendants that have a dojoClick property set to falsy), to avoid the delay before native browser click events, and regardless of whether evt.preventDefault() was called in a touch.press event listener.
Examples
--------
### Example 1
Used with dojo/on
```
define(["dojo/on", "dojo/touch"], function(on, touch){
on(node, touch.press, function(e){});
on(node, touch.move, function(e){});
on(node, touch.release, function(e){});
on(node, touch.cancel, function(e){});
```
### Example 2
Used with touch.\* directly
```
touch.press(node, function(e){});
touch.move(node, function(e){});
touch.release(node, function(e){});
touch.cancel(node, function(e){});
```
### Example 3
Have dojo/touch generate clicks without delay, with a default move threshold of 4 pixels
```
node.dojoClick = true;
```
### Example 4
Have dojo/touch generate clicks without delay, with a move threshold of 10 pixels horizontally and vertically
```
node.dojoClick = 10;
```
### Example 5
Have dojo/touch generate clicks without delay, with a move threshold of 50 pixels horizontally and 10 pixels vertically
```
node.dojoClick = {x:50, y:5};
```
### Example 6
Disable clicks without delay generated by dojo/touch on a node that has an ancestor with property dojoClick set to truthy
```
node.dojoClick = false;
```
Methods
-------
###
`cancel``(node,listener)`
Defined by [dojo/touch](../touch)
Register a listener to 'touchcancel'|'mouseleave' for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`enter``(node,listener)`
Defined by [dojo/touch](../touch)
Register a listener to mouse.enter or touch equivalent for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`leave``(node,listener)`
Defined by [dojo/touch](../touch)
Register a listener to mouse.leave or touch equivalent for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`move``(node,listener)`
Defined by [dojo/touch](../touch)
Register a listener that fires when the mouse cursor or a finger is dragged over the given node.
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`out``(node,listener)`
Defined by [dojo/touch](../touch)
Register a listener to 'mouseout' or touch equivalent for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`over``(node,listener)`
Defined by [dojo/touch](../touch)
Register a listener to 'mouseover' or touch equivalent for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`press``(node,listener)`
Defined by [dojo/touch](../touch)
Register a listener to 'touchstart'|'mousedown' for the given node
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
###
`release``(node,listener)`
Defined by [dojo/touch](../touch)
Register a listener to releasing the mouse button while the cursor is over the given node (i.e. "mouseup") or for removing the finger from the screen while touching the given node.
| Parameter | Type | Description |
| --- | --- | --- |
| node | Dom | Target node to listen to |
| listener | Function | Callback function |
**Returns:** any
A handle which will be used to remove the listener by handle.remove()
| programming_docs |
dojo dojo/_base/kernel.gears dojo/\_base/kernel.gears
========================
Summary
-------
TODOC
Properties
----------
### available
Defined by: [dojo/gears](../gears)
True if client is using Google Gears
Methods
-------
dojo dojo/_base/kernel.tests dojo/\_base/kernel.tests
========================
Summary
-------
D.O.H. Test files for Dojo unit testing.
dojo dojo/_base/query dojo/\_base/query
=================
Summary
-------
Deprecated. Use [dojo/query](../query) instead.
See the [dojo/\_base/query reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/query.html) for more information.
dojo dojo/_base/kernel dojo/\_base/kernel
==================
Summary
-------
This module is the foundational module of the dojo boot sequence; it defines the dojo object.
See the [dojo/\_base/kernel reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/kernel.html) for more information.
Properties
----------
### back
Defined by: [dojo/back](../back)
Browser history management resources
### baseUrl
Defined by: [dojo/\_base/configSpidermonkey](configspidermonkey)
### behavior
Defined by: [dojo/behavior](../behavior)
### cldr
Defined by: [dojo/cldr/monetary](../cldr/monetary)
### colors
Defined by: [dojo/colors](../colors)
### config
Defined by: [dojo/\_base/kernel](kernel)
This module defines the user configuration during bootstrap.
### connectPublisher
Defined by: [dojo/robotx](../robotx)
### contentHandlers
Defined by: [dojo/\_base/xhr](xhr)
A map of available XHR transport handle types. Name matches the `handleAs` attribute passed to XHR calls.
### currency
Defined by: [dojo/currency](../currency)
localized formatting and parsing routines for currencies
### data
Defined by: [dojo/data/util/filter](../data/util/filter)
### date
Defined by: [dojo/date/stamp](../date/stamp)
### dijit
Defined by: [dojo/\_base/kernel](kernel)
### dnd
Defined by: [dojo/dnd/common](../dnd/common)
### doc
Defined by: [dojo/\_base/window](window)
Alias for the current document. 'doc' can be modified for temporary context shifting. See also withDoc().
### dojox
Defined by: [dojo/\_base/kernel](kernel)
### fx
Defined by: [dojo/fx](../fx)
Effects library on top of Base animations
### gears
Defined by: [dojo/gears](../gears)
TODOC
### global
Defined by: [dojo/\_base/window](window)
Alias for the current window. 'global' can be modified for temporary context shifting. See also withGlobal().
### html
Defined by: [dojo/html](../html)
TODOC
### i18n
Defined by: [dojo/i18n](../i18n)
This module implements the [dojo/i18n](../i18n)! plugin and the v1.6- i18n API
### io
Defined by: [dojo/io/iframe](../io/iframe)
### isAir
Defined by: [dojo/\_base/sniff](sniff)
True if client is Adobe Air
### isAndroid
Defined by: [dojo/\_base/sniff](sniff)
Version as a Number if client is android browser. undefined otherwise.
### isAsync
Defined by: [dojo/\_base/kernel](kernel)
### isBrowser
Defined by: [dojo/\_base/configFirefoxExtension](configfirefoxextension)
### isChrome
Defined by: [dojo/\_base/sniff](sniff)
Version as a Number if client is Chrome browser. undefined otherwise.
### isCopyKey
Defined by: [dojox/grid/\_Grid](http://dojotoolkit.org/api/1.10/dojox/grid/_Grid)
### isFF
Defined by: [dojo/\_base/configFirefoxExtension](configfirefoxextension)
### isIE
Defined by: [dojo/\_base/sniff](sniff)
Version as a Number if client is MSIE(PC). undefined otherwise. Corresponds to major detected IE version (6, 7, 8, etc.)
### isIos
Defined by: [dojo/\_base/sniff](sniff)
Version as a Number if client is iPhone, iPod, or iPad. undefined otherwise.
### isKhtml
Defined by: [dojo/\_base/sniff](sniff)
Version as a Number if client is a KHTML browser. undefined otherwise. Corresponds to major detected version.
### isMac
Defined by: [dojo/\_base/sniff](sniff)
True if the client runs on Mac
### isMoz
Defined by: [dojo/\_base/configFirefoxExtension](configfirefoxextension)
### isMozilla
Defined by: [dojo/\_base/configFirefoxExtension](configfirefoxextension)
### isOpera
Defined by: [dojo/\_base/sniff](sniff)
Version as a Number if client is Opera. undefined otherwise. Corresponds to major detected version.
### isQuirks
Defined by: [dojo/\_base/configFirefoxExtension](configfirefoxextension)
### isSafari
Defined by: [dojo/\_base/sniff](sniff)
Version as a Number if client is Safari or iPhone. undefined otherwise.
### isSpidermonkey
Defined by: [dojo/\_base/configSpidermonkey](configspidermonkey)
### isWebKit
Defined by: [dojo/\_base/sniff](sniff)
Version as a Number if client is a WebKit-derived browser (Konqueror, Safari, Chrome, etc.). undefined otherwise.
### isWii
Defined by: [dojo/\_base/sniff](sniff)
True if client is Wii
### keys
Defined by: [dojo/keys](../keys)
Definitions for common key values. Client code should test keyCode against these named constants, as the actual codes can vary by browser.
### locale
Defined by: [dojo/\_base/configFirefoxExtension](configfirefoxextension)
### mouseButtons
Defined by: [dojo/mouse](../mouse)
### number
Defined by: [dojo/number](../number)
localized formatting and parsing routines for Number
### parser
Defined by: [dojox/mobile/parser](http://dojotoolkit.org/api/1.10/dojox/mobile/parser)
### publish
Defined by: [dojo/robotx](../robotx)
### query
Defined by: [dojo/query](../query)
### regexp
Defined by: [dojo/regexp](../regexp)
Regular expressions and Builder resources
### rpc
Defined by: [dojo/rpc/RpcService](../rpc/rpcservice)
### scopeMap
Defined by: [dojo/\_base/kernel](kernel)
### store
Defined by: [dojo/store/Cache](../store/cache)
### string
Defined by: [dojo/string](../string)
String utilities for Dojo
### subscribe
Defined by: [dojo/robotx](../robotx)
### tests
Defined by: [dojo/tests](../tests)
D.O.H. Test files for Dojo unit testing.
### toJsonIndentStr
Defined by: [dojo/\_base/json](json)
### touch
Defined by: [dojo/touch](../touch)
This module provides unified touch event handlers by exporting press, move, release and cancel which can also run well on desktop. Based on <http://dvcs.w3.org/hg/webevents/raw-file/tip/touchevents.html> Also, if the dojoClick property is set to truthy on a DOM node, [dojo/touch](../touch) generates click events immediately for this node and its descendants (except for descendants that have a dojoClick property set to falsy), to avoid the delay before native browser click events, and regardless of whether evt.preventDefault() was called in a touch.press event listener.
### version
Defined by: [dojo/\_base/kernel](kernel)
Version number of the Dojo Toolkit
### window
Defined by: [dojo/window](../window)
TODOC
Methods
-------
###
`AdapterRegistry``(returnWrappers)`
Defined by [dojo/AdapterRegistry](../adapterregistry)
A registry to make contextual calling/searching easier.
Objects of this class keep list of arrays in the form [name, check, wrap, directReturn] that are used to determine what the contextual result of a set of checked arguments is. All check/wrap functions in this registry should be of the same arity.
| Parameter | Type | Description |
| --- | --- | --- |
| returnWrappers | Boolean | *Optional* |
Examples
--------
### Example 1
```
// create a new registry
require(["dojo/AdapterRegistry"],
function(AdapterRegistry){
var reg = new AdapterRegistry();
reg.register("handleString",
function(str){
return typeof val == "string"
},
function(str){
// do something with the string here
}
);
reg.register("handleArr",
dojo.isArray,
function(arr){
// do something with the array here
}
);
// now we can pass reg.match() *either* an array or a string and
// the value we pass will get handled by the right function
reg.match("someValue"); // will call the first function
reg.match(["someValue"]); // will call the second
});
```
###
`addClass``(node,classStr)`
Defined by [dojo/dom-class](../dom-class)
Adds the specified classes to the end of the class list on the passed node. Will not re-apply duplicate classes.
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | String ID or DomNode reference to add a class string too |
| classStr | String | Array | A String class name to add, or several space-separated class names, or an array of class names. |
Examples
--------
### Example 1
Add a class to some node:
```
require(["dojo/dom-class"], function(domClass){
domClass.add("someNode", "anewClass");
});
```
### Example 2
Add two classes at once:
```
require(["dojo/dom-class"], function(domClass){
domClass.add("someNode", "firstClass secondClass");
});
```
### Example 3
Add two classes at once (using array):
```
require(["dojo/dom-class"], function(domClass){
domClass.add("someNode", ["firstClass", "secondClass"]);
});
```
### Example 4
Available in `dojo/NodeList` for multiple additions
```
require(["dojo/query"], function(query){
query("ul > li").addClass("firstLevel");
});
```
###
`addOnLoad``(priority,context,callback)`
Defined by [dojo/ready](../ready)
Add a function to execute on DOM content loaded and all requested modules have arrived and been evaluated. In most cases, the `domReady` plug-in should suffice and this method should not be needed.
When called in a non-browser environment, just checks that all requested modules have arrived and been evaluated.
| Parameter | Type | Description |
| --- | --- | --- |
| priority | Integer | *Optional*
The order in which to exec this callback relative to other callbacks, defaults to 1000 |
| context | undefined | The context in which to run execute callback, or a callback if not using context |
| callback | Function | *Optional*
The function to execute. |
Examples
--------
### Example 1
Simple DOM and Modules ready syntax
```
require(["dojo/ready"], function(ready){
ready(function(){ alert("Dom ready!"); });
});
```
### Example 2
Using a priority
```
require(["dojo/ready"], function(ready){
ready(2, function(){ alert("low priority ready!"); })
});
```
### Example 3
Using context
```
require(["dojo/ready"], function(ready){
ready(foo, function(){
// in here, this == foo
});
});
```
### Example 4
Using dojo/hitch style args:
```
require(["dojo/ready"], function(ready){
var foo = { dojoReady: function(){ console.warn(this, "dojo dom and modules ready."); } };
ready(foo, "dojoReady");
});
```
###
`addOnUnload``(obj,functionName)`
Defined by [dojo/\_base/unload](unload)
Registers a function to be triggered when the page unloads. Deprecated, use on(window, "beforeunload", lang.hitch(obj, functionName)) instead.
The first time that addOnUnload is called Dojo will register a page listener to trigger your unload handler with.
In a browser environment, the functions will be triggered during the window.onbeforeunload event. Be careful of doing too much work in an unload handler. onbeforeunload can be triggered if a link to download a file is clicked, or if the link is a javascript: link. In these cases, the onbeforeunload event fires, but the document is not actually destroyed. So be careful about doing destructive operations in a dojo.addOnUnload callback.
Further note that calling dojo.addOnUnload will prevent browsers from using a "fast back" cache to make page loading via back button instantaneous.
| Parameter | Type | Description |
| --- | --- | --- |
| obj | Object? | Function | *Optional* |
| functionName | String | Function | *Optional* |
Examples
--------
### Example 1
```
var afunc = function() {console.log("global function");};
require(["dojo/_base/unload"], function(unload) {
var foo = {bar: function(){ console.log("bar unloading...");},
data: "mydata"};
unload.addOnUnload(afunc);
unload.addOnUnload(foo, "bar");
unload.addOnUnload(foo, function(){console.log("", this.data);});
});
```
###
`addOnWindowUnload``(obj,functionName)`
Defined by [dojo/\_base/configFirefoxExtension](configfirefoxextension)
registers a function to be triggered when window.onunload fires. Be careful trying to modify the DOM or access JavaScript properties during this phase of page unloading: they may not always be available. Consider dojo.addOnUnload() if you need to modify the DOM or do heavy JavaScript work.
| Parameter | Type | Description |
| --- | --- | --- |
| obj | Object | *Optional* |
| functionName | String | Function | *Optional* |
Examples
--------
### Example 1
```
dojo.addOnWindowUnload(functionPointer)
dojo.addOnWindowUnload(object, "functionName")
dojo.addOnWindowUnload(object, function(){ /* ... */});
```
###
`anim``(node,properties,duration,easing,onEnd,delay)`
Defined by [dojo/\_base/fx](fx)
A simpler interface to `animateProperty()`, also returns an instance of `Animation` but begins the animation immediately, unlike nearly every other Dojo animation API.
Simpler (but somewhat less powerful) version of `animateProperty`. It uses defaults for many basic properties and allows for positional parameters to be used in place of the packed "property bag" which is used for other Dojo animation methods.
The `Animation` object returned will be already playing, so calling play() on it again is (usually) a no-op.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | a DOM node or the id of a node to animate CSS properties on |
| properties | Object | |
| duration | Integer | *Optional*
The number of milliseconds over which the animation should run. Defaults to the global animation default duration (350ms). |
| easing | Function | *Optional*
An easing function over which to calculate acceleration and deceleration of the animation through its duration. A default easing algorithm is provided, but you may plug in any you wish. A large selection of easing algorithms are available in `dojo/fx/easing`. |
| onEnd | Function | *Optional*
A function to be called when the animation finishes running. |
| delay | Integer | *Optional*
The number of milliseconds to delay beginning the animation by. The default is 0. |
**Returns:** undefined
Examples
--------
### Example 1
Fade out a node
```
basefx.anim("id", { opacity: 0 });
```
### Example 2
Fade out a node over a full second
```
basefx.anim("id", { opacity: 0 }, 1000);
```
###
`animateProperty``(args)`
Defined by [dojo/\_base/fx](fx)
Returns an animation that will transition the properties of node defined in `args` depending how they are defined in `args.properties`
Foundation of most [dojo/\_base/fx](fx) animations. It takes an object of "properties" corresponding to style properties, and animates them in parallel over a set duration.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* properties (Object, optional): A hash map of style properties to Objects describing the transition, such as the properties of \_Line with an additional 'units' property
* node (DOMNode|String): The node referenced in the animation
* duration (Integer, optional): Duration of the animation in milliseconds.
* easing (Function, optional): An easing function.
|
**Returns:** instance
Examples
--------
### Example 1
A simple animation that changes the width of the specified node.
```
basefx.animateProperty({
node: "nodeId",
properties: { width: 400 },
}).play();
```
Dojo figures out the start value for the width and converts the
integer specified for the width to the more expressive but verbose form `{ width: { end: '400', units: 'px' } }` which you can also specify directly. Defaults to 'px' if omitted.
### Example 2
Animate width, height, and padding over 2 seconds... the pedantic way:
```
basefx.animateProperty({ node: node, duration:2000,
properties: {
width: { start: '200', end: '400', units:"px" },
height: { start:'200', end: '400', units:"px" },
paddingTop: { start:'5', end:'50', units:"px" }
}
}).play();
```
Note 'paddingTop' is used over 'padding-top'. Multi-name CSS properties
are written using "mixed case", as the hyphen is illegal as an object key.
### Example 3
Plug in a different easing function and register a callback for when the animation ends. Easing functions accept values between zero and one and return a value on that basis. In this case, an exponential-in curve.
```
basefx.animateProperty({
node: "nodeId",
// dojo figures out the start value
properties: { width: { end: 400 } },
easing: function(n){
return (n==0) ? 0 : Math.pow(2, 10 * (n - 1));
},
onEnd: function(node){
// called when the animation finishes. The animation
// target is passed to this function
}
}).play(500); // delay playing half a second
```
### Example 4
Like all `Animation`s, animateProperty returns a handle to the Animation instance, which fires the events common to Dojo FX. Use `aspect.after` to access these events outside of the Animation definition:
```
var anim = basefx.animateProperty({
node:"someId",
properties:{
width:400, height:500
}
});
aspect.after(anim, "onEnd", function(){
console.log("animation ended");
}, true);
// play the animation now:
anim.play();
```
### Example 5
Each property can be a function whose return value is substituted along. Additionally, each measurement (eg: start, end) can be a function. The node reference is passed directly to callbacks.
```
basefx.animateProperty({
node:"mine",
properties:{
height:function(node){
// shrink this node by 50%
return domGeom.position(node).h / 2
},
width:{
start:function(node){ return 100; },
end:function(node){ return 200; }
}
}
}).play();
```
###
`Animation``(args)`
Defined by [dojo/\_base/fx](fx)
A generic animation class that fires callbacks into its handlers object at various states.
A generic animation class that fires callbacks into its handlers object at various states. Nearly all dojo animation functions return an instance of this method, usually without calling the .play() method beforehand. Therefore, you will likely need to call .play() on instances of `Animation` when one is returned.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | The 'magic argument', mixing all the properties into this animation instance. |
###
`attr``(node,name,value)`
Defined by [dojo/\_base/html](html)
Gets or sets an attribute on an HTML element.
Handles normalized getting and setting of attributes on DOM Nodes. If 2 arguments are passed, and a the second argument is a string, acts as a getter.
If a third argument is passed, or if the second argument is a map of attributes, acts as a setter.
When passing functions as values, note that they will not be directly assigned to slots on the node, but rather the default behavior will be removed and the new behavior will be added using `dojo.connect()`, meaning that event handler properties will be normalized and that some caveats with regards to non-standard behaviors for onsubmit apply. Namely that you should cancel form submission using `dojo.stopEvent()` on the passed event object instead of returning a boolean value from the handler itself.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to get or set the attribute on |
| name | String | Object | the name of the attribute to get or set. |
| value | String | *Optional*
The value to set for the attribute |
**Returns:** any | undefined
when used as a getter, the value of the requested attribute or null if that attribute does not have a specified or default value;
when used as a setter, the DOM node
Examples
--------
### Example 1
```
// get the current value of the "foo" attribute on a node
dojo.attr(dojo.byId("nodeId"), "foo");
// or we can just pass the id:
dojo.attr("nodeId", "foo");
```
### Example 2
```
// use attr() to set the tab index
dojo.attr("nodeId", "tabIndex", 3);
```
### Example 3
Set multiple values at once, including event handlers:
```
dojo.attr("formId", {
"foo": "bar",
"tabIndex": -1,
"method": "POST",
"onsubmit": function(e){
// stop submitting the form. Note that the IE behavior
// of returning true or false will have no effect here
// since our handler is connect()ed to the built-in
// onsubmit behavior and so we need to use
// dojo.stopEvent() to ensure that the submission
// doesn't proceed.
dojo.stopEvent(e);
// submit the form with Ajax
dojo.xhrPost({ form: "formId" });
}
});
```
### Example 4
Style is s special case: Only set with an object hash of styles
```
dojo.attr("someNode",{
id:"bar",
style:{
width:"200px", height:"100px", color:"#000"
}
});
```
### Example 5
Again, only set style as an object hash of styles:
```
var obj = { color:"#fff", backgroundColor:"#000" };
dojo.attr("someNode", "style", obj);
// though shorter to use `dojo.style()` in this case:
dojo.style("someNode", obj);
```
###
`blendColors``(start,end,weight,obj)`
Defined by [dojo/\_base/Color](color)
Blend colors end and start with weight from 0 to 1, 0.5 being a 50/50 blend, can reuse a previously allocated Color object for the result
| Parameter | Type | Description |
| --- | --- | --- |
| start | [dojo/\_base/Color](color) | |
| end | [dojo/\_base/Color](color) | |
| weight | Number | |
| obj | [dojo/\_base/Color](color) | *Optional* |
**Returns:** undefined
###
`body``(doc)`
Defined by [dojo/\_base/window](window)
Return the body element of the specified document or of dojo/\_base/window::doc.
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | *Optional* |
**Returns:** undefined
Examples
--------
### Example 1
```
win.body().appendChild(dojo.doc.createElement('div'));
```
###
`byId``(id,doc)`
Defined by [dojo/dom](../dom)
Returns DOM node with matching `id` attribute or falsy value (ex: null or undefined) if not found. If `id` is a DomNode, this function is a no-op.
| Parameter | Type | Description |
| --- | --- | --- |
| id | String | DOMNode | A string to match an HTML id attribute or a reference to a DOM Node |
| doc | Document | *Optional*
Document to work in. Defaults to the current value of dojo/\_base/window.doc. Can be used to retrieve node references from other documents. |
**Returns:** instance
Examples
--------
### Example 1
Look up a node by ID:
```
require(["dojo/dom"], function(dom){
var n = dom.byId("foo");
});
```
### Example 2
Check if a node exists, and use it.
```
require(["dojo/dom"], function(dom){
var n = dom.byId("bar");
if(n){ doStuff() ... }
});
```
### Example 3
Allow string or DomNode references to be passed to a custom function:
```
require(["dojo/dom"], function(dom){
var foo = function(nodeOrId){
nodeOrId = dom.byId(nodeOrId);
// ... more stuff
}
});
```
###
`cache``(module,url,value)`
Defined by [dojo/text](../text)
A getter and setter for storing the string content associated with the module and url arguments.
If module is a string that contains slashes, then it is interpretted as a fully resolved path (typically a result returned by require.toUrl), and url should not be provided. This is the preferred signature. If module is a string that does not contain slashes, then url must also be provided and module and url are used to call `dojo.moduleUrl()` to generate a module URL. This signature is deprecated. If value is specified, the cache value for the moduleUrl will be set to that value. Otherwise, dojo.cache will fetch the moduleUrl and store it in its internal cache and return that cached value for the URL. To clear a cache value pass null for value. Since XMLHttpRequest (XHR) is used to fetch the the URL contents, only modules on the same domain of the page can use this capability. The build system can inline the cache values though, to allow for xdomain hosting.
| Parameter | Type | Description |
| --- | --- | --- |
| module | String | Object | dojo/cldr/supplemental |
| url | String | The rest of the path to append to the path derived from the module argument. If module is an object, then this second argument should be the "value" argument instead. |
| value | String | Object | *Optional*
If a String, the value to use in the cache for the module/url combination. If an Object, it can have two properties: value and sanitize. The value property should be the value to use in the cache, and sanitize can be set to true or false, to indicate if XML declarations should be removed from the value and if the HTML inside a body tag in the value should be extracted as the real value. The value argument or the value property on the value argument are usually only used by the build system as it inlines cache content. |
**Returns:** undefined | null
Examples
--------
### Example 1
To ask dojo.cache to fetch content and store it in the cache (the dojo["cache"] style of call is used to avoid an issue with the build system erroneously trying to intern this example. To get the build system to intern your dojo.cache calls, use the "dojo.cache" style of call):
```
//If template.html contains "<h1>Hello</h1>" that will be
//the value for the text variable.
//Note: This is pre-AMD, deprecated syntax
var text = dojo["cache"]("my.module", "template.html");
```
### Example 2
To ask dojo.cache to fetch content and store it in the cache, and sanitize the input (the dojo["cache"] style of call is used to avoid an issue with the build system erroneously trying to intern this example. To get the build system to intern your dojo.cache calls, use the "dojo.cache" style of call):
```
//If template.html contains "<html><body><h1>Hello</h1></body></html>", the
//text variable will contain just "<h1>Hello</h1>".
//Note: This is pre-AMD, deprecated syntax
var text = dojo["cache"]("my.module", "template.html", {sanitize: true});
```
### Example 3
Same example as previous, but demonstrates how an object can be passed in as the first argument, then the value argument can then be the second argument.
```
//If template.html contains "<html><body><h1>Hello</h1></body></html>", the
//text variable will contain just "<h1>Hello</h1>".
//Note: This is pre-AMD, deprecated syntax
var text = dojo["cache"](new dojo._Url("my/module/template.html"), {sanitize: true});
```
###
`clearCache``()`
Defined by [dojo/\_base/array](array)
###
`Color``(color)`
Defined by [dojo/\_base/Color](color)
Takes a named string, hex string, array of rgb or rgba values, an object with r, g, b, and a properties, or another `Color` object and creates a new Color instance to work from.
| Parameter | Type | Description |
| --- | --- | --- |
| color | Array | String | Object | |
Examples
--------
### Example 1
Work with a Color instance:
```
require(["dojo/_base/color"], function(Color){
var c = new Color();
c.setColor([0,0,0]); // black
var hex = c.toHex(); // #000000
});
```
### Example 2
Work with a node's color:
```
require(["dojo/_base/color", "dojo/dom-style"], function(Color, domStyle){
var color = domStyle("someNode", "backgroundColor");
var n = new Color(color);
// adjust the color some
n.r *= .5;
console.log(n.toString()); // rgb(128, 255, 255);
});
```
###
`colorFromArray``(a,obj)`
Defined by [dojo/\_base/Color](color)
Builds a `Color` from a 3 or 4 element array, mapping each element in sequence to the rgb(a) values of the color.
| Parameter | Type | Description |
| --- | --- | --- |
| a | Array | |
| obj | [dojo/\_base/Color](color) | *Optional* |
**Returns:** any | undefined
A Color object. If obj is passed, it will be the return value.
Examples
--------
### Example 1
```
require(["dojo/_base/color"], function(Color){
var myColor = new Color().fromArray([237,237,237,0.5]); // grey, 50% alpha
});
```
###
`colorFromHex``(color,obj)`
Defined by [dojo/\_base/Color](color)
Converts a hex string with a '#' prefix to a color object. Supports 12-bit #rgb shorthand. Optionally accepts a `Color` object to update with the parsed value.
| Parameter | Type | Description |
| --- | --- | --- |
| color | String | |
| obj | [dojo/\_base/Color](color) | *Optional* |
**Returns:** any
A Color object. If obj is passed, it will be the return value.
Examples
--------
### Example 1
```
require(["dojo/_base/color"], function(Color){
var thing = new Color().fromHex("#ededed"); // grey, longhand
var thing2 = new Color().fromHex("#000"); // black, shorthand
});
```
###
`colorFromRgb``(color,obj)`
Defined by [dojo/colors](../colors)
get rgb(a) array from css-style color declarations
this function can handle all 4 CSS3 Color Module formats: rgb, rgba, hsl, hsla, including rgb(a) with percentage values.
| Parameter | Type | Description |
| --- | --- | --- |
| color | String | |
| obj | [dojo/\_base/Color](color) | *Optional* |
**Returns:** null
###
`colorFromString``(str,obj)`
Defined by [dojo/\_base/Color](color)
Parses `str` for a color value. Accepts hex, rgb, and rgba style color values.
Acceptable input values for str may include arrays of any form accepted by dojo.colorFromArray, hex strings such as "#aaaaaa", or rgb or rgba strings such as "rgb(133, 200, 16)" or "rgba(10, 10, 10, 50)"
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | |
| obj | [dojo/\_base/Color](color) | *Optional* |
**Returns:** any
A Color object. If obj is passed, it will be the return value.
###
`connect``(obj,event,context,method,dontFix)`
Defined by [dojo/\_base/connect](connect)
`dojo.connect` is a deprecated event handling and delegation method in Dojo. It allows one function to "listen in" on the execution of any other, triggering the second whenever the first is called. Many listeners may be attached to a function, and source functions may be either regular function calls or DOM events.
Connects listeners to actions, so that after event fires, a listener is called with the same arguments passed to the original function.
Since `dojo.connect` allows the source of events to be either a "regular" JavaScript function or a DOM event, it provides a uniform interface for listening to all the types of events that an application is likely to deal with though a single, unified interface. DOM programmers may want to think of it as "addEventListener for everything and anything".
When setting up a connection, the `event` parameter must be a string that is the name of the method/event to be listened for. If `obj` is null, `kernel.global` is assumed, meaning that connections to global methods are supported but also that you may inadvertently connect to a global by passing an incorrect object name or invalid reference.
`dojo.connect` generally is forgiving. If you pass the name of a function or method that does not yet exist on `obj`, connect will not fail, but will instead set up a stub method. Similarly, null arguments may simply be omitted such that fewer than 4 arguments may be required to set up a connection See the examples for details.
The return value is a handle that is needed to remove this connection with `dojo.disconnect`.
| Parameter | Type | Description |
| --- | --- | --- |
| obj | Object | *Optional*
The source object for the event function. Defaults to `kernel.global` if null. If obj is a DOM node, the connection is delegated to the DOM event manager (unless dontFix is true). |
| event | String | String name of the event function in obj. I.e. identifies a property `obj[event]`. |
| context | Object | null | The object that method will receive as "this". If context is null and method is a function, then method inherits the context of event. If method is a string then context must be the source object object for method (context[method]). If context is null, kernel.global is used. |
| method | String | Function | A function reference, or name of a function in context. The function identified by method fires after event does. method receives the same arguments as the event. See context argument comments for information on method's scope. |
| dontFix | Boolean | *Optional*
If obj is a DOM node, set dontFix to true to prevent delegation of this connection to the DOM event manager. |
**Returns:** undefined
Examples
--------
### Example 1
When obj.onchange(), do ui.update():
```
dojo.connect(obj, "onchange", ui, "update");
dojo.connect(obj, "onchange", ui, ui.update); // same
```
### Example 2
Using return value for disconnect:
```
var link = dojo.connect(obj, "onchange", ui, "update");
...
dojo.disconnect(link);
```
### Example 3
When onglobalevent executes, watcher.handler is invoked:
```
dojo.connect(null, "onglobalevent", watcher, "handler");
```
### Example 4
When ob.onCustomEvent executes, customEventHandler is invoked:
```
dojo.connect(ob, "onCustomEvent", null, "customEventHandler");
dojo.connect(ob, "onCustomEvent", "customEventHandler"); // same
```
### Example 5
When ob.onCustomEvent executes, customEventHandler is invoked with the same scope (this):
```
dojo.connect(ob, "onCustomEvent", null, customEventHandler);
dojo.connect(ob, "onCustomEvent", customEventHandler); // same
```
### Example 6
When globalEvent executes, globalHandler is invoked with the same scope (this):
```
dojo.connect(null, "globalEvent", null, globalHandler);
dojo.connect("globalEvent", globalHandler); // same
```
###
`contentBox``(node,box)`
Defined by [dojo/\_base/html](html)
Getter/setter for the content-box of node.
Returns an object in the expected format of box (regardless if box is passed). The object might look like: `{ l: 50, t: 200, w: 300: h: 150 }` for a node offset from its parent 50px to the left, 200px from the top with a content width of 300px and a content-height of 150px. Note that the content box may have a much larger border or margin box, depending on the box model currently in use and CSS values set/inherited for node. While the getter will return top and left values, the setter only accepts setting the width and height.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DomNode | String | id or reference to DOM Node to get/set box for |
| box | Object | *Optional*
If passed, denotes that dojo.contentBox() should update/set the content box for node. Box is an object in the above format, but only w (width) and h (height) are supported. All properties are optional if passed. |
**Returns:** undefined
###
`cookie``(name,value,props)`
Defined by [dojo/cookie](../cookie)
Get or set a cookie.
If one argument is passed, returns the value of the cookie For two or more arguments, acts as a setter.
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | Name of the cookie |
| value | String | *Optional*
Value for the cookie |
| props | Object | *Optional*
Properties for the cookie |
**Returns:** undefined
Examples
--------
### Example 1
set a cookie with the JSON-serialized contents of an object which will expire 5 days from now:
```
require(["dojo/cookie", "dojo/json"], function(cookie, json){
cookie("configObj", json.stringify(config, {expires: 5 }));
});
```
### Example 2
de-serialize a cookie back into a JavaScript object:
```
require(["dojo/cookie", "dojo/json"], function(cookie, json){
config = json.parse(cookie("configObj"));
});
```
### Example 3
delete a cookie:
```
require(["dojo/cookie"], function(cookie){
cookie("configObj", null, {expires: -1});
});
```
###
`coords``(node,includeScroll)`
Defined by [dojo/\_base/html](html)
Deprecated: Use position() for border-box x/y/w/h or marginBox() for margin-box w/h/l/t.
Returns an object that measures margin-box (w)idth/(h)eight and absolute position x/y of the border-box. Also returned is computed (l)eft and (t)op values in pixels from the node's offsetParent as returned from marginBox(). Return value will be in the form:
```
{ l: 50, t: 200, w: 300: h: 150, x: 100, y: 300 }
```
Does not act as a setter. If includeScroll is passed, the x and
y params are affected as one would expect in dojo.position().
| Parameter | Type | Description |
| --- | --- | --- |
| node | DomNode | String | |
| includeScroll | Boolean | *Optional* |
**Returns:** undefined
###
`create``(tag,attrs,refNode,pos)`
Defined by [dojo/dom-construct](../dom-construct)
Create an element, allowing for optional attribute decoration and placement.
A DOM Element creation function. A shorthand method for creating a node or a fragment, and allowing for a convenient optional attribute setting step, as well as an optional DOM placement reference.
Attributes are set by passing the optional object through `dojo.setAttr`. See `dojo.setAttr` for noted caveats and nuances, and API if applicable.
Placement is done via `dojo.place`, assuming the new node to be the action node, passing along the optional reference node and position.
| Parameter | Type | Description |
| --- | --- | --- |
| tag | DOMNode | String | A string of the element to create (eg: "div", "a", "p", "li", "script", "br"), or an existing DOM node to process. |
| attrs | Object | An object-hash of attributes to set on the newly created node. Can be null, if you don't want to set any attributes/styles. See: `dojo.setAttr` for a description of available attributes. |
| refNode | DOMNode | String | *Optional*
Optional reference node. Used by `dojo.place` to place the newly created node somewhere in the dom relative to refNode. Can be a DomNode reference or String ID of a node. |
| pos | String | *Optional*
Optional positional reference. Defaults to "last" by way of `dojo.place`, though can be set to "first","after","before","last", "replace" or "only" to further control the placement of the new node relative to the refNode. 'refNode' is required if a 'pos' is specified. |
**Returns:** undefined
Examples
--------
### Example 1
Create a DIV:
```
require(["dojo/dom-construct"], function(domConstruct){
var n = domConstruct.create("div");
});
```
### Example 2
Create a DIV with content:
```
require(["dojo/dom-construct"], function(domConstruct){
var n = domConstruct.create("div", { innerHTML:"<p>hi</p>" });
});
```
### Example 3
Place a new DIV in the BODY, with no attributes set
```
require(["dojo/dom-construct"], function(domConstruct){
var n = domConstruct.create("div", null, dojo.body());
});
```
### Example 4
Create an UL, and populate it with LI's. Place the list as the first-child of a node with id="someId":
```
require(["dojo/dom-construct", "dojo/_base/array"],
function(domConstruct, arrayUtil){
var ul = domConstruct.create("ul", null, "someId", "first");
var items = ["one", "two", "three", "four"];
arrayUtil.forEach(items, function(data){
domConstruct.create("li", { innerHTML: data }, ul);
});
});
```
### Example 5
Create an anchor, with an href. Place in BODY:
```
require(["dojo/dom-construct"], function(domConstruct){
domConstruct.create("a", { href:"foo.html", title:"Goto FOO!" }, dojo.body());
});
```
###
`declare``(className,superclass,props)`
Defined by [dojo/\_base/declare](declare)
Create a feature-rich constructor from compact notation.
Create a constructor using a compact notation for inheritance and prototype extension.
Mixin ancestors provide a type of multiple inheritance. Prototypes of mixin ancestors are copied to the new class: changes to mixin prototypes will not affect classes to which they have been mixed in.
Ancestors can be compound classes created by this version of declare(). In complex cases all base classes are going to be linearized according to C3 MRO algorithm (see <http://www.python.org/download/releases/2.3/mro/> for more details).
"className" is cached in "declaredClass" property of the new class, if it was supplied. The immediate super class will be cached in "superclass" property of the new class.
Methods in "props" will be copied and modified: "nom" property (the declared name of the method) will be added to all copied functions to help identify them for the internal machinery. Be very careful, while reusing methods: if you use the same function under different names, it can produce errors in some cases.
It is possible to use constructors created "manually" (without declare()) as bases. They will be called as usual during the creation of an instance, their methods will be chained, and even called by "this.inherited()".
Special property "-chains-" governs how to chain methods. It is a dictionary, which uses method names as keys, and hint strings as values. If a hint string is "after", this method will be called after methods of its base classes. If a hint string is "before", this method will be called before methods of its base classes.
If "constructor" is not mentioned in "-chains-" property, it will be chained using the legacy mode: using "after" chaining, calling preamble() method before each constructor, if available, and calling postscript() after all constructors were executed. If the hint is "after", it is chained as a regular method, but postscript() will be called after the chain of constructors. "constructor" cannot be chained "before", but it allows a special hint string: "manual", which means that constructors are not going to be chained in any way, and programmer will call them manually using this.inherited(). In the latter case postscript() will be called after the construction.
All chaining hints are "inherited" from base classes and potentially can be overridden. Be very careful when overriding hints! Make sure that all chained methods can work in a proposed manner of chaining.
Once a method was chained, it is impossible to unchain it. The only exception is "constructor". You don't need to define a method in order to supply a chaining hint.
If a method is chained, it cannot use this.inherited() because all other methods in the hierarchy will be called automatically.
Usually constructors and initializers of any kind are chained using "after" and destructors of any kind are chained as "before". Note that chaining assumes that chained methods do not return any value: any returned value will be discarded.
| Parameter | Type | Description |
| --- | --- | --- |
| className | String | *Optional*
The optional name of the constructor (loosely, a "class") stored in the "declaredClass" property in the created prototype. It will be used as a global name for a created constructor. |
| superclass | Function | Function[] | May be null, a Function, or an Array of Functions. This argument specifies a list of bases (the left-most one is the most deepest base). |
| props | Object | An object whose properties are copied to the created prototype. Add an instance-initialization function by making it a property named "constructor". |
**Returns:** [dojo/\_base/declare.\_\_DeclareCreatedObject](declare.__declarecreatedobject) | undefined
New constructor function.
Examples
--------
### Example 1
```
declare("my.classes.bar", my.classes.foo, {
// properties to be added to the class prototype
someValue: 2,
// initialization function
constructor: function(){
this.myComplicatedObject = new ReallyComplicatedObject();
},
// other functions
someMethod: function(){
doStuff();
}
});
```
### Example 2
```
var MyBase = declare(null, {
// constructor, properties, and methods go here
// ...
});
var MyClass1 = declare(MyBase, {
// constructor, properties, and methods go here
// ...
});
var MyClass2 = declare(MyBase, {
// constructor, properties, and methods go here
// ...
});
var MyDiamond = declare([MyClass1, MyClass2], {
// constructor, properties, and methods go here
// ...
});
```
### Example 3
```
var F = function(){ console.log("raw constructor"); };
F.prototype.method = function(){
console.log("raw method");
};
var A = declare(F, {
constructor: function(){
console.log("A.constructor");
},
method: function(){
console.log("before calling F.method...");
this.inherited(arguments);
console.log("...back in A");
}
});
new A().method();
// will print:
// raw constructor
// A.constructor
// before calling F.method...
// raw method
// ...back in A
```
### Example 4
```
var A = declare(null, {
"-chains-": {
destroy: "before"
}
});
var B = declare(A, {
constructor: function(){
console.log("B.constructor");
},
destroy: function(){
console.log("B.destroy");
}
});
var C = declare(B, {
constructor: function(){
console.log("C.constructor");
},
destroy: function(){
console.log("C.destroy");
}
});
new C().destroy();
// prints:
// B.constructor
// C.constructor
// C.destroy
// B.destroy
```
### Example 5
```
var A = declare(null, {
"-chains-": {
constructor: "manual"
}
});
var B = declare(A, {
constructor: function(){
// ...
// call the base constructor with new parameters
this.inherited(arguments, [1, 2, 3]);
// ...
}
});
```
### Example 6
```
var A = declare(null, {
"-chains-": {
m1: "before"
},
m1: function(){
console.log("A.m1");
},
m2: function(){
console.log("A.m2");
}
});
var B = declare(A, {
"-chains-": {
m2: "after"
},
m1: function(){
console.log("B.m1");
},
m2: function(){
console.log("B.m2");
}
});
var x = new B();
x.m1();
// prints:
// B.m1
// A.m1
x.m2();
// prints:
// A.m2
// B.m2
```
###
`Deferred``(canceller)`
Defined by [dojo/\_base/Deferred](deferred)
Deprecated. This module defines the legacy dojo/\_base/Deferred API. New code should use dojo/Deferred instead.
The Deferred API is based on the concept of promises that provide a generic interface into the eventual completion of an asynchronous action. The motivation for promises fundamentally is about creating a separation of concerns that allows one to achieve the same type of call patterns and logical data flow in asynchronous code as can be achieved in synchronous code. Promises allows one to be able to call a function purely with arguments needed for execution, without conflating the call with concerns of whether it is sync or async. One shouldn't need to alter a call's arguments if the implementation switches from sync to async (or vice versa). By having async functions return promises, the concerns of making the call are separated from the concerns of asynchronous interaction (which are handled by the promise).
The Deferred is a type of promise that provides methods for fulfilling the promise with a successful result or an error. The most important method for working with Dojo's promises is the then() method, which follows the CommonJS proposed promise API. An example of using a Dojo promise:
```
var resultingPromise = someAsyncOperation.then(function(result){
... handle result ...
},
function(error){
... handle error ...
});
```
The .then() call returns a new promise that represents the result of the execution of the callback. The callbacks will never affect the original promises value.
The Deferred instances also provide the following functions for backwards compatibility:
* addCallback(handler)
* addErrback(handler)
* callback(result)
* errback(result)
Callbacks are allowed to return promises themselves, so you can build complicated sequences of events with ease.
The creator of the Deferred may specify a canceller. The canceller is a function that will be called if Deferred.cancel is called before the Deferred fires. You can use this to implement clean aborting of an XMLHttpRequest, etc. Note that cancel will fire the deferred with a CancelledError (unless your canceller returns another kind of error), so the errbacks should be prepared to handle that error for cancellable Deferreds.
| Parameter | Type | Description |
| --- | --- | --- |
| canceller | Function | *Optional* |
Examples
--------
### Example 1
```
var deferred = new Deferred();
setTimeout(function(){ deferred.callback({success: true}); }, 1000);
return deferred;
```
### Example 2
Deferred objects are often used when making code asynchronous. It may be easiest to write functions in a synchronous manner and then split code using a deferred to trigger a response to a long-lived operation. For example, instead of register a callback function to denote when a rendering operation completes, the function can simply return a deferred:
```
// callback style:
function renderLotsOfData(data, callback){
var success = false
try{
for(var x in data){
renderDataitem(data[x]);
}
success = true;
}catch(e){ }
if(callback){
callback(success);
}
}
// using callback style
renderLotsOfData(someDataObj, function(success){
// handles success or failure
if(!success){
promptUserToRecover();
}
});
// NOTE: no way to add another callback here!!
```
### Example 3
Using a Deferred doesn't simplify the sending code any, but it provides a standard interface for callers and senders alike, providing both with a simple way to service multiple callbacks for an operation and freeing both sides from worrying about details such as "did this get called already?". With Deferreds, new callbacks can be added at any time.
```
// Deferred style:
function renderLotsOfData(data){
var d = new Deferred();
try{
for(var x in data){
renderDataitem(data[x]);
}
d.callback(true);
}catch(e){
d.errback(new Error("rendering failed"));
}
return d;
}
// using Deferred style
renderLotsOfData(someDataObj).then(null, function(){
promptUserToRecover();
});
// NOTE: addErrback and addCallback both return the Deferred
// again, so we could chain adding callbacks or save the
// deferred for later should we need to be notified again.
```
### Example 4
In this example, renderLotsOfData is synchronous and so both versions are pretty artificial. Putting the data display on a timeout helps show why Deferreds rock:
```
// Deferred style and async func
function renderLotsOfData(data){
var d = new Deferred();
setTimeout(function(){
try{
for(var x in data){
renderDataitem(data[x]);
}
d.callback(true);
}catch(e){
d.errback(new Error("rendering failed"));
}
}, 100);
return d;
}
// using Deferred style
renderLotsOfData(someDataObj).then(null, function(){
promptUserToRecover();
});
```
Note that the caller doesn't have to change his code at all to handle the asynchronous case.
###
`DeferredList``(list,fireOnOneCallback,fireOnOneErrback,consumeErrors,canceller)`
Defined by [dojo/DeferredList](../deferredlist)
Deprecated, use dojo/promise/all instead. Provides event handling for a group of Deferred objects.
DeferredList takes an array of existing deferreds and returns a new deferred of its own this new deferred will typically have its callback fired when all of the deferreds in the given list have fired their own deferreds. The parameters `fireOnOneCallback` and fireOnOneErrback, will fire before all the deferreds as appropriate
| Parameter | Type | Description |
| --- | --- | --- |
| list | Array | The list of deferreds to be synchronizied with this DeferredList |
| fireOnOneCallback | Boolean | *Optional*
Will cause the DeferredLists callback to be fired as soon as any of the deferreds in its list have been fired instead of waiting until the entire list has finished |
| fireOnOneErrback | Boolean | *Optional* |
| consumeErrors | Boolean | *Optional* |
| canceller | Function | *Optional*
A deferred canceller function, see dojo.Deferred |
###
`deprecated``(behaviour,extra,removal)`
Defined by [dojo/\_base/kernel](kernel)
Log a debug message to indicate that a behavior has been deprecated.
| Parameter | Type | Description |
| --- | --- | --- |
| behaviour | String | The API or behavior being deprecated. Usually in the form of "myApp.someFunction()". |
| extra | String | *Optional*
Text to append to the message. Often provides advice on a new function or facility to achieve the same goal during the deprecation period. |
| removal | String | *Optional*
Text to indicate when in the future the behavior will be removed. Usually a version number. |
Examples
--------
### Example 1
```
dojo.deprecated("myApp.getTemp()", "use myApp.getLocaleTemp() instead", "1.0");
```
###
`destroy``(node)`
Defined by [dojo/\_base/html](html)
| Parameter | Type | Description |
| --- | --- | --- |
| node | undefined | |
###
`disconnect``(handle)`
Defined by [dojo/\_base/connect](connect)
Remove a link created by dojo.connect.
Removes the connection between event and the method referenced by handle.
| Parameter | Type | Description |
| --- | --- | --- |
| handle | Handle | the return value of the dojo.connect call that created the connection. |
###
`docScroll``(doc)`
Defined by [dojo/dom-geometry](../dom-geometry)
Returns an object with {node, x, y} with corresponding offsets.
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | *Optional*
Optional document to query. If unspecified, use win.doc. |
**Returns:** Object | undefined
###
`empty``(node)`
Defined by [dojo/\_base/html](html)
| Parameter | Type | Description |
| --- | --- | --- |
| node | undefined | |
###
`eval``(scriptText)`
Defined by [dojo/\_base/kernel](kernel)
A legacy method created for use exclusively by internal Dojo methods. Do not use this method directly unless you understand its possibly-different implications on the platforms your are targeting.
Makes an attempt to evaluate scriptText in the global scope. The function works correctly for browsers that support indirect eval.
As usual, IE does not. On IE, the only way to implement global eval is to use execScript. Unfortunately, execScript does not return a value and breaks some current usages of dojo.eval. This implementation uses the technique of executing eval in the scope of a function that is a single scope frame below the global scope; thereby coming close to the global scope. Note carefully that
dojo.eval("var pi = 3.14;");
will define global pi in non-IE environments, but define pi only in a temporary local scope for IE. If you want to define a global variable using dojo.eval, write something like
dojo.eval("window.pi = 3.14;")
| Parameter | Type | Description |
| --- | --- | --- |
| scriptText | undefined | The text to evaluation. |
**Returns:** any
The result of the evaluation. Often `undefined`
###
`every``(arr,callback,thisObject)`
Defined by [dojo/\_base/array](array)
Determines whether or not every item in arr satisfies the condition implemented by callback.
This function corresponds to the JavaScript 1.6 Array.every() method, with one difference: when run over sparse arrays, this implementation passes the "holes" in the sparse array to the callback function with a value of undefined. JavaScript 1.6's every skips the holes in the sparse array. For more details, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/every>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | String | the array to iterate on. If a string, operates on individual characters. |
| callback | Function | String | a function is invoked with three arguments: item, index, and array and returns true if the condition is met. |
| thisObject | Object | *Optional*
may be used to scope the call to callback |
**Returns:** Boolean
Examples
--------
### Example 1
```
// returns false
array.every([1, 2, 3, 4], function(item){ return item>1; });
```
### Example 2
```
// returns true
array.every([1, 2, 3, 4], function(item){ return item>0; });
```
###
`exit``(exitcode)`
Defined by [dojo/\_base/configSpidermonkey](configspidermonkey)
| Parameter | Type | Description |
| --- | --- | --- |
| exitcode | undefined | |
###
`experimental``(moduleName,extra)`
Defined by [dojo/\_base/kernel](kernel)
Marks code as experimental.
This can be used to mark a function, file, or module as experimental. Experimental code is not ready to be used, and the APIs are subject to change without notice. Experimental code may be completed deleted without going through the normal deprecation process.
| Parameter | Type | Description |
| --- | --- | --- |
| moduleName | String | The name of a module, or the name of a module file or a specific function |
| extra | String | *Optional*
some additional message for the user |
Examples
--------
### Example 1
```
dojo.experimental("dojo.data.Result");
```
### Example 2
```
dojo.experimental("dojo.weather.toKelvin()", "PENDING approval from NOAA");
```
###
`fadeIn``(args)`
Defined by [dojo/\_base/fx](fx)
Returns an animation that will fade node defined in 'args' from its current opacity to fully opaque.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* node (DOMNode|String): The node referenced in the animation
* duration (Integer, optional): Duration of the animation in milliseconds.
* easing (Function, optional): An easing function.
|
**Returns:** undefined
###
`fadeOut``(args)`
Defined by [dojo/\_base/fx](fx)
Returns an animation that will fade node defined in 'args' from its current opacity to fully transparent.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* node (DOMNode|String): The node referenced in the animation
* duration (Integer, optional): Duration of the animation in milliseconds.
* easing (Function, optional): An easing function.
|
**Returns:** undefined
###
`fieldToObject``(inputNode)`
Defined by [dojo/dom-form](../dom-form)
Serialize a form field to a JavaScript object.
Returns the value encoded in a form field as as a string or an array of strings. Disabled form elements and unchecked radio and checkboxes are skipped. Multi-select elements are returned as an array of string values.
| Parameter | Type | Description |
| --- | --- | --- |
| inputNode | DOMNode | String | |
**Returns:** Object | undefined
###
`filter``(arr,callback,thisObject)`
Defined by [dojo/\_base/array](array)
Returns a new Array with those items from arr that match the condition implemented by callback.
This function corresponds to the JavaScript 1.6 Array.filter() method, with one difference: when run over sparse arrays, this implementation passes the "holes" in the sparse array to the callback function with a value of undefined. JavaScript 1.6's filter skips the holes in the sparse array. For more details, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | the array to iterate over. |
| callback | Function | String | a function that is invoked with three arguments (item, index, array). The return of this function is expected to be a boolean which determines whether the passed-in item will be included in the returned array. |
| thisObject | Object | *Optional*
may be used to scope the call to callback |
**Returns:** Array
Examples
--------
### Example 1
```
// returns [2, 3, 4]
array.filter([1, 2, 3, 4], function(item){ return item>1; });
```
###
`fixEvent``(evt,sender)`
Defined by [dojo/\_base/event](event)
normalizes properties on the event object including event bubbling methods, keystroke normalization, and x/y positions
| Parameter | Type | Description |
| --- | --- | --- |
| evt | Event | native event object |
| sender | DOMNode | node to treat as "currentTarget" |
**Returns:** Event
native event object
###
`fixIeBiDiScrollLeft``(scrollLeft,doc)`
Defined by [dojo/dom-geometry](../dom-geometry)
In RTL direction, scrollLeft should be a negative value, but IE returns a positive one. All codes using documentElement.scrollLeft must call this function to fix this error, otherwise the position will offset to right when there is a horizontal scrollbar.
| Parameter | Type | Description |
| --- | --- | --- |
| scrollLeft | Number | |
| doc | Document | *Optional*
Optional document to query. If unspecified, use win.doc. |
**Returns:** Number | number
###
`forEach``(arr,callback,thisObject)`
Defined by [dojo/\_base/array](array)
for every item in arr, callback is invoked. Return values are ignored. If you want to break out of the loop, consider using array.every() or array.some(). forEach does not allow breaking out of the loop over the items in arr.
This function corresponds to the JavaScript 1.6 Array.forEach() method, with one difference: when run over sparse arrays, this implementation passes the "holes" in the sparse array to the callback function with a value of undefined. JavaScript 1.6's forEach skips the holes in the sparse array. For more details, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/forEach>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | String | |
| callback | Function | String | |
| thisObject | Object | *Optional* |
Examples
--------
### Example 1
```
// log out all members of the array:
array.forEach(
[ "thinger", "blah", "howdy", 10 ],
function(item){
console.log(item);
}
);
```
### Example 2
```
// log out the members and their indexes
array.forEach(
[ "thinger", "blah", "howdy", 10 ],
function(item, idx, arr){
console.log(item, "at index:", idx);
}
);
```
### Example 3
```
// use a scoped object member as the callback
var obj = {
prefix: "logged via obj.callback:",
callback: function(item){
console.log(this.prefix, item);
}
};
// specifying the scope function executes the callback in that scope
array.forEach(
[ "thinger", "blah", "howdy", 10 ],
obj.callback,
obj
);
// alternately, we can accomplish the same thing with lang.hitch()
array.forEach(
[ "thinger", "blah", "howdy", 10 ],
lang.hitch(obj, "callback")
);
```
###
`formToJson``(formNode,prettyPrint)`
Defined by [dojo/dom-form](../dom-form)
Create a serialized JSON string from a form node or string ID identifying the form to serialize
| Parameter | Type | Description |
| --- | --- | --- |
| formNode | DOMNode | String | |
| prettyPrint | Boolean | *Optional* |
**Returns:** String | undefined
###
`formToObject``(formNode)`
Defined by [dojo/dom-form](../dom-form)
Serialize a form node to a JavaScript object.
Returns the values encoded in an HTML form as string properties in an object which it then returns. Disabled form elements, buttons, and other non-value form elements are skipped. Multi-select elements are returned as an array of string values.
| Parameter | Type | Description |
| --- | --- | --- |
| formNode | DOMNode | String | |
**Returns:** object
Examples
--------
### Example 1
This form:
```
<form id="test_form">
<input type="text" name="blah" value="blah">
<input type="text" name="no_value" value="blah" disabled>
<input type="button" name="no_value2" value="blah">
<select type="select" multiple name="multi" size="5">
<option value="blah">blah</option>
<option value="thud" selected>thud</option>
<option value="thonk" selected>thonk</option>
</select>
</form>
```
yields this object structure as the result of a call to formToObject():
```
{
blah: "blah",
multi: [
"thud",
"thonk"
]
};
```
###
`formToQuery``(formNode)`
Defined by [dojo/dom-form](../dom-form)
Returns a URL-encoded string representing the form passed as either a node or string ID identifying the form to serialize
| Parameter | Type | Description |
| --- | --- | --- |
| formNode | DOMNode | String | |
**Returns:** String | undefined
###
`fromJson``(js)`
Defined by [dojo/\_base/json](json)
Parses a JavaScript expression and returns a JavaScript value.
Throws for invalid JavaScript expressions. It does not use a strict JSON parser. It always delegates to eval(). The content passed to this method must therefore come from a trusted source. It is recommend that you use [dojo/json](../json)'s parse function for an implementation uses the (faster) native JSON parse when available.
| Parameter | Type | Description |
| --- | --- | --- |
| js | String | a string literal of a JavaScript expression, for instance: `'{ "foo": [ "bar", 1, { "baz": "thud" } ] }'` |
**Returns:** undefined
###
`getAttr``(node,name)`
Defined by [dojo/dom-attr](../dom-attr)
Gets an attribute on an HTML element.
Handles normalized getting of attributes on DOM Nodes.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to get the attribute on |
| name | String | the name of the attribute to get. |
**Returns:** any | undefined | null
the value of the requested attribute or null if that attribute does not have a specified or default value;
Examples
--------
### Example 1
```
// get the current value of the "foo" attribute on a node
require(["dojo/dom-attr", "dojo/dom"], function(domAttr, dom){
domAttr.get(dom.byId("nodeId"), "foo");
// or we can just pass the id:
domAttr.get("nodeId", "foo");
});
```
###
`getBorderExtents``(node,computedStyle)`
Defined by [dojo/dom-geometry](../dom-geometry)
returns an object with properties useful for noting the border dimensions.
* l/t/r/b = the sum of left/top/right/bottom border (respectively)
* w = the sum of the left and right border
* h = the sum of the top and bottom border
The w/h are used for calculating boxes. Normally application code will not need to invoke this directly, and will use the ...box... functions instead.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getComputedStyle``(node)`
Defined by [dojo/dom-style](../dom-style)
Returns a "computed style" object.
Gets a "computed style" object which can be used to gather information about the current state of the rendered node.
Note that this may behave differently on different browsers. Values may have different formats and value encodings across browsers.
Note also that this method is expensive. Wherever possible, reuse the returned object.
Use the [dojo/dom-style.get()](../dom-style#get) method for more consistent (pixelized) return values.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | A reference to a DOM node. Does NOT support taking an ID string for speed reasons. |
Examples
--------
### Example 1
```
require(["dojo/dom-style", "dojo/dom"], function(domStyle, dom){
domStyle.getComputedStyle(dom.byId('foo')).borderWidth;
});
```
### Example 2
Reusing the returned object, avoiding multiple lookups:
```
require(["dojo/dom-style", "dojo/dom"], function(domStyle, dom){
var cs = domStyle.getComputedStyle(dom.byId("someNode"));
var w = cs.width, h = cs.height;
});
```
###
`getContentBox``(node,computedStyle)`
Defined by [dojo/dom-geometry](../dom-geometry)
Returns an object that encodes the width, height, left and top positions of the node's content box, irrespective of the current box model.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getIeDocumentElementOffset``(doc)`
Defined by [dojo/dom-geometry](../dom-geometry)
returns the offset in x and y from the document body to the visual edge of the page for IE
The following values in IE contain an offset:
```
event.clientX
event.clientY
node.getBoundingClientRect().left
node.getBoundingClientRect().top
```
But other position related values do not contain this offset,
such as node.offsetLeft, node.offsetTop, node.style.left and node.style.top. The offset is always (2, 2) in LTR direction. When the body is in RTL direction, the offset counts the width of left scroll bar's width. This function computes the actual offset.
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | *Optional*
Optional document to query. If unspecified, use win.doc. |
**Returns:** object
###
`getL10nName``(moduleName,bundleName,locale)`
Defined by [dojo/i18n](../i18n)
| Parameter | Type | Description |
| --- | --- | --- |
| moduleName | undefined | |
| bundleName | undefined | |
| locale | undefined | |
**Returns:** string
###
`getMarginBox``(node,computedStyle)`
Defined by [dojo/dom-geometry](../dom-geometry)
returns an object that encodes the width, height, left and top positions of the node's margin box.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getMarginExtents``(node,computedStyle)`
Defined by [dojo/dom-geometry](../dom-geometry)
returns object with properties useful for box fitting with regards to box margins (i.e., the outer-box).
* l/t = marginLeft, marginTop, respectively
* w = total width, margin inclusive
* h = total height, margin inclusive
The w/h are used for calculating boxes. Normally application code will not need to invoke this directly, and will use the ...box... functions instead.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getMarginSize``(node,computedStyle)`
Defined by [dojo/dom-geometry](../dom-geometry)
returns an object that encodes the width and height of the node's margin box
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getNodeProp``(node,name)`
Defined by [dojo/dom-attr](../dom-attr)
Returns an effective value of a property or an attribute.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to remove the attribute from |
| name | String | the name of the attribute |
**Returns:** any
the value of the attribute
###
`getPadBorderExtents``(node,computedStyle)`
Defined by [dojo/dom-geometry](../dom-geometry)
Returns object with properties useful for box fitting with regards to padding.
* l/t/r/b = the sum of left/top/right/bottom padding and left/top/right/bottom border (respectively)
* w = the sum of the left and right padding and border
* h = the sum of the top and bottom padding and border
The w/h are used for calculating boxes. Normally application code will not need to invoke this directly, and will use the ...box... functions instead.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getPadExtents``(node,computedStyle)`
Defined by [dojo/dom-geometry](../dom-geometry)
Returns object with special values specifically useful for node fitting.
Returns an object with `w`, `h`, `l`, `t` properties:
```
l/t/r/b = left/top/right/bottom padding (respectively)
w = the total of the left and right padding
h = the total of the top and bottom padding
```
If 'node' has position, l/t forms the origin for child nodes.
The w/h are used for calculating boxes. Normally application code will not need to invoke this directly, and will use the ...box... functions instead.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
**Returns:** object
###
`getProp``(node,name)`
Defined by [dojo/dom-prop](../dom-prop)
Gets a property on an HTML element.
Handles normalized getting of properties on DOM nodes.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to get the property on |
| name | String | the name of the property to get. |
**Returns:** any | undefined
the value of the requested property or its default value
Examples
--------
### Example 1
```
// get the current value of the "foo" property on a node
require(["dojo/dom-prop", "dojo/dom"], function(domProp, dom){
domProp.get(dom.byId("nodeId"), "foo");
// or we can just pass the id:
domProp.get("nodeId", "foo");
});
```
###
`getStyle``(node,name)`
Defined by [dojo/dom-style](../dom-style)
Accesses styles on a node.
Getting the style value uses the computed style for the node, so the value will be a calculated value, not just the immediate node.style value. Also when getting values, use specific style names, like "borderBottomWidth" instead of "border" since compound values like "border" are not necessarily reflected as expected. If you want to get node dimensions, use [dojo/dom-geometry.getMarginBox()](../dom-geometry#getMarginBox), [dojo/dom-geometry.getContentBox()](../dom-geometry#getContentBox) or [dojo/dom-geometry.getPosition()](../dom-geometry#getPosition).
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to node to get style for |
| name | String | *Optional*
the style property to get |
**Returns:** undefined
Examples
--------
### Example 1
Passing only an ID or node returns the computed style object of the node:
```
require(["dojo/dom-style", "dojo/dom"], function(domStyle, dom){
domStyle.get("thinger");
});
```
### Example 2
Passing a node and a style property returns the current normalized, computed value for that property:
```
require(["dojo/dom-style", "dojo/dom"], function(domStyle, dom){
domStyle.get("thinger", "opacity"); // 1 by default
});
```
###
`hasAttr``(node,name)`
Defined by [dojo/dom-attr](../dom-attr)
Returns true if the requested attribute is specified on the given element, and false otherwise.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to check |
| name | String | the name of the attribute |
**Returns:** Boolean | contentWindow.document isn't accessible within IE7/8
true if the requested attribute is specified on the given element, and false otherwise
###
`hasClass``(node,classStr)`
Defined by [dojo/dom-class](../dom-class)
Returns whether or not the specified classes are a portion of the class list currently applied to the node.
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | String ID or DomNode reference to check the class for. |
| classStr | String | A string class name to look for. |
**Returns:** boolean
Examples
--------
### Example 1
Do something if a node with id="someNode" has class="aSillyClassName" present
```
if(dojo.hasClass("someNode","aSillyClassName")){ ... }
```
###
`hash``(hash,replace)`
Defined by [dojo/hash](../hash)
Gets or sets the hash string in the browser URL.
Handles getting and setting of location.hash.
* If no arguments are passed, acts as a getter.
* If a string is passed, acts as a setter.
| Parameter | Type | Description |
| --- | --- | --- |
| hash | String | *Optional*
the hash is set - #string. |
| replace | Boolean | *Optional*
If true, updates the hash value in the current history state instead of creating a new history state. |
**Returns:** any | undefined
when used as a getter, returns the current hash string. when used as a setter, returns the new hash string.
Examples
--------
### Example 1
```
topic.subscribe("/dojo/hashchange", context, callback);
function callback (hashValue){
// do something based on the hash value.
}
```
###
`indexOf``(arr,value,fromIndex,findLast)`
Defined by [dojo/\_base/array](array)
locates the first index of the provided value in the passed array. If the value is not found, -1 is returned.
This method corresponds to the JavaScript 1.6 Array.indexOf method, with two differences:
1. when run over sparse arrays, the Dojo function invokes the callback for every index whereas JavaScript 1.6's indexOf skips the holes in the sparse array.
2. uses equality (==) rather than strict equality (===)
For details on this method, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/indexOf>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | |
| value | Object | |
| fromIndex | Integer | *Optional* |
| findLast | Boolean | *Optional*
Makes indexOf() work like lastIndexOf(). Used internally; not meant for external usage. |
**Returns:** Number
###
`isBodyLtr``(doc)`
Defined by [dojo/dom-geometry](../dom-geometry)
Returns true if the current language is left-to-right, and false otherwise.
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | *Optional*
Optional document to query. If unspecified, use win.doc. |
**Returns:** Boolean | boolean
###
`isDescendant``(node,ancestor)`
Defined by [dojo/dom](../dom)
Returns true if node is a descendant of ancestor
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | string id or node reference to test |
| ancestor | DOMNode | String | string id or node reference of potential parent to test against |
**Returns:** boolean
Examples
--------
### Example 1
Test is node id="bar" is a descendant of node id="foo"
```
require(["dojo/dom"], function(dom){
if(dom.isDescendant("bar", "foo")){ ... }
});
```
###
`lastIndexOf``(arr,value,fromIndex)`
Defined by [dojo/\_base/array](array)
locates the last index of the provided value in the passed array. If the value is not found, -1 is returned.
This method corresponds to the JavaScript 1.6 Array.lastIndexOf method, with two differences:
1. when run over sparse arrays, the Dojo function invokes the callback for every index whereas JavaScript 1.6's lasIndexOf skips the holes in the sparse array.
2. uses equality (==) rather than strict equality (===)
For details on this method, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/lastIndexOf>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | undefined | |
| value | undefined | |
| fromIndex | Integer | *Optional* |
**Returns:** Number
###
`loadInit``(f)`
Defined by [dojo/\_base/loader](loader)
| Parameter | Type | Description |
| --- | --- | --- |
| f | undefined | |
###
`map``(arr,callback,thisObject,Ctr)`
Defined by [dojo/\_base/array](array)
applies callback to each element of arr and returns an Array with the results
This function corresponds to the JavaScript 1.6 Array.map() method, with one difference: when run over sparse arrays, this implementation passes the "holes" in the sparse array to the callback function with a value of undefined. JavaScript 1.6's map skips the holes in the sparse array. For more details, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | String | the array to iterate on. If a string, operates on individual characters. |
| callback | Function | String | a function is invoked with three arguments, (item, index, array), and returns a value |
| thisObject | Object | *Optional*
may be used to scope the call to callback |
| Ctr | undefined | |
**Returns:** Array | instance
Examples
--------
### Example 1
```
// returns [2, 3, 4, 5]
array.map([1, 2, 3, 4], function(item){ return item+1 });
```
###
`marginBox``(node,box)`
Defined by [dojo/\_base/html](html)
Getter/setter for the margin-box of node.
Getter/setter for the margin-box of node. Returns an object in the expected format of box (regardless if box is passed). The object might look like: `{ l: 50, t: 200, w: 300: h: 150 }` for a node offset from its parent 50px to the left, 200px from the top with a margin width of 300px and a margin-height of 150px.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DomNode | String | id or reference to DOM Node to get/set box for |
| box | Object | *Optional*
If passed, denotes that dojo.marginBox() should update/set the margin box for node. Box is an object in the above format. All properties are optional if passed. |
**Returns:** undefined
Examples
--------
### Example 1
Retrieve the margin box of a passed node
```
var box = dojo.marginBox("someNodeId");
console.dir(box);
```
### Example 2
Set a node's margin box to the size of another node
```
var box = dojo.marginBox("someNodeId");
dojo.marginBox("someOtherNode", box);
```
###
`moduleUrl``(module,url)`
Defined by [dojo/\_base/kernel](kernel)
Returns a URL relative to a module.
| Parameter | Type | Description |
| --- | --- | --- |
| module | String | dojo/dom-class |
| url | String | *Optional* |
**Returns:** string
Examples
--------
### Example 1
```
var pngPath = dojo.moduleUrl("acme","images/small.png");
console.dir(pngPath); // list the object properties
// create an image and set it's source to pngPath's value:
var img = document.createElement("img");
img.src = pngPath;
// add our image to the document
dojo.body().appendChild(img);
```
### Example 2
you may de-reference as far as you like down the package hierarchy. This is sometimes handy to avoid lengthy relative urls or for building portable sub-packages. In this example, the `acme.widget` and `acme.util` directories may be located under different roots (see `dojo.registerModulePath`) but the the modules which reference them can be unaware of their relative locations on the filesystem:
```
// somewhere in a configuration block
dojo.registerModulePath("acme.widget", "../../acme/widget");
dojo.registerModulePath("acme.util", "../../util");
// ...
// code in a module using acme resources
var tmpltPath = dojo.moduleUrl("acme.widget","templates/template.html");
var dataPath = dojo.moduleUrl("acme.util","resources/data.json");
```
###
`NodeList``(array)`
Defined by [dojo/query](../query)
Array-like object which adds syntactic sugar for chaining, common iteration operations, animation, and node manipulation. NodeLists are most often returned as the result of dojo/query() calls.
NodeList instances provide many utilities that reflect core Dojo APIs for Array iteration and manipulation, DOM manipulation, and event handling. Instead of needing to dig up functions in the dojo package, NodeLists generally make the full power of Dojo available for DOM manipulation tasks in a simple, chainable way.
| Parameter | Type | Description |
| --- | --- | --- |
| array | undefined | |
**Returns:** Array
Examples
--------
### Example 1
create a node list from a node
```
require(["dojo/query", "dojo/dom"
], function(query, dom){
query.NodeList(dom.byId("foo"));
});
```
### Example 2
get a NodeList from a CSS query and iterate on it
```
require(["dojo/on", "dojo/dom"
], function(on, dom){
var l = query(".thinger");
l.forEach(function(node, index, nodeList){
console.log(index, node.innerHTML);
});
});
```
### Example 3
use native and Dojo-provided array methods to manipulate a NodeList without needing to use dojo.\* functions explicitly:
```
require(["dojo/query", "dojo/dom-construct", "dojo/dom"
], function(query, domConstruct, dom){
var l = query(".thinger");
// since NodeLists are real arrays, they have a length
// property that is both readable and writable and
// push/pop/shift/unshift methods
console.log(l.length);
l.push(domConstruct.create("span"));
// dojo's normalized array methods work too:
console.log( l.indexOf(dom.byId("foo")) );
// ...including the special "function as string" shorthand
console.log( l.every("item.nodeType == 1") );
// NodeLists can be [..] indexed, or you can use the at()
// function to get specific items wrapped in a new NodeList:
var node = l[3]; // the 4th element
var newList = l.at(1, 3); // the 2nd and 4th elements
});
```
### Example 4
chainability is a key advantage of NodeLists:
```
require(["dojo/query", "dojo/NodeList-dom"
], function(query){
query(".thinger")
.onclick(function(e){ /* ... */ })
.at(1, 3, 8) // get a subset
.style("padding", "5px")
.forEach(console.log);
});
```
###
`objectToQuery``(map)`
Defined by [dojo/io-query](../io-query)
takes a name/value mapping object and returns a string representing a URL-encoded version of that object.
| Parameter | Type | Description |
| --- | --- | --- |
| map | Object | |
**Returns:** undefined
Examples
--------
### Example 1
this object:
```
{
blah: "blah",
multi: [
"thud",
"thonk"
]
};
```
yields the following query string:
```
"blah=blah&multi=thud&multi=thonk"
```
###
`place``(node,refNode,position)`
Defined by [dojo/dom-construct](../dom-construct)
Attempt to insert node into the DOM, choosing from various positioning options. Returns the first argument resolved to a DOM node.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | DocumentFragment | String | id or node reference, or HTML fragment starting with "<" to place relative to refNode |
| refNode | DOMNode | String | id or node reference to use as basis for placement |
| position | String | Number | *Optional*
string noting the position of node relative to refNode or a number indicating the location in the childNodes collection of refNode. Accepted string values are: * before
* after
* replace
* only
* first
* last
"first" and "last" indicate positions as children of refNode, "replace" replaces refNode, "only" replaces all children. position defaults to "last" if not specified |
**Returns:** DOMNode | undefined
Returned values is the first argument resolved to a DOM node.
.place() is also a method of `dojo/NodeList`, allowing `dojo/query` node lookups.
Examples
--------
### Example 1
Place a node by string id as the last child of another node by string id:
```
require(["dojo/dom-construct"], function(domConstruct){
domConstruct.place("someNode", "anotherNode");
});
```
### Example 2
Place a node by string id before another node by string id
```
require(["dojo/dom-construct"], function(domConstruct){
domConstruct.place("someNode", "anotherNode", "before");
});
```
### Example 3
Create a Node, and place it in the body element (last child):
```
require(["dojo/dom-construct", "dojo/_base/window"
], function(domConstruct, win){
domConstruct.place("<div></div>", win.body());
});
```
### Example 4
Put a new LI as the first child of a list by id:
```
require(["dojo/dom-construct"], function(domConstruct){
domConstruct.place("<li></li>", "someUl", "first");
});
```
###
`platformRequire``(modMap)`
Defined by [dojo/\_base/loader](loader)
require one or more modules based on which host environment Dojo is currently operating in
This method takes a "map" of arrays which one can use to optionally load dojo modules. The map is indexed by the possible dojo.name *values, with two additional values: "default" and "common". The items in the "default" array will be loaded if none of the other items have been chosen based on dojo.name*, set by your host environment. The items in the "common" array will *always* be loaded, regardless of which list is chosen.
| Parameter | Type | Description |
| --- | --- | --- |
| modMap | Object | |
Examples
--------
### Example 1
```
dojo.platformRequire({
browser: [
"foo.sample", // simple module
"foo.test",
["foo.bar.baz", true] // skip object check in _loadModule (dojo.require)
],
default: [ "foo.sample._base" ],
common: [ "important.module.common" ]
});
```
###
`popContext``()`
Defined by [dojo/\_base/configFirefoxExtension](configfirefoxextension)
If the context stack contains elements, ensure that subsequent code executes in the *previous* context to the current context. The current context set ([global, document]) is returned.
###
`position``(node,includeScroll)`
Defined by [dojo/dom-geometry](../dom-geometry)
Gets the position and size of the passed element relative to the viewport (if includeScroll==false), or relative to the document root (if includeScroll==true).
Returns an object of the form: `{ x: 100, y: 300, w: 20, h: 15 }`. If includeScroll==true, the x and y values will include any document offsets that may affect the position relative to the viewport. Uses the border-box model (inclusive of border and padding but not margin). Does not act as a setter.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | |
| includeScroll | Boolean | *Optional* |
**Returns:** Object | object
###
`prop``(node,name,value)`
Defined by [dojo/\_base/html](html)
Gets or sets a property on an HTML element.
Handles normalized getting and setting of properties on DOM Nodes. If 2 arguments are passed, and a the second argument is a string, acts as a getter.
If a third argument is passed, or if the second argument is a map of attributes, acts as a setter.
When passing functions as values, note that they will not be directly assigned to slots on the node, but rather the default behavior will be removed and the new behavior will be added using `dojo.connect()`, meaning that event handler properties will be normalized and that some caveats with regards to non-standard behaviors for onsubmit apply. Namely that you should cancel form submission using `dojo.stopEvent()` on the passed event object instead of returning a boolean value from the handler itself.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DomNode | String | id or reference to the element to get or set the property on |
| name | String | Object | the name of the property to get or set. |
| value | String | *Optional*
The value to set for the property |
**Returns:** any
when used as a getter, the value of the requested property or null if that attribute does not have a specified or default value;
when used as a setter, the DOM node
Examples
--------
### Example 1
```
// get the current value of the "foo" property on a node
dojo.prop(dojo.byId("nodeId"), "foo");
// or we can just pass the id:
dojo.prop("nodeId", "foo");
```
### Example 2
```
// use prop() to set the tab index
dojo.prop("nodeId", "tabIndex", 3);
```
### Example 3
Set multiple values at once, including event handlers:
```
dojo.prop("formId", {
"foo": "bar",
"tabIndex": -1,
"method": "POST",
"onsubmit": function(e){
// stop submitting the form. Note that the IE behavior
// of returning true or false will have no effect here
// since our handler is connect()ed to the built-in
// onsubmit behavior and so we need to use
// dojo.stopEvent() to ensure that the submission
// doesn't proceed.
dojo.stopEvent(e);
// submit the form with Ajax
dojo.xhrPost({ form: "formId" });
}
});
```
### Example 4
Style is s special case: Only set with an object hash of styles
```
dojo.prop("someNode",{
id:"bar",
style:{
width:"200px", height:"100px", color:"#000"
}
});
```
### Example 5
Again, only set style as an object hash of styles:
```
var obj = { color:"#fff", backgroundColor:"#000" };
dojo.prop("someNode", "style", obj);
// though shorter to use `dojo.style()` in this case:
dojo.style("someNode", obj);
```
###
`provide``(mid)`
Defined by [dojo/\_base/loader](loader)
| Parameter | Type | Description |
| --- | --- | --- |
| mid | undefined | |
###
`pushContext``(g,d)`
Defined by [dojo/\_base/configFirefoxExtension](configfirefoxextension)
causes subsequent calls to Dojo methods to assume the passed object and, optionally, document as the default scopes to use. A 2-element array of the previous global and document are returned.
dojo.pushContext treats contexts as a stack. The auto-detected contexts which are initially provided using dojo.setContext() require authors to keep state in order to "return" to a previous context, whereas the dojo.pushContext and dojo.popContext methods provide a more natural way to augment blocks of code to ensure that they execute in a different window or frame without issue. If called without any arguments, the default context (the context when Dojo is first loaded) is instead pushed into the stack. If only a single string is passed, a node in the intitial context's document is looked up and its contextWindow and contextDocument properties are used as the context to push. This means that iframes can be given an ID and code can be executed in the scope of the iframe's document in subsequent calls easily.
| Parameter | Type | Description |
| --- | --- | --- |
| g | Object | String | *Optional*
The global context. If a string, the id of the frame to search for a context and document. |
| d | MDocumentElement | *Optional*
The document element to execute subsequent code with. |
###
`queryToObject``(str)`
Defined by [dojo/io-query](../io-query)
Create an object representing a de-serialized query section of a URL. Query keys with multiple values are returned in an array.
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | |
**Returns:** object
Examples
--------
### Example 1
This string:
```
"foo=bar&foo=baz&thinger=%20spaces%20=blah&zonk=blarg&"
```
results in this object structure:
```
{
foo: [ "bar", "baz" ],
thinger: " spaces =blah",
zonk: "blarg"
}
```
Note that spaces and other urlencoded entities are correctly handled.
###
`rawXhrPost``(args)`
Defined by [dojo/\_base/xhr](xhr)
Sends an HTTP POST request to the server. In addition to the properties listed for the dojo.\_\_XhrArgs type, the following property is allowed:
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See `dojo/_base/xhr.contentHandlers`
* sync (Boolean, optional): false is default. Indicates whether the request should be a synchronous (blocking) request.
* headers (Object, optional): Additional HTTP headers to send in the request.
* failOk (Boolean, optional): false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
* contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
* load: This function will be called on a successful HTTP response code.
* error: This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
* handle: This function will be called at the end of every request, whether or not an error occurs.
* url (String): URL to server endpoint.
* content (Object, optional): Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
* timeout (Integer, optional): Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
* form (DOMNode, optional): DOM node for a form. Used to extract the form values and send to the server.
* preventCache (Boolean, optional): Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
* rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for dojo/\_base/xhr.rawXhrPost and dojo/\_base/xhr.rawXhrPut respectively.
* ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via dojo/topic.publish() for different phases of an IO operation. See dojo/main.\_\_IoPublish for a list of topics that are published.
|
**Returns:** undefined
###
`rawXhrPut``(args)`
Defined by [dojo/\_base/xhr](xhr)
Sends an HTTP PUT request to the server. In addition to the properties listed for the dojo.\_\_XhrArgs type, the following property is allowed:
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See `dojo/_base/xhr.contentHandlers`
* sync (Boolean, optional): false is default. Indicates whether the request should be a synchronous (blocking) request.
* headers (Object, optional): Additional HTTP headers to send in the request.
* failOk (Boolean, optional): false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
* contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
* load: This function will be called on a successful HTTP response code.
* error: This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
* handle: This function will be called at the end of every request, whether or not an error occurs.
* url (String): URL to server endpoint.
* content (Object, optional): Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
* timeout (Integer, optional): Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
* form (DOMNode, optional): DOM node for a form. Used to extract the form values and send to the server.
* preventCache (Boolean, optional): Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
* rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for dojo/\_base/xhr.rawXhrPost and dojo/\_base/xhr.rawXhrPut respectively.
* ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via dojo/topic.publish() for different phases of an IO operation. See dojo/main.\_\_IoPublish for a list of topics that are published.
|
**Returns:** undefined
###
`ready``(priority,context,callback)`
Defined by [dojo/ready](../ready)
Add a function to execute on DOM content loaded and all requested modules have arrived and been evaluated. In most cases, the `domReady` plug-in should suffice and this method should not be needed.
When called in a non-browser environment, just checks that all requested modules have arrived and been evaluated.
| Parameter | Type | Description |
| --- | --- | --- |
| priority | Integer | *Optional*
The order in which to exec this callback relative to other callbacks, defaults to 1000 |
| context | undefined | The context in which to run execute callback, or a callback if not using context |
| callback | Function | *Optional*
The function to execute. |
Examples
--------
### Example 1
Simple DOM and Modules ready syntax
```
require(["dojo/ready"], function(ready){
ready(function(){ alert("Dom ready!"); });
});
```
### Example 2
Using a priority
```
require(["dojo/ready"], function(ready){
ready(2, function(){ alert("low priority ready!"); })
});
```
### Example 3
Using context
```
require(["dojo/ready"], function(ready){
ready(foo, function(){
// in here, this == foo
});
});
```
### Example 4
Using dojo/hitch style args:
```
require(["dojo/ready"], function(ready){
var foo = { dojoReady: function(){ console.warn(this, "dojo dom and modules ready."); } };
ready(foo, "dojoReady");
});
```
###
`registerModulePath``(moduleName,prefix)`
Defined by [dojo/\_base/loader](loader)
Maps a module name to a path
An unregistered module is given the default path of ../[module], relative to Dojo root. For example, module acme is mapped to ../acme. If you want to use a different module name, use dojo.registerModulePath.
| Parameter | Type | Description |
| --- | --- | --- |
| moduleName | String | |
| prefix | String | |
Examples
--------
### Example 1
If your dojo.js is located at this location in the web root:
```
/myapp/js/dojo/dojo/dojo.js
```
and your modules are located at:
```
/myapp/js/foo/bar.js
/myapp/js/foo/baz.js
/myapp/js/foo/thud/xyzzy.js
```
Your application can tell Dojo to locate the "foo" namespace by calling:
```
dojo.registerModulePath("foo", "../../foo");
```
At which point you can then use dojo.require() to load the
modules (assuming they provide() the same things which are required). The full code might be:
```
<script type="text/javascript"
src="/myapp/js/dojo/dojo/dojo.js"></script>
<script type="text/javascript">
dojo.registerModulePath("foo", "../../foo");
dojo.require("foo.bar");
dojo.require("foo.baz");
dojo.require("foo.thud.xyzzy");
</script>
```
###
`removeAttr``(node,name)`
Defined by [dojo/dom-attr](../dom-attr)
Removes an attribute from an HTML element.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to remove the attribute from |
| name | String | the name of the attribute to remove |
###
`removeClass``(node,classStr)`
Defined by [dojo/dom-class](../dom-class)
Removes the specified classes from node. No `contains()` check is required.
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | String ID or DomNode reference to remove the class from. |
| classStr | String | Array | *Optional*
An optional String class name to remove, or several space-separated class names, or an array of class names. If omitted, all class names will be deleted. |
Examples
--------
### Example 1
Remove a class from some node:
```
require(["dojo/dom-class"], function(domClass){
domClass.remove("someNode", "firstClass");
});
```
### Example 2
Remove two classes from some node:
```
require(["dojo/dom-class"], function(domClass){
domClass.remove("someNode", "firstClass secondClass");
});
```
### Example 3
Remove two classes from some node (using array):
```
require(["dojo/dom-class"], function(domClass){
domClass.remove("someNode", ["firstClass", "secondClass"]);
});
```
### Example 4
Remove all classes from some node:
```
require(["dojo/dom-class"], function(domClass){
domClass.remove("someNode");
});
```
### Example 5
Available in `dojo/NodeList` for multiple removal
```
require(["dojo/query"], function(query){
query("ul > li").removeClass("foo");
});
```
###
`replaceClass``(node,addClassStr,removeClassStr)`
Defined by [dojo/dom-class](../dom-class)
Replaces one or more classes on a node if not present. Operates more quickly than calling dojo.removeClass and dojo.addClass
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | String ID or DomNode reference to remove the class from. |
| addClassStr | String | Array | A String class name to add, or several space-separated class names, or an array of class names. |
| removeClassStr | String | Array | *Optional*
A String class name to remove, or several space-separated class names, or an array of class names. |
Examples
--------
### Example 1
```
require(["dojo/dom-class"], function(domClass){
domClass.replace("someNode", "add1 add2", "remove1 remove2");
});
```
### Example 2
Replace all classes with addMe
```
require(["dojo/dom-class"], function(domClass){
domClass.replace("someNode", "addMe");
});
```
### Example 3
Available in `dojo/NodeList` for multiple toggles
```
require(["dojo/query"], function(query){
query(".findMe").replaceClass("addMe", "removeMe");
});
```
###
`require``(moduleName,omitModuleCheck)`
Defined by [dojo/\_base/loader](loader)
loads a Javascript module from the appropriate URI
Modules are loaded via dojo.require by using one of two loaders: the normal loader and the xdomain loader. The xdomain loader is used when dojo was built with a custom build that specified loader=xdomain and the module lives on a modulePath that is a whole URL, with protocol and a domain. The versions of Dojo that are on the Google and AOL CDNs use the xdomain loader.
If the module is loaded via the xdomain loader, it is an asynchronous load, since the module is added via a dynamically created script tag. This means that dojo.require() can return before the module has loaded. However, this should only happen in the case where you do dojo.require calls in the top-level HTML page, or if you purposely avoid the loader checking for dojo.require dependencies in your module by using a syntax like dojo["require"] to load the module.
Sometimes it is useful to not have the loader detect the dojo.require calls in the module so that you can dynamically load the modules as a result of an action on the page, instead of right at module load time.
Also, for script blocks in an HTML page, the loader does not pre-process them, so it does not know to download the modules before the dojo.require calls occur.
So, in those two cases, when you want on-the-fly module loading or for script blocks in the HTML page, special care must be taken if the dojo.required code is loaded asynchronously. To make sure you can execute code that depends on the dojo.required modules, be sure to add the code that depends on the modules in a dojo.addOnLoad() callback. dojo.addOnLoad waits for all outstanding modules to finish loading before executing.
This type of syntax works with both xdomain and normal loaders, so it is good practice to always use this idiom for on-the-fly code loading and in HTML script blocks. If at some point you change loaders and where the code is loaded from, it will all still work.
More on how dojo.require `dojo.require("A.B")` first checks to see if symbol A.B is defined. If it is, it is simply returned (nothing to do).
If it is not defined, it will look for `A/B.js` in the script root directory.
`dojo.require` throws an exception if it cannot find a file to load, or if the symbol `A.B` is not defined after loading.
It returns the object `A.B`, but note the caveats above about on-the-fly loading and HTML script blocks when the xdomain loader is loading a module.
`dojo.require()` does nothing about importing symbols into the current namespace. It is presumed that the caller will take care of that.
| Parameter | Type | Description |
| --- | --- | --- |
| moduleName | String | module name to load, using periods for separators, e.g. "dojo.date.locale". Module paths are de-referenced by dojo's internal mapping of locations to names and are disambiguated by longest prefix. See `dojo.registerModulePath()` for details on registering new modules. |
| omitModuleCheck | Boolean | *Optional*
if `true`, omitModuleCheck skips the step of ensuring that the loaded file actually defines the symbol it is referenced by. For example if it called as `dojo.require("a.b.c")` and the file located at `a/b/c.js` does not define an object `a.b.c`, and exception will be throws whereas no exception is raised when called as `dojo.require("a.b.c", true)` |
**Returns:** any
the required namespace object
Examples
--------
### Example 1
To use dojo.require in conjunction with dojo.ready:
```
dojo.require("foo");
dojo.require("bar");
dojo.addOnLoad(function(){
//you can now safely do something with foo and bar
});
```
### Example 2
For example, to import all symbols into a local block, you might write:
```
with (dojo.require("A.B")) {
...
}
```
And to import just the leaf symbol to a local variable:
```
var B = dojo.require("A.B");
...
```
###
`requireAfterIf``(condition,moduleName,omitModuleCheck)`
Defined by [dojo/\_base/loader](loader)
If the condition is true then call `dojo.require()` for the specified resource
| Parameter | Type | Description |
| --- | --- | --- |
| condition | Boolean | |
| moduleName | String | |
| omitModuleCheck | Boolean | *Optional* |
Examples
--------
### Example 1
```
dojo.requireIf(dojo.isBrowser, "my.special.Module");
```
###
`requireIf``(condition,moduleName,omitModuleCheck)`
Defined by [dojo/\_base/loader](loader)
If the condition is true then call `dojo.require()` for the specified resource
| Parameter | Type | Description |
| --- | --- | --- |
| condition | Boolean | |
| moduleName | String | |
| omitModuleCheck | Boolean | *Optional* |
Examples
--------
### Example 1
```
dojo.requireIf(dojo.isBrowser, "my.special.Module");
```
###
`requireLocalization``(moduleName,bundleName,locale)`
Defined by [dojo/\_base/loader](loader)
| Parameter | Type | Description |
| --- | --- | --- |
| moduleName | String | |
| bundleName | String | |
| locale | String | *Optional* |
###
`safeMixin``(target,source)`
Defined by [dojo/\_base/declare](declare)
Mix in properties skipping a constructor and decorating functions like it is done by declare().
This function is used to mix in properties like lang.mixin does, but it skips a constructor property and decorates functions like declare() does.
It is meant to be used with classes and objects produced with declare. Functions mixed in with dojo.safeMixin can use this.inherited() like normal methods.
This function is used to implement extend() method of a constructor produced with declare().
| Parameter | Type | Description |
| --- | --- | --- |
| target | Object | Target object to accept new properties. |
| source | Object | Source object for new properties. |
**Returns:** Object
Target object to accept new properties.
Examples
--------
### Example 1
```
var A = declare(null, {
m1: function(){
console.log("A.m1");
},
m2: function(){
console.log("A.m2");
}
});
var B = declare(A, {
m1: function(){
this.inherited(arguments);
console.log("B.m1");
}
});
B.extend({
m2: function(){
this.inherited(arguments);
console.log("B.m2");
}
});
var x = new B();
dojo.safeMixin(x, {
m1: function(){
this.inherited(arguments);
console.log("X.m1");
},
m2: function(){
this.inherited(arguments);
console.log("X.m2");
}
});
x.m2();
// prints:
// A.m1
// B.m1
// X.m1
```
###
`setAttr``(node,name,value)`
Defined by [dojo/dom-attr](../dom-attr)
Sets an attribute on an HTML element.
Handles normalized setting of attributes on DOM Nodes.
When passing functions as values, note that they will not be directly assigned to slots on the node, but rather the default behavior will be removed and the new behavior will be added using `dojo.connect()`, meaning that event handler properties will be normalized and that some caveats with regards to non-standard behaviors for onsubmit apply. Namely that you should cancel form submission using `dojo.stopEvent()` on the passed event object instead of returning a boolean value from the handler itself.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to set the attribute on |
| name | String | Object | the name of the attribute to set, or a hash of key-value pairs to set. |
| value | String | *Optional*
the value to set for the attribute, if the name is a string. |
**Returns:** any | undefined
the DOM node
Examples
--------
### Example 1
```
// use attr() to set the tab index
require(["dojo/dom-attr"], function(domAttr){
domAttr.set("nodeId", "tabIndex", 3);
});
```
### Example 2
Set multiple values at once, including event handlers:
```
require(["dojo/dom-attr"],
function(domAttr){
domAttr.set("formId", {
"foo": "bar",
"tabIndex": -1,
"method": "POST"
}
});
```
###
`setContentSize``(node,box,computedStyle)`
Defined by [dojo/dom-geometry](../dom-geometry)
Sets the size of the node's contents, irrespective of margins, padding, or borders.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| box | Object | hash with optional "w", and "h" properties for "width", and "height" respectively. All specified properties should have numeric values in whole pixels. |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
###
`setContext``(globalObject,globalDocument)`
Defined by [dojo/\_base/window](window)
changes the behavior of many core Dojo functions that deal with namespace and DOM lookup, changing them to work in a new global context (e.g., an iframe). The varibles dojo.global and dojo.doc are modified as a result of calling this function and the result of `dojo.body()` likewise differs.
| Parameter | Type | Description |
| --- | --- | --- |
| globalObject | Object | |
| globalDocument | DocumentElement | |
###
`setMarginBox``(node,box,computedStyle)`
Defined by [dojo/dom-geometry](../dom-geometry)
sets the size of the node's margin box and placement (left/top), irrespective of box model. Think of it as a passthrough to setBox that handles box-model vagaries for you.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| box | Object | hash with optional "l", "t", "w", and "h" properties for "left", "right", "width", and "height" respectively. All specified properties should have numeric values in whole pixels. |
| computedStyle | Object | *Optional*
This parameter accepts computed styles object. If this parameter is omitted, the functions will call dojo/dom-style.getComputedStyle to get one. It is a better way, calling dojo/dom-style.getComputedStyle once, and then pass the reference to this computedStyle parameter. Wherever possible, reuse the returned object of dojo/dom-style.getComputedStyle(). |
###
`setProp``(node,name,value)`
Defined by [dojo/dom-prop](../dom-prop)
Sets a property on an HTML element.
Handles normalized setting of properties on DOM nodes.
When passing functions as values, note that they will not be directly assigned to slots on the node, but rather the default behavior will be removed and the new behavior will be added using `dojo.connect()`, meaning that event handler properties will be normalized and that some caveats with regards to non-standard behaviors for onsubmit apply. Namely that you should cancel form submission using `dojo.stopEvent()` on the passed event object instead of returning a boolean value from the handler itself.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to the element to set the property on |
| name | String | Object | the name of the property to set, or a hash object to set multiple properties at once. |
| value | String | *Optional*
The value to set for the property |
**Returns:** any | undefined
the DOM node
Examples
--------
### Example 1
```
// use prop() to set the tab index
require(["dojo/dom-prop"], function(domProp){
domProp.set("nodeId", "tabIndex", 3);
});
```
### Example 2
Set multiple values at once, including event handlers:
```
require(["dojo/dom-prop"], function(domProp){
domProp.set("formId", {
"foo": "bar",
"tabIndex": -1,
"method": "POST",
});
});
```
###
`setSelectable``(node,selectable)`
Defined by [dojo/dom](../dom)
| Parameter | Type | Description |
| --- | --- | --- |
| node | undefined | |
| selectable | undefined | |
###
`setStyle``(node,name,value)`
Defined by [dojo/dom-style](../dom-style)
Sets styles on a node.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to node to set style for |
| name | String | Object | the style property to set in DOM-accessor format ("borderWidth", not "border-width") or an object with key/value pairs suitable for setting each property. |
| value | String | *Optional*
If passed, sets value on the node for style, handling cross-browser concerns. When setting a pixel value, be sure to include "px" in the value. For instance, top: "200px". Otherwise, in some cases, some browsers will not apply the style. |
**Returns:** String | undefined
If passed, sets value on the node for style, handling cross-browser concerns. When setting a pixel value, be sure to include "px" in the value. For instance, top: "200px". Otherwise, in some cases, some browsers will not apply the style.
Examples
--------
### Example 1
Passing a node, a style property, and a value changes the current display of the node and returns the new computed value
```
require(["dojo/dom-style"], function(domStyle){
domStyle.set("thinger", "opacity", 0.5); // == 0.5
});
```
### Example 2
Passing a node, an object-style style property sets each of the values in turn and returns the computed style object of the node:
```
require(["dojo/dom-style"], function(domStyle){
domStyle.set("thinger", {
"opacity": 0.5,
"border": "3px solid black",
"height": "300px"
});
});
```
### Example 3
When the CSS style property is hyphenated, the JavaScript property is camelCased. font-size becomes fontSize, and so on.
```
require(["dojo/dom-style", "dojo/dom"], function(domStyle, dom){
domStyle.set("thinger",{
fontSize:"14pt",
letterSpacing:"1.2em"
});
});
```
### Example 4
dojo/NodeList implements .style() using the same syntax, omitting the "node" parameter, calling dojo/dom-style.get() on every element of the list. See: `dojo/query` and `dojo/NodeList`
```
require(["dojo/dom-style", "dojo/query", "dojo/NodeList-dom"],
function(domStyle, query){
query(".someClassName").style("visibility","hidden");
// or
query("#baz > div").style({
opacity:0.75,
fontSize:"13pt"
});
});
```
###
`some``(arr,callback,thisObject)`
Defined by [dojo/\_base/array](array)
Determines whether or not any item in arr satisfies the condition implemented by callback.
This function corresponds to the JavaScript 1.6 Array.some() method, with one difference: when run over sparse arrays, this implementation passes the "holes" in the sparse array to the callback function with a value of undefined. JavaScript 1.6's some skips the holes in the sparse array. For more details, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/some>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | String | the array to iterate over. If a string, operates on individual characters. |
| callback | Function | String | a function is invoked with three arguments: item, index, and array and returns true if the condition is met. |
| thisObject | Object | *Optional*
may be used to scope the call to callback |
**Returns:** Boolean
Examples
--------
### Example 1
```
// is true
array.some([1, 2, 3, 4], function(item){ return item>1; });
```
### Example 2
```
// is false
array.some([1, 2, 3, 4], function(item){ return item<1; });
```
###
`Stateful``()`
Defined by [dojo/Stateful](../stateful)
###
`stopEvent``(evt)`
Defined by [dojo/\_base/event](event)
prevents propagation and clobbers the default action of the passed event
| Parameter | Type | Description |
| --- | --- | --- |
| evt | Event | The event object. If omitted, window.event is used on IE. |
###
`style``(node,name,value)`
Defined by [dojo/\_base/html](html)
Accesses styles on a node. If 2 arguments are passed, acts as a getter. If 3 arguments are passed, acts as a setter.
Getting the style value uses the computed style for the node, so the value will be a calculated value, not just the immediate node.style value. Also when getting values, use specific style names, like "borderBottomWidth" instead of "border" since compound values like "border" are not necessarily reflected as expected. If you want to get node dimensions, use `dojo.marginBox()`, `dojo.contentBox()` or `dojo.position()`.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | String | id or reference to node to get/set style for |
| name | String | Object | *Optional*
the style property to set in DOM-accessor format ("borderWidth", not "border-width") or an object with key/value pairs suitable for setting each property. |
| value | String | *Optional*
If passed, sets value on the node for style, handling cross-browser concerns. When setting a pixel value, be sure to include "px" in the value. For instance, top: "200px". Otherwise, in some cases, some browsers will not apply the style. |
**Returns:** any | undefined
when used as a getter, return the computed style of the node if passing in an ID or node, or return the normalized, computed value for the property when passing in a node and a style property
Examples
--------
### Example 1
Passing only an ID or node returns the computed style object of the node:
```
dojo.style("thinger");
```
### Example 2
Passing a node and a style property returns the current normalized, computed value for that property:
```
dojo.style("thinger", "opacity"); // 1 by default
```
### Example 3
Passing a node, a style property, and a value changes the current display of the node and returns the new computed value
```
dojo.style("thinger", "opacity", 0.5); // == 0.5
```
### Example 4
Passing a node, an object-style style property sets each of the values in turn and returns the computed style object of the node:
```
dojo.style("thinger", {
"opacity": 0.5,
"border": "3px solid black",
"height": "300px"
});
```
### Example 5
When the CSS style property is hyphenated, the JavaScript property is camelCased. font-size becomes fontSize, and so on.
```
dojo.style("thinger",{
fontSize:"14pt",
letterSpacing:"1.2em"
});
```
### Example 6
dojo/NodeList implements .style() using the same syntax, omitting the "node" parameter, calling dojo.style() on every element of the list. See: `dojo/query` and `dojo/NodeList`
```
dojo.query(".someClassName").style("visibility","hidden");
// or
dojo.query("#baz > div").style({
opacity:0.75,
fontSize:"13pt"
});
```
###
`toDom``(frag,doc)`
Defined by [dojo/dom-construct](../dom-construct)
instantiates an HTML fragment returning the corresponding DOM.
| Parameter | Type | Description |
| --- | --- | --- |
| frag | String | the HTML fragment |
| doc | DocumentNode | *Optional*
optional document to use when creating DOM nodes, defaults to dojo/\_base/window.doc if not specified. |
**Returns:** any | undefined
Document fragment, unless it's a single node in which case it returns the node itself
Examples
--------
### Example 1
Create a table row:
```
require(["dojo/dom-construct"], function(domConstruct){
var tr = domConstruct.toDom("<tr><td>First!</td></tr>");
});
```
###
`toggleClass``(node,classStr,condition)`
Defined by [dojo/dom-class](../dom-class)
Adds a class to node if not present, or removes if present. Pass a boolean condition if you want to explicitly add or remove. Returns the condition that was specified directly or indirectly.
| Parameter | Type | Description |
| --- | --- | --- |
| node | String | DOMNode | String ID or DomNode reference to toggle a class string |
| classStr | String | Array | A String class name to toggle, or several space-separated class names, or an array of class names. |
| condition | Boolean | *Optional*
If passed, true means to add the class, false means to remove. Otherwise dojo.hasClass(node, classStr) is used to detect the class presence. |
**Returns:** Boolean
If passed, true means to add the class, false means to remove. Otherwise dojo.hasClass(node, classStr) is used to detect the class presence.
Examples
--------
### Example 1
```
require(["dojo/dom-class"], function(domClass){
domClass.toggle("someNode", "hovered");
});
```
### Example 2
Forcefully add a class
```
require(["dojo/dom-class"], function(domClass){
domClass.toggle("someNode", "hovered", true);
});
```
### Example 3
Available in `dojo/NodeList` for multiple toggles
```
require(["dojo/query"], function(query){
query(".toggleMe").toggleClass("toggleMe");
});
```
###
`toJson``(it,prettyPrint)`
Defined by [dojo/\_base/json](json)
Returns a [JSON](http://json.org) serialization of an object.
Returns a [JSON](http://json.org) serialization of an object. Note that this doesn't check for infinite recursion, so don't do that! It is recommend that you use [dojo/json](../json)'s stringify function for an lighter and faster implementation that matches the native JSON API and uses the native JSON serializer when available.
| Parameter | Type | Description |
| --- | --- | --- |
| it | Object | an object to be serialized. Objects may define their own serialization via a special "**json**" or "json" function property. If a specialized serializer has been defined, it will be used as a fallback. Note that in 1.6, toJson would serialize undefined, but this no longer supported since it is not supported by native JSON serializer. |
| prettyPrint | Boolean | *Optional*
if true, we indent objects and arrays to make the output prettier. The variable `dojo.toJsonIndentStr` is used as the indent string -- to use something other than the default (tab), change that variable before calling dojo.toJson(). Note that if native JSON support is available, it will be used for serialization, and native implementations vary on the exact spacing used in pretty printing. |
**Returns:** any | undefined
A JSON string serialization of the passed-in object.
Examples
--------
### Example 1
simple serialization of a trivial object
```
var jsonStr = dojo.toJson({ howdy: "stranger!", isStrange: true });
doh.is('{"howdy":"stranger!","isStrange":true}', jsonStr);
```
### Example 2
a custom serializer for an objects of a particular class:
```
dojo.declare("Furby", null, {
furbies: "are strange",
furbyCount: 10,
__json__: function(){
},
});
```
###
`toPixelValue``(node,value)`
Defined by [dojo/dom-style](../dom-style)
converts style value to pixels on IE or return a numeric value.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DOMNode | |
| value | String | |
**Returns:** Number
###
`unsubscribe``(handle)`
Defined by [dojo/\_base/connect](connect)
Remove a topic listener.
| Parameter | Type | Description |
| --- | --- | --- |
| handle | Handle | The handle returned from a call to subscribe. |
Examples
--------
### Example 1
```
var alerter = dojo.subscribe("alerts", null, function(caption, message){ alert(caption + "\n" + message); };
...
dojo.unsubscribe(alerter);
```
###
`when``(valueOrPromise,callback,errback,progback)`
Defined by [dojo/when](../when)
Transparently applies callbacks to values and/or promises.
Accepts promises but also transparently handles non-promises. If no callbacks are provided returns a promise, regardless of the initial value. Foreign promises are converted.
If callbacks are provided and the initial value is not a promise, the callback is executed immediately with no error handling. Returns a promise if the initial value is a promise, or the result of the callback otherwise.
| Parameter | Type | Description |
| --- | --- | --- |
| valueOrPromise | undefined | Either a regular value or an object with a `then()` method that follows the Promises/A specification. |
| callback | Function | *Optional*
Callback to be invoked when the promise is resolved, or a non-promise is received. |
| errback | Function | *Optional*
Callback to be invoked when the promise is rejected. |
| progback | Function | *Optional*
Callback to be invoked when the promise emits a progress update. |
**Returns:** [dojo/promise/Promise](../promise/promise) | summary: | name:
Promise, or if a callback is provided, the result of the callback.
###
`windowUnloaded``()`
Defined by [dojo/\_base/configFirefoxExtension](configfirefoxextension)
signal fired by impending window destruction. You may use dojo.addOnWIndowUnload() or dojo.connect() to this method to perform page/application cleanup methods. See dojo.addOnWindowUnload for more info.
###
`withDoc``(documentObject,callback,thisObject,cbArguments)`
Defined by [dojo/\_base/window](window)
Invoke callback with documentObject as dojo/\_base/window::doc.
Invoke callback with documentObject as [dojo/\_base/window](window)::doc. If provided, callback will be executed in the context of object thisObject When callback() returns or throws an error, the [dojo/\_base/window](window)::doc will be restored to its previous state.
| Parameter | Type | Description |
| --- | --- | --- |
| documentObject | DocumentElement | |
| callback | Function | |
| thisObject | Object | *Optional* |
| cbArguments | Array | *Optional* |
**Returns:** undefined
###
`withGlobal``(globalObject,callback,thisObject,cbArguments)`
Defined by [dojo/\_base/window](window)
Invoke callback with globalObject as dojo.global and globalObject.document as dojo.doc.
Invoke callback with globalObject as dojo.global and globalObject.document as dojo.doc. If provided, globalObject will be executed in the context of object thisObject When callback() returns or throws an error, the dojo.global and dojo.doc will be restored to its previous state.
| Parameter | Type | Description |
| --- | --- | --- |
| globalObject | Object | |
| callback | Function | |
| thisObject | Object | *Optional* |
| cbArguments | Array | *Optional* |
**Returns:** undefined
###
`xhr``(method,args)`
Defined by [dojox/rpc/Client](http://dojotoolkit.org/api/1.10/dojox/rpc/Client)
| Parameter | Type | Description |
| --- | --- | --- |
| method | undefined | |
| args | undefined | |
**Returns:** undefined
###
`xhrDelete``(args)`
Defined by [dojo/\_base/xhr](xhr)
Sends an HTTP DELETE request to the server.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See `dojo/_base/xhr.contentHandlers`
* sync (Boolean, optional): false is default. Indicates whether the request should be a synchronous (blocking) request.
* headers (Object, optional): Additional HTTP headers to send in the request.
* failOk (Boolean, optional): false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
* contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
* load: This function will be called on a successful HTTP response code.
* error: This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
* handle: This function will be called at the end of every request, whether or not an error occurs.
* url (String): URL to server endpoint.
* content (Object, optional): Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
* timeout (Integer, optional): Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
* form (DOMNode, optional): DOM node for a form. Used to extract the form values and send to the server.
* preventCache (Boolean, optional): Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
* rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for dojo/\_base/xhr.rawXhrPost and dojo/\_base/xhr.rawXhrPut respectively.
* ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via dojo/topic.publish() for different phases of an IO operation. See dojo/main.\_\_IoPublish for a list of topics that are published.
|
**Returns:** undefined
###
`xhrGet``(args)`
Defined by [dojo/\_base/xhr](xhr)
Sends an HTTP GET request to the server.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See `dojo/_base/xhr.contentHandlers`
* sync (Boolean, optional): false is default. Indicates whether the request should be a synchronous (blocking) request.
* headers (Object, optional): Additional HTTP headers to send in the request.
* failOk (Boolean, optional): false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
* contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
* load: This function will be called on a successful HTTP response code.
* error: This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
* handle: This function will be called at the end of every request, whether or not an error occurs.
* url (String): URL to server endpoint.
* content (Object, optional): Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
* timeout (Integer, optional): Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
* form (DOMNode, optional): DOM node for a form. Used to extract the form values and send to the server.
* preventCache (Boolean, optional): Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
* rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for dojo/\_base/xhr.rawXhrPost and dojo/\_base/xhr.rawXhrPut respectively.
* ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via dojo/topic.publish() for different phases of an IO operation. See dojo/main.\_\_IoPublish for a list of topics that are published.
|
**Returns:** undefined
###
`xhrPost``(args)`
Defined by [dojo/\_base/xhr](xhr)
Sends an HTTP POST request to the server. In addition to the properties listed for the dojo.\_\_XhrArgs type, the following property is allowed:
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See `dojo/_base/xhr.contentHandlers`
* sync (Boolean, optional): false is default. Indicates whether the request should be a synchronous (blocking) request.
* headers (Object, optional): Additional HTTP headers to send in the request.
* failOk (Boolean, optional): false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
* contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
* load: This function will be called on a successful HTTP response code.
* error: This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
* handle: This function will be called at the end of every request, whether or not an error occurs.
* url (String): URL to server endpoint.
* content (Object, optional): Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
* timeout (Integer, optional): Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
* form (DOMNode, optional): DOM node for a form. Used to extract the form values and send to the server.
* preventCache (Boolean, optional): Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
* rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for dojo/\_base/xhr.rawXhrPost and dojo/\_base/xhr.rawXhrPut respectively.
* ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via dojo/topic.publish() for different phases of an IO operation. See dojo/main.\_\_IoPublish for a list of topics that are published.
|
**Returns:** undefined
###
`xhrPut``(args)`
Defined by [dojo/\_base/xhr](xhr)
Sends an HTTP PUT request to the server. In addition to the properties listed for the dojo.\_\_XhrArgs type, the following property is allowed:
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See `dojo/_base/xhr.contentHandlers`
* sync (Boolean, optional): false is default. Indicates whether the request should be a synchronous (blocking) request.
* headers (Object, optional): Additional HTTP headers to send in the request.
* failOk (Boolean, optional): false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
* contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
* load: This function will be called on a successful HTTP response code.
* error: This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
* handle: This function will be called at the end of every request, whether or not an error occurs.
* url (String): URL to server endpoint.
* content (Object, optional): Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
* timeout (Integer, optional): Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
* form (DOMNode, optional): DOM node for a form. Used to extract the form values and send to the server.
* preventCache (Boolean, optional): Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
* rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for dojo/\_base/xhr.rawXhrPost and dojo/\_base/xhr.rawXhrPut respectively.
* ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via dojo/topic.publish() for different phases of an IO operation. See dojo/main.\_\_IoPublish for a list of topics that are published.
|
**Returns:** undefined
| programming_docs |
dojo dojo/_base/array dojo/\_base/array
=================
Summary
-------
The Javascript v1.6 array extensions.
See the [dojo/\_base/array reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/array.html) for more information.
Methods
-------
###
`clearCache``()`
Defined by [dojo/\_base/array](array)
###
`every``(arr,callback,thisObject)`
Defined by [dojo/\_base/array](array)
Determines whether or not every item in arr satisfies the condition implemented by callback.
This function corresponds to the JavaScript 1.6 Array.every() method, with one difference: when run over sparse arrays, this implementation passes the "holes" in the sparse array to the callback function with a value of undefined. JavaScript 1.6's every skips the holes in the sparse array. For more details, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/every>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | String | the array to iterate on. If a string, operates on individual characters. |
| callback | Function | String | a function is invoked with three arguments: item, index, and array and returns true if the condition is met. |
| thisObject | Object | *Optional*
may be used to scope the call to callback |
**Returns:** Boolean
Examples
--------
### Example 1
```
// returns false
array.every([1, 2, 3, 4], function(item){ return item>1; });
```
### Example 2
```
// returns true
array.every([1, 2, 3, 4], function(item){ return item>0; });
```
###
`filter``(arr,callback,thisObject)`
Defined by [dojo/\_base/array](array)
Returns a new Array with those items from arr that match the condition implemented by callback.
This function corresponds to the JavaScript 1.6 Array.filter() method, with one difference: when run over sparse arrays, this implementation passes the "holes" in the sparse array to the callback function with a value of undefined. JavaScript 1.6's filter skips the holes in the sparse array. For more details, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | the array to iterate over. |
| callback | Function | String | a function that is invoked with three arguments (item, index, array). The return of this function is expected to be a boolean which determines whether the passed-in item will be included in the returned array. |
| thisObject | Object | *Optional*
may be used to scope the call to callback |
**Returns:** Array
Examples
--------
### Example 1
```
// returns [2, 3, 4]
array.filter([1, 2, 3, 4], function(item){ return item>1; });
```
###
`forEach``(arr,callback,thisObject)`
Defined by [dojo/\_base/array](array)
for every item in arr, callback is invoked. Return values are ignored. If you want to break out of the loop, consider using array.every() or array.some(). forEach does not allow breaking out of the loop over the items in arr.
This function corresponds to the JavaScript 1.6 Array.forEach() method, with one difference: when run over sparse arrays, this implementation passes the "holes" in the sparse array to the callback function with a value of undefined. JavaScript 1.6's forEach skips the holes in the sparse array. For more details, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/forEach>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | String | |
| callback | Function | String | |
| thisObject | Object | *Optional* |
Examples
--------
### Example 1
```
// log out all members of the array:
array.forEach(
[ "thinger", "blah", "howdy", 10 ],
function(item){
console.log(item);
}
);
```
### Example 2
```
// log out the members and their indexes
array.forEach(
[ "thinger", "blah", "howdy", 10 ],
function(item, idx, arr){
console.log(item, "at index:", idx);
}
);
```
### Example 3
```
// use a scoped object member as the callback
var obj = {
prefix: "logged via obj.callback:",
callback: function(item){
console.log(this.prefix, item);
}
};
// specifying the scope function executes the callback in that scope
array.forEach(
[ "thinger", "blah", "howdy", 10 ],
obj.callback,
obj
);
// alternately, we can accomplish the same thing with lang.hitch()
array.forEach(
[ "thinger", "blah", "howdy", 10 ],
lang.hitch(obj, "callback")
);
```
###
`indexOf``(arr,value,fromIndex,findLast)`
Defined by [dojo/\_base/array](array)
locates the first index of the provided value in the passed array. If the value is not found, -1 is returned.
This method corresponds to the JavaScript 1.6 Array.indexOf method, with two differences:
1. when run over sparse arrays, the Dojo function invokes the callback for every index whereas JavaScript 1.6's indexOf skips the holes in the sparse array.
2. uses equality (==) rather than strict equality (===)
For details on this method, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/indexOf>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | |
| value | Object | |
| fromIndex | Integer | *Optional* |
| findLast | Boolean | *Optional*
Makes indexOf() work like lastIndexOf(). Used internally; not meant for external usage. |
**Returns:** Number
###
`lastIndexOf``(arr,value,fromIndex)`
Defined by [dojo/\_base/array](array)
locates the last index of the provided value in the passed array. If the value is not found, -1 is returned.
This method corresponds to the JavaScript 1.6 Array.lastIndexOf method, with two differences:
1. when run over sparse arrays, the Dojo function invokes the callback for every index whereas JavaScript 1.6's lasIndexOf skips the holes in the sparse array.
2. uses equality (==) rather than strict equality (===)
For details on this method, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/lastIndexOf>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | undefined | |
| value | undefined | |
| fromIndex | Integer | *Optional* |
**Returns:** Number
###
`map``(arr,callback,thisObject,Ctr)`
Defined by [dojo/\_base/array](array)
applies callback to each element of arr and returns an Array with the results
This function corresponds to the JavaScript 1.6 Array.map() method, with one difference: when run over sparse arrays, this implementation passes the "holes" in the sparse array to the callback function with a value of undefined. JavaScript 1.6's map skips the holes in the sparse array. For more details, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | String | the array to iterate on. If a string, operates on individual characters. |
| callback | Function | String | a function is invoked with three arguments, (item, index, array), and returns a value |
| thisObject | Object | *Optional*
may be used to scope the call to callback |
| Ctr | undefined | |
**Returns:** Array | instance
Examples
--------
### Example 1
```
// returns [2, 3, 4, 5]
array.map([1, 2, 3, 4], function(item){ return item+1 });
```
###
`some``(arr,callback,thisObject)`
Defined by [dojo/\_base/array](array)
Determines whether or not any item in arr satisfies the condition implemented by callback.
This function corresponds to the JavaScript 1.6 Array.some() method, with one difference: when run over sparse arrays, this implementation passes the "holes" in the sparse array to the callback function with a value of undefined. JavaScript 1.6's some skips the holes in the sparse array. For more details, see: <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/some>
| Parameter | Type | Description |
| --- | --- | --- |
| arr | Array | String | the array to iterate over. If a string, operates on individual characters. |
| callback | Function | String | a function is invoked with three arguments: item, index, and array and returns true if the condition is met. |
| thisObject | Object | *Optional*
may be used to scope the call to callback |
**Returns:** Boolean
Examples
--------
### Example 1
```
// is true
array.some([1, 2, 3, 4], function(item){ return item>1; });
```
### Example 2
```
// is false
array.some([1, 2, 3, 4], function(item){ return item<1; });
```
dojo dojo/_base/window.doc dojo/\_base/window.doc
======================
Summary
-------
Alias for the current document. 'doc' can be modified for temporary context shifting. See also withDoc().
Use this rather than referring to 'window.document' to ensure your code runs correctly in managed contexts.
Examples
--------
### Example 1
```
n.appendChild(dojo.doc.createElement('div'));
```
Properties
----------
### documentElement
Defined by: [dojox/gfx/\_base](http://dojotoolkit.org/api/1.10/dojox/gfx/_base)
### dojoClick
Defined by: [dojox/mobile/common](http://dojotoolkit.org/api/1.10/dojox/mobile/common)
dojo dojo/_base/kernel.__XhrArgs dojo/\_base/kernel.\_\_XhrArgs
==============================
Summary
-------
In addition to the properties listed for the dojo.\_IoArgs type, the following properties are allowed for dojo.xhr\* methods.
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new kernel.__XhrArgs()`
Properties
----------
### content
Defined by: [dojo/\_base/xhr](xhr)
Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
### contentType
Defined by: [dojo/\_base/xhr](xhr)
"application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
### failOk
Defined by: [dojo/\_base/xhr](xhr)
false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
### form
Defined by: [dojo/\_base/xhr](xhr)
DOM node for a form. Used to extract the form values and send to the server.
### handleAs
Defined by: [dojo/\_base/xhr](xhr)
Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See [dojo/\_base/xhr.contentHandlers](xhr.contenthandlers)
### headers
Defined by: [dojo/\_base/xhr](xhr)
Additional HTTP headers to send in the request.
### ioPublish
Defined by: [dojo/\_base/xhr](xhr)
Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via [dojo/topic.publish()](../topic#publish) for different phases of an IO operation. See [dojo/main.\_\_IoPublish](../main.__iopublish) for a list of topics that are published.
### preventCache
Defined by: [dojo/\_base/xhr](xhr)
Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
### rawBody
Defined by: [dojo/\_base/xhr](xhr)
Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for [dojo/\_base/xhr.rawXhrPost](xhr#rawXhrPost) and [dojo/\_base/xhr.rawXhrPut](xhr#rawXhrPut) respectively.
### sync
Defined by: [dojo/\_base/xhr](xhr)
false is default. Indicates whether the request should be a synchronous (blocking) request.
### timeout
Defined by: [dojo/\_base/xhr](xhr)
Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
### url
Defined by: [dojo/\_base/xhr](xhr)
URL to server endpoint.
Methods
-------
###
`error``(response,ioArgs)`
Defined by [dojo/\_base/xhr](xhr)
This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
| Parameter | Type | Description |
| --- | --- | --- |
| response | Object | The response in the format as defined with handleAs. |
| ioArgs | [dojo/main.\_\_IoCallbackArgs](../main.__iocallbackargs) | Provides additional information about the request. |
###
`handle``(loadOrError,response,ioArgs)`
Defined by [dojo/\_base/xhr](xhr)
This function will be called at the end of every request, whether or not an error occurs.
| Parameter | Type | Description |
| --- | --- | --- |
| loadOrError | String | Provides a string that tells you whether this function was called because of success (load) or failure (error). |
| response | Object | The response in the format as defined with handleAs. |
| ioArgs | [dojo/main.\_\_IoCallbackArgs](../main.__iocallbackargs) | Provides additional information about the request. |
###
`load``(response,ioArgs)`
Defined by [dojo/\_base/xhr](xhr)
This function will be called on a successful HTTP response code.
| Parameter | Type | Description |
| --- | --- | --- |
| response | Object | The response in the format as defined with handleAs. |
| ioArgs | [dojo/main.\_\_IoCallbackArgs](../main.__iocallbackargs) | Provides additional information about the request. |
dojo dojo/_base/kernel.store dojo/\_base/kernel.store
========================
Properties
----------
### util
Defined by: [dojo/store/util/QueryResults](../store/util/queryresults)
Methods
-------
###
`Cache``(masterStore,cachingStore,options)`
Defined by [dojo/store/Cache](../store/cache)
| Parameter | Type | Description |
| --- | --- | --- |
| masterStore | undefined | |
| cachingStore | undefined | |
| options | undefined | |
**Returns:** undefined
###
`DataStore``()`
Defined by [dojo/store/DataStore](../store/datastore)
###
`JsonRest``()`
Defined by [dojo/store/JsonRest](../store/jsonrest)
###
`Memory``()`
Defined by [dojo/store/Memory](../store/memory)
###
`Observable``(store)`
Defined by [dojo/store/Observable](../store/observable)
The Observable store wrapper takes a store and sets an observe method on query() results that can be used to monitor results for changes.
Observable wraps an existing store so that notifications can be made when a query is performed.
| Parameter | Type | Description |
| --- | --- | --- |
| store | [dojo/store/api/Store](../store/api/store) | |
**Returns:** undefined
Examples
--------
### Example 1
Create a Memory store that returns an observable query, and then log some information about that query.
```
var store = Observable(new Memory({
data: [
{id: 1, name: "one", prime: false},
{id: 2, name: "two", even: true, prime: true},
{id: 3, name: "three", prime: true},
{id: 4, name: "four", even: true, prime: false},
{id: 5, name: "five", prime: true}
]
}));
var changes = [], results = store.query({ prime: true });
var observer = results.observe(function(object, previousIndex, newIndex){
changes.push({previousIndex:previousIndex, newIndex:newIndex, object:object});
});
```
See the Observable tests for more information.
dojo dojo/_base/config dojo/\_base/config
==================
Summary
-------
This module defines the user configuration during bootstrap.
By defining user configuration as a module value, an entire configuration can be specified in a build, thereby eliminating the need for sniffing and or explicitly setting in the global variable dojoConfig. Also, when multiple instances of dojo exist in a single application, each will necessarily be located at an unique absolute module identifier as given by the package configuration. Implementing configuration as a module allows for specifying unique, per-instance configurations.
See the [dojo/\_base/config reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/config.html) for more information.
Examples
--------
### Example 1
Create a second instance of dojo with a different, instance-unique configuration (assume the loader and dojo.js are already loaded).
```
// specify a configuration that creates a new instance of dojo at the absolute module identifier "myDojo"
require({
packages:[{
name:"myDojo",
location:".", //assume baseUrl points to dojo.js
}]
});
// specify a configuration for the myDojo instance
define("myDojo/config", {
// normal configuration variables go here, e.g.,
locale:"fr-ca"
});
// load and use the new instance of dojo
require(["myDojo"], function(dojo){
// dojo is the new instance of dojo
// use as required
});
```
Properties
----------
###
`addOnLoad`
Defined by: [dojo/\_base/config](config)
Adds a callback via [dojo/ready](../ready). Useful when Dojo is added after the page loads and djConfig.afterOnLoad is true. Supports the same arguments as [dojo/ready](../ready). When using a function reference, use `djConfig.addOnLoad = function(){};`. For object with function name use `djConfig.addOnLoad = [myObject, "functionName"];` and for object with function reference use `djConfig.addOnLoad = [myObject, function(){}];`
### afterOnLoad
Defined by: [dojo/ready](../ready)
### baseUrl
Defined by: [dojo/\_base/kernel](kernel)
###
`callback`
Defined by: [dojo/\_base/config](config)
Defines a callback to be used when dependencies are defined before the loader has been loaded. When provided, they cause the loader to execute require(deps, callback) once it has finished loading. Should be used with deps.
### debugContainerId
Defined by: [dojo/\_firebug/firebug](../_firebug/firebug)
### debugHeight
Defined by: [dojo/robotx](../robotx)
### defaultDuration
Defined by: [dojo/\_base/config](config)
Default duration, in milliseconds, for wipe and fade animations within dijits. Assigned to dijit.defaultDuration.
### deferredInstrumentation
Defined by: [dojo/\_base/config](config)
Whether deferred instrumentation should be loaded or included in builds.
###
`deps`
Defined by: [dojo/\_base/config](config)
Defines dependencies to be used before the loader has been loaded. When provided, they cause the loader to execute require(deps, callback) once it has finished loading. Should be used with callback.
### dojoBlankHtmlUrl
Defined by: [dojo/\_base/config](config)
Used by some modules to configure an empty iframe. Used by [dojo/io/iframe](../io/iframe) and [dojo/back](../back), and [dijit/popup](http://dojotoolkit.org/api/1.10/dijit/popup) support in IE where an iframe is needed to make sure native controls do not bleed through the popups. Normally this configuration variable does not need to be set, except when using cross-domain/CDN Dojo builds. Save dojo/resources/blank.html to your domain and set `djConfig.dojoBlankHtmlUrl` to the path on your domain your copy of blank.html.
### extraLocale
Defined by: [dojo/\_base/config](config)
No default value. Specifies additional locales whose resources should also be loaded alongside the default locale when calls to `dojo.requireLocalization()` are processed.
### ioPublish
Defined by: [dojo/\_base/config](config)
Set this to true to enable publishing of topics for the different phases of IO operations. Publishing is done via [dojo/topic.publish()](../topic#publish). See [dojo/main.\_\_IoPublish](../main.__iopublish) for a list of topics that are published.
### isDebug
Defined by: [dojo/\_base/config](config)
Defaults to `false`. If set to `true`, ensures that Dojo provides extended debugging feedback via Firebug. If Firebug is not available on your platform, setting `isDebug` to `true` will force Dojo to pull in (and display) the version of Firebug Lite which is integrated into the Dojo distribution, thereby always providing a debugging/logging console when `isDebug` is enabled. Note that Firebug's `console.*` methods are ALWAYS defined by Dojo. If `isDebug` is false and you are on a platform without Firebug, these methods will be defined as no-ops.
### locale
Defined by: [dojo/\_base/config](config)
The locale to assume for loading localized resources in this page, specified according to [RFC 3066](http://www.ietf.org/rfc/rfc3066.txt). Must be specified entirely in lowercase, e.g. `en-us` and `zh-cn`. See the documentation for `dojo.i18n` and `dojo.requireLocalization` for details on loading localized resources. If no locale is specified, Dojo assumes the locale of the user agent, according to `navigator.userLanguage` or `navigator.language` properties.
### modulePaths
Defined by: [dojo/\_base/config](config)
A map of module names to paths relative to `dojo.baseUrl`. The key/value pairs correspond directly to the arguments which `dojo.registerModulePath` accepts. Specifying `djConfig.modulePaths = { "foo": "../../bar" }` is the equivalent of calling `dojo.registerModulePath("foo", "../../bar");`. Multiple modules may be configured via `djConfig.modulePaths`.
### parseOnLoad
Defined by: [dojo/\_base/config](config)
Run the parser after the page is loaded
### require
Defined by: [dojo/\_base/config](config)
An array of module names to be loaded immediately after dojo.js has been included in a page.
### transparentColor
Defined by: [dojo/\_base/config](config)
Array containing the r, g, b components used as transparent color in dojo.Color; if undefined, [255,255,255] (white) will be used.
### urchin
Defined by: [dojox/analytics/Urchin](http://dojotoolkit.org/api/1.10/dojox/analytics/Urchin)
Used by `dojox.analytics.Urchin` as the default UA-123456-7 account number used when being created. Alternately, you can pass an acct:"" parameter to the constructor a la: new dojox.analytics.Urchin({ acct:"UA-123456-7" });
### useCustomLogger
Defined by: [dojo/\_base/config](config)
If set to a value that evaluates to true such as a string or array and isDebug is true and Firebug is not available or running, then it bypasses the creation of Firebug Lite allowing you to define your own console object.
### useDeferredInstrumentation
Defined by: [dojo/\_base/config](config)
Whether the deferred instrumentation should be used.
* `"report-rejections"`: report each rejection as it occurs.
* `true` or `1` or `"report-unhandled-rejections"`: wait 1 second in an attempt to detect unhandled rejections.
| programming_docs |
dojo dojo/_base/xhr.contentHandlers dojo/\_base/xhr.contentHandlers
===============================
Summary
-------
A map of available XHR transport handle types. Name matches the `handleAs` attribute passed to XHR calls.
A map of available XHR transport handle types. Name matches the `handleAs` attribute passed to XHR calls. Each contentHandler is called, passing the xhr object for manipulation. The return value from the contentHandler will be passed to the `load` or `handle` functions defined in the original xhr call.
Examples
--------
### Example 1
Creating a custom content-handler:
```
xhr.contentHandlers.makeCaps = function(xhr){
return xhr.responseText.toUpperCase();
}
// and later:
dojo.xhrGet({
url:"foo.txt",
handleAs:"makeCaps",
load: function(data){ /* data is a toUpper version of foo.txt */ }
});
```
Methods
-------
###
`auto``(xhr)`
Defined by [dojox/rpc/Service](http://dojotoolkit.org/api/1.10/dojox/rpc/Service)
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
###
`javascript``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler which evaluates the response data, expecting it to be valid JavaScript
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`json``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler which returns a JavaScript object created from the response data
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`json-comment-filtered``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler which expects comment-filtered JSON.
A contentHandler which expects comment-filtered JSON. the json-comment-filtered option was implemented to prevent "JavaScript Hijacking", but it is less secure than standard JSON. Use standard JSON instead. JSON prefixing can be used to subvert hijacking.
Will throw a notice suggesting to use application/json mimetype, as json-commenting can introduce security issues. To decrease the chances of hijacking, use the standard `json` contentHandler, and prefix your "JSON" with: {}&&
use djConfig.useCommentedJson = true to turn off the notice
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`json-comment-optional``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler which checks the presence of comment-filtered JSON and alternates between the `json` and `json-comment-filtered` contentHandlers.
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`text``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler which simply returns the plaintext response data
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`xml``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler returning an XML Document parsed from the response data
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
dojo dojo/_base/kernel.string dojo/\_base/kernel.string
=========================
Summary
-------
String utilities for Dojo
Methods
-------
###
`escape``(str)`
Defined by [dojo/string](../string)
Efficiently escape a string for insertion into HTML (innerHTML or attributes), replacing &, <, >, ", ', and / characters.
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | the string to escape |
###
`pad``(text,size,ch,end)`
Defined by [dojo/string](../string)
Pad a string to guarantee that it is at least `size` length by filling with the character `ch` at either the start or end of the string. Pads at the start, by default.
| Parameter | Type | Description |
| --- | --- | --- |
| text | String | the string to pad |
| size | Integer | length to provide padding |
| ch | String | *Optional*
character to pad, defaults to '0' |
| end | Boolean | *Optional*
adds padding at the end if true, otherwise pads at start |
**Returns:** number
Examples
--------
### Example 1
```
// Fill the string to length 10 with "+" characters on the right. Yields "Dojo++++++".
string.pad("Dojo", 10, "+", true);
```
###
`rep``(str,num)`
Defined by [dojo/string](../string)
Efficiently replicate a string `n` times.
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | the string to replicate |
| num | Integer | number of times to replicate the string |
**Returns:** string | undefined
###
`substitute``(template,map,transform,thisObject)`
Defined by [dojo/string](../string)
Performs parameterized substitutions on a string. Throws an exception if any parameter is unmatched.
| Parameter | Type | Description |
| --- | --- | --- |
| template | String | a string with expressions in the form `${key}` to be replaced or `${key:format}` which specifies a format function. keys are case-sensitive. |
| map | Object | Array | hash to search for substitutions |
| transform | Function | *Optional*
a function to process all parameters before substitution takes place, e.g. mylib.encodeXML |
| thisObject | Object | *Optional*
where to look for optional format function; default to the global namespace |
**Returns:** undefined
Examples
--------
### Example 1
Substitutes two expressions in a string from an Array or Object
```
// returns "File 'foo.html' is not found in directory '/temp'."
// by providing substitution data in an Array
string.substitute(
"File '${0}' is not found in directory '${1}'.",
["foo.html","/temp"]
);
// also returns "File 'foo.html' is not found in directory '/temp'."
// but provides substitution data in an Object structure. Dotted
// notation may be used to traverse the structure.
string.substitute(
"File '${name}' is not found in directory '${info.dir}'.",
{ name: "foo.html", info: { dir: "/temp" } }
);
```
### Example 2
Use a transform function to modify the values:
```
// returns "file 'foo.html' is not found in directory '/temp'."
string.substitute(
"${0} is not found in ${1}.",
["foo.html","/temp"],
function(str){
// try to figure out the type
var prefix = (str.charAt(0) == "/") ? "directory": "file";
return prefix + " '" + str + "'";
}
);
```
### Example 3
Use a formatter
```
// returns "thinger -- howdy"
string.substitute(
"${0:postfix}", ["thinger"], null, {
postfix: function(value, key){
return value + " -- howdy";
}
}
);
```
###
`trim``(str)`
Defined by [dojo/string](../string)
Trims whitespace from both sides of the string
This version of trim() was taken from [Steven Levithan's blog](http://blog.stevenlevithan.com/archives/faster-trim-javascript). The short yet performant version of this function is [dojo/\_base/lang.trim()](lang#trim), which is part of Dojo base. Uses String.prototype.trim instead, if available.
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | String to be trimmed |
**Returns:** String | string
Returns the trimmed string
dojo dojo/_base/kernel.back dojo/\_base/kernel.back
=======================
Summary
-------
Browser history management resources
Methods
-------
###
`addToHistory``(args)`
Defined by [dojo/back](../back)
adds a state object (args) to the history list.
To support getting back button notifications, the object argument should implement a function called either "back", "backButton", or "handle". The string "back" will be passed as the first and only argument to this callback.
To support getting forward button notifications, the object argument should implement a function called either "forward", "forwardButton", or "handle". The string "forward" will be passed as the first and only argument to this callback.
If you want the browser location string to change, define "changeUrl" on the object. If the value of "changeUrl" is true, then a unique number will be appended to the URL as a fragment identifier (<http://some.domain.com/path#uniquenumber>). If it is any other value that does not evaluate to false, that value will be used as the fragment identifier. For example, if changeUrl: 'page1', then the URL will look like: <http://some.domain.com/path#page1>
There are problems with using [dojo/back](../back) with semantically-named fragment identifiers ("hash values" on an URL). In most browsers it will be hard for [dojo/back](../back) to know distinguish a back from a forward event in those cases. For back/forward support to work best, the fragment ID should always be a unique value (something using new Date().getTime() for example). If you want to detect hash changes using semantic fragment IDs, then consider using [dojo/hash](../hash) instead (in Dojo 1.4+).
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | The state object that will be added to the history list. |
Examples
--------
### Example 1
```
back.addToHistory({
back: function(){ console.log('back pressed'); },
forward: function(){ console.log('forward pressed'); },
changeUrl: true
});
```
###
`getHash``()`
Defined by [dojo/back](../back)
**Returns:** undefined
###
`goBack``()`
Defined by [dojo/back](../back)
private method. Do not call this directly.
###
`goForward``()`
Defined by [dojo/back](../back)
private method. Do not call this directly.
###
`init``()`
Defined by [dojo/back](../back)
Initializes the undo stack. This must be called from a
dojo dojo/_base/kernel.keys dojo/\_base/kernel.keys
=======================
Summary
-------
Definitions for common key values. Client code should test keyCode against these named constants, as the actual codes can vary by browser.
Properties
----------
### ALT
Defined by: [dojo/keys](../keys)
### BACKSPACE
Defined by: [dojo/keys](../keys)
### CAPS\_LOCK
Defined by: [dojo/keys](../keys)
### CLEAR
Defined by: [dojo/keys](../keys)
### copyKey
Defined by: [dojo/keys](../keys)
### CTRL
Defined by: [dojo/keys](../keys)
### DELETE
Defined by: [dojo/keys](../keys)
### DOWN\_ARROW
Defined by: [dojo/keys](../keys)
### DOWN\_DPAD
Defined by: [dojo/keys](../keys)
### END
Defined by: [dojo/keys](../keys)
### ENTER
Defined by: [dojo/keys](../keys)
### ESCAPE
Defined by: [dojo/keys](../keys)
### F1
Defined by: [dojo/keys](../keys)
### F10
Defined by: [dojo/keys](../keys)
### F11
Defined by: [dojo/keys](../keys)
### F12
Defined by: [dojo/keys](../keys)
### F13
Defined by: [dojo/keys](../keys)
### F14
Defined by: [dojo/keys](../keys)
### F15
Defined by: [dojo/keys](../keys)
### F2
Defined by: [dojo/keys](../keys)
### F3
Defined by: [dojo/keys](../keys)
### F4
Defined by: [dojo/keys](../keys)
### F5
Defined by: [dojo/keys](../keys)
### F6
Defined by: [dojo/keys](../keys)
### F7
Defined by: [dojo/keys](../keys)
### F8
Defined by: [dojo/keys](../keys)
### F9
Defined by: [dojo/keys](../keys)
### HELP
Defined by: [dojo/keys](../keys)
### HOME
Defined by: [dojo/keys](../keys)
### INSERT
Defined by: [dojo/keys](../keys)
### LEFT\_ARROW
Defined by: [dojo/keys](../keys)
### LEFT\_DPAD
Defined by: [dojo/keys](../keys)
### LEFT\_WINDOW
Defined by: [dojo/keys](../keys)
### META
Defined by: [dojo/keys](../keys)
### NUM\_LOCK
Defined by: [dojo/keys](../keys)
### NUMPAD\_0
Defined by: [dojo/keys](../keys)
### NUMPAD\_1
Defined by: [dojo/keys](../keys)
### NUMPAD\_2
Defined by: [dojo/keys](../keys)
### NUMPAD\_3
Defined by: [dojo/keys](../keys)
### NUMPAD\_4
Defined by: [dojo/keys](../keys)
### NUMPAD\_5
Defined by: [dojo/keys](../keys)
### NUMPAD\_6
Defined by: [dojo/keys](../keys)
### NUMPAD\_7
Defined by: [dojo/keys](../keys)
### NUMPAD\_8
Defined by: [dojo/keys](../keys)
### NUMPAD\_9
Defined by: [dojo/keys](../keys)
### NUMPAD\_DIVIDE
Defined by: [dojo/keys](../keys)
### NUMPAD\_ENTER
Defined by: [dojo/keys](../keys)
### NUMPAD\_MINUS
Defined by: [dojo/keys](../keys)
### NUMPAD\_MULTIPLY
Defined by: [dojo/keys](../keys)
### NUMPAD\_PERIOD
Defined by: [dojo/keys](../keys)
### NUMPAD\_PLUS
Defined by: [dojo/keys](../keys)
### PAGE\_DOWN
Defined by: [dojo/keys](../keys)
### PAGE\_UP
Defined by: [dojo/keys](../keys)
### PAUSE
Defined by: [dojo/keys](../keys)
### RIGHT\_ARROW
Defined by: [dojo/keys](../keys)
### RIGHT\_DPAD
Defined by: [dojo/keys](../keys)
### RIGHT\_WINDOW
Defined by: [dojo/keys](../keys)
### SCROLL\_LOCK
Defined by: [dojo/keys](../keys)
### SELECT
Defined by: [dojo/keys](../keys)
### SHIFT
Defined by: [dojo/keys](../keys)
### SPACE
Defined by: [dojo/keys](../keys)
### TAB
Defined by: [dojo/keys](../keys)
### UP\_ARROW
Defined by: [dojo/keys](../keys)
### UP\_DPAD
Defined by: [dojo/keys](../keys)
dojo dojo/_base/kernel.data dojo/\_base/kernel.data
=======================
Properties
----------
### api
Defined by: [dojo/data/api/Read](../data/api/read)
### util
Defined by: [dojo/data/util/filter](../data/util/filter)
Methods
-------
###
`ItemFileReadStore``()`
Defined by [dojo/data/ItemFileReadStore](../data/itemfilereadstore)
###
`ItemFileWriteStore``()`
Defined by [dojo/data/ItemFileWriteStore](../data/itemfilewritestore)
###
`ObjectStore``()`
Defined by [dojo/data/ObjectStore](../data/objectstore)
dojo dojo/_base/kernel.colors dojo/\_base/kernel.colors
=========================
Methods
-------
###
`makeGrey``(g,a)`
Defined by [dojo/colors](../colors)
creates a greyscale color with an optional alpha
| Parameter | Type | Description |
| --- | --- | --- |
| g | Number | |
| a | Number | *Optional* |
dojo dojo/_base/unload dojo/\_base/unload
==================
Summary
-------
This module contains the document and window unload detection API. This module is deprecated. Use on(window, "unload", func) and on(window, "beforeunload", func) instead.
See the [dojo/\_base/unload reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/unload.html) for more information.
Methods
-------
###
`addOnUnload``(obj,functionName)`
Defined by [dojo/\_base/unload](unload)
Registers a function to be triggered when the page unloads. Deprecated, use on(window, "beforeunload", lang.hitch(obj, functionName)) instead.
The first time that addOnUnload is called Dojo will register a page listener to trigger your unload handler with.
In a browser environment, the functions will be triggered during the window.onbeforeunload event. Be careful of doing too much work in an unload handler. onbeforeunload can be triggered if a link to download a file is clicked, or if the link is a javascript: link. In these cases, the onbeforeunload event fires, but the document is not actually destroyed. So be careful about doing destructive operations in a dojo.addOnUnload callback.
Further note that calling dojo.addOnUnload will prevent browsers from using a "fast back" cache to make page loading via back button instantaneous.
| Parameter | Type | Description |
| --- | --- | --- |
| obj | Object? | Function | *Optional* |
| functionName | String | Function | *Optional* |
Examples
--------
### Example 1
```
var afunc = function() {console.log("global function");};
require(["dojo/_base/unload"], function(unload) {
var foo = {bar: function(){ console.log("bar unloading...");},
data: "mydata"};
unload.addOnUnload(afunc);
unload.addOnUnload(foo, "bar");
unload.addOnUnload(foo, function(){console.log("", this.data);});
});
```
###
`addOnWindowUnload``(obj,functionName)`
Defined by [dojo/\_base/unload](unload)
Registers a function to be triggered when window.onunload fires. Deprecated, use on(window, "unload", lang.hitch(obj, functionName)) instead.
The first time that addOnWindowUnload is called Dojo will register a page listener to trigger your unload handler with. Note that registering these handlers may destroy "fastback" page caching in browsers that support it. Be careful trying to modify the DOM or access JavaScript properties during this phase of page unloading: they may not always be available. Consider addOnUnload() if you need to modify the DOM or do heavy JavaScript work since it fires at the equivalent of the page's "onbeforeunload" event.
| Parameter | Type | Description |
| --- | --- | --- |
| obj | Object | Function | *Optional* |
| functionName | String | Function | *Optional* |
Examples
--------
### Example 1
```
var afunc = function() {console.log("global function");};
require(["dojo/_base/unload"], function(unload) {
var foo = {bar: function(){ console.log("bar unloading...");},
data: "mydata"};
unload.addOnWindowUnload(afunc);
unload.addOnWindowUnload(foo, "bar");
unload.addOnWindowUnload(foo, function(){console.log("", this.data);});
});
```
dojo dojo/_base/declare dojo/\_base/declare
===================
Summary
-------
Create a feature-rich constructor from compact notation.
Create a constructor using a compact notation for inheritance and prototype extension.
Mixin ancestors provide a type of multiple inheritance. Prototypes of mixin ancestors are copied to the new class: changes to mixin prototypes will not affect classes to which they have been mixed in.
Ancestors can be compound classes created by this version of declare(). In complex cases all base classes are going to be linearized according to C3 MRO algorithm (see <http://www.python.org/download/releases/2.3/mro/> for more details).
"className" is cached in "declaredClass" property of the new class, if it was supplied. The immediate super class will be cached in "superclass" property of the new class.
Methods in "props" will be copied and modified: "nom" property (the declared name of the method) will be added to all copied functions to help identify them for the internal machinery. Be very careful, while reusing methods: if you use the same function under different names, it can produce errors in some cases.
It is possible to use constructors created "manually" (without declare()) as bases. They will be called as usual during the creation of an instance, their methods will be chained, and even called by "this.inherited()".
Special property "-chains-" governs how to chain methods. It is a dictionary, which uses method names as keys, and hint strings as values. If a hint string is "after", this method will be called after methods of its base classes. If a hint string is "before", this method will be called before methods of its base classes.
If "constructor" is not mentioned in "-chains-" property, it will be chained using the legacy mode: using "after" chaining, calling preamble() method before each constructor, if available, and calling postscript() after all constructors were executed. If the hint is "after", it is chained as a regular method, but postscript() will be called after the chain of constructors. "constructor" cannot be chained "before", but it allows a special hint string: "manual", which means that constructors are not going to be chained in any way, and programmer will call them manually using this.inherited(). In the latter case postscript() will be called after the construction.
All chaining hints are "inherited" from base classes and potentially can be overridden. Be very careful when overriding hints! Make sure that all chained methods can work in a proposed manner of chaining.
Once a method was chained, it is impossible to unchain it. The only exception is "constructor". You don't need to define a method in order to supply a chaining hint.
If a method is chained, it cannot use this.inherited() because all other methods in the hierarchy will be called automatically.
Usually constructors and initializers of any kind are chained using "after" and destructors of any kind are chained as "before". Note that chaining assumes that chained methods do not return any value: any returned value will be discarded.
Usage
-----
declare`(className,superclass,props);`
| Parameter | Type | Description |
| --- | --- | --- |
| className | String | *Optional*
The optional name of the constructor (loosely, a "class") stored in the "declaredClass" property in the created prototype. It will be used as a global name for a created constructor. |
| superclass | Function | Function[] | May be null, a Function, or an Array of Functions. This argument specifies a list of bases (the left-most one is the most deepest base). |
| props | Object | An object whose properties are copied to the created prototype. Add an instance-initialization function by making it a property named "constructor". |
**Returns:** [dojo/\_base/declare.\_\_DeclareCreatedObject](declare.__declarecreatedobject) | undefined
New constructor function.
See the [dojo/\_base/declare reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/declare.html) for more information.
Examples
--------
### Example 1
```
declare("my.classes.bar", my.classes.foo, {
// properties to be added to the class prototype
someValue: 2,
// initialization function
constructor: function(){
this.myComplicatedObject = new ReallyComplicatedObject();
},
// other functions
someMethod: function(){
doStuff();
}
});
```
### Example 2
```
var MyBase = declare(null, {
// constructor, properties, and methods go here
// ...
});
var MyClass1 = declare(MyBase, {
// constructor, properties, and methods go here
// ...
});
var MyClass2 = declare(MyBase, {
// constructor, properties, and methods go here
// ...
});
var MyDiamond = declare([MyClass1, MyClass2], {
// constructor, properties, and methods go here
// ...
});
```
### Example 3
```
var F = function(){ console.log("raw constructor"); };
F.prototype.method = function(){
console.log("raw method");
};
var A = declare(F, {
constructor: function(){
console.log("A.constructor");
},
method: function(){
console.log("before calling F.method...");
this.inherited(arguments);
console.log("...back in A");
}
});
new A().method();
// will print:
// raw constructor
// A.constructor
// before calling F.method...
// raw method
// ...back in A
```
### Example 4
```
var A = declare(null, {
"-chains-": {
destroy: "before"
}
});
var B = declare(A, {
constructor: function(){
console.log("B.constructor");
},
destroy: function(){
console.log("B.destroy");
}
});
var C = declare(B, {
constructor: function(){
console.log("C.constructor");
},
destroy: function(){
console.log("C.destroy");
}
});
new C().destroy();
// prints:
// B.constructor
// C.constructor
// C.destroy
// B.destroy
```
### Example 5
```
var A = declare(null, {
"-chains-": {
constructor: "manual"
}
});
var B = declare(A, {
constructor: function(){
// ...
// call the base constructor with new parameters
this.inherited(arguments, [1, 2, 3]);
// ...
}
});
```
### Example 6
```
var A = declare(null, {
"-chains-": {
m1: "before"
},
m1: function(){
console.log("A.m1");
},
m2: function(){
console.log("A.m2");
}
});
var B = declare(A, {
"-chains-": {
m2: "after"
},
m1: function(){
console.log("B.m1");
},
m2: function(){
console.log("B.m2");
}
});
var x = new B();
x.m1();
// prints:
// B.m1
// A.m1
x.m2();
// prints:
// A.m2
// B.m2
```
Properties
----------
Methods
-------
###
`safeMixin``(target,source)`
Defined by [dojo/\_base/declare](declare)
Mix in properties skipping a constructor and decorating functions like it is done by declare().
This function is used to mix in properties like lang.mixin does, but it skips a constructor property and decorates functions like declare() does.
It is meant to be used with classes and objects produced with declare. Functions mixed in with dojo.safeMixin can use this.inherited() like normal methods.
This function is used to implement extend() method of a constructor produced with declare().
| Parameter | Type | Description |
| --- | --- | --- |
| target | Object | Target object to accept new properties. |
| source | Object | Source object for new properties. |
**Returns:** Object
Target object to accept new properties.
Examples
--------
### Example 1
```
var A = declare(null, {
m1: function(){
console.log("A.m1");
},
m2: function(){
console.log("A.m2");
}
});
var B = declare(A, {
m1: function(){
this.inherited(arguments);
console.log("B.m1");
}
});
B.extend({
m2: function(){
this.inherited(arguments);
console.log("B.m2");
}
});
var x = new B();
dojo.safeMixin(x, {
m1: function(){
this.inherited(arguments);
console.log("X.m1");
},
m2: function(){
this.inherited(arguments);
console.log("X.m2");
}
});
x.m2();
// prints:
// A.m1
// B.m1
// X.m1
```
| programming_docs |
dojo dojo/_base/xhr dojo/\_base/xhr
===============
Summary
-------
Deprecated. Use [dojo/request](../request) instead.
Sends an HTTP request with the given method. See also dojo.xhrGet(), xhrPost(), xhrPut() and dojo.xhrDelete() for shortcuts for those HTTP methods. There are also methods for "raw" PUT and POST methods via dojo.rawXhrPut() and dojo.rawXhrPost() respectively.
Usage
-----
xhr`(method,args,hasBody);`
| Parameter | Type | Description |
| --- | --- | --- |
| method | String | HTTP method to be used, such as GET, POST, PUT, DELETE. Should be uppercase. |
| args | Object | |
| hasBody | Boolean | *Optional*
If the request has an HTTP body, then pass true for hasBody. |
**Returns:** undefined
See the [dojo/\_base/xhr reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/xhr.html) for more information.
Properties
----------
### contentHandlers
Defined by: [dojo/\_base/xhr](xhr)
A map of available XHR transport handle types. Name matches the `handleAs` attribute passed to XHR calls.
Methods
-------
###
`del``(args)`
Defined by [dojo/\_base/xhr](xhr)
Sends an HTTP DELETE request to the server.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See `dojo/_base/xhr.contentHandlers`
* sync (Boolean, optional): false is default. Indicates whether the request should be a synchronous (blocking) request.
* headers (Object, optional): Additional HTTP headers to send in the request.
* failOk (Boolean, optional): false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
* contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
* load: This function will be called on a successful HTTP response code.
* error: This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
* handle: This function will be called at the end of every request, whether or not an error occurs.
* url (String): URL to server endpoint.
* content (Object, optional): Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
* timeout (Integer, optional): Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
* form (DOMNode, optional): DOM node for a form. Used to extract the form values and send to the server.
* preventCache (Boolean, optional): Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
* rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for dojo/\_base/xhr.rawXhrPost and dojo/\_base/xhr.rawXhrPut respectively.
* ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via dojo/topic.publish() for different phases of an IO operation. See dojo/main.\_\_IoPublish for a list of topics that are published.
|
**Returns:** undefined
###
`fieldToObject``(inputNode)`
Defined by [dojo/\_base/xhr](xhr)
Serialize a form field to a JavaScript object.
Returns the value encoded in a form field as as a string or an array of strings. Disabled form elements and unchecked radio and checkboxes are skipped. Multi-select elements are returned as an array of string values.
| Parameter | Type | Description |
| --- | --- | --- |
| inputNode | DOMNode | String | |
**Returns:** Object | undefined
###
`formToJson``(formNode,prettyPrint)`
Defined by [dojo/\_base/xhr](xhr)
Create a serialized JSON string from a form node or string ID identifying the form to serialize
| Parameter | Type | Description |
| --- | --- | --- |
| formNode | DOMNode | String | |
| prettyPrint | Boolean | *Optional* |
**Returns:** String | undefined
###
`formToObject``(formNode)`
Defined by [dojo/\_base/xhr](xhr)
Serialize a form node to a JavaScript object.
Returns the values encoded in an HTML form as string properties in an object which it then returns. Disabled form elements, buttons, and other non-value form elements are skipped. Multi-select elements are returned as an array of string values.
| Parameter | Type | Description |
| --- | --- | --- |
| formNode | DOMNode | String | |
**Returns:** object
Examples
--------
### Example 1
This form:
```
<form id="test_form">
<input type="text" name="blah" value="blah">
<input type="text" name="no_value" value="blah" disabled>
<input type="button" name="no_value2" value="blah">
<select type="select" multiple name="multi" size="5">
<option value="blah">blah</option>
<option value="thud" selected>thud</option>
<option value="thonk" selected>thonk</option>
</select>
</form>
```
yields this object structure as the result of a call to formToObject():
```
{
blah: "blah",
multi: [
"thud",
"thonk"
]
};
```
###
`formToQuery``(formNode)`
Defined by [dojo/\_base/xhr](xhr)
Returns a URL-encoded string representing the form passed as either a node or string ID identifying the form to serialize
| Parameter | Type | Description |
| --- | --- | --- |
| formNode | DOMNode | String | |
**Returns:** String | undefined
###
`get``(args)`
Defined by [dojo/\_base/xhr](xhr)
Sends an HTTP GET request to the server.
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See `dojo/_base/xhr.contentHandlers`
* sync (Boolean, optional): false is default. Indicates whether the request should be a synchronous (blocking) request.
* headers (Object, optional): Additional HTTP headers to send in the request.
* failOk (Boolean, optional): false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
* contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
* load: This function will be called on a successful HTTP response code.
* error: This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
* handle: This function will be called at the end of every request, whether or not an error occurs.
* url (String): URL to server endpoint.
* content (Object, optional): Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
* timeout (Integer, optional): Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
* form (DOMNode, optional): DOM node for a form. Used to extract the form values and send to the server.
* preventCache (Boolean, optional): Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
* rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for dojo/\_base/xhr.rawXhrPost and dojo/\_base/xhr.rawXhrPut respectively.
* ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via dojo/topic.publish() for different phases of an IO operation. See dojo/main.\_\_IoPublish for a list of topics that are published.
|
**Returns:** undefined
###
`objectToQuery``(map)`
Defined by [dojo/\_base/xhr](xhr)
takes a name/value mapping object and returns a string representing a URL-encoded version of that object.
| Parameter | Type | Description |
| --- | --- | --- |
| map | Object | |
**Returns:** undefined
Examples
--------
### Example 1
this object:
```
{
blah: "blah",
multi: [
"thud",
"thonk"
]
};
```
yields the following query string:
```
"blah=blah&multi=thud&multi=thonk"
```
###
`post``(args)`
Defined by [dojo/\_base/xhr](xhr)
Sends an HTTP POST request to the server. In addition to the properties listed for the dojo.\_\_XhrArgs type, the following property is allowed:
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See `dojo/_base/xhr.contentHandlers`
* sync (Boolean, optional): false is default. Indicates whether the request should be a synchronous (blocking) request.
* headers (Object, optional): Additional HTTP headers to send in the request.
* failOk (Boolean, optional): false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
* contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
* load: This function will be called on a successful HTTP response code.
* error: This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
* handle: This function will be called at the end of every request, whether or not an error occurs.
* url (String): URL to server endpoint.
* content (Object, optional): Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
* timeout (Integer, optional): Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
* form (DOMNode, optional): DOM node for a form. Used to extract the form values and send to the server.
* preventCache (Boolean, optional): Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
* rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for dojo/\_base/xhr.rawXhrPost and dojo/\_base/xhr.rawXhrPut respectively.
* ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via dojo/topic.publish() for different phases of an IO operation. See dojo/main.\_\_IoPublish for a list of topics that are published.
|
**Returns:** undefined
###
`put``(args)`
Defined by [dojo/\_base/xhr](xhr)
Sends an HTTP PUT request to the server. In addition to the properties listed for the dojo.\_\_XhrArgs type, the following property is allowed:
| Parameter | Type | Description |
| --- | --- | --- |
| args | Object | An object with the following properties:* handleAs (String, optional): Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml. See `dojo/_base/xhr.contentHandlers`
* sync (Boolean, optional): false is default. Indicates whether the request should be a synchronous (blocking) request.
* headers (Object, optional): Additional HTTP headers to send in the request.
* failOk (Boolean, optional): false is default. Indicates whether a request should be allowed to fail (and therefore no console error message in the event of a failure)
* contentType (String|Boolean): "application/x-www-form-urlencoded" is default. Set to false to prevent a Content-Type header from being sent, or to a string to send a different Content-Type.
* load: This function will be called on a successful HTTP response code.
* error: This function will be called when the request fails due to a network or server error, the url is invalid, etc. It will also be called if the load or handle callback throws an exception, unless djConfig.debugAtAllCosts is true. This allows deployed applications to continue to run even when a logic error happens in the callback, while making it easier to troubleshoot while in debug mode.
* handle: This function will be called at the end of every request, whether or not an error occurs.
* url (String): URL to server endpoint.
* content (Object, optional): Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
* timeout (Integer, optional): Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
* form (DOMNode, optional): DOM node for a form. Used to extract the form values and send to the server.
* preventCache (Boolean, optional): Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
* rawBody (String, optional): Sets the raw body for an HTTP request. If this is used, then the content property is ignored. This is mostly useful for HTTP methods that have a body to their requests, like PUT or POST. This property can be used instead of postData and putData for dojo/\_base/xhr.rawXhrPost and dojo/\_base/xhr.rawXhrPut respectively.
* ioPublish (Boolean, optional): Set this explicitly to false to prevent publishing of topics related to IO operations. Otherwise, if djConfig.ioPublish is set to true, topics will be published via dojo/topic.publish() for different phases of an IO operation. See dojo/main.\_\_IoPublish for a list of topics that are published.
|
**Returns:** undefined
###
`queryToObject``(str)`
Defined by [dojo/\_base/xhr](xhr)
Create an object representing a de-serialized query section of a URL. Query keys with multiple values are returned in an array.
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | |
**Returns:** object
Examples
--------
### Example 1
This string:
```
"foo=bar&foo=baz&thinger=%20spaces%20=blah&zonk=blarg&"
```
results in this object structure:
```
{
foo: [ "bar", "baz" ],
thinger: " spaces =blah",
zonk: "blarg"
}
```
Note that spaces and other urlencoded entities are correctly handled.
dojo dojo/_base/Deferred dojo/\_base/Deferred
====================
Summary
-------
Deprecated. This module defines the legacy [dojo/\_base/Deferred](deferred) API. New code should use [dojo/Deferred](../deferred) instead.
The Deferred API is based on the concept of promises that provide a generic interface into the eventual completion of an asynchronous action. The motivation for promises fundamentally is about creating a separation of concerns that allows one to achieve the same type of call patterns and logical data flow in asynchronous code as can be achieved in synchronous code. Promises allows one to be able to call a function purely with arguments needed for execution, without conflating the call with concerns of whether it is sync or async. One shouldn't need to alter a call's arguments if the implementation switches from sync to async (or vice versa). By having async functions return promises, the concerns of making the call are separated from the concerns of asynchronous interaction (which are handled by the promise).
The Deferred is a type of promise that provides methods for fulfilling the promise with a successful result or an error. The most important method for working with Dojo's promises is the then() method, which follows the CommonJS proposed promise API. An example of using a Dojo promise:
```
var resultingPromise = someAsyncOperation.then(function(result){
... handle result ...
},
function(error){
... handle error ...
});
```
The .then() call returns a new promise that represents the result of the execution of the callback. The callbacks will never affect the original promises value.
The Deferred instances also provide the following functions for backwards compatibility:
* addCallback(handler)
* addErrback(handler)
* callback(result)
* errback(result)
Callbacks are allowed to return promises themselves, so you can build complicated sequences of events with ease.
The creator of the Deferred may specify a canceller. The canceller is a function that will be called if Deferred.cancel is called before the Deferred fires. You can use this to implement clean aborting of an XMLHttpRequest, etc. Note that cancel will fire the deferred with a CancelledError (unless your canceller returns another kind of error), so the errbacks should be prepared to handle that error for cancellable Deferreds.
Usage
-----
Deferred`(canceller);`
| Parameter | Type | Description |
| --- | --- | --- |
| canceller | Function | *Optional* |
See the [dojo/\_base/Deferred reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/Deferred.html) for more information.
Examples
--------
### Example 1
```
var deferred = new Deferred();
setTimeout(function(){ deferred.callback({success: true}); }, 1000);
return deferred;
```
### Example 2
Deferred objects are often used when making code asynchronous. It may be easiest to write functions in a synchronous manner and then split code using a deferred to trigger a response to a long-lived operation. For example, instead of register a callback function to denote when a rendering operation completes, the function can simply return a deferred:
```
// callback style:
function renderLotsOfData(data, callback){
var success = false
try{
for(var x in data){
renderDataitem(data[x]);
}
success = true;
}catch(e){ }
if(callback){
callback(success);
}
}
// using callback style
renderLotsOfData(someDataObj, function(success){
// handles success or failure
if(!success){
promptUserToRecover();
}
});
// NOTE: no way to add another callback here!!
```
### Example 3
Using a Deferred doesn't simplify the sending code any, but it provides a standard interface for callers and senders alike, providing both with a simple way to service multiple callbacks for an operation and freeing both sides from worrying about details such as "did this get called already?". With Deferreds, new callbacks can be added at any time.
```
// Deferred style:
function renderLotsOfData(data){
var d = new Deferred();
try{
for(var x in data){
renderDataitem(data[x]);
}
d.callback(true);
}catch(e){
d.errback(new Error("rendering failed"));
}
return d;
}
// using Deferred style
renderLotsOfData(someDataObj).then(null, function(){
promptUserToRecover();
});
// NOTE: addErrback and addCallback both return the Deferred
// again, so we could chain adding callbacks or save the
// deferred for later should we need to be notified again.
```
### Example 4
In this example, renderLotsOfData is synchronous and so both versions are pretty artificial. Putting the data display on a timeout helps show why Deferreds rock:
```
// Deferred style and async func
function renderLotsOfData(data){
var d = new Deferred();
setTimeout(function(){
try{
for(var x in data){
renderDataitem(data[x]);
}
d.callback(true);
}catch(e){
d.errback(new Error("rendering failed"));
}
}, 100);
return d;
}
// using Deferred style
renderLotsOfData(someDataObj).then(null, function(){
promptUserToRecover();
});
```
Note that the caller doesn't have to change his code at all to handle the asynchronous case.
Properties
----------
### fired
Defined by: [dojo/\_base/Deferred](deferred)
### promise
Defined by: [dojo/\_base/Deferred](deferred)
Methods
-------
###
`addBoth``(callback)`
Defined by [dojo/\_base/Deferred](deferred)
Add handler as both successful callback and error callback for this deferred instance.
| Parameter | Type | Description |
| --- | --- | --- |
| callback | Function | |
**Returns:** any | undefined
Returns this deferred object.
###
`addCallback``(callback)`
Defined by [dojo/\_base/Deferred](deferred)
Adds successful callback for this deferred instance.
| Parameter | Type | Description |
| --- | --- | --- |
| callback | Function | |
**Returns:** any | undefined
Returns this deferred object.
###
`addCallbacks``(callback,errback)`
Defined by [dojo/\_base/Deferred](deferred)
Adds callback and error callback for this deferred instance.
| Parameter | Type | Description |
| --- | --- | --- |
| callback | Function | *Optional*
The callback attached to this deferred object. |
| errback | Function | *Optional*
The error callback attached to this deferred object. |
**Returns:** any
Returns this deferred object.
###
`addErrback``(errback)`
Defined by [dojo/\_base/Deferred](deferred)
Adds error callback for this deferred instance.
| Parameter | Type | Description |
| --- | --- | --- |
| errback | Function | |
**Returns:** any | undefined
Returns this deferred object.
###
`callback``(value)`
Defined by [dojo/\_base/Deferred](deferred)
Fulfills the Deferred instance successfully with the provide value
| Parameter | Type | Description |
| --- | --- | --- |
| value | undefined | |
###
`cancel``()`
Defined by [dojo/\_base/Deferred](deferred)
Cancels the asynchronous operation
###
`errback``(error)`
Defined by [dojo/\_base/Deferred](deferred)
Fulfills the Deferred instance as an error with the provided error
| Parameter | Type | Description |
| --- | --- | --- |
| error | undefined | |
###
`isCanceled``()`
Defined by [dojo/\_base/Deferred](deferred)
Checks whether the deferred has been canceled.
**Returns:** Boolean
###
`isFulfilled``()`
Defined by [dojo/\_base/Deferred](deferred)
Checks whether the deferred has been resolved or rejected.
**Returns:** Boolean
###
`isRejected``()`
Defined by [dojo/\_base/Deferred](deferred)
Checks whether the deferred has been rejected.
**Returns:** Boolean
###
`isResolved``()`
Defined by [dojo/\_base/Deferred](deferred)
Checks whether the deferred has been resolved.
**Returns:** Boolean
###
`progress``(update)`
Defined by [dojo/\_base/Deferred](deferred)
Send progress events to all listeners
| Parameter | Type | Description |
| --- | --- | --- |
| update | undefined | |
###
`reject``(error)`
Defined by [dojo/\_base/Deferred](deferred)
Fulfills the Deferred instance as an error with the provided error
| Parameter | Type | Description |
| --- | --- | --- |
| error | undefined | |
###
`resolve``(value)`
Defined by [dojo/\_base/Deferred](deferred)
Fulfills the Deferred instance successfully with the provide value
| Parameter | Type | Description |
| --- | --- | --- |
| value | undefined | |
###
`then``(resolvedCallback,errorCallback,progressCallback)`
Defined by [dojo/\_base/Deferred](deferred)
Adds a fulfilledHandler, errorHandler, and progressHandler to be called for completion of a promise. The fulfilledHandler is called when the promise is fulfilled. The errorHandler is called when a promise fails. The progressHandler is called for progress events. All arguments are optional and non-function values are ignored. The progressHandler is not only an optional argument, but progress events are purely optional. Promise providers are not required to ever create progress events.
This function will return a new promise that is fulfilled when the given fulfilledHandler or errorHandler callback is finished. This allows promise operations to be chained together. The value returned from the callback handler is the fulfillment value for the returned promise. If the callback throws an error, the returned promise will be moved to failed state.
| Parameter | Type | Description |
| --- | --- | --- |
| resolvedCallback | Function | *Optional* |
| errorCallback | Function | *Optional* |
| progressCallback | Function | *Optional* |
**Returns:** any
Returns a new promise that represents the result of the execution of the callback. The callbacks will never affect the original promises value.
Examples
--------
### Example 1
An example of using a CommonJS compliant promise:
```
asyncComputeTheAnswerToEverything().
then(addTwo).
then(printResult, onError);
>44
```
###
`when``(valueOrPromise,callback,errback,progback)`
Defined by [dojo/when](../when)
Transparently applies callbacks to values and/or promises.
Accepts promises but also transparently handles non-promises. If no callbacks are provided returns a promise, regardless of the initial value. Foreign promises are converted.
If callbacks are provided and the initial value is not a promise, the callback is executed immediately with no error handling. Returns a promise if the initial value is a promise, or the result of the callback otherwise.
| Parameter | Type | Description |
| --- | --- | --- |
| valueOrPromise | undefined | Either a regular value or an object with a `then()` method that follows the Promises/A specification. |
| callback | Function | *Optional*
Callback to be invoked when the promise is resolved, or a non-promise is received. |
| errback | Function | *Optional*
Callback to be invoked when the promise is rejected. |
| progback | Function | *Optional*
Callback to be invoked when the promise emits a progress update. |
**Returns:** [dojo/promise/Promise](../promise/promise) | summary: | name:
Promise, or if a callback is provided, the result of the callback.
| programming_docs |
dojo dojo/_base/kernel.window dojo/\_base/kernel.window
=========================
Summary
-------
TODOC
Methods
-------
###
`get``(doc)`
Defined by [dojo/window](../window)
Get window object associated with document doc.
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | The document to get the associated window for. |
**Returns:** undefined
###
`getBox``(doc)`
Defined by [dojo/window](../window)
Returns the dimensions and scroll position of the viewable area of a browser window
| Parameter | Type | Description |
| --- | --- | --- |
| doc | Document | *Optional* |
**Returns:** object
###
`scrollIntoView``(node,pos)`
Defined by [dojo/window](../window)
Scroll the passed node into view using minimal movement, if it is not already.
| Parameter | Type | Description |
| --- | --- | --- |
| node | DomNode | |
| pos | Object | *Optional* |
dojo dojo/_base/connect dojo/\_base/connect
===================
Summary
-------
This module defines the dojo.connect API. This modules also provides keyboard event handling helpers. This module exports an extension event for emulating Firefox's keypress handling. However, this extension event exists primarily for backwards compatibility and is not recommended. WebKit and IE uses an alternate keypress handling (only firing for printable characters, to distinguish from keydown events), and most consider the WebKit/IE behavior more desirable.
See the [dojo/\_base/connect reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/connect.html) for more information.
Methods
-------
###
`connect``(obj,event,context,method,dontFix)`
Defined by [dojo/\_base/connect](connect)
`dojo.connect` is a deprecated event handling and delegation method in Dojo. It allows one function to "listen in" on the execution of any other, triggering the second whenever the first is called. Many listeners may be attached to a function, and source functions may be either regular function calls or DOM events.
Connects listeners to actions, so that after event fires, a listener is called with the same arguments passed to the original function.
Since `dojo.connect` allows the source of events to be either a "regular" JavaScript function or a DOM event, it provides a uniform interface for listening to all the types of events that an application is likely to deal with though a single, unified interface. DOM programmers may want to think of it as "addEventListener for everything and anything".
When setting up a connection, the `event` parameter must be a string that is the name of the method/event to be listened for. If `obj` is null, `kernel.global` is assumed, meaning that connections to global methods are supported but also that you may inadvertently connect to a global by passing an incorrect object name or invalid reference.
`dojo.connect` generally is forgiving. If you pass the name of a function or method that does not yet exist on `obj`, connect will not fail, but will instead set up a stub method. Similarly, null arguments may simply be omitted such that fewer than 4 arguments may be required to set up a connection See the examples for details.
The return value is a handle that is needed to remove this connection with `dojo.disconnect`.
| Parameter | Type | Description |
| --- | --- | --- |
| obj | Object | *Optional*
The source object for the event function. Defaults to `kernel.global` if null. If obj is a DOM node, the connection is delegated to the DOM event manager (unless dontFix is true). |
| event | String | String name of the event function in obj. I.e. identifies a property `obj[event]`. |
| context | Object | null | The object that method will receive as "this". If context is null and method is a function, then method inherits the context of event. If method is a string then context must be the source object object for method (context[method]). If context is null, kernel.global is used. |
| method | String | Function | A function reference, or name of a function in context. The function identified by method fires after event does. method receives the same arguments as the event. See context argument comments for information on method's scope. |
| dontFix | Boolean | *Optional*
If obj is a DOM node, set dontFix to true to prevent delegation of this connection to the DOM event manager. |
**Returns:** undefined
Examples
--------
### Example 1
When obj.onchange(), do ui.update():
```
dojo.connect(obj, "onchange", ui, "update");
dojo.connect(obj, "onchange", ui, ui.update); // same
```
### Example 2
Using return value for disconnect:
```
var link = dojo.connect(obj, "onchange", ui, "update");
...
dojo.disconnect(link);
```
### Example 3
When onglobalevent executes, watcher.handler is invoked:
```
dojo.connect(null, "onglobalevent", watcher, "handler");
```
### Example 4
When ob.onCustomEvent executes, customEventHandler is invoked:
```
dojo.connect(ob, "onCustomEvent", null, "customEventHandler");
dojo.connect(ob, "onCustomEvent", "customEventHandler"); // same
```
### Example 5
When ob.onCustomEvent executes, customEventHandler is invoked with the same scope (this):
```
dojo.connect(ob, "onCustomEvent", null, customEventHandler);
dojo.connect(ob, "onCustomEvent", customEventHandler); // same
```
### Example 6
When globalEvent executes, globalHandler is invoked with the same scope (this):
```
dojo.connect(null, "globalEvent", null, globalHandler);
dojo.connect("globalEvent", globalHandler); // same
```
###
`connectPublisher``(topic,obj,event)`
Defined by [dojo/\_base/connect](connect)
Ensure that every time obj.event() is called, a message is published on the topic. Returns a handle which can be passed to dojo.disconnect() to disable subsequent automatic publication on the topic.
| Parameter | Type | Description |
| --- | --- | --- |
| topic | String | The name of the topic to publish. |
| obj | Object | *Optional*
The source object for the event function. Defaults to kernel.global if null. |
| event | String | The name of the event function in obj. I.e. identifies a property obj[event]. |
**Returns:** undefined
Examples
--------
### Example 1
```
dojo.connectPublisher("/ajax/start", dojo, "xhrGet");
```
###
`disconnect``(handle)`
Defined by [dojo/\_base/connect](connect)
Remove a link created by dojo.connect.
Removes the connection between event and the method referenced by handle.
| Parameter | Type | Description |
| --- | --- | --- |
| handle | Handle | the return value of the dojo.connect call that created the connection. |
###
`isCopyKey``(e)`
Defined by [dojo/\_base/connect](connect)
Checks an event for the copy key (meta on Mac, and ctrl anywhere else)
| Parameter | Type | Description |
| --- | --- | --- |
| e | Event | Event object to examine |
**Returns:** undefined
###
`publish``(topic,args)`
Defined by [dojo/\_base/connect](connect)
Invoke all listener method subscribed to topic.
| Parameter | Type | Description |
| --- | --- | --- |
| topic | String | The name of the topic to publish. |
| args | Array | *Optional*
An array of arguments. The arguments will be applied to each topic subscriber (as first class parameters, via apply). |
**Returns:** undefined
Examples
--------
### Example 1
```
dojo.subscribe("alerts", null, function(caption, message){ alert(caption + "\n" + message); };
dojo.publish("alerts", [ "read this", "hello world" ]);
```
###
`subscribe``(topic,context,method)`
Defined by [dojo/\_base/connect](connect)
Attach a listener to a named topic. The listener function is invoked whenever the named topic is published (see: dojo.publish). Returns a handle which is needed to unsubscribe this listener.
| Parameter | Type | Description |
| --- | --- | --- |
| topic | String | The topic to which to subscribe. |
| context | Object | *Optional*
Scope in which method will be invoked, or null for default scope. |
| method | String | Function | The name of a function in context, or a function reference. This is the function that is invoked when topic is published. |
**Returns:** undefined
Examples
--------
### Example 1
```
dojo.subscribe("alerts", null, function(caption, message){ alert(caption + "\n" + message); });
dojo.publish("alerts", [ "read this", "hello world" ]);
```
###
`unsubscribe``(handle)`
Defined by [dojo/\_base/connect](connect)
Remove a topic listener.
| Parameter | Type | Description |
| --- | --- | --- |
| handle | Handle | The handle returned from a call to subscribe. |
Examples
--------
### Example 1
```
var alerter = dojo.subscribe("alerts", null, function(caption, message){ alert(caption + "\n" + message); };
...
dojo.unsubscribe(alerter);
```
dojo dojo/_base/kernel._contentHandlers dojo/\_base/kernel.\_contentHandlers
====================================
Summary
-------
A map of available XHR transport handle types. Name matches the `handleAs` attribute passed to XHR calls.
A map of available XHR transport handle types. Name matches the `handleAs` attribute passed to XHR calls. Each contentHandler is called, passing the xhr object for manipulation. The return value from the contentHandler will be passed to the `load` or `handle` functions defined in the original xhr call.
Examples
--------
### Example 1
Creating a custom content-handler:
```
xhr.contentHandlers.makeCaps = function(xhr){
return xhr.responseText.toUpperCase();
}
// and later:
dojo.xhrGet({
url:"foo.txt",
handleAs:"makeCaps",
load: function(data){ /* data is a toUpper version of foo.txt */ }
});
```
Methods
-------
###
`auto``(xhr)`
Defined by [dojox/rpc/Service](http://dojotoolkit.org/api/1.10/dojox/rpc/Service)
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
###
`javascript``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler which evaluates the response data, expecting it to be valid JavaScript
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`json``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler which returns a JavaScript object created from the response data
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`json-comment-filtered``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler which expects comment-filtered JSON.
A contentHandler which expects comment-filtered JSON. the json-comment-filtered option was implemented to prevent "JavaScript Hijacking", but it is less secure than standard JSON. Use standard JSON instead. JSON prefixing can be used to subvert hijacking.
Will throw a notice suggesting to use application/json mimetype, as json-commenting can introduce security issues. To decrease the chances of hijacking, use the standard `json` contentHandler, and prefix your "JSON" with: {}&&
use djConfig.useCommentedJson = true to turn off the notice
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`json-comment-optional``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler which checks the presence of comment-filtered JSON and alternates between the `json` and `json-comment-filtered` contentHandlers.
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`text``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler which simply returns the plaintext response data
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`xml``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler returning an XML Document parsed from the response data
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
dojo dojo/_base/declare.__DeclareCreatedObject dojo/\_base/declare.\_\_DeclareCreatedObject
============================================
Summary
-------
[dojo/\_base/declare()](declare) returns a constructor `C`. `new C()` returns an Object with the following methods, in addition to the methods and properties specified via the arguments passed to declare().
**Note:** This is not a real constructor, but just a description of the type of object that should be passed as a parameter to some method(s), and/or the return value from some method(s). In other words, the type exists only for documentation purposes, and you **cannot** call `new declare.__DeclareCreatedObject()`
Methods
-------
###
`createSubclass``(mixins,props)`
Defined by [dojo/\_base/declare](declare)
Create a subclass of the declared class from a list of base classes.
Create a constructor using a compact notation for inheritance and prototype extension.
Mixin ancestors provide a type of multiple inheritance. Prototypes of mixin ancestors are copied to the new class: changes to mixin prototypes will not affect classes to which they have been mixed in.
| Parameter | Type | Description |
| --- | --- | --- |
| mixins | Function[] | Specifies a list of bases (the left-most one is the most deepest base). |
| props | Object | *Optional*
An optional object whose properties are copied to the created prototype. |
**Returns:** [dojo/\_base/declare.\_\_DeclareCreatedObject](declare.__declarecreatedobject)
New constructor function.
Examples
--------
### Example 1
```
var A = declare(null, {
m1: function(){},
s1: "bar"
});
var B = declare(null, {
m2: function(){},
s2: "foo"
});
var C = declare(null, {
});
var D1 = A.createSubclass([B, C], {
m1: function(){},
d1: 42
});
var d1 = new D1();
// this is equivalent to:
var D2 = declare([A, B, C], {
m1: function(){},
d1: 42
});
var d2 = new D2();
```
###
`extend``(source)`
Defined by [dojo/\_base/declare](declare)
Adds all properties and methods of source to constructor's prototype, making them available to all instances created with constructor. This method is specific to constructors created with declare().
Adds source properties to the constructor's prototype. It can override existing properties.
This method is similar to dojo.extend function, but it is specific to constructors produced by declare(). It is implemented using dojo.safeMixin, and it skips a constructor property, and properly decorates copied functions.
| Parameter | Type | Description |
| --- | --- | --- |
| source | Object | Source object which properties are going to be copied to the constructor's prototype. |
Examples
--------
### Example 1
```
var A = declare(null, {
m1: function(){},
s1: "Popokatepetl"
});
A.extend({
m1: function(){},
m2: function(){},
f1: true,
d1: 42
});
```
###
`getInherited``(name,args)`
Defined by [dojo/\_base/declare](declare)
Returns a super method.
This method is a convenience method for "this.inherited()". It uses the same algorithm but instead of executing a super method, it returns it, or "undefined" if not found.
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | *Optional*
The optional method name. Should be the same as the caller's name. Usually "name" is specified in complex dynamic cases, when the calling method was dynamically added, undecorated by declare(), and it cannot be determined. |
| args | Arguments | The caller supply this argument, which should be the original "arguments". |
**Returns:** any | object
Returns a super method (Function) or "undefined".
Examples
--------
### Example 1
```
var B = declare(A, {
method: function(a, b){
var super = this.getInherited(arguments);
// ...
if(!super){
console.log("there is no super method");
return 0;
}
return super.apply(this, arguments);
}
});
```
###
`inherited``(name,args,newArgs)`
Defined by [dojo/\_base/declare](declare)
Calls a super method.
This method is used inside method of classes produced with declare() to call a super method (next in the chain). It is used for manually controlled chaining. Consider using the regular chaining, because it is faster. Use "this.inherited()" only in complex cases.
This method cannot me called from automatically chained constructors including the case of a special (legacy) constructor chaining. It cannot be called from chained methods.
If "this.inherited()" cannot find the next-in-chain method, it does nothing and returns "undefined". The last method in chain can be a default method implemented in Object, which will be called last.
If "name" is specified, it is assumed that the method that received "args" is the parent method for this call. It is looked up in the chain list and if it is found the next-in-chain method is called. If it is not found, the first-in-chain method is called.
If "name" is not specified, it will be derived from the calling method (using a methoid property "nom").
| Parameter | Type | Description |
| --- | --- | --- |
| name | String | *Optional*
The optional method name. Should be the same as the caller's name. Usually "name" is specified in complex dynamic cases, when the calling method was dynamically added, undecorated by declare(), and it cannot be determined. |
| args | Arguments | The caller supply this argument, which should be the original "arguments". |
| newArgs | Object | *Optional*
If "true", the found function will be returned without executing it. If Array, it will be used to call a super method. Otherwise "args" will be used. |
**Returns:** any | object
Whatever is returned by a super method, or a super method itself, if "true" was specified as newArgs.
Examples
--------
### Example 1
```
var B = declare(A, {
method1: function(a, b, c){
this.inherited(arguments);
},
method2: function(a, b){
return this.inherited(arguments, [a + b]);
}
});
// next method is not in the chain list because it is added
// manually after the class was created.
B.prototype.method3 = function(){
console.log("This is a dynamically-added method.");
this.inherited("method3", arguments);
};
```
### Example 2
```
var B = declare(A, {
method: function(a, b){
var super = this.inherited(arguments, true);
// ...
if(!super){
console.log("there is no super method");
return 0;
}
return super.apply(this, arguments);
}
});
```
###
`isInstanceOf``(cls)`
Defined by [dojo/\_base/declare](declare)
Checks the inheritance chain to see if it is inherited from this class.
This method is used with instances of classes produced with declare() to determine of they support a certain interface or not. It models "instanceof" operator.
| Parameter | Type | Description |
| --- | --- | --- |
| cls | Function | Class constructor. |
**Returns:** any | object
"true", if this object is inherited from this class, "false" otherwise.
Examples
--------
### Example 1
```
var A = declare(null, {
// constructor, properties, and methods go here
// ...
});
var B = declare(null, {
// constructor, properties, and methods go here
// ...
});
var C = declare([A, B], {
// constructor, properties, and methods go here
// ...
});
var D = declare(A, {
// constructor, properties, and methods go here
// ...
});
var a = new A(), b = new B(), c = new C(), d = new D();
console.log(a.isInstanceOf(A)); // true
console.log(b.isInstanceOf(A)); // false
console.log(c.isInstanceOf(A)); // true
console.log(d.isInstanceOf(A)); // true
console.log(a.isInstanceOf(B)); // false
console.log(b.isInstanceOf(B)); // true
console.log(c.isInstanceOf(B)); // true
console.log(d.isInstanceOf(B)); // false
console.log(a.isInstanceOf(C)); // false
console.log(b.isInstanceOf(C)); // false
console.log(c.isInstanceOf(C)); // true
console.log(d.isInstanceOf(C)); // false
console.log(a.isInstanceOf(D)); // false
console.log(b.isInstanceOf(D)); // false
console.log(c.isInstanceOf(D)); // false
console.log(d.isInstanceOf(D)); // true
```
| programming_docs |
dojo dojo/_base/Color dojo/\_base/Color
=================
Summary
-------
Takes a named string, hex string, array of rgb or rgba values, an object with r, g, b, and a properties, or another `Color` object and creates a new Color instance to work from.
Usage
-----
Color`(color);`
| Parameter | Type | Description |
| --- | --- | --- |
| color | Array | String | Object | |
See the [dojo/\_base/Color reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/_base/Color.html) for more information.
Examples
--------
### Example 1
Work with a Color instance:
```
require(["dojo/_base/color"], function(Color){
var c = new Color();
c.setColor([0,0,0]); // black
var hex = c.toHex(); // #000000
});
```
### Example 2
Work with a node's color:
```
require(["dojo/_base/color", "dojo/dom-style"], function(Color, domStyle){
var color = domStyle("someNode", "backgroundColor");
var n = new Color(color);
// adjust the color some
n.r *= .5;
console.log(n.toString()); // rgb(128, 255, 255);
});
```
Properties
----------
### a
Defined by: [dojo/\_base/Color](color)
### b
Defined by: [dojo/\_base/Color](color)
### g
Defined by: [dojo/\_base/Color](color)
### named
Defined by: [dojo/\_base/Color](color)
Dictionary list of all CSS named colors, by name. Values are 3-item arrays with corresponding RG and B values.
### r
Defined by: [dojo/\_base/Color](color)
Methods
-------
###
`blendColors``(start,end,weight,obj)`
Defined by [dojo/\_base/Color](color)
Blend colors end and start with weight from 0 to 1, 0.5 being a 50/50 blend, can reuse a previously allocated Color object for the result
| Parameter | Type | Description |
| --- | --- | --- |
| start | [dojo/\_base/Color](color) | |
| end | [dojo/\_base/Color](color) | |
| weight | Number | |
| obj | [dojo/\_base/Color](color) | *Optional* |
**Returns:** undefined
###
`fromArray``(a,obj)`
Defined by [dojo/\_base/Color](color)
Builds a `Color` from a 3 or 4 element array, mapping each element in sequence to the rgb(a) values of the color.
| Parameter | Type | Description |
| --- | --- | --- |
| a | Array | |
| obj | [dojo/\_base/Color](color) | *Optional* |
**Returns:** any | undefined
A Color object. If obj is passed, it will be the return value.
Examples
--------
### Example 1
```
require(["dojo/_base/color"], function(Color){
var myColor = new Color().fromArray([237,237,237,0.5]); // grey, 50% alpha
});
```
###
`fromHex``(color,obj)`
Defined by [dojo/\_base/Color](color)
Converts a hex string with a '#' prefix to a color object. Supports 12-bit #rgb shorthand. Optionally accepts a `Color` object to update with the parsed value.
| Parameter | Type | Description |
| --- | --- | --- |
| color | String | |
| obj | [dojo/\_base/Color](color) | *Optional* |
**Returns:** any
A Color object. If obj is passed, it will be the return value.
Examples
--------
### Example 1
```
require(["dojo/_base/color"], function(Color){
var thing = new Color().fromHex("#ededed"); // grey, longhand
var thing2 = new Color().fromHex("#000"); // black, shorthand
});
```
###
`fromRgb``(color,obj)`
Defined by [dojo/colors](../colors)
get rgb(a) array from css-style color declarations
this function can handle all 4 CSS3 Color Module formats: rgb, rgba, hsl, hsla, including rgb(a) with percentage values.
| Parameter | Type | Description |
| --- | --- | --- |
| color | String | |
| obj | [dojo/\_base/Color](color) | *Optional* |
**Returns:** null
###
`fromString``(str,obj)`
Defined by [dojo/\_base/Color](color)
Parses `str` for a color value. Accepts hex, rgb, and rgba style color values.
Acceptable input values for str may include arrays of any form accepted by dojo.colorFromArray, hex strings such as "#aaaaaa", or rgb or rgba strings such as "rgb(133, 200, 16)" or "rgba(10, 10, 10, 50)"
| Parameter | Type | Description |
| --- | --- | --- |
| str | String | |
| obj | [dojo/\_base/Color](color) | *Optional* |
**Returns:** any
A Color object. If obj is passed, it will be the return value.
###
`makeGrey``(g,a)`
Defined by [dojo/colors](../colors)
creates a greyscale color with an optional alpha
| Parameter | Type | Description |
| --- | --- | --- |
| g | Number | |
| a | Number | *Optional* |
###
`sanitize``()`
Defined by [dojo/colors](../colors)
makes sure that the object has correct attributes
###
`setColor``(color)`
Defined by [dojo/\_base/Color](color)
Takes a named string, hex string, array of rgb or rgba values, an object with r, g, b, and a properties, or another `Color` object and sets this color instance to that value.
| Parameter | Type | Description |
| --- | --- | --- |
| color | Array | String | Object | |
**Returns:** function
Takes a named string, hex string, array of rgb or rgba values, an object with r, g, b, and a properties, or another `Color` object and sets this color instance to that value.
Examples
--------
### Example 1
```
require(["dojo/_base/color"], function(Color){
var c = new Color(); // no color
c.setColor("#ededed"); // greyish
});
```
###
`toCmy``()`
Defined by [dojox/color/\_base](http://dojotoolkit.org/api/1.10/dojox/color/_base)
Convert this Color to a CMY definition.
**Returns:** object
###
`toCmyk``()`
Defined by [dojox/color/\_base](http://dojotoolkit.org/api/1.10/dojox/color/_base)
Convert this Color to a CMYK definition.
**Returns:** object
###
`toCss``(includeAlpha)`
Defined by [dojo/\_base/Color](color)
Returns a css color string in rgb(a) representation
| Parameter | Type | Description |
| --- | --- | --- |
| includeAlpha | Boolean | *Optional* |
**Returns:** string
Examples
--------
### Example 1
```
require(["dojo/_base/color"], function(Color){
var c = new Color("#FFF").toCss();
console.log(c); // rgb('255','255','255')
});
```
###
`toHex``()`
Defined by [dojo/\_base/Color](color)
Returns a CSS color string in hexadecimal representation
**Returns:** string
Examples
--------
### Example 1
```
require(["dojo/_base/color"], function(Color){
console.log(new Color([0,0,0]).toHex()); // #000000
});
```
###
`toHsl``()`
Defined by [dojox/color/\_base](http://dojotoolkit.org/api/1.10/dojox/color/_base)
Convert this Color to an HSL definition.
**Returns:** object
###
`toHsv``()`
Defined by [dojox/color/\_base](http://dojotoolkit.org/api/1.10/dojox/color/_base)
Convert this Color to an HSV definition.
**Returns:** object
###
`toRgb``()`
Defined by [dojo/\_base/Color](color)
Returns 3 component array of rgb values
**Returns:** Array
Examples
--------
### Example 1
```
require(["dojo/_base/color"], function(Color){
var c = new Color("#000000");
console.log(c.toRgb()); // [0,0,0]
});
```
###
`toRgba``()`
Defined by [dojo/\_base/Color](color)
Returns a 4 component array of rgba values from the color represented by this object.
**Returns:** Array
###
`toString``()`
Defined by [dojo/\_base/Color](color)
Returns a visual representation of the color
**Returns:** undefined
dojo dojo/_base/kernel.contentHandlers dojo/\_base/kernel.contentHandlers
==================================
Summary
-------
A map of available XHR transport handle types. Name matches the `handleAs` attribute passed to XHR calls.
A map of available XHR transport handle types. Name matches the `handleAs` attribute passed to XHR calls. Each contentHandler is called, passing the xhr object for manipulation. The return value from the contentHandler will be passed to the `load` or `handle` functions defined in the original xhr call.
Examples
--------
### Example 1
Creating a custom content-handler:
```
xhr.contentHandlers.makeCaps = function(xhr){
return xhr.responseText.toUpperCase();
}
// and later:
dojo.xhrGet({
url:"foo.txt",
handleAs:"makeCaps",
load: function(data){ /* data is a toUpper version of foo.txt */ }
});
```
Methods
-------
###
`auto``(xhr)`
Defined by [dojox/rpc/Service](http://dojotoolkit.org/api/1.10/dojox/rpc/Service)
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
###
`javascript``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler which evaluates the response data, expecting it to be valid JavaScript
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`json``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler which returns a JavaScript object created from the response data
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`json-comment-filtered``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler which expects comment-filtered JSON.
A contentHandler which expects comment-filtered JSON. the json-comment-filtered option was implemented to prevent "JavaScript Hijacking", but it is less secure than standard JSON. Use standard JSON instead. JSON prefixing can be used to subvert hijacking.
Will throw a notice suggesting to use application/json mimetype, as json-commenting can introduce security issues. To decrease the chances of hijacking, use the standard `json` contentHandler, and prefix your "JSON" with: {}&&
use djConfig.useCommentedJson = true to turn off the notice
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`json-comment-optional``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler which checks the presence of comment-filtered JSON and alternates between the `json` and `json-comment-filtered` contentHandlers.
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`text``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler which simply returns the plaintext response data
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
###
`xml``(xhr)`
Defined by [dojo/\_base/xhr](xhr)
A contentHandler returning an XML Document parsed from the response data
| Parameter | Type | Description |
| --- | --- | --- |
| xhr | undefined | |
**Returns:** undefined
dojo dojo/store/JsonRest dojo/store/JsonRest
===================
Extends[dojo/store/api/Store](api/store) Summary
-------
This is a basic store for RESTful communicating with a server through JSON formatted data. It implements [dojo/store/api/Store](api/store).
Usage
-----
var foo = new JsonRest`(options);` Defined by [dojo/store/JsonRest](jsonrest)
| Parameter | Type | Description |
| --- | --- | --- |
| options | [dojo/store/JsonRest](jsonrest) | This provides any configuration information that will be mixed into the store |
See the [dojo/store/JsonRest reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/store/JsonRest.html) for more information.
Properties
----------
### accepts
Defined by: [dojo/store/JsonRest](jsonrest)
Defines the Accept header to use on HTTP requests
### ascendingPrefix
Defined by: [dojo/store/JsonRest](jsonrest)
The prefix to apply to sort attribute names that are ascending
### descendingPrefix
Defined by: [dojo/store/JsonRest](jsonrest)
The prefix to apply to sort attribute names that are ascending
### headers
Defined by: [dojo/store/JsonRest](jsonrest)
Additional headers to pass in all requests to the server. These can be overridden by passing additional headers to calls to the store.
### idProperty
Defined by: [dojo/store/JsonRest](jsonrest)
Indicates the property to use as the identity property. The values of this property should be unique.
###
`queryEngine`
Defined by: [dojo/store/api/Store](api/store)
If the store can be queried locally (on the client side in JS), this defines the query engine to use for querying the data store. This takes a query and query options and returns a function that can execute the provided query on a JavaScript array. The queryEngine may be replace to provide more sophisticated querying capabilities. For example:
```
var query = store.queryEngine({foo:"bar"}, {count:10});
query(someArray) -> filtered array
```
The returned query function may have a "matches" property that can be
used to determine if an object matches the query. For example:
```
query.matches({id:"some-object", foo:"bar"}) -> true
query.matches({id:"some-object", foo:"something else"}) -> false
```
### target
Defined by: [dojo/store/JsonRest](jsonrest)
The target base URL to use for all requests to the server. This string will be prepended to the id to generate the URL (relative or absolute) for requests sent to the server
Methods
-------
###
`add``(object,options)`
Defined by [dojo/store/JsonRest](jsonrest)
Adds an object. This will trigger a PUT request to the server if the object has an id, otherwise it will trigger a POST request.
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to store. |
| options | Object | *Optional*
Additional metadata for storing the data. Includes an "id" property if a specific id is to be used. |
**Returns:** undefined
###
`get``(id,options)`
Defined by [dojo/store/JsonRest](jsonrest)
Retrieves an object by its identity. This will trigger a GET request to the server using the url `this.target + id`.
| Parameter | Type | Description |
| --- | --- | --- |
| id | Number | The identity to use to lookup the object |
| options | Object | *Optional*
HTTP headers. For consistency with other methods, if a `headers` key exists on this object, it will be used to provide HTTP headers instead. |
**Returns:** Object | undefined
The object in the store that matches the given id.
###
`getChildren``(parent,options)`
Defined by [dojo/store/api/Store](api/store)
Retrieves the children of an object.
| Parameter | Type | Description |
| --- | --- | --- |
| parent | Object | The object to find the children of. |
| options | [dojo/store/api/Store.QueryOptions](api/store.queryoptions) | *Optional*
Additional options to apply to the retrieval of the children. |
**Returns:** [dojo/store/api/Store.QueryResults](api/store.queryresults)
A result set of the children of the parent object.
###
`getIdentity``(object)`
Defined by [dojo/store/JsonRest](jsonrest)
Returns an object's identity
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to get the identity from |
**Returns:** Number | undefined
###
`getMetadata``(object)`
Defined by [dojo/store/api/Store](api/store)
Returns any metadata about the object. This may include attribution, cache directives, history, or version information.
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to return metadata for. |
**Returns:** Object
An object containing metadata.
###
`put``(object,options)`
Defined by [dojo/store/JsonRest](jsonrest)
Stores an object. This will trigger a PUT request to the server if the object has an id, otherwise it will trigger a POST request.
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to store. |
| options | Object | *Optional*
Additional metadata for storing the data. Includes an "id" property if a specific id is to be used. |
**Returns:** [dojo/\_base/Deferred](../_base/deferred) | undefined
###
`query``(query,options)`
Defined by [dojo/store/JsonRest](jsonrest)
Queries the store for objects. This will trigger a GET request to the server, with the query added as a query string.
| Parameter | Type | Description |
| --- | --- | --- |
| query | Object | The query to use for retrieving objects from the store. |
| options | Object | *Optional*
The optional arguments to apply to the resultset. |
**Returns:** [dojo/store/api/Store.QueryResults](api/store.queryresults) | undefined
The results of the query, extended with iterative methods.
###
`remove``(id,options)`
Defined by [dojo/store/JsonRest](jsonrest)
Deletes an object by its identity. This will trigger a DELETE request to the server.
| Parameter | Type | Description |
| --- | --- | --- |
| id | Number | The identity to use to delete the object |
| options | Object | *Optional*
HTTP headers. |
**Returns:** undefined
###
`transaction``()`
Defined by [dojo/store/api/Store](api/store)
Starts a new transaction. Note that a store user might not call transaction() prior to using put, delete, etc. in which case these operations effectively could be thought of as "auto-commit" style actions.
**Returns:** [dojo/store/api/Store.Transaction](api/store.transaction)
This represents the new current transaction.
dojo dojo/store/Observable dojo/store/Observable
=====================
Summary
-------
The Observable store wrapper takes a store and sets an observe method on query() results that can be used to monitor results for changes.
Observable wraps an existing store so that notifications can be made when a query is performed.
Usage
-----
Observable`(store);`
| Parameter | Type | Description |
| --- | --- | --- |
| store | [dojo/store/api/Store](api/store) | |
**Returns:** undefined
See the [dojo/store/Observable reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/store/Observable.html) for more information.
Examples
--------
### Example 1
Create a Memory store that returns an observable query, and then log some information about that query.
```
var store = Observable(new Memory({
data: [
{id: 1, name: "one", prime: false},
{id: 2, name: "two", even: true, prime: true},
{id: 3, name: "three", prime: true},
{id: 4, name: "four", even: true, prime: false},
{id: 5, name: "five", prime: true}
]
}));
var changes = [], results = store.query({ prime: true });
var observer = results.observe(function(object, previousIndex, newIndex){
changes.push({previousIndex:previousIndex, newIndex:newIndex, object:object});
});
```
See the Observable tests for more information.
Methods
-------
dojo dojo/store/Cache dojo/store/Cache
================
Extends[dojo/store/api/Store](api/store) Summary
-------
The Cache store wrapper takes a master store and a caching store, caches data from the master into the caching store for faster lookup. Normally one would use a memory store for the caching store and a server store like JsonRest for the master store.
Usage
-----
var foo = new Cache`(masterStore,cachingStore,options);` Defined by [dojo/store/Cache](cache)
| Parameter | Type | Description |
| --- | --- | --- |
| masterStore | undefined | This is the authoritative store, all uncached requests or non-safe requests will be made against this store. |
| cachingStore | undefined | This is the caching store that will be used to store responses for quick access. Typically this should be a local store. |
| options | Object | *Optional*
These are additional options for how caching is handled. |
See the [dojo/store/Cache reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/store/Cache.html) for more information.
Examples
--------
### Example 1
```
var master = new Memory(data);
var cacher = new Memory();
var store = new Cache(master, cacher);
```
Properties
----------
### idProperty
Defined by: [dojo/store/api/Store](api/store)
If the store has a single primary key, this indicates the property to use as the identity property. The values of this property should be unique.
###
`queryEngine`
Defined by: [dojo/store/api/Store](api/store)
If the store can be queried locally (on the client side in JS), this defines the query engine to use for querying the data store. This takes a query and query options and returns a function that can execute the provided query on a JavaScript array. The queryEngine may be replace to provide more sophisticated querying capabilities. For example:
```
var query = store.queryEngine({foo:"bar"}, {count:10});
query(someArray) -> filtered array
```
The returned query function may have a "matches" property that can be
used to determine if an object matches the query. For example:
```
query.matches({id:"some-object", foo:"bar"}) -> true
query.matches({id:"some-object", foo:"something else"}) -> false
```
Methods
-------
###
`add``(object,directives)`
Defined by [dojo/store/Cache](cache)
Add the given object to the store.
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to add to the store. |
| directives | [dojo/store/api/Store.AddOptions](api/store#AddOptions) | *Optional*
Any additional parameters needed to describe how the add should be performed. |
**Returns:** Number
The new id for the object.
###
`evict``(id)`
Defined by [dojo/store/Cache](cache)
Remove the object with the given id from the underlying caching store.
| Parameter | Type | Description |
| --- | --- | --- |
| id | Number | The identifier for the object in question. |
###
`get``(id,directives)`
Defined by [dojo/store/Cache](cache)
Get the object with the specific id.
| Parameter | Type | Description |
| --- | --- | --- |
| id | Number | The identifier for the object in question. |
| directives | Object | *Optional*
Any additional parameters needed to describe how the get should be performed. |
**Returns:** [dojo/store/api/Store.QueryResults](api/store.queryresults)
A QueryResults object.
###
`getChildren``(parent,options)`
Defined by [dojo/store/api/Store](api/store)
Retrieves the children of an object.
| Parameter | Type | Description |
| --- | --- | --- |
| parent | Object | The object to find the children of. |
| options | [dojo/store/api/Store.QueryOptions](api/store.queryoptions) | *Optional*
Additional options to apply to the retrieval of the children. |
**Returns:** [dojo/store/api/Store.QueryResults](api/store.queryresults)
A result set of the children of the parent object.
###
`getIdentity``(object)`
Defined by [dojo/store/api/Store](api/store)
Returns an object's identity
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to get the identity from |
**Returns:** String|Number
###
`getMetadata``(object)`
Defined by [dojo/store/api/Store](api/store)
Returns any metadata about the object. This may include attribution, cache directives, history, or version information.
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to return metadata for. |
**Returns:** Object
An object containing metadata.
###
`put``(object,directives)`
Defined by [dojo/store/Cache](cache)
Put the object into the store (similar to an HTTP PUT).
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to put to the store. |
| directives | [dojo/store/api/Store.PutDirectives](api/store.putdirectives) | *Optional*
Any additional parameters needed to describe how the put should be performed. |
**Returns:** Number
The new id for the object.
###
`query``(query,directives)`
Defined by [dojo/store/Cache](cache)
Query the underlying master store and cache any results.
| Parameter | Type | Description |
| --- | --- | --- |
| query | Object | String | The object or string containing query information. Dependent on the query engine used. |
| directives | [dojo/store/api/Store.QueryOptions](api/store.queryoptions) | *Optional*
An optional keyword arguments object with additional parameters describing the query. |
**Returns:** [dojo/store/api/Store.QueryResults](api/store.queryresults)
A QueryResults object that can be used to iterate over.
###
`remove``(id)`
Defined by [dojo/store/Cache](cache)
Remove the object with the specific id.
| Parameter | Type | Description |
| --- | --- | --- |
| id | Number | The identifier for the object in question. |
###
`transaction``()`
Defined by [dojo/store/api/Store](api/store)
Starts a new transaction. Note that a store user might not call transaction() prior to using put, delete, etc. in which case these operations effectively could be thought of as "auto-commit" style actions.
**Returns:** [dojo/store/api/Store.Transaction](api/store.transaction)
This represents the new current transaction.
| programming_docs |
dojo dojo/store/Memory dojo/store/Memory
=================
Extends[dojo/store/api/Store](api/store) Summary
-------
This is a basic in-memory object store. It implements [dojo/store/api/Store](api/store).
Usage
-----
var foo = new Memory`(options);` Defined by [dojo/store/Memory](memory)
| Parameter | Type | Description |
| --- | --- | --- |
| options | [dojo/store/Memory](memory) | This provides any configuration information that will be mixed into the store. This should generally include the data property to provide the starting set of data. |
See the [dojo/store/Memory reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/store/Memory.html) for more information.
Properties
----------
### data
Defined by: [dojo/store/Memory](memory)
The array of all the objects in the memory store
### idProperty
Defined by: [dojo/store/Memory](memory)
Indicates the property to use as the identity property. The values of this property should be unique.
### index
Defined by: [dojo/store/Memory](memory)
An index of data indices into the data array by id
Methods
-------
###
`add``(object,options)`
Defined by [dojo/store/Memory](memory)
Creates an object, throws an error if the object already exists
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to store. |
| options | [dojo/store/api/Store.PutDirectives](api/store.putdirectives) | *Optional*
Additional metadata for storing the data. Includes an "id" property if a specific id is to be used. |
**Returns:** Number | undefined
###
`get``(id)`
Defined by [dojo/store/Memory](memory)
Retrieves an object by its identity
| Parameter | Type | Description |
| --- | --- | --- |
| id | Number | The identity to use to lookup the object |
**Returns:** Object | undefined
The object in the store that matches the given id.
###
`getChildren``(parent,options)`
Defined by [dojo/store/api/Store](api/store)
Retrieves the children of an object.
| Parameter | Type | Description |
| --- | --- | --- |
| parent | Object | The object to find the children of. |
| options | [dojo/store/api/Store.QueryOptions](api/store.queryoptions) | *Optional*
Additional options to apply to the retrieval of the children. |
**Returns:** [dojo/store/api/Store.QueryResults](api/store.queryresults)
A result set of the children of the parent object.
###
`getIdentity``(object)`
Defined by [dojo/store/Memory](memory)
Returns an object's identity
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to get the identity from |
**Returns:** Number | undefined
###
`getMetadata``(object)`
Defined by [dojo/store/api/Store](api/store)
Returns any metadata about the object. This may include attribution, cache directives, history, or version information.
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to return metadata for. |
**Returns:** Object
An object containing metadata.
###
`put``(object,options)`
Defined by [dojo/store/Memory](memory)
Stores an object
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to store. |
| options | [dojo/store/api/Store.PutDirectives](api/store.putdirectives) | *Optional*
Additional metadata for storing the data. Includes an "id" property if a specific id is to be used. |
**Returns:** Number | undefined
###
`query``(query,options)`
Defined by [dojo/store/Memory](memory)
Queries the store for objects.
| Parameter | Type | Description |
| --- | --- | --- |
| query | Object | The query to use for retrieving objects from the store. |
| options | [dojo/store/api/Store.QueryOptions](api/store.queryoptions) | *Optional*
The optional arguments to apply to the resultset. |
**Returns:** [dojo/store/api/Store.QueryResults](api/store.queryresults) | undefined
The results of the query, extended with iterative methods.
Examples
--------
### Example 1
Given the following store:
```
var store = new Memory({
data: [
{id: 1, name: "one", prime: false },
{id: 2, name: "two", even: true, prime: true},
{id: 3, name: "three", prime: true},
{id: 4, name: "four", even: true, prime: false},
{id: 5, name: "five", prime: true}
]
});
```
...find all items where "prime" is true:
```
var results = store.query({ prime: true });
```
...or find all items where "even" is true:
```
var results = store.query({ even: true });
```
###
`queryEngine``(query,options)`
Defined by [dojo/store/Memory](memory)
Defines the query engine to use for querying the data store
| Parameter | Type | Description |
| --- | --- | --- |
| query | Object | An object hash with fields that may match fields of items in the store. Values in the hash will be compared by normal == operator, but regular expressions or any object that provides a test() method are also supported and can be used to match strings by more complex expressions (and then the regex's or object's test() method will be used to match values). |
| options | [dojo/store/api/Store.QueryOptions](api/store.queryoptions) | *Optional*
An object that contains optional information such as sort, start, and count. |
**Returns:** Function | function
A function that caches the passed query under the field "matches". See any of the "query" methods on dojo.stores.
###
`remove``(id)`
Defined by [dojo/store/Memory](memory)
Deletes an object by its identity
| Parameter | Type | Description |
| --- | --- | --- |
| id | Number | The identity to use to delete the object |
**Returns:** Boolean | boolean
Returns true if an object was removed, falsy (undefined) if no object matched the id
###
`setData``(data)`
Defined by [dojo/store/Memory](memory)
Sets the given data as the source for this store, and indexes it
| Parameter | Type | Description |
| --- | --- | --- |
| data | Object[] | An array of objects to use as the source of data. |
###
`transaction``()`
Defined by [dojo/store/api/Store](api/store)
Starts a new transaction. Note that a store user might not call transaction() prior to using put, delete, etc. in which case these operations effectively could be thought of as "auto-commit" style actions.
**Returns:** [dojo/store/api/Store.Transaction](api/store.transaction)
This represents the new current transaction.
dojo dojo/store/DataStore dojo/store/DataStore
====================
Extends[dojo/store/api/Store](api/store) Summary
-------
This is an adapter for using Dojo Data stores with an object store consumer. You can provide a Dojo data store and use this adapter to interact with it through the Dojo object store API
Usage
-----
var foo = new DataStore`(options);` Defined by [dojo/store/DataStore](datastore)
| Parameter | Type | Description |
| --- | --- | --- |
| options | Object | *Optional*
This provides any configuration information that will be mixed into the store, including a reference to the Dojo data store under the property "store". |
See the [dojo/store/DataStore reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/store/DataStore.html) for more information.
Properties
----------
### idProperty
Defined by: [dojo/store/DataStore](datastore)
The object property to use to store the identity of the store items.
### store
Defined by: [dojo/store/DataStore](datastore)
The object store to convert to a data store
### target
Defined by: [dojo/store/DataStore](datastore)
Methods
-------
###
`add``(object,options)`
Defined by [dojo/store/DataStore](datastore)
Creates an object, throws an error if the object already exists
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to store. |
| options | [dojo/store/api/Store.PutDirectives](api/store.putdirectives) | *Optional*
Additional metadata for storing the data. Includes an "id" property if a specific id is to be used. |
**Returns:** Number | undefined
###
`get``(id,options)`
Defined by [dojo/store/DataStore](datastore)
Retrieves an object by it's identity. This will trigger a fetchItemByIdentity
| Parameter | Type | Description |
| --- | --- | --- |
| id | Object | *Optional*
The identity to use to lookup the object |
| options | undefined | |
**Returns:** undefined
###
`getChildren``(parent,options)`
Defined by [dojo/store/api/Store](api/store)
Retrieves the children of an object.
| Parameter | Type | Description |
| --- | --- | --- |
| parent | Object | The object to find the children of. |
| options | [dojo/store/api/Store.QueryOptions](api/store.queryoptions) | *Optional*
Additional options to apply to the retrieval of the children. |
**Returns:** [dojo/store/api/Store.QueryResults](api/store.queryresults)
A result set of the children of the parent object.
###
`getIdentity``(object)`
Defined by [dojo/store/DataStore](datastore)
Fetch the identity for the given object.
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The data object to get the identity from. |
**Returns:** Number | undefined
The id of the given object.
###
`getMetadata``(object)`
Defined by [dojo/store/api/Store](api/store)
Returns any metadata about the object. This may include attribution, cache directives, history, or version information.
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to return metadata for. |
**Returns:** Object
An object containing metadata.
###
`put``(object,options)`
Defined by [dojo/store/DataStore](datastore)
Stores an object by its identity.
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to store. |
| options | Object | *Optional*
Additional metadata for storing the data. Includes a reference to an id that the object may be stored with (i.e. { id: "foo" }). |
**Returns:** undefined
###
`query``(query,options)`
Defined by [dojo/store/DataStore](datastore)
Queries the store for objects.
| Parameter | Type | Description |
| --- | --- | --- |
| query | Object | The query to use for retrieving objects from the store |
| options | Object | *Optional*
Optional options object as used by the underlying dojo.data Store. |
**Returns:** [dojo/store/api/Store.QueryResults](api/store.queryresults) | undefined
A query results object that can be used to iterate over results.
###
`queryEngine``(query,options)`
Defined by [dojo/store/DataStore](datastore)
Defines the query engine to use for querying the data store
| Parameter | Type | Description |
| --- | --- | --- |
| query | Object | An object hash with fields that may match fields of items in the store. Values in the hash will be compared by normal == operator, but regular expressions or any object that provides a test() method are also supported and can be used to match strings by more complex expressions (and then the regex's or object's test() method will be used to match values). |
| options | [dojo/store/api/Store.QueryOptions](api/store.queryoptions) | *Optional*
An object that contains optional information such as sort, start, and count. |
**Returns:** Function | function
A function that caches the passed query under the field "matches". See any of the "query" methods on dojo.stores.
###
`remove``(id)`
Defined by [dojo/store/DataStore](datastore)
Deletes an object by its identity.
| Parameter | Type | Description |
| --- | --- | --- |
| id | Object | The identity to use to delete the object |
**Returns:** undefined
###
`transaction``()`
Defined by [dojo/store/api/Store](api/store)
Starts a new transaction. Note that a store user might not call transaction() prior to using put, delete, etc. in which case these operations effectively could be thought of as "auto-commit" style actions.
**Returns:** [dojo/store/api/Store.Transaction](api/store.transaction)
This represents the new current transaction.
dojo dojo/store/util/SimpleQueryEngine dojo/store/util/SimpleQueryEngine
=================================
Summary
-------
Simple query engine that matches using filter functions, named filter functions or objects by name-value on a query object hash
The SimpleQueryEngine provides a way of getting a QueryResults through the use of a simple object hash as a filter. The hash will be used to match properties on data objects with the corresponding value given. In other words, only exact matches will be returned.
This function can be used as a template for more complex query engines; for example, an engine can be created that accepts an object hash that contains filtering functions, or a string that gets evaluated, etc.
When creating a new dojo.store, simply set the store's queryEngine field as a reference to this function.
Usage
-----
SimpleQueryEngine`(query,options);`
| Parameter | Type | Description |
| --- | --- | --- |
| query | Object | An object hash with fields that may match fields of items in the store. Values in the hash will be compared by normal == operator, but regular expressions or any object that provides a test() method are also supported and can be used to match strings by more complex expressions (and then the regex's or object's test() method will be used to match values). |
| options | [dojo/store/api/Store.QueryOptions](../api/store.queryoptions) | *Optional*
An object that contains optional information such as sort, start, and count. |
**Returns:** Function | function
A function that caches the passed query under the field "matches". See any of the "query" methods on dojo.stores.
See the [dojo/store/util/SimpleQueryEngine reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/store/util/SimpleQueryEngine.html) for more information.
Examples
--------
### Example 1
Define a store with a reference to this engine, and set up a query method.
```
var myStore = function(options){
// ...more properties here
this.queryEngine = SimpleQueryEngine;
// define our query method
this.query = function(query, options){
return QueryResults(this.queryEngine(query, options)(this.data));
};
};
```
Methods
-------
dojo dojo/store/util/QueryResults dojo/store/util/QueryResults
============================
Summary
-------
A function that wraps the results of a store query with additional methods.
QueryResults is a basic wrapper that allows for array-like iteration over any kind of returned data from a query. While the simplest store will return a plain array of data, other stores may return deferreds or promises; this wrapper makes sure that *all* results can be treated the same.
Additional methods include `forEach`, `filter` and `map`.
Usage
-----
QueryResults`(results);`
| Parameter | Type | Description |
| --- | --- | --- |
| results | Array | [dojo/promise/Promise](../../promise/promise) | The result set as an array, or a promise for an array. |
**Returns:** any | Array|[dojo/promise/Promise](../../promise/promise) | undefined
An array-like object that can be used for iterating over.
See the [dojo/store/util/QueryResults reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/store/util/QueryResults.html) for more information.
Examples
--------
### Example 1
Query a store and iterate over the results.
```
store.query({ prime: true }).forEach(function(item){
// do something
});
```
Methods
-------
dojo dojo/store/api/Store.Transaction dojo/store/api/Store.Transaction
================================
Summary
-------
This is an object returned from transaction() calls that represents the current transaction.
Methods
-------
###
`abort``(callback,thisObject)`
Defined by [dojo/store/api/Store](store)
Aborts the transaction. This may throw an error if it fails. Of if the operation is asynchronous, it may return a promise that represents the eventual success or failure of the abort.
| Parameter | Type | Description |
| --- | --- | --- |
| callback | undefined | |
| thisObject | undefined | |
###
`commit``()`
Defined by [dojo/store/api/Store](store)
Commits the transaction. This may throw an error if it fails. Of if the operation is asynchronous, it may return a promise that represents the eventual success or failure of the commit.
dojo dojo/store/api/Store.QueryResults dojo/store/api/Store.QueryResults
=================================
Summary
-------
This is an object returned from query() calls that provides access to the results of a query. Queries may be executed asynchronously.
Properties
----------
### total
Defined by: [dojo/store/api/Store](store)
This property should be included in if the query options included the "count" property limiting the result set. This property indicates the total number of objects matching the query (as if "start" and "count" weren't present). This may be a promise if the query is asynchronous.
Methods
-------
###
`filter``(callback,thisObject)`
Defined by [dojo/store/api/Store](store)
Filters the query results, based on <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter>. Note that this may executed asynchronously. The callback may be called after this function returns.
| Parameter | Type | Description |
| --- | --- | --- |
| callback | undefined | Function that is called for each object in the query results |
| thisObject | undefined | The object to use as |this| in the callback. |
**Returns:** [dojo/store/api/Store.QueryResults](store.queryresults)
###
`forEach``(callback,thisObject)`
Defined by [dojo/store/api/Store](store)
Iterates over the query results, based on <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/forEach>. Note that this may executed asynchronously. The callback may be called after this function returns.
| Parameter | Type | Description |
| --- | --- | --- |
| callback | undefined | Function that is called for each object in the query results |
| thisObject | undefined | The object to use as |this| in the callback. |
###
`map``(callback,thisObject)`
Defined by [dojo/store/api/Store](store)
Maps the query results, based on <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map>. Note that this may executed asynchronously. The callback may be called after this function returns.
| Parameter | Type | Description |
| --- | --- | --- |
| callback | undefined | Function that is called for each object in the query results |
| thisObject | undefined | The object to use as |this| in the callback. |
**Returns:** [dojo/store/api/Store.QueryResults](store.queryresults)
###
`observe``(listener,includeAllUpdates)`
Defined by [dojo/store/api/Store](store)
This registers a callback for notification of when data is modified in the query results. This is an optional method, and is usually provided by dojo/store/Observable.
| Parameter | Type | Description |
| --- | --- | --- |
| listener | Function | The listener function is called when objects in the query results are modified to affect the query result. The listener function is called with the following arguments:
```
listener(object, removedFrom, insertedInto);
```
* The object parameter indicates the object that was create, modified, or deleted.
* The removedFrom parameter indicates the index in the result array where the object used to be. If the value is -1, then the object is an addition to this result set (due to a new object being created, or changed such that it is a part of the result set).
* The insertedInto parameter indicates the index in the result array where the object should be now. If the value is -1, then the object is a removal from this result set (due to an object being deleted, or changed such that it is not a part of the result set).
|
| includeAllUpdates | undefined | This indicates whether or not to include object updates that do not affect the inclusion or order of the object in the query results. By default this is false, which means that if any object is updated in such a way that it remains in the result set and it's position in result sets is not affected, then the listener will not be fired. |
###
`then``(callback,errorHandler)`
Defined by [dojo/store/api/Store](store)
This registers a callback for when the query is complete, if the query is asynchronous. This is an optional method, and may not be present for synchronous queries.
| Parameter | Type | Description |
| --- | --- | --- |
| callback | undefined | This is called when the query is completed successfully, and is passed a single argument that is an array representing the query results. |
| errorHandler | undefined | This is called if the query failed, and is passed a single argument that is the error for the failure. |
| programming_docs |
dojo dojo/store/api/Store.QueryOptions dojo/store/api/Store.QueryOptions
=================================
Summary
-------
Optional object with additional parameters for query results.
Properties
----------
### count
Defined by: [dojo/store/api/Store](store)
The number of how many results should be returned.
### sort
Defined by: [dojo/store/api/Store](store)
A list of attributes to sort on, as well as direction For example:
```
[{attribute:"price, descending: true}].
```
If the sort parameter is omitted, then the natural order of the store may be
applied if there is a natural order.
### start
Defined by: [dojo/store/api/Store](store)
The first result to begin iteration on
dojo dojo/store/api/Store.SortInformation dojo/store/api/Store.SortInformation
====================================
Summary
-------
An object describing what attribute to sort on, and the direction of the sort.
Properties
----------
### attribute
Defined by: [dojo/store/api/Store](store)
The name of the attribute to sort on.
### descending
Defined by: [dojo/store/api/Store](store)
The direction of the sort. Default is false.
dojo dojo/store/api/Store dojo/store/api/Store
====================
Summary
-------
This is an abstract API that data provider implementations conform to. This file defines methods signatures and intentionally leaves all the methods unimplemented. For more information on the , please visit: <http://dojotoolkit.org/reference-guide/dojo/store.html> Every method and property is optional, and is only needed if the functionality it provides is required. Every method may return a promise for the specified return value if the execution of the operation is asynchronous (except for query() which already defines an async return value).
Properties
----------
### idProperty
Defined by: [dojo/store/api/Store](store)
If the store has a single primary key, this indicates the property to use as the identity property. The values of this property should be unique.
###
`queryEngine`
Defined by: [dojo/store/api/Store](store)
If the store can be queried locally (on the client side in JS), this defines the query engine to use for querying the data store. This takes a query and query options and returns a function that can execute the provided query on a JavaScript array. The queryEngine may be replace to provide more sophisticated querying capabilities. For example:
```
var query = store.queryEngine({foo:"bar"}, {count:10});
query(someArray) -> filtered array
```
The returned query function may have a "matches" property that can be
used to determine if an object matches the query. For example:
```
query.matches({id:"some-object", foo:"bar"}) -> true
query.matches({id:"some-object", foo:"something else"}) -> false
```
Methods
-------
###
`add``(object,directives)`
Defined by [dojo/store/api/Store](store)
Creates an object, throws an error if the object already exists
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to store. |
| directives | [dojo/store/api/Store.PutDirectives](store.putdirectives) | *Optional*
Additional directives for creating objects. |
**Returns:** Number|String
###
`get``(id)`
Defined by [dojo/store/api/Store](store)
Retrieves an object by its identity
| Parameter | Type | Description |
| --- | --- | --- |
| id | Number | The identity to use to lookup the object |
**Returns:** Object
The object in the store that matches the given id.
###
`getChildren``(parent,options)`
Defined by [dojo/store/api/Store](store)
Retrieves the children of an object.
| Parameter | Type | Description |
| --- | --- | --- |
| parent | Object | The object to find the children of. |
| options | [dojo/store/api/Store.QueryOptions](store.queryoptions) | *Optional*
Additional options to apply to the retrieval of the children. |
**Returns:** [dojo/store/api/Store.QueryResults](store.queryresults)
A result set of the children of the parent object.
###
`getIdentity``(object)`
Defined by [dojo/store/api/Store](store)
Returns an object's identity
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to get the identity from |
**Returns:** String|Number
###
`getMetadata``(object)`
Defined by [dojo/store/api/Store](store)
Returns any metadata about the object. This may include attribution, cache directives, history, or version information.
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to return metadata for. |
**Returns:** Object
An object containing metadata.
###
`put``(object,directives)`
Defined by [dojo/store/api/Store](store)
Stores an object
| Parameter | Type | Description |
| --- | --- | --- |
| object | Object | The object to store. |
| directives | [dojo/store/api/Store.PutDirectives](store.putdirectives) | *Optional*
Additional directives for storing objects. |
**Returns:** Number|String
###
`PutDirectives``()`
Defined by [dojo/store/api/Store](store)
###
`query``(query,options)`
Defined by [dojo/store/api/Store](store)
Queries the store for objects. This does not alter the store, but returns a set of data from the store.
| Parameter | Type | Description |
| --- | --- | --- |
| query | String | Object | Function | The query to use for retrieving objects from the store. |
| options | [dojo/store/api/Store.QueryOptions](store.queryoptions) | The optional arguments to apply to the resultset. |
**Returns:** [dojo/store/api/Store.QueryResults](store.queryresults)
The results of the query, extended with iterative methods.
Examples
--------
### Example 1
Given the following store:
...find all items where "prime" is true:
```
store.query({ prime: true }).forEach(function(object){
// handle each object
});
```
###
`QueryOptions``()`
Defined by [dojo/store/api/Store](store)
###
`QueryResults``()`
Defined by [dojo/store/api/Store](store)
###
`remove``(id)`
Defined by [dojo/store/api/Store](store)
Deletes an object by its identity
| Parameter | Type | Description |
| --- | --- | --- |
| id | Number | The identity to use to delete the object |
###
`SortInformation``()`
Defined by [dojo/store/api/Store](store)
###
`transaction``()`
Defined by [dojo/store/api/Store](store)
Starts a new transaction. Note that a store user might not call transaction() prior to using put, delete, etc. in which case these operations effectively could be thought of as "auto-commit" style actions.
**Returns:** [dojo/store/api/Store.Transaction](store.transaction)
This represents the new current transaction.
###
`Transaction``()`
Defined by [dojo/store/api/Store](store)
dojo dojo/store/api/Store.PutDirectives dojo/store/api/Store.PutDirectives
==================================
Summary
-------
Directives passed to put() and add() handlers for guiding the update and creation of stored objects.
Properties
----------
### before
Defined by: [dojo/store/api/Store](store)
If the collection of objects in the store has a natural ordering, this indicates that the created or updated object should be placed before the object specified by the value of this property. A value of null indicates that the object should be last.
### id
Defined by: [dojo/store/api/Store](store)
Indicates the identity of the object if a new object is created
### overwrite
Defined by: [dojo/store/api/Store](store)
If this is provided as a boolean it indicates that the object should or should not overwrite an existing object. A value of true indicates that a new object should not be created, the operation should update an existing object. A value of false indicates that an existing object should not be updated, a new object should be created (which is the same as an add() operation). When this property is not provided, either an update or creation is acceptable.
### parent
Defined by: [dojo/store/api/Store](store)
If the store is hierarchical (with single parenting) this property indicates the new parent of the created or updated object.
dojo dojo/router/RouterBase dojo/router/RouterBase
======================
Summary
-------
A module that allows one to easily map hash-based structures into callbacks. The router module is a singleton, offering one central point for all registrations of this type.
Usage
-----
var foo = new RouterBase`(kwArgs);` Defined by [dojo/router/RouterBase](routerbase)
| Parameter | Type | Description |
| --- | --- | --- |
| kwArgs | undefined | |
See the [dojo/router/RouterBase reference documentation](http://dojotoolkit.org/reference-guide/1.10/dojo/router.html) for more information.
Examples
--------
### Example 1
```
var router = new RouterBase({});
router.register("/widgets/:id", function(evt){
// If "/widgets/3" was matched,
// evt.params.id === "3"
xhr.get({
url: "/some/path/" + evt.params.id,
load: function(data){
// ...
}
});
});
```
Properties
----------
### globMatch
Defined by: [dojo/router/RouterBase](routerbase)
### globReplacement
Defined by: [dojo/router/RouterBase](routerbase)
### idMatch
Defined by: [dojo/router/RouterBase](routerbase)
### idReplacement
Defined by: [dojo/router/RouterBase](routerbase)
Methods
-------
###
`destroy``()`
Defined by [dojo/router/RouterBase](routerbase)
###
`go``(path,replace)`
Defined by [dojo/router/RouterBase](routerbase)
A simple pass-through to make changing the hash easy, without having to require dojo/hash directly. It also synchronously fires off any routes that match.
| Parameter | Type | Description |
| --- | --- | --- |
| path | undefined | |
| replace | undefined | |
**Returns:** boolean | undefined
Examples
--------
### Example 1
```
router.go("/foo/bar");
```
###
`register``(route,callback)`
Defined by [dojo/router/RouterBase](routerbase)
Registers a route to a handling callback
Given either a string or a regular expression, the router will monitor the page's hash and respond to changes that match the string or regex as provided.
When provided a regex for the route:
* Matching is performed, and the resulting capture groups are passed through to the callback as an array.
When provided a string for the route:
* The string is parsed as a URL-like structure, like "/foo/bar"
* If any portions of that URL are prefixed with a colon (:), they will be parsed out and provided to the callback as properties of an object.
* If the last piece of the URL-like structure is prefixed with a star (\*) instead of a colon, it will be replaced in the resulting regex with a greedy (.+) match and anything remaining on the hash will be provided as a property on the object passed into the callback. Think of it like a basic means of globbing the end of a route.
| Parameter | Type | Description |
| --- | --- | --- |
| route | String | RegExp | A string or regular expression which will be used when monitoring hash changes. |
| callback | Function | When the hash matches a pattern as described in the route, this callback will be executed. It will receive an event object that will have several properties: * params: Either an array or object of properties pulled from the new hash
* oldPath: The hash in its state before the change
* newPath: The new hash being shifted to
* preventDefault: A method that will stop hash changes from being actually applied to the active hash. This only works if the hash change was initiated using `router.go`, as changes initiated more directly to the location.hash property will already be in place
* stopImmediatePropagation: When called, will stop any further bound callbacks on this particular route from being executed. If two distinct routes are bound that are different, but both happen to match the current hash in some way, this will *not* keep other routes from receiving notice of the change.
|
**Returns:** Object | undefined
A plain JavaScript object to be used as a handle for either removing this specific callback's registration, as well as to add new callbacks with the same route initially used.
Examples
--------
### Example 1
```
router.register("/foo/:bar/*baz", function(object){
// If the hash was "/foo/abc/def/ghi",
// object.bar === "abc"
// object.baz === "def/ghi"
});
```
###
`registerBefore``(route,callback)`
Defined by [dojo/router/RouterBase](routerbase)
Registers a route to a handling callback, except before any previously registered callbacks
Much like the `register` method, `registerBefore` allows us to register route callbacks to happen before any previously registered callbacks. See the documentation for `register` for more details and examples.
| Parameter | Type | Description |
| --- | --- | --- |
| route | String | RegExp | |
| callback | Function | |
**Returns:** undefined
###
`startup``(defaultPath)`
Defined by [dojo/router/RouterBase](routerbase)
This method must be called to activate the router. Until startup is called, no hash changes will trigger route callbacks.
| Parameter | Type | Description |
| --- | --- | --- |
| defaultPath | undefined | |
padrino Top Level Namespace Top Level Namespace
===================
Defined Under Namespace
-----------------------
**Modules:** [FileSet](fileset "FileSet (module)"), [Haml](haml "Haml (module)"), [Kernel](kernel "Kernel (module)"), [Padrino](padrino "Padrino (module)") **Classes:** [Module](module "Module (class)"), [Numeric](numeric "Numeric (class)"), [Object](object "Object (class)"), [String](string "String (class)"), [TemporaryString](temporarystring "TemporaryString (class)")
Constant Summary [collapse](#)
-------------------------------
RACK\_ENV = Defines our constants
```
ENV['RACK_ENV'] ||= 'development'
```
PADRINO\_ROOT =
```
File.expand_path('../..', __FILE__)
```
PADRINO\_I18N\_LOCALE =
```
true
```
PADRINO\_LOG\_LEVEL = Defines the log level for a Padrino project.
```
ENV['PADRINO_LOG_LEVEL']
```
PADRINO\_LOGGER = Defines the logger used for a Padrino project.
```
ENV['PADRINO_LOGGER']
```
SafeBuffer =
```
Padrino::SafeBuffer
```
Instance Method Summary
------------------------
* `[#**root** ⇒ Object](toplevel#root-instance_method "#root (instance method)")` Require initializers before all other dependencies.
Instance Method Details
-----------------------
### #root ⇒ Object
Require initializers before all other dependencies. Dependencies from 'config' folder are NOT re-required on reload.
padrino Class: Numeric Class: Numeric
==============
Inherits: [Object](object "Object (class)") * [Object](object "Object (class)")
* Numeric
Instance Method Summary
------------------------
* `[#**html\_safe?** ⇒ Boolean](numeric#html_safe%3F-instance_method "#html_safe? (instance method)")`
Instance Method Details
-----------------------
### #html\_safe? ⇒ Boolean
#### Returns:
* (`Boolean`)
padrino Class: TemporaryString Class: TemporaryString
======================
Inherits: [String](string "String (class)") * [Object](object "Object (class)")
* [String](string "String (class)")
* TemporaryString
Instance Method Summary
------------------------
* `[#**to\_s** ⇒ Object](temporarystring#to_s-instance_method "#to_s (instance method)")`
### Methods inherited from String
[#camelize](string#camelize-instance_method "String#camelize (method)"), [#classify](string#classify-instance_method "String#classify (method)"), [#colorize](string#colorize-instance_method "String#colorize (method)"), [#constantize](string#constantize-instance_method "String#constantize (method)"), [#html\_safe](string#html_safe-instance_method "String#html_safe (method)"), [#pluralize](string#pluralize-instance_method "String#pluralize (method)"), [#underscore](string#underscore-instance_method "String#underscore (method)")
Instance Method Details
-----------------------
### #to\_s ⇒ Object
padrino Padrino Padrino
=======
Padrino is the godfather of Sinatra. Follow us on [www.padrinorb.com](http://padrinorb.com) and on twitter [@padrinorb](https://twitter.com/padrinorb). Join us on
Preface
-------
Padrino is a ruby framework built upon the excellent [Sinatra Web Library](http://www.sinatrarb.com). Sinatra is a DSL for creating simple web applications in Ruby quickly and with minimal effort. This framework tries to make it as fun and easy as possible to code more advanced web applications by building upon the Sinatra philosophies and foundations.
Introduction
------------
Many people love that Sinatra is simple and lightweight but soon begin to miss the great deal of functionality provided by other web frameworks such as Django or Rails when building non-trivial applications.
Our goal with this framework is to adhere to the essence of Sinatra and at the same time create a standard library of tools, helpers and components that will make Sinatra suitable for increasingly complex applications.
Here is a brief overview of functionality provided by the Padrino framework:
Agnostic
Full support for many popular testing, templating, mocking, and data storage choices.
Generators
Create Padrino applications, models, controllers i.e: padrino-gen project.
Mountable
Unlike other ruby frameworks, principally designed for mounting multiple apps.
Routing
Full url named routes, named params, before/after filter support.
Tag Helpers
View helpers such as: tag, content\_tag, input\_tag.
Asset Helpers
View helpers such as: link\_to, image\_tag, javascript\_include\_tag.
Form Helpers
Builder support such as: form\_tag, form\_for, field\_set\_tag, text\_field.
Text Helpers
Useful formatting like: time\_ago\_in\_words, js\_escape\_html, sanitize\_html.
Mailer
Fast and simple delivery support for sending emails (akin to ActionMailer).
Caching
Simple route and fragment caching to easily speed up your web requests.
Admin
Built-in Admin interface (like Django)
Logging
Provide a unified logger that can interact with your ORM or any library.
Reloading
Automatically reloads server code during development.
Localization
Full support of I18n language localization and can auto-set user's locale.
Keep in mind, developers are able to individually pull in these modular components [into existing Sinatra applications](http://padrinorb.com/guides/advanced-usage/standalone-usage-in-sinatra/) or use them altogether for a full-stack Padrino application.
Installation
------------
To install the padrino framework, simply grab the latest version from [RubyGems](https://rubygems.org):
```
$ gem install padrino
```
This will install the necessary padrino gems to get you started. Now you are ready to use this gem to enhance your Sinatra projects or to create new Padrino applications.
For a more detailed look at installing Padrino, check out the [Installation Guide](http://padrinorb.com/guides/getting-started/installation/).
Usage
-----
Padrino is a framework which builds on the existing functionality of Sinatra and provides a variety of additional tools and helpers to build upon that foundation. This README and Padrino documentation in general will focus on the enhancements to the core Sinatra functionality. To use Padrino, one should be familiar with the basic usage of Sinatra itself.
You can also check out the [Why Learn Padrino?](http://padrinorb.com/guides/introduction/why-learn-padrino/) introduction to learn more about how Sinatra and Padrino work together.
For information on how to use a specific gem in isolation within an existing Sinatra project, checkout the guide for [Using Padrino within Sinatra](http://padrinorb.com/guides/advanced-usage/standalone-usage-in-sinatra/).
Getting Started
---------------
Once a developer understands Sinatra, Padrino is quite easy to get comfortable with since Padrino is simply a superset of existing Sinatra functionality!
First, be sure to read over the [Getting Started](http://padrinorb.com/guides/getting-started/overview/) guide to learn more about how Sinatra and Padrino work together.
Best way to learn more about building Padrino applications is to read following resources:
* [Padrino Guides](http://padrinorb.com/guides) - Guides outlining the major functionality within Padrino.
* [Blog Tutorial](http://padrinorb.com/guides/getting-started/blog-tutorial/) - Step-by-step guide to building a blog application with Padrino.
* [Padrino API](https://www.rubydoc.info/github/padrino/padrino-framework) - YARD documentation for the Padrino framework.
* [Quick Overview](http://padrinorb.com/guides/getting-started/basic-projects/) - Outlines basic generation commands.
The individual Padrino sub-gems also contain README's which outlines their functionality.
Further Questions
-----------------
Can't find an answer in the resources above?
* Ask any questions on the .
Bug reporting
-------------
Log it onto Github by [creating a new issue](https://github.com/padrino/padrino-framework/issues).
Be sure to include all relevant information, like the versions of Padrino, Rack, Sinatra, Ruby and operating system you are using.
A minimal project showing the issue published on Github with Gemfile.lock is also extremely helpful.
Copyright
---------
Copyright © 2010-2016 Padrino. See LICENSE for details.
| programming_docs |
padrino Module: FileSet Module: FileSet
===============
Extended by: [FileSet](fileset "FileSet (module)") Included in: [FileSet](fileset "FileSet (module)") Overview
--------
FileSet helper method for iterating and interacting with files inside a directory
Instance Method Summary
------------------------
* `[#**glob**(glob\_pattern, file\_path = nil) ⇒ Object](fileset#glob-instance_method "#glob (instance method)")` Iterates over every file in the glob pattern and yields to a block Returns the list of files matching the glob pattern FileSet.glob('padrino-core/application/\*.rb', \_\_FILE\_\_) { |file| load file }.
* `[#**glob\_require**(glob\_pattern, file\_path = nil) ⇒ Object](fileset#glob_require-instance_method "#glob_require (instance method)")` Requires each file matched in the glob pattern into the application FileSet.glob\_require('padrino-core/application/\*.rb', \_\_FILE\_\_).
Instance Method Details
-----------------------
### #glob(glob\_pattern, file\_path = nil) ⇒ Object
Iterates over every file in the glob pattern and yields to a block Returns the list of files matching the glob pattern FileSet.glob('padrino-core/application/\*.rb', \_\_FILE\_\_) { |file| load file }
### #glob\_require(glob\_pattern, file\_path = nil) ⇒ Object
Requires each file matched in the glob pattern into the application FileSet.glob\_require('padrino-core/application/\*.rb', \_\_FILE\_\_)
padrino Class: Module Class: Module
=============
Inherits: [Object](object "Object (class)") * [Object](object "Object (class)")
* Module
Overview
--------
Make sure we can always use the class name In reloader for accessing class\_name Foo.\_orig\_klass\_name
padrino Module: Padrino Module: Padrino
===============
Extended by:
[Configuration](padrino/configuration "Padrino::Configuration (module)"), [Loader](padrino/loader "Padrino::Loader (module)")
Overview
--------
This module is based on Sequel 5.4.0 sequel-5.4.0/lib/sequel/model/default\_inflections.rb
Defined Under Namespace
-----------------------
**Modules:** [Admin](padrino/admin "Padrino::Admin (module)"), [ApplicationSetup](padrino/applicationsetup "Padrino::ApplicationSetup (module)"), [Cache](padrino/cache "Padrino::Cache (module)"), [Configuration](padrino/configuration "Padrino::Configuration (module)"), [Flash](padrino/flash "Padrino::Flash (module)"), [Generators](padrino/generators "Padrino::Generators (module)"), [Helpers](padrino/helpers "Padrino::Helpers (module)"), [Inflections](padrino/inflections "Padrino::Inflections (module)"), [Loader](padrino/loader "Padrino::Loader (module)"), [Mailer](padrino/mailer "Padrino::Mailer (module)"), [Module](padrino/module "Padrino::Module (module)"), [ParamsProtection](padrino/paramsprotection "Padrino::ParamsProtection (module)"), [PathRouter](padrino/pathrouter "Padrino::PathRouter (module)"), [Performance](padrino/performance "Padrino::Performance (module)"), [Reloader](padrino/reloader "Padrino::Reloader (module)"), [Rendering](padrino/rendering "Padrino::Rendering (module)"), [Routing](padrino/routing "Padrino::Routing (module)"), [Tasks](padrino/tasks "Padrino::Tasks (module)"), [Utils](padrino/utils "Padrino::Utils (module)") **Classes:** [Application](padrino/application "Padrino::Application (class)"), [AuthenticityToken](padrino/authenticitytoken "Padrino::AuthenticityToken (class)"), [Filter](padrino/filter "Padrino::Filter (class)"), [Logger](padrino/logger "Padrino::Logger (class)"), [Mounter](padrino/mounter "Padrino::Mounter (class)"), [Router](padrino/router "Padrino::Router (class)"), [SafeBuffer](padrino/safebuffer "Padrino::SafeBuffer (class)"), [Server](padrino/server "Padrino::Server (class)")
Constant Summary [collapse](#)
-------------------------------
PADRINO\_IGNORE\_CALLERS = List of callers in a Padrino application that should be ignored as part of a stack trace.
```
[
%r{lib/padrino-.*$},
%r{/padrino-.*/(lib|bin)},
%r{/bin/padrino$},
%r{/sinatra(/(base|main|show_?exceptions))?\.rb$},
%r{lib/tilt.*\.rb$},
%r{lib/rack.*\.rb$},
%r{lib/mongrel.*\.rb$},
%r{lib/shotgun.*\.rb$},
%r{bin/shotgun$},
%r{\(.*\)},
%r{shoulda/context\.rb$},
%r{mocha/integration},
%r{test/unit},
%r{rake_test_loader\.rb},
%r{custom_require\.rb$},
%r{active_support},
%r{/thor},
%r{/lib/bundler},
]
```
VERSION = The version constant for the current version of Padrino.
```
'0.15.0'
```
DEFAULT\_INFLECTIONS\_PROC = Proc that is instance evaled to create the default inflections for both the model inflector and the inflector extension.
```
proc do
plural(/$/, 's')
plural(/s$/i, 's')
plural(/(alias|(?:stat|octop|vir|b)us)$/i, '\1es')
plural(/(buffal|tomat)o$/i, '\1oes')
plural(/([ti])um$/i, '\1a')
plural(/sis$/i, 'ses')
plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')
plural(/(hive)$/i, '\1s')
plural(/([^aeiouy]|qu)y$/i, '\1ies')
plural(/(x|ch|ss|sh)$/i, '\1es')
plural(/(matr|vert|ind)ix|ex$/i, '\1ices')
plural(/([m|l])ouse$/i, '\1ice')
singular(/s$/i, '')
singular(/([ti])a$/i, '\1um')
singular(/(analy|ba|cri|diagno|parenthe|progno|synop|the)ses$/i, '\1sis')
singular(/([^f])ves$/i, '\1fe')
singular(/([h|t]ive)s$/i, '\1')
singular(/([lr])ves$/i, '\1f')
singular(/([^aeiouy]|qu)ies$/i, '\1y')
singular(/(m)ovies$/i, '\1ovie')
singular(/(x|ch|ss|sh)es$/i, '\1')
singular(/([m|l])ice$/i, '\1ouse')
singular(/buses$/i, 'bus')
singular(/oes$/i, 'o')
singular(/shoes$/i, 'shoe')
singular(/(alias|(?:stat|octop|vir|b)us)es$/i, '\1')
singular(/(vert|ind)ices$/i, '\1ex')
singular(/matrices$/i, 'matrix')
irregular('person', 'people')
irregular('man', 'men')
irregular('child', 'children')
irregular('sex', 'sexes')
irregular('move', 'moves')
irregular('quiz', 'quizzes')
irregular('testis', 'testes')
uncountable(%w(equipment information rice money species series fish sheep news))
end
```
Class Attribute Summary
-----------------------
* `[.**mounted\_root**(\*args) ⇒ String](padrino#mounted_root-class_method "mounted_root (class method)")` The root to the mounted apps base directory.
Class Method Summary
---------------------
* `[.**add\_middleware**(router) ⇒ Object](padrino#add_middleware-class_method "add_middleware (class method)")` Creates Rack stack with the router added to the middleware chain.
* `[.**after\_load**(&block) ⇒ Object](padrino#after_load-class_method "after_load (class method)")`
* `[.**application** ⇒ Padrino::Router](padrino#application-class_method "application (class method)")` The resulting rack builder mapping each 'mounted' application.
* `[.**before\_load**(&block) ⇒ Object](padrino#before_load-class_method "before_load (class method)")`
* `[.**bin**(\*args) ⇒ Boolean](padrino#bin-class_method "bin (class method)")` This method return the correct location of padrino bin or exec it using Kernel#system with the given args.
* `[.**bin\_gen**(\*args) ⇒ Object](padrino#bin_gen-class_method "bin_gen (class method)")` This method return the correct location of padrino-gen bin or exec it using Kernel#system with the given args.
* `[.**cache** ⇒ Object](padrino#cache-class_method "cache (class method)")` Returns the caching engine.
* `[.**cache=**(value) ⇒ Object](padrino#cache=-class_method "cache= (class method)")` Set the caching engine.
* `[.**clear\_middleware!** ⇒ Array](padrino#clear_middleware!-class_method "clear_middleware! (class method)")` Clears all previously configured middlewares.
* `[.**configure\_apps** { ... } ⇒ Object](padrino#configure_apps-class_method "configure_apps (class method)")` Configure Global Project Settings for mounted apps.
* `[.**env** ⇒ Symbol](padrino#env-class_method "env (class method)")` Helper method that return [RACK\_ENV](toplevel#RACK_ENV-constant "RACK_ENV (constant)").
* `[.**gem**(name, main\_module) ⇒ Object](padrino#gem-class_method "gem (class method)")` Registers a gem with padrino.
* `[.**gems** ⇒ Object](padrino#gems-class_method "gems (class method)")`
* `[.**global\_configurations** ⇒ Object](padrino#global_configurations-class_method "global_configurations (class method)")` Stores global configuration blocks.
* `[.**insert\_mounted\_app**(mounter) ⇒ Object](padrino#insert_mounted_app-class_method "insert_mounted_app (class method)")` Inserts a Mounter object into the mounted applications (avoids duplicates).
* `[.**logger** ⇒ Padrino::Logger](padrino#logger-class_method "logger (class method)")`
* `[.**logger=**(value) ⇒ Object](padrino#logger=-class_method "logger= (class method)")` Set the padrino logger.
* `[.**middleware** ⇒ Array<Array<Class, Array, Proc>>](padrino#middleware-class_method "middleware (class method)")` A Rack::Builder object that allows to add middlewares in front of all Padrino applications.
* `[.**modules** ⇒ Object](padrino#modules-class_method "modules (class method)")`
* `[.**mount**(name, options = {}) ⇒ Object](padrino#mount-class_method "mount (class method)")` Mounts a new sub-application onto Padrino project.
* `[.**mounted\_apps** ⇒ Array](padrino#mounted_apps-class_method "mounted_apps (class method)")` The mounted padrino applications (MountedApp objects).
* `[.**perf\_memusage\_command** ⇒ Object](padrino#perf_memusage_command-class_method "perf_memusage_command (class method)")`
* `[.**root**(\*args) ⇒ String](padrino#root-class_method "root (class method)")` Helper method for file references.
* `[.**ruby\_command** ⇒ String](padrino#ruby_command-class_method "ruby_command (class method)")` Return the path to the ruby interpreter taking into account multiple installations and windows extensions.
* `[.**run!**(options = {}) ⇒ Object](padrino#run!-class_method "run! (class method)")` Runs the Padrino apps as a self-hosted server using: thin, mongrel, or WEBrick in that order.
* `[.**set\_encoding** ⇒ NilClass](padrino#set_encoding-class_method "set_encoding (class method)")` Set `Encoding.default_internal` and `Encoding.default_external` to `Encoding::UFT_8`.
* `[.**use**(mw, \*args) { ... } ⇒ Object](padrino#use-class_method "use (class method)")` Convenience method for adding a Middleware to the whole padrino app.
* `[.**version** ⇒ String](padrino#version-class_method "version (class method)")` The current Padrino version.
Instance Method Summary
------------------------
* `[#**RUBY\_IGNORE\_CALLERS** ⇒ Object](padrino#RUBY_IGNORE_CALLERS-instance_method "#RUBY_IGNORE_CALLERS (instance method)")` Add rubinius (and hopefully other VM implementations) ignore patterns …
### Methods included from Loader
[after\_load](padrino/loader#after_load-instance_method "Padrino::Loader#after_load (method)"), [before\_load](padrino/loader#before_load-instance_method "Padrino::Loader#before_load (method)"), [called\_from](padrino/loader#called_from-instance_method "Padrino::Loader#called_from (method)"), [clear!](padrino/loader#clear!-instance_method "Padrino::Loader#clear! (method)"), [dependency\_paths](padrino/loader#dependency_paths-instance_method "Padrino::Loader#dependency_paths (method)"), [load!](padrino/loader#load!-instance_method "Padrino::Loader#load! (method)"), [loaded?](padrino/loader#loaded%3F-instance_method "Padrino::Loader#loaded? (method)"), [precompile\_all\_routes!](padrino/loader#precompile_all_routes!-instance_method "Padrino::Loader#precompile_all_routes! (method)"), [reload!](padrino/loader#reload!-instance_method "Padrino::Loader#reload! (method)"), [require\_dependencies](padrino/loader#require_dependencies-instance_method "Padrino::Loader#require_dependencies (method)")
### Methods included from Configuration
[config](padrino/configuration#config-instance_method "Padrino::Configuration#config (method)"), [configure](padrino/configuration#configure-instance_method "Padrino::Configuration#configure (method)")
Class Attribute Details
-----------------------
### .mounted\_root(\*args) ⇒ String
Returns the root to the mounted apps base directory.
#### Parameters:
* `args` (`Array`)
#### Returns:
* (`[String](string "String (class)")`) — the root to the mounted apps base directory.
Class Method Details
--------------------
### .add\_middleware(router) ⇒ Object
Creates Rack stack with the router added to the middleware chain.
### .after\_load(&block) ⇒ Object
### .application ⇒ Padrino::Router
The resulting rack builder mapping each 'mounted' application.
#### Returns:
* (`[Padrino::Router](padrino/router "Padrino::Router (class)")`) — The router for the application.
#### Raises:
* (`ApplicationLoadError`) — No applications were mounted.
### .before\_load(&block) ⇒ Object
### .bin(\*args) ⇒ Boolean
This method return the correct location of padrino bin or exec it using Kernel#system with the given args.
#### Examples:
```
Padrino.bin('start', '-e production')
```
#### Parameters:
* `args` (`Array`) — command or commands to execute
#### Returns:
* (`Boolean`)
### .bin\_gen(\*args) ⇒ Object
This method return the correct location of padrino-gen bin or exec it using Kernel#system with the given args.
#### Examples:
```
Padrino.bin_gen(:app, name.to_s, "-r=#{destination_root}")
```
#### Parameters:
* `args.` (`Array<[String](string "String (class)")>`) — Splat of arguments to pass to padrino-gen.
### .cache ⇒ Object
Returns the caching engine.
#### Examples:
```
# with: Padrino.cache = Padrino::Cache.new(:File, :dir => /my/cache/path)
Padrino.cache['val'] = 'test'
Padrino.cache['val'] # => 'test'
Padrino.cache.delete('val')
Padrino.cache.clear
```
### .cache=(value) ⇒ Object
Set the caching engine.
#### Examples:
```
Padrino.cache = Padrino::Cache.new(:LRUHash) # default choice
Padrino.cache = Padrino::Cache.new(:File, :dir => Padrino.root('tmp', app_name.to_s, 'cache')) # Keeps cached values in file
Padrino.cache = Padrino::Cache.new(:Memcached) # Uses default server at localhost
Padrino.cache = Padrino::Cache.new(:Memcached, :server => '127.0.0.1:11211', :exception_retry_limit => 1)
Padrino.cache = Padrino::Cache.new(:Memcached, :backend => memcached_or_dalli_instance)
Padrino.cache = Padrino::Cache.new(:Redis) # Uses default server at localhost
Padrino.cache = Padrino::Cache.new(:Redis, :host => '127.0.0.1', :port => 6379, :db => 0)
Padrino.cache = Padrino::Cache.new(:Redis, :backend => redis_instance)
Padrino.cache = Padrino::Cache.new(:Mongo) # Uses default server at localhost
Padrino.cache = Padrino::Cache.new(:Mongo, :backend => mongo_client_instance)
# You can manage your cache from anywhere in your app:
Padrino.cache['val'] = 'test'
Padrino.cache['val'] # => 'test'
Padrino.cache.delete('val')
Padrino.cache.clear
```
#### Parameters:
* `value` — Instance of Moneta store
### .clear\_middleware! ⇒ Array
Clears all previously configured middlewares.
#### Returns:
* (`Array`) — An empty array
### .configure\_apps { ... } ⇒ Object
Configure Global Project Settings for mounted apps. These can be overloaded in each individual app's own personal configuration. This can be used like:
#### Examples:
```
Padrino.configure_apps do
enable :sessions
disable :raise_errors
end
```
#### Yields:
* The given block will be called to configure each application.
### .env ⇒ Symbol
Helper method that return [RACK\_ENV](toplevel#RACK_ENV-constant "RACK_ENV (constant)").
#### Returns:
* (`Symbol`) — The Padrino Environment.
### .gem(name, main\_module) ⇒ Object
Registers a gem with padrino. This relieves the caller from setting up loadpaths by itself and enables Padrino to look up apps in gem folder.
The name given has to be the proper gem name as given in the gemspec.
#### Parameters:
* `name` (`[String](string "String (class)")`) — The name of the gem being registered.
* `main_module` (`[Module](padrino/module "Padrino::Module (module)")`) — The main module of the gem.
### .gems ⇒ Object
### .global\_configurations ⇒ Object
Stores global configuration blocks.
### .insert\_mounted\_app(mounter) ⇒ Object
Inserts a Mounter object into the mounted applications (avoids duplicates).
#### Parameters:
* `mounter` (`[Padrino::Mounter](padrino/mounter "Padrino::Mounter (class)")`)
### .logger ⇒ Padrino::Logger
#### Examples:
```
logger.debug "foo"
logger.warn "bar"
```
#### Returns:
* (`[Padrino::Logger](padrino/logger "Padrino::Logger (class)")`)
### .logger=(value) ⇒ Object
Set the padrino logger.
#### Examples:
using ruby default logger
```
require 'logger'
new_logger = ::Logger.new(STDOUT)
new_logger.extend(Padrino::Logger::Extensions)
Padrino.logger = new_logger
```
using ActiveSupport
```
require 'active_support/buffered_logger'
Padrino.logger = Buffered.new(STDOUT)
```
using custom logger class
```
require 'logger'
class CustomLogger < ::Logger
include Padrino::Logger::Extensions
end
Padrino.logger = CustomLogger.new(STDOUT)
```
#### Parameters:
* `value` (`[Object](object "Object (class)")`) — an object that respond to <<, write, puts, debug, warn, devel, etc..
#### Returns:
* (`[Object](object "Object (class)")`) — The given value.
### .middleware ⇒ Array<Array<Class, Array, Proc>>
A Rack::Builder object that allows to add middlewares in front of all Padrino applications.
#### Returns:
* (`Array<Array<Class, Array, Proc>>`) — The middleware classes.
### .modules ⇒ Object
### .mount(name, options = {}) ⇒ Object
Mounts a new sub-application onto Padrino project.
#### Examples:
```
Padrino.mount("blog_app").to("/blog")
```
#### See Also:
* Padrino::Mounter#new
### .mounted\_apps ⇒ Array
Returns the mounted padrino applications (MountedApp objects).
#### Returns:
* (`Array`) — the mounted padrino applications (MountedApp objects)
### .perf\_memusage\_command ⇒ Object
### .root(\*args) ⇒ String
Helper method for file references.
#### Examples:
```
# Referencing a file in config called settings.yml
Padrino.root("config", "settings.yml")
# returns PADRINO_ROOT + "/config/setting.yml"
```
#### Parameters:
* `args` (`Array<[String](string "String (class)")>`) — The directories to join to [PADRINO\_ROOT](toplevel#PADRINO_ROOT-constant "PADRINO_ROOT (constant)").
#### Returns:
* (`[String](string "String (class)")`) — The absolute path.
### .ruby\_command ⇒ String
Return the path to the ruby interpreter taking into account multiple installations and windows extensions.
#### Returns:
* (`[String](string "String (class)")`) — path to ruby bin executable
### .run!(options = {}) ⇒ Object
Runs the Padrino apps as a self-hosted server using: thin, mongrel, or WEBrick in that order.
#### Examples:
```
Padrino.run! # with these defaults => host: "127.0.0.1", port: "3000", adapter: the first found
Padrino.run!("0.0.0.0", "4000", "mongrel") # use => host: "0.0.0.0", port: "4000", adapter: "mongrel"
```
### .set\_encoding ⇒ NilClass
Set `Encoding.default_internal` and `Encoding.default_external` to `Encoding::UFT_8`.
Please note that in `1.9.2` with some template engines like `haml` you should turn off Encoding.default\_internal to prevent problems.
#### Returns:
* (`NilClass`)
#### See Also:
* [https://github.com/rtomayko/tilt/issues/75](https://github.com/rtomayko/tilt/issues/75 "https://github.com/rtomayko/tilt/issues/75")
### .use(mw, \*args) { ... } ⇒ Object
Convenience method for adding a Middleware to the whole padrino app.
#### Parameters:
* `m` (`Class`) — The middleware class.
* `args` (`Array`) — The arguments for the middleware.
#### Yields:
* The given block will be passed to the initialized middleware.
### .version ⇒ String
The current Padrino version.
#### Returns:
* (`[String](string "String (class)")`) — The version number.
Instance Method Details
-----------------------
### #RUBY\_IGNORE\_CALLERS ⇒ Object
Add rubinius (and hopefully other VM implementations) ignore patterns …
| programming_docs |
padrino Class: Object Class: Object
=============
Inherits: BasicObject Instance Method Summary
------------------------
* `[#**html\_safe?** ⇒ Boolean](object#html_safe%3F-instance_method "#html_safe? (instance method)")`
Instance Method Details
-----------------------
### #html\_safe? ⇒ Boolean
#### Returns:
* (`Boolean`)
padrino Class: String Class: String
=============
Inherits: [Object](object "Object (class)") * [Object](object "Object (class)")
* String
Overview
--------
Add colors
Direct Known Subclasses
-----------------------
[Padrino::Routing::Parent](padrino/routing/parent "Padrino::Routing::Parent (class)"), [Padrino::SafeBuffer](padrino/safebuffer "Padrino::SafeBuffer (class)"), [TemporaryString](temporarystring "TemporaryString (class)")
Defined Under Namespace
-----------------------
**Classes:** [Colorizer](string/colorizer "String::Colorizer (class)")
Instance Method Summary
------------------------
* `[#**camelize** ⇒ Object](string#camelize-instance_method "#camelize (instance method)")`
* `[#**classify** ⇒ Object](string#classify-instance_method "#classify (instance method)")`
* `[#**colorize**(args) ⇒ Object](string#colorize-instance_method "#colorize (instance method)")` colorize(:red).
* `[#**constantize** ⇒ Object](string#constantize-instance_method "#constantize (instance method)")`
* `[#**html\_safe** ⇒ Object](string#html_safe-instance_method "#html_safe (instance method)")`
* `[#**pluralize** ⇒ Object](string#pluralize-instance_method "#pluralize (instance method)")`
* `[#**underscore** ⇒ Object](string#underscore-instance_method "#underscore (instance method)")`
Instance Method Details
-----------------------
### #camelize ⇒ Object
### #classify ⇒ Object
### #colorize(args) ⇒ Object
colorize(:red)
### #constantize ⇒ Object
### #html\_safe ⇒ Object
### #pluralize ⇒ Object
### #underscore ⇒ Object
padrino Module: Haml Module: Haml
============
Defined Under Namespace
-----------------------
**Modules:** [Helpers](haml/helpers "Haml::Helpers (module)"), [Util](haml/util "Haml::Util (module)")
padrino Module: Kernel Module: Kernel
==============
Instance Method Summary
------------------------
* `[#**logger** ⇒ Object](kernel#logger-instance_method "#logger (instance method)")` Define a logger available every where in our app.
Instance Method Details
-----------------------
### #logger ⇒ Object
Define a logger available every where in our app
padrino Module: Haml::Util Module: Haml::Util
==================
Class Method Summary
---------------------
* `[.**rails\_xss\_safe?** ⇒ Boolean](util#rails_xss_safe%3F-class_method "rails_xss_safe? (class method)")`
Class Method Details
--------------------
### .rails\_xss\_safe? ⇒ Boolean
#### Returns:
* (`Boolean`)
padrino Class: Sinatra::Request Class: Sinatra::Request
=======================
Inherits: [Object](../object "Object (class)") * [Object](../object "Object (class)")
* Sinatra::Request
Overview
--------
Adds to Sinatra `controller` informations
Instance Attribute Summary
--------------------------
* `[#**route\_obj** ⇒ Object](request#route_obj-instance_method "#route_obj (instance method)")` Returns the value of attribute route\_obj.
Instance Method Summary
------------------------
* `[#**action** ⇒ Object](request#action-instance_method "#action (instance method)")`
* `[#**controller** ⇒ Object](request#controller-instance_method "#controller (instance method)")`
Instance Attribute Details
--------------------------
### #route\_obj ⇒ Object
Returns the value of attribute route\_obj
Instance Method Details
-----------------------
### #action ⇒ Object
### #controller ⇒ Object
padrino Class: String::Colorizer Class: String::Colorizer
========================
Inherits: [Object](../object "Object (class)") * [Object](../object "Object (class)")
* String::Colorizer
Overview
--------
Used to colorize strings for the shell
Class Method Summary
---------------------
* `[.**colors** ⇒ Object](colorizer#colors-class_method "colors (class method)")` Returns colors integer mapping.
* `[.**modes** ⇒ Object](colorizer#modes-class_method "modes (class method)")` Returns modes integer mapping.
Class Method Details
--------------------
### .colors ⇒ Object
Returns colors integer mapping
### .modes ⇒ Object
Returns modes integer mapping
padrino Module: Padrino::Routing Module: Padrino::Routing
========================
Overview
--------
Padrino provides advanced routing definition support to make routes and url generation much easier. This routing system supports named route aliases and easy access to url paths. The benefits of this is that instead of having to hard-code route urls into every area of your application, now we can just define the urls in a single spot and then attach an alias which can be used to refer to the url throughout the application.
Defined Under Namespace
-----------------------
**Modules:** [ClassMethods](routing/classmethods "Padrino::Routing::ClassMethods (module)"), [InstanceMethods](routing/instancemethods "Padrino::Routing::InstanceMethods (module)") **Classes:** [BlockArityError](routing/blockarityerror "Padrino::Routing::BlockArityError (class)"), [Parent](routing/parent "Padrino::Routing::Parent (class)"), [UnrecognizedException](routing/unrecognizedexception "Padrino::Routing::UnrecognizedException (class)")
Constant Summary [collapse](#)
-------------------------------
CONTENT\_TYPE\_ALIASES = Defines common content-type alias mappings.
```
{ :htm => :html }
```
ROUTE\_PRIORITY = Defines the available route priorities supporting route deferrals.
```
{:high => 0, :normal => 1, :low => 2}
```
Class Method Summary
---------------------
* `[.**registered**(app) ⇒ Object](routing#registered-class_method "registered (class method)") (also: included)` Main class that register this extension.
Class Method Details
--------------------
### .registered(app) ⇒ Object Also known as: included
Main class that register this extension.
padrino Module: Padrino::Helpers Module: Padrino::Helpers
========================
Overview
--------
This component provides a variety of view helpers related to html markup generation. There are helpers for generating tags, forms, links, images, and more. Most of the basic methods should be very familiar to anyone who has used rails view helpers.
Defined Under Namespace
-----------------------
**Modules:** [AssetTagHelpers](helpers/assettaghelpers "Padrino::Helpers::AssetTagHelpers (module)"), [FormBuilder](helpers/formbuilder "Padrino::Helpers::FormBuilder (module)"), [FormHelpers](helpers/formhelpers "Padrino::Helpers::FormHelpers (module)"), [FormatHelpers](helpers/formathelpers "Padrino::Helpers::FormatHelpers (module)"), [NumberHelpers](helpers/numberhelpers "Padrino::Helpers::NumberHelpers (module)"), [OutputHelpers](helpers/outputhelpers "Padrino::Helpers::OutputHelpers (module)"), [RenderHelpers](helpers/renderhelpers "Padrino::Helpers::RenderHelpers (module)"), [TagHelpers](helpers/taghelpers "Padrino::Helpers::TagHelpers (module)"), [TranslationHelpers](helpers/translationhelpers "Padrino::Helpers::TranslationHelpers (module)")
Class Method Summary
---------------------
* `[.**registered**(app) ⇒ Object](helpers#registered-class_method "registered (class method)")` Registers these helpers into your application:.
Class Method Details
--------------------
### .registered(app) ⇒ Object
Registers these helpers into your application:
```
Padrino::Helpers::OutputHelpers
Padrino::Helpers::TagHelpers
Padrino::Helpers::AssetTagHelpers
Padrino::Helpers::FormHelpers
Padrino::Helpers::FormatHelpers
Padrino::Helpers::RenderHelpers
Padrino::Helpers::NumberHelpers
```
#### Examples:
Register the helper module
```
require 'padrino-helpers'
class Padrino::Application
register Padrino::Helpers
end
```
#### Parameters:
* `app` (`Sinatra::Application`) — The specified Padrino application.
padrino Module: Padrino::Tasks Module: Padrino::Tasks
======================
Overview
--------
This module it's used for bootstrap with padrino rake third party tasks, in your gem/plugin/extension you need only do this:
#### Examples:
```
Padrino::Tasks.files << yourtask.rb
Padrino::Tasks.files.concat(Dir["/path/to/all/my/tasks/*.rb"])
Padrino::Tasks.files.unshift("yourtask.rb")
```
Class Method Summary
---------------------
* `[.**files** ⇒ Object](tasks#files-class_method "files (class method)")` Returns a list of files to handle with padrino rake.
Class Method Details
--------------------
### .files ⇒ Object
Returns a list of files to handle with padrino rake
padrino Class: Padrino::Application Class: Padrino::Application
===========================
Inherits: Sinatra::Base * [Object](../object "Object (class)")
* Sinatra::Base
* Padrino::Application
Overview
--------
Subclasses of this become independent Padrino applications (stemming from Sinatra::Application). These subclassed applications can be easily mounted into other Padrino applications as well.
Class Method Summary
---------------------
* `[.**default**(option, \*args, &block) ⇒ Object](application#default-class_method "default (class method)")`
* `[.**dependencies** ⇒ Array](application#dependencies-class_method "dependencies (class method)")` Returns default list of path globs to load as dependencies.
* `[.**layout\_path**(layout) ⇒ Object](application#layout_path-class_method "layout_path (class method)")` Returns an absolute path of application layout.
* `[.**prerequisites** ⇒ Object](application#prerequisites-class_method "prerequisites (class method)")` An array of file to load before your app.rb, basically are files which our app depends on.
* `[.**reload!** ⇒ TrueClass](application#reload!-class_method "reload! (class method)")` Reloads the application files from all defined load paths.
* `[.**reset\_routes!** ⇒ TrueClass](application#reset_routes!-class_method "reset_routes! (class method)")` Resets application routes to only routes not defined by the user.
* `[.**routes** ⇒ Object](application#routes-class_method "routes (class method)")` Returns the routes of our app.
* `[.**run!**(options = {}) ⇒ Object](application#run!-class_method "run! (class method)")` Run the Padrino app as a self-hosted server using Thin, Mongrel or WEBrick (in that order).
* `[.**view\_path**(view) ⇒ Object](application#view_path-class_method "view_path (class method)")` Returns an absolute path of view in application views folder.
Instance Method Summary
------------------------
* `[#**logger** ⇒ Padrino::Logger](application#logger-instance_method "#logger (instance method)")` Returns the logger for this application.
Class Method Details
--------------------
### .default(option, \*args, &block) ⇒ Object
### .dependencies ⇒ Array
Returns default list of path globs to load as dependencies. Appends custom dependency patterns to the be loaded for your Application.
#### Examples:
```
MyApp.dependencies << "#{Padrino.root}/uploaders/**/*.rb"
MyApp.dependencies << Padrino.root('other_app', 'controllers.rb')
```
#### Returns:
* (`Array`) — list of path globs to load as dependencies
### .layout\_path(layout) ⇒ Object
Returns an absolute path of application layout.
#### Examples:
```
Admin.layout_path :application #=> "/home/user/test/admin/views/layouts/application"
```
### .prerequisites ⇒ Object
An array of file to load before your app.rb, basically are files which our app depends on.
By default we look for files:
```
# List of default files that we are looking for:
yourapp/models.rb
yourapp/models/**/*.rb
yourapp/lib.rb
yourapp/lib/**/*.rb
```
#### Examples:
Adding a custom prerequisite
```
MyApp.prerequisites << Padrino.root('my_app', 'custom_model.rb')
```
### .reload! ⇒ TrueClass
Reloads the application files from all defined load paths.
This method is used from our Padrino Reloader during development mode in order to reload the source files.
#### Examples:
```
MyApp.reload!
```
#### Returns:
* (`TrueClass`)
### .reset\_routes! ⇒ TrueClass
Resets application routes to only routes not defined by the user.
#### Examples:
```
MyApp.reset_routes!
```
#### Returns:
* (`TrueClass`)
### .routes ⇒ Object
Returns the routes of our app.
#### Examples:
```
MyApp.routes
```
### .run!(options = {}) ⇒ Object
Run the Padrino app as a self-hosted server using Thin, Mongrel or WEBrick (in that order).
#### See Also:
* [Server#start](server#start-instance_method "Padrino::Server#start (method)")
### .view\_path(view) ⇒ Object
Returns an absolute path of view in application views folder.
#### Examples:
```
Admin.view_path 'users/index' #=> "/home/user/test/admin/views/users/index"
```
Instance Method Details
-----------------------
### #logger ⇒ Padrino::Logger
Returns the logger for this application.
#### Returns:
* (`[Padrino::Logger](logger "Padrino::Logger (class)")`) — Logger associated with this app.
padrino Module: Padrino::Admin Module: Padrino::Admin
======================
Overview
--------
Padrino::Admin is beautiful Ajax Admin, with these features:
Orm Agnostic
Adapters for datamapper, activerecord, mongomapper, couchdb (now only: datamapper and activerecord), ohm
Authentication
Support for Account authentication, Account Permission management
Scaffold
You can simply create a new “admin interface” simply providing a Model
Ajax Uploads
You can upload file, manage them and attach them to any model in a quick and simple way (coming soon)
Defined Under Namespace
-----------------------
**Modules:** [AccessControl](admin/accesscontrol "Padrino::Admin::AccessControl (module)"), [Generators](admin/generators "Padrino::Admin::Generators (module)"), [Helpers](admin/helpers "Padrino::Admin::Helpers (module)") **Classes:** [AccessControlError](admin/accesscontrolerror "Padrino::Admin::AccessControlError (class)")
Class Method Summary
---------------------
* `[.**registered**(app) ⇒ Object](admin#registered-class_method "registered (class method)") (also: included)`
Class Method Details
--------------------
### .registered(app) ⇒ Object Also known as: included
padrino Class: Padrino::Router Class: Padrino::Router
======================
Inherits: [Object](../object "Object (class)") * [Object](../object "Object (class)")
* Padrino::Router
Overview
--------
This class is an extended version of Rack::URLMap.
Padrino::Router like Rack::URLMap dispatches in such a way that the longest paths are tried first, since they are most specific.
Features:
* Map a path to the specified App
* Ignore server names (this solve issues with vhost and domain aliases)
* Use hosts instead of server name for mappings (this help us with our vhost and domain aliases)
#### Examples:
```
routes = Padrino::Router.new do
map(:path => "/", :to => PadrinoWeb, :host => "padrino.local")
map(:path => "/", :to => Admin, :host => "admin.padrino.local")
end
run routes
routes = Padrino::Router.new do
map(:path => "/", :to => PadrinoWeb, :host => /*.padrino.local/)
end
run routes
```
Instance Method Summary
------------------------
* `[#**call**(env) ⇒ Object](router#call-instance_method "#call (instance method)")` The call handler setup to route a request given the mappings specified.
* `[#**initialize**(\*mapping, &block) ⇒ Router](router#initialize-instance_method "#initialize (instance method)")` constructor A new instance of Router.
* `[#**map**(options = {}) ⇒ Array](router#map-instance_method "#map (instance method)")` Map a route path and host to a specified application.
Constructor Details
-------------------
### #initialize(\*mapping, &block) ⇒ Router
Returns a new instance of Router.
Instance Method Details
-----------------------
### #call(env) ⇒ Object
The call handler setup to route a request given the mappings specified.
### #map(options = {}) ⇒ Array
Map a route path and host to a specified application.
#### Examples:
```
map(:path => "/", :to => PadrinoWeb, :host => "padrino.local")
```
#### Parameters:
* `options` (`Hash`) *(defaults to: `{}`)* — The options to map.
#### Options Hash (`options`):
* `:to` (`Sinatra::Application`) — The class of the application to mount.
* `:path` (`[String](../string "String (class)")`) — default: `"/"` — The path to map the specified application.
* `:host` (`[String](../string "String (class)")`) — The host to map the specified application.
#### Returns:
* (`Array`) — The sorted route mappings.
#### Raises:
* (`ArgumentError`)
padrino Module: Padrino::Inflections Module: Padrino::Inflections
============================
Extended by: [Inflections](inflections "Padrino::Inflections (module)") Included in: [Inflections](inflections "Padrino::Inflections (module)") Overview
--------
This module acts as a singleton returned/yielded by Sequel.inflections, which is used to override or specify additional inflection rules for Sequel. Examples:
```
Sequel.inflections do |inflect|
inflect.plural /^(ox)$/i, '\1\2en'
inflect.singular /^(ox)en/i, '\1'
inflect.irregular 'octopus', 'octopi'
inflect.uncountable "equipment"
end
```
New rules are added at the top. So in the example above, the irregular rule for octopus will now be the first of the pluralization and singularization rules that is runs. This guarantees that your rules run before any of the rules that may already have been loaded.
Constant Summary [collapse](#)
-------------------------------
CAMELIZE\_CONVERT\_REGEXP =
```
/(^|_)(.)/.freeze
```
CAMELIZE\_MODULE\_REGEXP =
```
/\/(.?)/.freeze
```
DASH =
```
'-'.freeze
```
DEMODULIZE\_CONVERT\_REGEXP =
```
/^.*::/.freeze
```
EMPTY\_STRING =
```
''.freeze
```
SLASH =
```
'/'.freeze
```
VALID\_CONSTANT\_NAME\_REGEXP =
```
/\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/.freeze
```
UNDERSCORE =
```
'_'.freeze
```
UNDERSCORE\_CONVERT\_REGEXP1 =
```
/([A-Z]+)([A-Z][a-z])/.freeze
```
UNDERSCORE\_CONVERT\_REGEXP2 =
```
/([a-z\d])([A-Z])/.freeze
```
UNDERSCORE\_CONVERT\_REPLACE =
```
'\1_\2'.freeze
```
UNDERSCORE\_MODULE\_REGEXP =
```
/::/.freeze
```
Class Attribute Summary
-----------------------
* `[.**plurals** ⇒ Object](inflections#plurals-class_method "plurals (class method)")` readonly Array of two element arrays, first containing a regex, and the second containing a substitution pattern, used for plurization.
* `[.**singulars** ⇒ Object](inflections#singulars-class_method "singulars (class method)")` readonly Array of two element arrays, first containing a regex, and the second containing a substitution pattern, used for singularization.
* `[.**uncountables** ⇒ Object](inflections#uncountables-class_method "uncountables (class method)")` readonly Array of strings for words were the singular form is the same as the plural form.
Class Method Summary
---------------------
* `[.**clear**(scope = :all) ⇒ Object](inflections#clear-class_method "clear (class method)")` Clears the loaded inflections within a given scope (default is :all).
* `[.**irregular**(singular, plural) ⇒ Object](inflections#irregular-class_method "irregular (class method)")` Specifies a new irregular that applies to both pluralization and singularization at the same time.
* `[.**plural**(rule, replacement) ⇒ Object](inflections#plural-class_method "plural (class method)")` Specifies a new pluralization rule and its replacement.
* `[.**singular**(rule, replacement) ⇒ Object](inflections#singular-class_method "singular (class method)")` Specifies a new singularization rule and its replacement.
* `[.**uncountable**(\*words) ⇒ Object](inflections#uncountable-class_method "uncountable (class method)")` Add uncountable words that shouldn't be attempted inflected.
Instance Method Summary
------------------------
* `[#**camelize**(s) ⇒ Object](inflections#camelize-instance_method "#camelize (instance method)")` Convert the given string to CamelCase.
* `[#**classify**(s) ⇒ Object](inflections#classify-instance_method "#classify (instance method)")` Create a class name from a plural table name like Rails does for table names to models.
* `[#**constantize**(s) ⇒ Object](inflections#constantize-instance_method "#constantize (instance method)")` Tries to find a declared constant with the name specified in the string.
* `[#**demodulize**(s) ⇒ Object](inflections#demodulize-instance_method "#demodulize (instance method)")` Removes the module part from the expression in the string.
* `[#**humanize**(s) ⇒ Object](inflections#humanize-instance_method "#humanize (instance method)")` Capitalizes the first word, turns underscores into spaces, and strips a trailing '\_id' if present.
* `[#**pluralize**(s) ⇒ Object](inflections#pluralize-instance_method "#pluralize (instance method)")` Returns the plural form of the word in the string.
* `[#**singularize**(s) ⇒ Object](inflections#singularize-instance_method "#singularize (instance method)")` The reverse of pluralize, returns the singular form of a word in a string.
* `[#**underscore**(s) ⇒ Object](inflections#underscore-instance_method "#underscore (instance method)")` The reverse of camelize.
Class Attribute Details
-----------------------
### .plurals ⇒ Object (readonly)
Array of two element arrays, first containing a regex, and the second containing a substitution pattern, used for plurization.
### .singulars ⇒ Object (readonly)
Array of two element arrays, first containing a regex, and the second containing a substitution pattern, used for singularization.
### .uncountables ⇒ Object (readonly)
Array of strings for words were the singular form is the same as the plural form
Class Method Details
--------------------
### .clear(scope = :all) ⇒ Object
Clears the loaded inflections within a given scope (default is :all). Give the scope as a symbol of the inflection type, the options are: :plurals, :singulars, :uncountables
Examples:
```
clear :all
clear :plurals
```
### .irregular(singular, plural) ⇒ Object
Specifies a new irregular that applies to both pluralization and singularization at the same time. This can only be used for strings, not regular expressions. You simply pass the irregular in singular and plural form.
Examples:
```
irregular 'octopus', 'octopi'
irregular 'person', 'people'
```
### .plural(rule, replacement) ⇒ Object
Specifies a new pluralization rule and its replacement. The rule can either be a string or a regular expression. The replacement should always be a string that may include references to the matched data from the rule.
Example:
```
plural(/(x|ch|ss|sh)$/i, '\1es')
```
### .singular(rule, replacement) ⇒ Object
Specifies a new singularization rule and its replacement. The rule can either be a string or a regular expression. The replacement should always be a string that may include references to the matched data from the rule.
Example:
```
singular(/([^aeiouy]|qu)ies$/i, '\1y')
```
### .uncountable(\*words) ⇒ Object
Add uncountable words that shouldn't be attempted inflected.
Examples:
```
uncountable "money"
uncountable "money", "information"
uncountable %w( money information rice )
```
Instance Method Details
-----------------------
### #camelize(s) ⇒ Object
Convert the given string to CamelCase. Will also convert '/' to '::' which is useful for converting paths to namespaces.
### #classify(s) ⇒ Object
Create a class name from a plural table name like Rails does for table names to models.
### #constantize(s) ⇒ Object
Tries to find a declared constant with the name specified in the string. It raises a NameError when the name is not in CamelCase or is not initialized.
#### Raises:
* (`NameError`)
### #demodulize(s) ⇒ Object
Removes the module part from the expression in the string
### #humanize(s) ⇒ Object
Capitalizes the first word, turns underscores into spaces, and strips a trailing '\_id' if present.
### #pluralize(s) ⇒ Object
Returns the plural form of the word in the string.
### #singularize(s) ⇒ Object
The reverse of pluralize, returns the singular form of a word in a string.
### #underscore(s) ⇒ Object
The reverse of camelize. Makes an underscored form from the expression in the string. Also changes '::' to '/' to convert namespaces to paths.
| programming_docs |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.