# type

id: sheet
directory: .
list_fields: ["title"]
default_format: md
markdown_body_is_field: body
json_schema:
{"type": "object", "properties": {"title": {"type": "string", "title": "title", "description": ""}, "category": {"type": "string", "title": "category", "description": ""}, "tags": {"title": "tags", "description": "", "type": "array", "items": {"type": "string"}, "uniqueItems": false}, "prism_languages": {"title": "prism_languages", "description": "", "type": "array", "items": {"type": "string"}, "uniqueItems": false}, "intro": {"type": "string", "title": "intro", "description": ""}, "updated": {"type": "string", "format": "date", "title": "updated", "description": ""}, "weight": {"type": "integer", "title": "weight", "description": ""}, "body": {"type": "string", "title": "body", "description": "", "format": "textarea"}}, "$schema": "https://json-schema.org/draft/2020-12/schema"}


# record_sheet

id: datatig
git_filename: ./datatig.yaml
format: yaml
field_title: Devhints
data:
{"title": "Devhints", "description": "Website at https://devhints.io/ Source at https://github.com/rstacruz/cheatsheets", "types": [{"id": "sheet", "directory": ".", "markdown_body_is_field": "body", "default_format": "md", "fields": [{"id": "title"}, {"id": "category"}, {"id": "tags", "type": "list-strings"}, {"id": "prism_languages", "type": "list-strings"}, {"id": "intro"}, {"id": "updated", "type": "date"}, {"id": "weight", "type": "integer"}, {"id": "body", "type": "markdown"}]}]}


id: zsh
git_filename: ./zsh.md
format: md
field_title: zsh
field_category: CLI
data:
{"title": "zsh", "category": "CLI", "body": "### Expressions\n\n| Expression        | Example             | Description\n| ---               | ---                 | ---\n| `!!`              | `sudo !!`           | Last command (`sudo !!`)\n| ---               | ---                 | ---\n| `!*`              | `vim !*`            | Last command's parameters (`vim !*`)\n| `!^`              |                     | Last command's first parameter\n| `!$`              |                     | Last command's last parameter\n| ---               | ---                 | ---\n| `!?ls` `<tab>`    | `sudo !?mv` `<tab>` | Command and params of last `ls` command\n| `!?ls?:*` `<tab>` |                     | Params of last `ls` command\n| ---               | ---                 | ---\n| `*(m0)`           | `rm *(m0)`          | Last modified today\n| `*(m-4)`          |                     | Last modified <4 days ago\n{: .-headers}\n\n### Change default shell\n\n```bash\nchsh -s `which zsh`\n```\n\n### Process Substitution\n\n| Expression        | Example                                               | Description\n| ---               | ---                                                   | ---\n| `<(COMMAND)`      | `grep \"needle\" <(curl \"https://haystack.io\")`         | Replace argument with _named pipe/FIFO_ (read-only) with command output\n| `=(COMMAND)`      | `vim =(curl \"https://haystack.io\")`                   | Replace argument with _file_ (writable) containing command output\n{: .-headers}\n\n### Also see\n\n- [Bash cheatsheet](./bash)\n\nZsh is mostly compatible with Bash, so most everything in Bash's cheatsheet also applies."}

field_body:
### Expressions

| Expression        | Example             | Description
| ---               | ---                 | ---
| `!!`              | `sudo !!`           | Last command (`sudo !!`)
| ---               | ---                 | ---
| `!*`              | `vim !*`            | Last command's parameters (`vim !*`)
| `!^`              |                     | Last command's first parameter
| `!$`              |                     | Last command's last parameter
| ---               | ---                 | ---
| `!?ls` `<tab>`    | `sudo !?mv` `<tab>` | Command and params of last `ls` command
| `!?ls?:*` `<tab>` |                     | Params of last `ls` command
| ---               | ---                 | ---
| `*(m0)`           | `rm *(m0)`          | Last modified today
| `*(m-4)`          |                     | Last modified <4 days ago
{: .-headers}

### Change default shell

```bash
chsh -s `which zsh`
```

### Process Substitution

| Expression        | Example                                               | Description
| ---               | ---                                                   | ---
| `<(COMMAND)`      | `grep "needle" <(curl "https://haystack.io")`         | Replace argument with _named pipe/FIFO_ (read-only) with command output
| `=(COMMAND)`      | `vim =(curl "https://haystack.io")`                   | Replace argument with _file_ (writable) containing command output
{: .-headers}

### Also see

- [Bash cheatsheet](./bash)

Zsh is mostly compatible with Bash, so most everything in Bash's cheatsheet also applies.


id: zombie
git_filename: ./zombie.md
format: md
field_title: Zombie
field_category: JavaScript libraries
field_intro: [Zombie](http://zombie.js.org/) is a full-stack testing solution for Node.js.
data:
{"title": "Zombie", "category": "JavaScript libraries", "intro": "[Zombie](http://zombie.js.org/) is a full-stack testing solution for Node.js.\n", "body": "## Zombie\n\n### Examples\n\n```js\nbrowser\n  .visit(\"http://.../\", ->)\n  .fill(\"email\", \"zombie@underworld.dead\")\n  .fill(\"password\", \"eat-the-living\")\n  .select(\"Born\", \"1985\")\n  .uncheck(\"Send newsletter\")\n  .clickLink(\"Link name\")\n  .pressButton(\"Sign\", () => { ... })\n  .text(\"H1\")\n```\n\n### Expectations\n\n```js\nexpect(browser.query(\"#brains\"))\n\nexpect(browser.body.queryAll(\".hand\")).length 2\n\nconsole.log(browser.html())\nconsole.log(browser.html(\"table.parts\"))\n\nexpect(Browser.text(\".card-nopad small\"), \"A better way to get around!\")\n```"}

field_body:
## Zombie

### Examples

```js
browser
  .visit("http://.../", ->)
  .fill("email", "zombie@underworld.dead")
  .fill("password", "eat-the-living")
  .select("Born", "1985")
  .uncheck("Send newsletter")
  .clickLink("Link name")
  .pressButton("Sign", () => { ... })
  .text("H1")
```

### Expectations

```js
expect(browser.query("#brains"))

expect(browser.body.queryAll(".hand")).length 2

console.log(browser.html())
console.log(browser.html("table.parts"))

expect(Browser.text(".card-nopad small"), "A better way to get around!")
```


id: znc
git_filename: ./znc.md
format: md
field_title: ZNC bouncer
field_intro: A quick reference to the [ZNC](https://znc.bg) IRC bouncer's common commands.
data:
{"title": "ZNC bouncer", "intro": "A quick reference to the [ZNC](https://znc.bg) IRC bouncer's common commands.\n", "body": "## Start\n\n```\n/msg *status addserver irc.undernet.org [6667]\n/msg *status connect\n\n/msg *status loadmod webadmin\n/msg *status loadmod admin\n/msg *status loadmod away\n/msg *status loadmod awaynick\n/msg *status loadmod clientnotify    # Notifies when another client logs\n/msg *status loadmod keepnick\n/msg *status loadmod kickrejoin\n```\n\n## Away\n\n```\n/msg *status loadmod away\n/msg *away away\n/msg *away back\n/msg *away show   #=> Show messages\n/msg *away delete all\n```\n\n## Watch\n\n```\n/msg *status loadmod watch\n/msg *watch list\n/msg *watch add * *watch *rico*\n/msg *watch add * *watch *%nick%*\n```"}

field_body:
## Start

```
/msg *status addserver irc.undernet.org [6667]
/msg *status connect

/msg *status loadmod webadmin
/msg *status loadmod admin
/msg *status loadmod away
/msg *status loadmod awaynick
/msg *status loadmod clientnotify    # Notifies when another client logs
/msg *status loadmod keepnick
/msg *status loadmod kickrejoin
```

## Away

```
/msg *status loadmod away
/msg *away away
/msg *away back
/msg *away show   #=> Show messages
/msg *away delete all
```

## Watch

```
/msg *status loadmod watch
/msg *watch list
/msg *watch add * *watch *rico*
/msg *watch add * *watch *%nick%*
```


id: yum
git_filename: ./yum.md
format: md
field_title: YUM
field_category: CLI
field_updated: 2024-02-07
field_updated___timezone: UTC
data:
{"title": "YUM", "category": "CLI", "updated": "2024-02-07", "body": "## Commands\n\n### Help and lists\n\n```bash\nyum help                     # Display yum commands and options\nyum list available           # List all available packages\nyum list installed           # List all installed packages\nyum list kernel              # List installed and available kernel packages\nyum info vsftpd              # List info about vsftpd package\n```\n\n### Searching and dependencies\n\n```bash\nyum deplist nfs-utils        # List dependencies for nfs-utils\nyum provides \"*bin/top\"      # Show package containing top command\nyum search samba             # Find packages with samba in name or description\n```\n\n### Updating and security\n\n```bash\nyum updateinfo security      # Get info on available security updates\nyum update --security        # Apply security-related package updates\n```\n\n### Managing repositories\n\n```bash\nyum repolist                     # Display enabled software repositories\nyum repoinfo rhel-7-server-rpms  # See info on specific repo\nyum repo-pkgs my-rpms list       # List packages from a specific repo\n```\n\n### Installation and upgrades\n\n```bash\nyum install vsftpd           # Install the vsftpd package\nyum update                   # Update all packages\nyum downgrade abc            # Downgrade the abc package to an earlier version\nyum autoremove httpd         # Remove httpd and unneeded packages\n```\n\n### Package groups\n\n```bash\nyum groupinstall \"Web server\"    # Install Web Server packages\n```\n\n### Troubleshooting\n\n```bash\nyum history list             # List all yum transactions\nyum clean packages           # Delete packages saved in cache\n```\n\n### Popular options\n\n```bash\n-y                           # Assume yes if prompted\n--disablerepo=epel           # Disable a specific repo for a command\n--downloadonly               # Download package to cache but don't install\n```"}

field_body:
## Commands

### Help and lists

```bash
yum help                     # Display yum commands and options
yum list available           # List all available packages
yum list installed           # List all installed packages
yum list kernel              # List installed and available kernel packages
yum info vsftpd              # List info about vsftpd package
```

### Searching and dependencies

```bash
yum deplist nfs-utils        # List dependencies for nfs-utils
yum provides "*bin/top"      # Show package containing top command
yum search samba             # Find packages with samba in name or description
```

### Updating and security

```bash
yum updateinfo security      # Get info on available security updates
yum update --security        # Apply security-related package updates
```

### Managing repositories

```bash
yum repolist                     # Display enabled software repositories
yum repoinfo rhel-7-server-rpms  # See info on specific repo
yum repo-pkgs my-rpms list       # List packages from a specific repo
```

### Installation and upgrades

```bash
yum install vsftpd           # Install the vsftpd package
yum update                   # Update all packages
yum downgrade abc            # Downgrade the abc package to an earlier version
yum autoremove httpd         # Remove httpd and unneeded packages
```

### Package groups

```bash
yum groupinstall "Web server"    # Install Web Server packages
```

### Troubleshooting

```bash
yum history list             # List all yum transactions
yum clean packages           # Delete packages saved in cache
```

### Popular options

```bash
-y                           # Assume yes if prompted
--disablerepo=epel           # Disable a specific repo for a command
--downloadonly               # Download package to cache but don't install
```


id: yarn
git_filename: ./yarn.md
format: md
field_title: Yarn
field_category: JavaScript libraries
field_tags: Featurable
field_prism_languages: json, bash
field_updated: 2019-09-30
field_updated___timezone: UTC
data:
{"title": "Yarn", "category": "JavaScript libraries", "weight": -3, "updated": "2019-09-30", "prism_languages": ["json", "bash"], "tags": ["Featurable"], "body": "### npm equivalents\n\n| npm | yarn |\n| --- | ---- |\n| `npm init` | `yarn init` |\n| `npm install` | `yarn` |\n| `npm install gulp --save` | `yarn add gulp` |\n| `npm install gulp --save-dev --save-exact` | `yarn add gulp --dev --exact` |\n| `npm install -g gulp` | `yarn global add gulp` |\n| `npm update` | `yarn upgrade` |\n| `./node_modules/.bin/gulp` | `yarn run gulp` |\n{: .-left-align.-headers}\n\n### yarn install\n\n```\n--no-lockfile\n--pure-lockfile\n--frozen-lockfile\n--silent\n--offline\n--update-checksums\n--check-files\n--flat\n--force\n--ignore-scripts\n--modules-folder <path>\n--production[=true|false]\n```\n\nThese options are available for `yarn install`.\n\n### yarn add\n\n```\n--dev\n--peer\n--optional\n--exact\n--tilde\n```\n\nThese options are available for `yarn add`.\n\n### Workspaces\n\nIn `package.json`:\n{: .-setup}\n\n```json\n\"workspaces\": [\n  \"packages/*\"\n]\n```\n\n```\njest/\n\u251c\u2500 package.json\n\u2514\u2500 packages/\n   \u251c\u2500 jest-matcher-utils/\n   \u2502  \u2514\u2500 package.json\n   \u2514\u2500 jest-diff/\n      \u2514\u2500 package.json\n```\n{: .-box-chars}\n\n(New in 1.0) Allows monorepos to share packages with each other. See: [Introducing workspaces](https://yarnpkg.com/blog/2017/08/02/introducing-workspaces/)\n\n### Selective version resolution\n\nIn `package.json`:\n{: .-setup}\n\n```json\n\"resolutions\": {\n  \"**/sass-brunch/node-sass\": \"4.5.2\"\n}\n```\n\n(New in 1.0) Allows you to specify versions for sub-dependencies. See: [Selective version resolutions](https://github.com/yarnpkg/yarn/pull/4105)\n\n### Create\n\n```bash\nyarn create react-app hello\n```\n\nInstall `create-react-app` and runs it. See: [yarn create](https://github.com/yarnpkg/rfcs/blob/master/implemented/0000-yarn-create.md)"}

field_body:
### npm equivalents

| npm | yarn |
| --- | ---- |
| `npm init` | `yarn init` |
| `npm install` | `yarn` |
| `npm install gulp --save` | `yarn add gulp` |
| `npm install gulp --save-dev --save-exact` | `yarn add gulp --dev --exact` |
| `npm install -g gulp` | `yarn global add gulp` |
| `npm update` | `yarn upgrade` |
| `./node_modules/.bin/gulp` | `yarn run gulp` |
{: .-left-align.-headers}

### yarn install

```
--no-lockfile
--pure-lockfile
--frozen-lockfile
--silent
--offline
--update-checksums
--check-files
--flat
--force
--ignore-scripts
--modules-folder <path>
--production[=true|false]
```

These options are available for `yarn install`.

### yarn add

```
--dev
--peer
--optional
--exact
--tilde
```

These options are available for `yarn add`.

### Workspaces

In `package.json`:
{: .-setup}

```json
"workspaces": [
  "packages/*"
]
```

```
jest/
├─ package.json
└─ packages/
   ├─ jest-matcher-utils/
   │  └─ package.json
   └─ jest-diff/
      └─ package.json
```
{: .-box-chars}

(New in 1.0) Allows monorepos to share packages with each other. See: [Introducing workspaces](https://yarnpkg.com/blog/2017/08/02/introducing-workspaces/)

### Selective version resolution

In `package.json`:
{: .-setup}

```json
"resolutions": {
  "**/sass-brunch/node-sass": "4.5.2"
}
```

(New in 1.0) Allows you to specify versions for sub-dependencies. See: [Selective version resolutions](https://github.com/yarnpkg/yarn/pull/4105)

### Create

```bash
yarn create react-app hello
```

Install `create-react-app` and runs it. See: [yarn create](https://github.com/yarnpkg/rfcs/blob/master/implemented/0000-yarn-create.md)


id: yargs
git_filename: ./yargs.md
format: md
field_title: Yargs
field_category: JavaScript libraries
data:
{"title": "Yargs", "category": "JavaScript libraries", "body": "### Basic usage\n\n```js\nvar argv = require('yargs').argv;\n\nargv._         // [ ... ]\nargv.$0        // \"node bin/mybin\"\nargv.verbose   // --verbose\n```\n\n### Help and version\n\n```js\nvar argv = require('yargs')\n\n  // version\n  .alias('v', 'version')\n  .version(function() { return require('../package').version; })\n  .describe('v', 'show version information')\n\n  // help text\n  .alias('h', 'help')\n  .help('help')\n  .usage('Usage: $0 -x [num]')\n  .showHelpOnFail(false, \"Specify --help for available options\")\n```\n\n### Options\n\n```js\n  .option('f', {\n      alias : 'file',\n      describe: 'x marks the spot',\n      type: 'string', /* array | boolean | string */\n      nargs: 1,\n      demand: true,\n      demand: 'file is required',\n      default: '/etc/passwd'\n      // also: count:true, requiresArg:true\n  })\n\n  .options({\n    f: { ... }\n  })\n```\n\n### Examples and more help stuff\n\n```js\n  // more help\n  .example('...')\n  .epilog('copyright 2015')\n  .command('start', 'start a server')\n```\n\n### Stacking\n\n```js\n  .count('verbose')\n\nargv.verbose // -vvv => 3\n```\n\n### Reject non explicits\n\n```js\n  .strict()\n```\n\n### Methods\n\n```\nyargs.showHelp()\nyargs.help() //=>string\n```"}

field_body:
### Basic usage

```js
var argv = require('yargs').argv;

argv._         // [ ... ]
argv.$0        // "node bin/mybin"
argv.verbose   // --verbose
```

### Help and version

```js
var argv = require('yargs')

  // version
  .alias('v', 'version')
  .version(function() { return require('../package').version; })
  .describe('v', 'show version information')

  // help text
  .alias('h', 'help')
  .help('help')
  .usage('Usage: $0 -x [num]')
  .showHelpOnFail(false, "Specify --help for available options")
```

### Options

```js
  .option('f', {
      alias : 'file',
      describe: 'x marks the spot',
      type: 'string', /* array | boolean | string */
      nargs: 1,
      demand: true,
      demand: 'file is required',
      default: '/etc/passwd'
      // also: count:true, requiresArg:true
  })

  .options({
    f: { ... }
  })
```

### Examples and more help stuff

```js
  // more help
  .example('...')
  .epilog('copyright 2015')
  .command('start', 'start a server')
```

### Stacking

```js
  .count('verbose')

argv.verbose // -vvv => 3
```

### Reject non explicits

```js
  .strict()
```

### Methods

```
yargs.showHelp()
yargs.help() //=>string
```


id: yaml
git_filename: ./yaml.md
format: md
field_title: Yaml
field_category: Markup
field_prism_languages: yaml
data:
{"title": "Yaml", "category": "Markup", "prism_languages": ["yaml"], "body": "### Dictionaries and lists\n\n```yaml\n# comments start with \"#\"\n# dictionary are written like \"key: value\"\nname: Martin D'vloper\nlanguages:\n  perl: Elite\n  python: Elite\n  pascal: Lame\n\n# list items beginn with a \"- \"\nfoods:\n  - Apple\n  - Orange\n  - Strawberry\n  - Mango\n\n# booleans are lower case\nemployed: true\n```\n\n\n### Multiline strings\n\n```yaml\n# Literal Block Scalar\nMultiline: |\n  exactly as you see\n  will appear these three\n  lines of poetry\n```\n\n```yaml\n# Folded Block Scalar\nMultiline: <\n  this is really a\n  single line of text\n  despite appearances\n```\n\n### Inheritance\n\n```yaml\nparent: &defaults\n  a: 2\n  b: 3\n\nchild:\n  <<: *defaults\n  b: 4\n```\n\n### Reference content\n\n```yaml\nvalues: &ref\n  - These values\n  - will be reused below\n  \nother_values:\n  <<: *ref\n```"}

field_body:
### Dictionaries and lists

```yaml
# comments start with "#"
# dictionary are written like "key: value"
name: Martin D'vloper
languages:
  perl: Elite
  python: Elite
  pascal: Lame

# list items beginn with a "- "
foods:
  - Apple
  - Orange
  - Strawberry
  - Mango

# booleans are lower case
employed: true
```


### Multiline strings

```yaml
# Literal Block Scalar
Multiline: |
  exactly as you see
  will appear these three
  lines of poetry
```

```yaml
# Folded Block Scalar
Multiline: <
  this is really a
  single line of text
  despite appearances
```

### Inheritance

```yaml
parent: &defaults
  a: 2
  b: 3

child:
  <<: *defaults
  b: 4
```

### Reference content

```yaml
values: &ref
  - These values
  - will be reused below
  
other_values:
  <<: *ref
```


id: xpath
git_filename: ./xpath.md
format: md
field_title: Xpath
field_category: HTML
field_tags: Featured
data:
{"title": "Xpath", "category": "HTML", "tags": ["Featured"], "weight": -5, "description": "$x('//div//p//*') == $('div p *'), $x('//[@id=\"item\"]') == $('#item'), and many other Xpath examples.\n", "body": "## Testing\n\n### Xpath test bed\n{: .-intro}\n\nTest queries in the Xpath test bed:\n\n- [Xpath test bed](http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm) _(whitebeam.org)_\n\n### Browser console\n\n```js\n$x(\"//div\")\n```\n\nWorks in Firefox and Chromium browsers.\n\n## Selectors\n\n### Descendant selectors\n\n| CSS                          | Xpath                                                    | ?                       |\n| ----                         | ----                                                     | --                      |\n| `h1`                         | `//h1`                                                   | [?](#prefixes)          |\n| `div p`                      | `//div//p`                                               | [?](#axes)              |\n| `ul > li`                    | `//ul/li`                                                | [?](#axes)              |\n| `ul > li > a`                | `//ul/li/a`                                              |                         |\n| `div > *`                    | `//div/*`                                                |                         |\n| ----                         | ----                                                     | --                      |\n| `:root`                      | `/`                                                      | [?](#prefixes)          |\n| `:root > body`               | `/body`                                                  |                         |\n{: .xp}\n\n### Attribute selectors\n\n| CSS                          | Xpath                                                    | ?                       |\n| ----                         | ----                                                     | --                      |\n| `#id`                        | `//*[@id=\"id\"]`                                           | [?](#predicates)        |\n| `.class`                     | `//*[@class=\"class\"]` *...[kinda](#class-check)*          |                         |\n| `input[type=\"submit\"]`       | `//input[@type=\"submit\"]`                                |                         |\n| `a#abc[for=\"xyz\"]`           | `//a[@id=\"abc\"][@for=\"xyz\"]`                             | [?](#chaining-order)    |\n| `a[rel]`                     | `//a[@rel]`                                              |                         |\n| ----                         | ----                                                     | --                      |\n| `a[href^='/']`               | `//a[starts-with(@href, '/')]`                           | [?](#string-functions)  |\n| `a[href$='pdf']`             | `//a[ends-with(@href, '.pdf')]`                          |                         |\n| `a[href*='://']`             | `//a[contains(@href, '://')]`                            |                         |\n| `a[rel~='help']`             | `//a[contains(@rel, 'help')]` *...[kinda](#class-check)* |                         |\n{: .xp}\n\n### Order selectors\n\n| CSS                          | Xpath                                                    | ?                       |\n| ----                         | ----                                                     | --                      |\n| `ul > li:first-of-type`      | `//ul/li[1]`                                             | [?](#indexing)          |\n| `ul > li:nth-of-type(2)`     | `//ul/li[2]`                                             |                         |\n| `ul > li:last-of-type`       | `//ul/li[last()]`                                        |                         |\n| `li#id:first-of-type`        | `//li[1][@id=\"id\"]`                                      | [?](#chaining-order)    |\n| `a:first-child`              | `//*[1][name()=\"a\"]`                                     |                         |\n| `a:last-child`               | `//*[last()][name()=\"a\"]`                                |                         |\n{: .xp}\n\n### Siblings\n\n| CSS                          | Xpath                                                    | ?                       |\n| ----                         | ----                                                     | --                      |\n| `h1 ~ ul`                    | `//h1/following-sibling::ul`                             | [?](#using-axes)        |\n| `h1 + ul`                    | `//h1/following-sibling::ul[1]`                          |                         |\n| `h1 ~ #id`                   | `//h1/following-sibling::[@id=\"id\"]`                     |                         |\n{: .xp}\n\n### jQuery\n\n| CSS                          | Xpath                                                    | ?                       |\n| ----                         | ----                                                     | --                      |\n| `$('ul > li').parent()`      | `//ul/li/..`                                             | [?](#other-axes)        |\n| `$('li').closest('section')` | `//li/ancestor-or-self::section`                         |                         |\n| `$('a').attr('href')`        | `//a/@href`                                              | [?](#steps)             |\n| `$('span').text()`           | `//span/text()`                                          |                         |\n{: .xp}\n\n### Other things\n\n| CSS                          | Xpath                                                    | ?                       |\n| ----                         | ----                                                     | --                      |\n| `h1:not([id])`               | `//h1[not(@id)]`                                         | [?](#boolean-functions) |\n| Text match                   | `//button[text()=\"Submit\"]`                              | [?](#operators)         |\n| Text match (substring)       | `//button[contains(text(),\"Go\")]`                        |                         |\n| Arithmetic                   | `//product[@price > 2.50]`                               |                         |\n| Has children                 | `//ul[*]`                                                |                         |\n| Has children (specific)      | `//ul[li]`                                               |                         |\n| Or logic                     | `//a[@name or @href]`                                    | [?](#operators)         |\n| Union (joins results)        | `//a | //div`                                            | [?](#unions)            |\n{: .xp}\n\n<style>\n/* ensure tables align */\ntable.xp {table-layout: fixed;}\ntable.xp tr>:nth-child(1) {width: 35%;}\ntable.xp tr>:nth-child(2) {width: auto;}\ntable.xp tr>:nth-child(3) {width: 10%; text-align:right;}\n</style>\n\n### Class check\n\n```bash\n//div[contains(concat(' ',normalize-space(@class),' '),' foobar ')]\n```\n\nXpath doesn't have the \"check if part of space-separated list\" operator, so this is the workaround ([source](http://pivotallabs.com/xpath-css-class-matching/)).\n\nExpressions\n-----------\n\n### Steps and axes\n\n| `//` | `ul` | `/`  | `a[@id='link']` |\n| Axis | Step | Axis | Step            |\n{: .-css-breakdown}\n\n### Prefixes\n\n| Prefix | Example               | What     |\n| ---    | ---                   | ---      |\n| `//`   | `//hr[@class='edge']` | Anywhere |\n| `./`   | `./a`                 | Relative |\n| `/`    | `/html/body/div`      | Root     |\n{: .-headers}\n\nBegin your expression with any of these.\n\n### Axes\n\n| Axis | Example             | What       |\n| ---  | ---                 | ---        |\n| `/`  | `//ul/li/a`         | Child      |\n| `//` | `//[@id=\"list\"]//a` | Descendant |\n{: .-headers}\n\nSeparate your steps with `/`. Use two (`//`) if you don't want to select direct children.\n\n### Steps\n\n```bash\n//div\n//div[@name='box']\n//[@id='link']\n```\n\nA step may have an element name (`div`) and [predicates](#predicate) (`[...]`). Both are optional.\nThey can also be these other things:\n\n```bash\n//a/text()     #=> \"Go home\"\n//a/@href      #=> \"index.html\"\n//a/*          #=> All a's child elements\n```\n\nPredicates\n----------\n\n### Predicates\n\n```bash\n//div[true()]\n//div[@class=\"head\"]\n//div[@class=\"head\"][@id=\"top\"]\n```\n\nRestricts a nodeset only if some condition is true. They can be chained.\n\n### Operators\n\n```bash\n# Comparison\n//a[@id = \"xyz\"]\n//a[@id != \"xyz\"]\n//a[@price > 25]\n```\n\n```bash\n# Logic (and/or)\n//div[@id=\"head\" and position()=2]\n//div[(x and y) or not(z)]\n```\n\nUse comparison and logic operators to make conditionals.\n\n### Using nodes\n\n```bash\n# Use them inside functions\n//ul[count(li) > 2]\n//ul[count(li[@class='hide']) > 0]\n```\n\n```bash\n# This returns `<ul>` that has a `<li>` child\n//ul[li]\n```\n\nYou can use nodes inside predicates.\n\n### Indexing\n\n```bash\n//a[1]                  # first <a>\n//a[last()]             # last <a>\n//ol/li[2]              # second <li>\n//ol/li[position()=2]   # same as above\n//ol/li[position()>1]   # :not(:first-of-type)\n```\n\nUse `[]` with a number, or `last()` or `position()`.\n\n### Chaining order\n\n```bash\na[1][@href='/']\na[@href='/'][1]\n```\n\nOrder is significant, these two are different.\n\n### Nesting predicates\n\n```\n//section[.//h1[@id='hi']]\n```\n\nThis returns `<section>` if it has an `<h1>` descendant with `id='hi'`.\n\nFunctions\n---------\n\n### Node functions\n\n```bash\nname()                     # //[starts-with(name(), 'h')]\ntext()                     # //button[text()=\"Submit\"]\n                           # //button/text()\nlang(str)\nnamespace-uri()\n```\n\n```bash\ncount()                    # //table[count(tr)=1]\nposition()                 # //ol/li[position()=2]\n```\n\n### Boolean functions\n\n```bash\nnot(expr)                  # button[not(starts-with(text(),\"Submit\"))]\n```\n\n### String functions\n\n```bash\ncontains()                 # font[contains(@class,\"head\")]\nstarts-with()              # font[starts-with(@class,\"head\")]\nends-with()                # font[ends-with(@class,\"head\")]\n```\n\n```bash\nconcat(x,y)\nsubstring(str, start, len)\nsubstring-before(\"01/02\", \"/\")  #=> 01\nsubstring-after(\"01/02\", \"/\")   #=> 02\ntranslate()\nnormalize-space()\nstring-length()\n```\n\n### Type conversion\n\n```bash\nstring()\nnumber()\nboolean()\n```\n\nAxes\n----\n\n### Using axes\n\n```bash\n//ul/li                       # ul > li\n//ul/child::li                # ul > li (same)\n//ul/following-sibling::li    # ul ~ li\n//ul/descendant-or-self::li   # ul li\n//ul/ancestor-or-self::li     # $('ul').closest('li')\n```\n\nSteps of an expression are separated by `/`, usually used to pick child nodes. That's not always true: you can specify a different \"axis\" with `::`.\n\n| `//` | `ul` | `/child::` | `li` |\n| Axis | Step | Axis       | Step |\n{: .-css-breakdown}\n\n### Child axis\n\n```bash\n# both the same\n//ul/li/a\n//child::ul/child::li/child::a\n```\n\n`child::` is the default axis. This makes `//a/b/c` work.\n\n```bash\n# both the same\n# this works because `child::li` is truthy, so the predicate succeeds\n//ul[li]\n//ul[child::li]\n```\n\n```bash\n# both the same\n//ul[count(li) > 2]\n//ul[count(child::li) > 2]\n```\n\n### Descendant-or-self axis\n\n```bash\n# both the same\n//div//h4\n//div/descendant-or-self::h4\n```\n\n`//` is short for the `descendant-or-self::` axis.\n\n```bash\n# both the same\n//ul//[last()]\n//ul/descendant-or-self::[last()]\n```\n\n### Other axes\n\n| Axis                 | Abbrev | Notes                                            |\n| ---                  | ---    | ---                                              |\n| `ancestor`           |        |                                                  |\n| `ancestor-or-self`   |        |                                                  |\n| ---                  | ---    | ---                                              |\n| `attribute`          | `@`    | `@href` is short for `attribute::href`           |\n| `child`              |        | `div` is short for `child::div`                  |\n| `descendant`         |        |                                                  |\n| `descendant-or-self` | `//`   | `//` is short for `/descendant-or-self::node()/` |\n| `namespace`          |        |                                                  |\n| ---                  | ---    | ---                                              |\n| `self`               | `.`    | `.` is short for `self::node()`                  |\n| `parent`             | `..`   | `..` is short for `parent::node()`               |\n| ---                  | ---    | ---                                              |\n| `following`          |        |                                                  |\n| `following-sibling`  |        |                                                  |\n| `preceding`          |        |                                                  |\n| `preceding-sibling`  |        |                                                  |\n{: .-headers}\n\nThere are other axes you can use.\n\n### Unions\n\n```bash\n//a | //span\n```\n\nUse `|` to join two expressions.\n\nMore examples\n-------------\n\n### Examples\n\n```bash\n//*                 # all elements\ncount(//*)          # count all elements\n(//h1)[1]/text()    # text of the first h1 heading\n//li[span]          # find a <li> with an <span> inside it\n                    # ...expands to //li[child::span]\n//ul/li/..          # use .. to select a parent\n```\n\n### Find a parent\n\n```bash\n//section[h1[@id='section-name']]\n```\nFinds a `<section>` that directly contains `h1#section-name`\n\n```bash\n//section[//h1[@id='section-name']]\n```\n\nFinds a `<section>` that contains `h1#section-name`.\n(Same as above, but uses descendant-or-self instead of child)\n\n### Closest\n\n```bash\n./ancestor-or-self::[@class=\"box\"]\n```\n\nWorks like jQuery's `$().closest('.box')`.\n\n### Attributes\n\n```bash\n//item[@price > 2*@discount]\n```\n\nFinds `<item>` and check its attributes\n\nReferences\n----------\n{: .-one-column}\n\n* [Xpath test bed](http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm) _(whitebeam.org)_"}

field_body:
## Testing

### Xpath test bed
{: .-intro}

Test queries in the Xpath test bed:

- [Xpath test bed](http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm) _(whitebeam.org)_

### Browser console

```js
$x("//div")
```

Works in Firefox and Chromium browsers.

## Selectors

### Descendant selectors

| CSS                          | Xpath                                                    | ?                       |
| ----                         | ----                                                     | --                      |
| `h1`                         | `//h1`                                                   | [?](#prefixes)          |
| `div p`                      | `//div//p`                                               | [?](#axes)              |
| `ul > li`                    | `//ul/li`                                                | [?](#axes)              |
| `ul > li > a`                | `//ul/li/a`                                              |                         |
| `div > *`                    | `//div/*`                                                |                         |
| ----                         | ----                                                     | --                      |
| `:root`                      | `/`                                                      | [?](#prefixes)          |
| `:root > body`               | `/body`                                                  |                         |
{: .xp}

### Attribute selectors

| CSS                          | Xpath                                                    | ?                       |
| ----                         | ----                                                     | --                      |
| `#id`                        | `//*[@id="id"]`                                           | [?](#predicates)        |
| `.class`                     | `//*[@class="class"]` *...[kinda](#class-check)*          |                         |
| `input[type="submit"]`       | `//input[@type="submit"]`                                |                         |
| `a#abc[for="xyz"]`           | `//a[@id="abc"][@for="xyz"]`                             | [?](#chaining-order)    |
| `a[rel]`                     | `//a[@rel]`                                              |                         |
| ----                         | ----                                                     | --                      |
| `a[href^='/']`               | `//a[starts-with(@href, '/')]`                           | [?](#string-functions)  |
| `a[href$='pdf']`             | `//a[ends-with(@href, '.pdf')]`                          |                         |
| `a[href*='://']`             | `//a[contains(@href, '://')]`                            |                         |
| `a[rel~='help']`             | `//a[contains(@rel, 'help')]` *...[kinda](#class-check)* |                         |
{: .xp}

### Order selectors

| CSS                          | Xpath                                                    | ?                       |
| ----                         | ----                                                     | --                      |
| `ul > li:first-of-type`      | `//ul/li[1]`                                             | [?](#indexing)          |
| `ul > li:nth-of-type(2)`     | `//ul/li[2]`                                             |                         |
| `ul > li:last-of-type`       | `//ul/li[last()]`                                        |                         |
| `li#id:first-of-type`        | `//li[1][@id="id"]`                                      | [?](#chaining-order)    |
| `a:first-child`              | `//*[1][name()="a"]`                                     |                         |
| `a:last-child`               | `//*[last()][name()="a"]`                                |                         |
{: .xp}

### Siblings

| CSS                          | Xpath                                                    | ?                       |
| ----                         | ----                                                     | --                      |
| `h1 ~ ul`                    | `//h1/following-sibling::ul`                             | [?](#using-axes)        |
| `h1 + ul`                    | `//h1/following-sibling::ul[1]`                          |                         |
| `h1 ~ #id`                   | `//h1/following-sibling::[@id="id"]`                     |                         |
{: .xp}

### jQuery

| CSS                          | Xpath                                                    | ?                       |
| ----                         | ----                                                     | --                      |
| `$('ul > li').parent()`      | `//ul/li/..`                                             | [?](#other-axes)        |
| `$('li').closest('section')` | `//li/ancestor-or-self::section`                         |                         |
| `$('a').attr('href')`        | `//a/@href`                                              | [?](#steps)             |
| `$('span').text()`           | `//span/text()`                                          |                         |
{: .xp}

### Other things

| CSS                          | Xpath                                                    | ?                       |
| ----                         | ----                                                     | --                      |
| `h1:not([id])`               | `//h1[not(@id)]`                                         | [?](#boolean-functions) |
| Text match                   | `//button[text()="Submit"]`                              | [?](#operators)         |
| Text match (substring)       | `//button[contains(text(),"Go")]`                        |                         |
| Arithmetic                   | `//product[@price > 2.50]`                               |                         |
| Has children                 | `//ul[*]`                                                |                         |
| Has children (specific)      | `//ul[li]`                                               |                         |
| Or logic                     | `//a[@name or @href]`                                    | [?](#operators)         |
| Union (joins results)        | `//a | //div`                                            | [?](#unions)            |
{: .xp}

<style>
/* ensure tables align */
table.xp {table-layout: fixed;}
table.xp tr>:nth-child(1) {width: 35%;}
table.xp tr>:nth-child(2) {width: auto;}
table.xp tr>:nth-child(3) {width: 10%; text-align:right;}
</style>

### Class check

```bash
//div[contains(concat(' ',normalize-space(@class),' '),' foobar ')]
```

Xpath doesn't have the "check if part of space-separated list" operator, so this is the workaround ([source](http://pivotallabs.com/xpath-css-class-matching/)).

Expressions
-----------

### Steps and axes

| `//` | `ul` | `/`  | `a[@id='link']` |
| Axis | Step | Axis | Step            |
{: .-css-breakdown}

### Prefixes

| Prefix | Example               | What     |
| ---    | ---                   | ---      |
| `//`   | `//hr[@class='edge']` | Anywhere |
| `./`   | `./a`                 | Relative |
| `/`    | `/html/body/div`      | Root     |
{: .-headers}

Begin your expression with any of these.

### Axes

| Axis | Example             | What       |
| ---  | ---                 | ---        |
| `/`  | `//ul/li/a`         | Child      |
| `//` | `//[@id="list"]//a` | Descendant |
{: .-headers}

Separate your steps with `/`. Use two (`//`) if you don't want to select direct children.

### Steps

```bash
//div
//div[@name='box']
//[@id='link']
```

A step may have an element name (`div`) and [predicates](#predicate) (`[...]`). Both are optional.
They can also be these other things:

```bash
//a/text()     #=> "Go home"
//a/@href      #=> "index.html"
//a/*          #=> All a's child elements
```

Predicates
----------

### Predicates

```bash
//div[true()]
//div[@class="head"]
//div[@class="head"][@id="top"]
```

Restricts a nodeset only if some condition is true. They can be chained.

### Operators

```bash
# Comparison
//a[@id = "xyz"]
//a[@id != "xyz"]
//a[@price > 25]
```

```bash
# Logic (and/or)
//div[@id="head" and position()=2]
//div[(x and y) or not(z)]
```

Use comparison and logic operators to make conditionals.

### Using nodes

```bash
# Use them inside functions
//ul[count(li) > 2]
//ul[count(li[@class='hide']) > 0]
```

```bash
# This returns `<ul>` that has a `<li>` child
//ul[li]
```

You can use nodes inside predicates.

### Indexing

```bash
//a[1]                  # first <a>
//a[last()]             # last <a>
//ol/li[2]              # second <li>
//ol/li[position()=2]   # same as above
//ol/li[position()>1]   # :not(:first-of-type)
```

Use `[]` with a number, or `last()` or `position()`.

### Chaining order

```bash
a[1][@href='/']
a[@href='/'][1]
```

Order is significant, these two are different.

### Nesting predicates

```
//section[.//h1[@id='hi']]
```

This returns `<section>` if it has an `<h1>` descendant with `id='hi'`.

Functions
---------

### Node functions

```bash
name()                     # //[starts-with(name(), 'h')]
text()                     # //button[text()="Submit"]
                           # //button/text()
lang(str)
namespace-uri()
```

```bash
count()                    # //table[count(tr)=1]
position()                 # //ol/li[position()=2]
```

### Boolean functions

```bash
not(expr)                  # button[not(starts-with(text(),"Submit"))]
```

### String functions

```bash
contains()                 # font[contains(@class,"head")]
starts-with()              # font[starts-with(@class,"head")]
ends-with()                # font[ends-with(@class,"head")]
```

```bash
concat(x,y)
substring(str, start, len)
substring-before("01/02", "/")  #=> 01
substring-after("01/02", "/")   #=> 02
translate()
normalize-space()
string-length()
```

### Type conversion

```bash
string()
number()
boolean()
```

Axes
----

### Using axes

```bash
//ul/li                       # ul > li
//ul/child::li                # ul > li (same)
//ul/following-sibling::li    # ul ~ li
//ul/descendant-or-self::li   # ul li
//ul/ancestor-or-self::li     # $('ul').closest('li')
```

Steps of an expression are separated by `/`, usually used to pick child nodes. That's not always true: you can specify a different "axis" with `::`.

| `//` | `ul` | `/child::` | `li` |
| Axis | Step | Axis       | Step |
{: .-css-breakdown}

### Child axis

```bash
# both the same
//ul/li/a
//child::ul/child::li/child::a
```

`child::` is the default axis. This makes `//a/b/c` work.

```bash
# both the same
# this works because `child::li` is truthy, so the predicate succeeds
//ul[li]
//ul[child::li]
```

```bash
# both the same
//ul[count(li) > 2]
//ul[count(child::li) > 2]
```

### Descendant-or-self axis

```bash
# both the same
//div//h4
//div/descendant-or-self::h4
```

`//` is short for the `descendant-or-self::` axis.

```bash
# both the same
//ul//[last()]
//ul/descendant-or-self::[last()]
```

### Other axes

| Axis                 | Abbrev | Notes                                            |
| ---                  | ---    | ---                                              |
| `ancestor`           |        |                                                  |
| `ancestor-or-self`   |        |                                                  |
| ---                  | ---    | ---                                              |
| `attribute`          | `@`    | `@href` is short for `attribute::href`           |
| `child`              |        | `div` is short for `child::div`                  |
| `descendant`         |        |                                                  |
| `descendant-or-self` | `//`   | `//` is short for `/descendant-or-self::node()/` |
| `namespace`          |        |                                                  |
| ---                  | ---    | ---                                              |
| `self`               | `.`    | `.` is short for `self::node()`                  |
| `parent`             | `..`   | `..` is short for `parent::node()`               |
| ---                  | ---    | ---                                              |
| `following`          |        |                                                  |
| `following-sibling`  |        |                                                  |
| `preceding`          |        |                                                  |
| `preceding-sibling`  |        |                                                  |
{: .-headers}

There are other axes you can use.

### Unions

```bash
//a | //span
```

Use `|` to join two expressions.

More examples
-------------

### Examples

```bash
//*                 # all elements
count(//*)          # count all elements
(//h1)[1]/text()    # text of the first h1 heading
//li[span]          # find a <li> with an <span> inside it
                    # ...expands to //li[child::span]
//ul/li/..          # use .. to select a parent
```

### Find a parent

```bash
//section[h1[@id='section-name']]
```
Finds a `<section>` that directly contains `h1#section-name`

```bash
//section[//h1[@id='section-name']]
```

Finds a `<section>` that contains `h1#section-name`.
(Same as above, but uses descendant-or-self instead of child)

### Closest

```bash
./ancestor-or-self::[@class="box"]
```

Works like jQuery's `$().closest('.box')`.

### Attributes

```bash
//item[@price > 2*@discount]
```

Finds `<item>` and check its attributes

References
----------
{: .-one-column}

* [Xpath test bed](http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm) _(whitebeam.org)_


id: weinre
git_filename: ./weinre.md
format: md
field_title: Weinre
field_category: JavaScript libraries
field_tags: Archived
data:
{"title": "Weinre", "category": "JavaScript libraries", "tags": ["Archived"], "intro": "[weinre](https://www.npmjs.com/package/weinre) is a remote Web inspector. Note that it has been deprecated since 2016.\n", "archived": "Weinre has been deprecated since 2016.", "body": "### Usage\n\n#### Install:\n\n```\n$ npm install -g weinre\n```\n\n#### Start the server:\n\n```\n$ weinre --boundHost 0.0.0.0\n$ open http://localhost:8080\n```\n\n### HTML to inject\n\n<!--prettier-ignore -->\n```html\n<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.async=1;js.src='http://'+location.hostname+':8080/target/target-script-min.js#anonymous';fjs.parentNode.insertBefore(js,fjs);}}(document,'script','weinre');</script>\n```\n\n### References\n\n- [Weinre](http://people.apache.org/~pmuellr/weinre/)"}

field_intro:
[weinre](https://www.npmjs.com/package/weinre) is a remote Web inspector. Note that it has been deprecated since 2016.

field_body:
### Usage

#### Install:

```
$ npm install -g weinre
```

#### Start the server:

```
$ weinre --boundHost 0.0.0.0
$ open http://localhost:8080
```

### HTML to inject

<!--prettier-ignore -->
```html
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.async=1;js.src='http://'+location.hostname+':8080/target/target-script-min.js#anonymous';fjs.parentNode.insertBefore(js,fjs);}}(document,'script','weinre');</script>
```

### References

- [Weinre](http://people.apache.org/~pmuellr/weinre/)


id: weechat
git_filename: ./weechat.md
format: md
field_title: Weechat
field_category: Apps
data:
{"title": "Weechat", "category": "Apps", "body": "## Keys\n{: .-three-column}\n\n### Buffers\n\n| Shortcut         | Description                      |\n| ---              | ---                              |\n| `^s` / `^u`      | Set unread marker on all windows |\n| ---              | ---                              |\n| `^p, A-left`     | Switch buffer left               |\n| `^n, A-right`    | Switch buffer right              |\n| `A-a`            | Next buffer with activity        |\n| `A-0...9`        | Switch buffers                   |\n| ---              | ---                              |\n| `F9` /` F10`     | Scroll buffer title              |\n| `F11` / `F12`    | Scroll nick list                 |\n| ---              | ---                              |\n| `A-w A-Left`     | Switch windows                   |\n| `A-w A-b`        | Balance windows                  |\n{: .-shortcuts}\n\n(`A-` is alt.)\n\n### Window commands\n\n| Shortcut         | Description                      |\n| ---              | ---                              |\n| `/window splith` | Split horizontal                 |\n| `/window splitv` | Split vertical                   |\n| `/window zoom`   | Zoom                             |\n\n### Search\n\n| `^r`              | Search      |\n| `Enter` `^j` `^m` | Stop search |\n{: .-shortcuts}"}

field_body:
## Keys
{: .-three-column}

### Buffers

| Shortcut         | Description                      |
| ---              | ---                              |
| `^s` / `^u`      | Set unread marker on all windows |
| ---              | ---                              |
| `^p, A-left`     | Switch buffer left               |
| `^n, A-right`    | Switch buffer right              |
| `A-a`            | Next buffer with activity        |
| `A-0...9`        | Switch buffers                   |
| ---              | ---                              |
| `F9` /` F10`     | Scroll buffer title              |
| `F11` / `F12`    | Scroll nick list                 |
| ---              | ---                              |
| `A-w A-Left`     | Switch windows                   |
| `A-w A-b`        | Balance windows                  |
{: .-shortcuts}

(`A-` is alt.)

### Window commands

| Shortcut         | Description                      |
| ---              | ---                              |
| `/window splith` | Split horizontal                 |
| `/window splitv` | Split vertical                   |
| `/window zoom`   | Zoom                             |

### Search

| `^r`              | Search      |
| `Enter` `^j` `^m` | Stop search |
{: .-shortcuts}


id: webpack
git_filename: ./webpack.md
format: md
field_title: Webpack
field_category: JavaScript libraries
field_updated: 2017-09-26
field_updated___timezone: UTC
data:
{"title": "Webpack", "category": "JavaScript libraries", "updated": "2017-09-26", "intro": "This is a very basic \"getting started with Webpack\" guide for use with [Webpack](https://webpack.js.org) v3. This doesn't cover all features, but it should get you started in understanding the config file format.\n", "body": "### Basic config\n\n#### webpack.config.js\n\n```js\nmodule.exports = {\n  context: __dirname,\n  entry: 'src/app.js',\n  output: {\n    path: __dirname + '/public',\n    filename: 'app.js'\n  }\n}\n```\n\n#### Terminal\n\n```bash\nnpm install --save-dev webpack\n```\n\n| `webpack` | build\n| `webpack -- -p` | build production\n| `webpack -- --watch` | compile continuously\n\nThis compiles `src/app.js` into `public/app.js`. (Note: you may need to use `./node_modules/.bin/webpack` as a command if you're not invoking Webpack via npm scripts.)\n\n### Multiple files\n\n#### webpack.config.js\n\n```js\nmodule.exports = {\n  entry: {\n    app: 'src/app.js',\n    vendor: 'src/vendor.js'\n  },\n  output: {\n    path: __dirname + '/public',\n    filename: '[name].js'\n  }\n}\n```\n{: data-line=\"2,3,4,8\"}\n\nThis creates `app.js` and `vendor.js`.\n\n## Loaders\n\n### Babel\n\n#### Terminal\n\n```bash\nnpm install --save-dev \\\n  babel-loader \\\n  babel-preset-env \\\n  babel-preset-react\n```\n\n#### webpack.config.js\n\n```js\nmodule.exports = {\n  \u00b7\u00b7\u00b7\n  module: {\n    rules: [\n      { test: /\\.js$/,\n        exclude: /node_modules/,\n        use: [\n          { loader: 'babel-loader' }\n        ]\n      }\n    ]\n  }\n}\n```\n{: data-line=\"3,4,5,6,7,8\"}\n\n#### .babelrc\n\n```js\n{\n  \"presets\": [ \"env\", \"react\" ]\n}\n```\n\nAdds support for [Babel](http://babeljs.io).\n\n### CSS\n\n#### Terminal\n\n```bash\nnpm install --save-dev \\\n  css-loader \\\n  style-loader\n```\n\n#### webpack.config.js\n\n```js\nmodule.exports = {\n  \u00b7\u00b7\u00b7\n  module: {\n    rules: [\n     { test: /\\.css$/,\n       exclude: /node_modules/,\n       use: [\n         { loader: 'style-loader' },\n         { loader: 'css-loader' }\n       ]\n      }\n    ]\n  }\n}\n```\n{: data-line=\"3,4,5,6,7,8,9\"}\n\n#### Your JavaScript\n\n```js\nimport './styles.css'\n// or:\nrequire('./styles.css')\n```\n\nThis allows you to use CSS inside your JavaScript. This packages your CSS inside your JavaScript bundle.\n\n### PostCSS\n\n#### Terminal\n\n```\nnpm install --save-dev \\\n  postcss-loader \\\n  postcss-cssnext\n```\n\n#### webpack.config.js\n\n```js\n\u00b7\u00b7\u00b7\n// Inside module.rules[]:\n{ test: /\\.css$/,\n  exclude: /node_modules/,\n  use: [\n    { loader: 'style-loader' },\n    { loader: 'css-loader' },\n    { loader: 'postcss-loader' }\n\u00b7\u00b7\u00b7\n```\n{: data-line=\"8\"}\n\n#### postcss.config.js\n\n```js\nmodule.exports = {\n  plugins: [\n    require('postcss-cssnext')()\n  ]\n}\n```\n{: data-line=\"3\"}\n\nThis example adds [postcss-cssnext](https://www.npmjs.com/package/postcss-cssnext) support to your CSS files.\n\n## Other features\n\n### Dev server\n\n#### package.json\n\n```json\n{ \u00b7\u00b7\u00b7\n  \"scripts\": {\n    \"dev\": \"webpack-dev-server\"\n  }\n}\n```\n{: data-line=\"3\"}\n\n#### Terminal\n\n```bash\nnpm install --save-dev \\\n  webpack-dev-server\n```\n\n```bash\nnpm run dev\n```\n\nThis starts an HTTP server for development (port 8080 by default)."}

field_intro:
This is a very basic "getting started with Webpack" guide for use with [Webpack](https://webpack.js.org) v3. This doesn't cover all features, but it should get you started in understanding the config file format.

field_body:
### Basic config

#### webpack.config.js

```js
module.exports = {
  context: __dirname,
  entry: 'src/app.js',
  output: {
    path: __dirname + '/public',
    filename: 'app.js'
  }
}
```

#### Terminal

```bash
npm install --save-dev webpack
```

| `webpack` | build
| `webpack -- -p` | build production
| `webpack -- --watch` | compile continuously

This compiles `src/app.js` into `public/app.js`. (Note: you may need to use `./node_modules/.bin/webpack` as a command if you're not invoking Webpack via npm scripts.)

### Multiple files

#### webpack.config.js

```js
module.exports = {
  entry: {
    app: 'src/app.js',
    vendor: 'src/vendor.js'
  },
  output: {
    path: __dirname + '/public',
    filename: '[name].js'
  }
}
```
{: data-line="2,3,4,8"}

This creates `app.js` and `vendor.js`.

## Loaders

### Babel

#### Terminal

```bash
npm install --save-dev \
  babel-loader \
  babel-preset-env \
  babel-preset-react
```

#### webpack.config.js

```js
module.exports = {
  ···
  module: {
    rules: [
      { test: /\.js$/,
        exclude: /node_modules/,
        use: [
          { loader: 'babel-loader' }
        ]
      }
    ]
  }
}
```
{: data-line="3,4,5,6,7,8"}

#### .babelrc

```js
{
  "presets": [ "env", "react" ]
}
```

Adds support for [Babel](http://babeljs.io).

### CSS

#### Terminal

```bash
npm install --save-dev \
  css-loader \
  style-loader
```

#### webpack.config.js

```js
module.exports = {
  ···
  module: {
    rules: [
     { test: /\.css$/,
       exclude: /node_modules/,
       use: [
         { loader: 'style-loader' },
         { loader: 'css-loader' }
       ]
      }
    ]
  }
}
```
{: data-line="3,4,5,6,7,8,9"}

#### Your JavaScript

```js
import './styles.css'
// or:
require('./styles.css')
```

This allows you to use CSS inside your JavaScript. This packages your CSS inside your JavaScript bundle.

### PostCSS

#### Terminal

```
npm install --save-dev \
  postcss-loader \
  postcss-cssnext
```

#### webpack.config.js

```js
···
// Inside module.rules[]:
{ test: /\.css$/,
  exclude: /node_modules/,
  use: [
    { loader: 'style-loader' },
    { loader: 'css-loader' },
    { loader: 'postcss-loader' }
···
```
{: data-line="8"}

#### postcss.config.js

```js
module.exports = {
  plugins: [
    require('postcss-cssnext')()
  ]
}
```
{: data-line="3"}

This example adds [postcss-cssnext](https://www.npmjs.com/package/postcss-cssnext) support to your CSS files.

## Other features

### Dev server

#### package.json

```json
{ ···
  "scripts": {
    "dev": "webpack-dev-server"
  }
}
```
{: data-line="3"}

#### Terminal

```bash
npm install --save-dev \
  webpack-dev-server
```

```bash
npm run dev
```

This starts an HTTP server for development (port 8080 by default).


id: web-workers
git_filename: ./web-workers.md
format: md
field_title: Web workers
field_category: JavaScript
field_updated: 2017-10-30
field_updated___timezone: UTC
data:
{"title": "Web workers", "category": "JavaScript", "updated": "2017-10-30", "weight": -1, "body": "## Web workers\n\n#### Client\n\n```js\nvar worker = new Worker('worker.js')\n\nworker.onmessage = function (message) {\n  alert(JSON.stringify(message.data))\n})\n\nworker.postMessage('hello!')\n```\n\nMessages can be anything that can be serialized into JSON (objects, arrays, strings, numbers, booleans). See: [structured clone](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)\n\n#### Worker\n\n```js\nself.onmessage = function (message) {\n  \u00b7\u00b7\u00b7\n}\n\nself.postMessage({ msg: 'hello' })\n```\n\n### Message data\n\n#### [MessageEvent]\n\n```js\nbubbles: false\ncancelBubble: false\ncancelable: false\nclipboardData: undefined\ncurrentTarget: Worker\ndata: \"Hello\"             \u2190 the data\ndefaultPrevented: false\neventPhase: 0\nlastEventId: \"\"\norigin: \"\"\nports: Array[0]\nreturnValue: true\nsource: null\nsrcElement: Worker\ntarget: Worker\ntimeStamp: 1344821022383\ntype: \"message\"\n```\n\nThese are the contents of `message` on onmessage."}

field_body:
## Web workers

#### Client

```js
var worker = new Worker('worker.js')

worker.onmessage = function (message) {
  alert(JSON.stringify(message.data))
})

worker.postMessage('hello!')
```

Messages can be anything that can be serialized into JSON (objects, arrays, strings, numbers, booleans). See: [structured clone](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)

#### Worker

```js
self.onmessage = function (message) {
  ···
}

self.postMessage({ msg: 'hello' })
```

### Message data

#### [MessageEvent]

```js
bubbles: false
cancelBubble: false
cancelable: false
clipboardData: undefined
currentTarget: Worker
data: "Hello"             ← the data
defaultPrevented: false
eventPhase: 0
lastEventId: ""
origin: ""
ports: Array[0]
returnValue: true
source: null
srcElement: Worker
target: Worker
timeStamp: 1344821022383
type: "message"
```

These are the contents of `message` on onmessage.


id: watchman
git_filename: ./watchman.md
format: md
field_title: Watchman
field_updated: 2017-10-18
field_updated___timezone: UTC
data:
{"title": "Watchman", "updated": "2017-10-18", "weight": -1, "keywords": ["watchman watch ~/src", "watchman watch-list", "watchman -- trigger ~/rsc remake '*.js' -- make "], "body": "### Getting started\n\n```bash\nwatchman watch ./src\n```\n\nAdds `./src` to the watch list.\n\n```bash\nwatchman -- trigger ./src retest '*.js' -- npm test\n```\n\nAdds a trigger called `retest` to run `npm test` every time `*.js` changes in `./src`.\n\n### Watching\n\n```\nwatchman watch ~/src\nwatchman watch-list\nwatchman watch-del ~/src\n```\n\n## Also see\n\n * [Documentation](https://facebook.github.io/watchman/docs/install.html) _(facebook.github.io)_"}

field_body:
### Getting started

```bash
watchman watch ./src
```

Adds `./src` to the watch list.

```bash
watchman -- trigger ./src retest '*.js' -- npm test
```

Adds a trigger called `retest` to run `npm test` every time `*.js` changes in `./src`.

### Watching

```
watchman watch ~/src
watchman watch-list
watchman watch-del ~/src
```

## Also see

 * [Documentation](https://facebook.github.io/watchman/docs/install.html) _(facebook.github.io)_


id: watchexec
git_filename: ./watchexec.md
format: md
field_title: Watchexec
field_category: CLI
field_updated: 2017-10-18
field_updated___timezone: UTC
data:
{"title": "Watchexec", "updated": "2017-10-18", "category": "CLI", "weight": -1, "keywords": ["watchexec --excts js,jsx -- npm test", "watchexec --help"], "intro": "[mattgreen/watchexec](https://github.com/mattgreen/watchexec) runs commands whenever certain files change.\n", "body": "### Installation\n\n#### OSX\n\n```bash\nbrew install watchexec\n```\n\n#### Rust\n\n```bash\ncargo install watchexec\n```\n\nFor Linux and Windows, get it from [GitHub releases](https://github.com/mattgreen/watchexec).\n\n### Getting started\n\n```bash\nwatchexec --exts js,jsx -- npm test\n```\n\nRuns `npm test` when `js,jsx` files change.\n\n```bash\nwatchman -w lib -w test -- npm test\n```\n\nRuns `npm test` when `lib/` and `test/` files change.\n\n### Other options\n\n#### Flags\n\n| `-c` `--clear`   | Clear screen                         |\n| `-r` `--restart` | Restart process if its still running |\n\n#### Options\n\n| `-s` `--signal SIGKILL` | Kill signal to use            |\n| `-d` `--debounce MS`    | Debounce by `MS` milliseconds |\n| `-e` `--exts EXTS`      | Extensions                    |\n| `-i` `--ignore PATTERN` | Ignore these files            |\n| `-w` `--watch PATH`     | Watch these directories       |\n\n## Also see\n\n* [mattgreen/watchexec](https://github.com/mattgreen/watchexec) _(github.com)_"}

field_intro:
[mattgreen/watchexec](https://github.com/mattgreen/watchexec) runs commands whenever certain files change.

field_body:
### Installation

#### OSX

```bash
brew install watchexec
```

#### Rust

```bash
cargo install watchexec
```

For Linux and Windows, get it from [GitHub releases](https://github.com/mattgreen/watchexec).

### Getting started

```bash
watchexec --exts js,jsx -- npm test
```

Runs `npm test` when `js,jsx` files change.

```bash
watchman -w lib -w test -- npm test
```

Runs `npm test` when `lib/` and `test/` files change.

### Other options

#### Flags

| `-c` `--clear`   | Clear screen                         |
| `-r` `--restart` | Restart process if its still running |

#### Options

| `-s` `--signal SIGKILL` | Kill signal to use            |
| `-d` `--debounce MS`    | Debounce by `MS` milliseconds |
| `-e` `--exts EXTS`      | Extensions                    |
| `-i` `--ignore PATTERN` | Ignore these files            |
| `-w` `--watch PATH`     | Watch these directories       |

## Also see

* [mattgreen/watchexec](https://github.com/mattgreen/watchexec) _(github.com)_


id: vue@1.0.28
git_filename: ./vue@1.0.28.md
format: md
field_title: Vue.js v1.0.28
field_category: JavaScript
data:
{"title": "Vue.js v1.0.28", "category": "JavaScript", "deprecated": true, "weight": -10, "intro": "**Deprecated:** this guide targets an old version of Vuej.js (v1.0.28). See the [updated Vue.js cheatsheet](vue) for new versions.\n", "body": "{% raw %}\n\n### Lists\n\n```html\n<li v-for=\"todo in todos\">\n  {{ todo.text }}\n  {{ $index }}\n</li>\n```\n\n### Events\n\n```html\n<button v-on:click='submit'>Go</button>\n```\n\n### Components\n\n```js\nnew Vue({\n  components: { app: App }\n})\n```\n\n## API\n\n```js\nVue.extend({ ... })        // creating components\nVue.nextTick(() => {...})\n\nVue.set(object, key, val)  // reactive\nVue.delete(object, key)\n\nVue.directive('my-dir', { bind, update, unbind })\n// <div v-my-dir='...'></div>\n\nVue.elementDirective('my-dir', { bind, update, unbind })\n// <my-dir>...</my-dir>\n\nVue.component('my-component', Vue.extend({ .. }))\n\nVue.partial('my-partial', '<div>hi {{msg}}</div>')\n// <partial name='my-partial'></partial>\n```\n\n```js\nnew Vue({\n  data: { ... }\n  props: ['size'],\n  props: { size: Number },\n  computed: { fullname() { return this.name + ' ' + this.lastName } },\n  methods: { go() { ... } },\n  watch: { a (val, oldVal) { ... } },\n  el: '#foo',\n  template: '...',\n  replace: true, // replace element (default true)\n\n  // lifecycle\n  created () {},\n  beforeCompile () {},\n  compiled () {},\n  ready () {}, // $el is inserted for the first time\n  attached () {},\n  detached () {},\n  beforeDestroy () {},\n  destroyed () {},\n\n  // options\n  directives: {},\n  elementDirectives: {},\n  filters: {},\n  components: {},\n  transitions: {},\n  partials: {}\n})\n```\n\n## Vue templates\nVia [vueify](https://www.npmjs.com/package/vueify)\n\n```js\n// app.vue\n<template>\n  <h1 class=\"red\">{{msg}}</h1>\n</template>\n \n<script>\n  module.exports = {\n    data () {\n      return {\n        msg: 'Hello world!'\n      }\n    }\n  }\n</script> \n```\n\nAlso\n\n```html\n<template lang='jade'>\nh1(class='red') {{msg}}\n</template>\n```\n\n{% endraw %}"}

field_intro:
**Deprecated:** this guide targets an old version of Vuej.js (v1.0.28). See the [updated Vue.js cheatsheet](vue) for new versions.

field_body:
{% raw %}

### Lists

```html
<li v-for="todo in todos">
  {{ todo.text }}
  {{ $index }}
</li>
```

### Events

```html
<button v-on:click='submit'>Go</button>
```

### Components

```js
new Vue({
  components: { app: App }
})
```

## API

```js
Vue.extend({ ... })        // creating components
Vue.nextTick(() => {...})

Vue.set(object, key, val)  // reactive
Vue.delete(object, key)

Vue.directive('my-dir', { bind, update, unbind })
// <div v-my-dir='...'></div>

Vue.elementDirective('my-dir', { bind, update, unbind })
// <my-dir>...</my-dir>

Vue.component('my-component', Vue.extend({ .. }))

Vue.partial('my-partial', '<div>hi {{msg}}</div>')
// <partial name='my-partial'></partial>
```

```js
new Vue({
  data: { ... }
  props: ['size'],
  props: { size: Number },
  computed: { fullname() { return this.name + ' ' + this.lastName } },
  methods: { go() { ... } },
  watch: { a (val, oldVal) { ... } },
  el: '#foo',
  template: '...',
  replace: true, // replace element (default true)

  // lifecycle
  created () {},
  beforeCompile () {},
  compiled () {},
  ready () {}, // $el is inserted for the first time
  attached () {},
  detached () {},
  beforeDestroy () {},
  destroyed () {},

  // options
  directives: {},
  elementDirectives: {},
  filters: {},
  components: {},
  transitions: {},
  partials: {}
})
```

## Vue templates
Via [vueify](https://www.npmjs.com/package/vueify)

```js
// app.vue
<template>
  <h1 class="red">{{msg}}</h1>
</template>
 
<script>
  module.exports = {
    data () {
      return {
        msg: 'Hello world!'
      }
    }
  }
</script> 
```

Also

```html
<template lang='jade'>
h1(class='red') {{msg}}
</template>
```

{% endraw %}


id: vue
git_filename: ./vue.md
format: md
field_title: Vue.js
field_category: JavaScript
field_updated: 2019-12-26
field_updated___timezone: UTC
data:
{"title": "Vue.js", "category": "JavaScript", "updated": "2019-12-26", "weight": -10, "intro": "[Vue.js](https://vuejs.org/) is an open-source Model\u2013view\u2013viewmodel JavaScript framework for building user interfaces and single-page applications.\n", "body": "{%raw%}\n\nExpressions\n----------\n{: .-three-column}\n\n### Expressions\n\n```html\n<div id=\"app\">\n  <p>I have a {{ product }}</p>\n  <p>{{ product + 's' }}</p>\n  <p>{{ isWorking ? 'YES' : 'NO' }}</p>\n  <p>{{ product.getSalePrice() }}</p>\n</div>\n```\n\nSee: [Delimiters](https://vuejs.org/v2/api/#delimiters)\n\n### Binding\n\n```html\n<a v-bind:href=\"url\">...</a>\n```\n\n#### Shorthand syntax\n```html\n<a :href=\"url\">...</a>\n```\n{: data-line=\"1\"}\n\n#### True or false will add or remove attribute\n```html\n<button :disabled=\"isButtonDisabled\">...\n```\n\n#### If isActive is truthy, the class \u2018active\u2019 will appear\n```html\n<div :class=\"{ active: isActive }\">...\n```\n\n#### Style color set to value of activeColor\n```html\n<div :style=\"{ color: activeColor }\">\n```\n\nSee: [v-bind](https://vuejs.org/v2/api/#v-bind)\n\n### Directives\n\n#### Element inserted/removed based on truthiness\n```html\n<p v-if=\"inStock\">{{ product }}</p>\n```\n```html\n<p v-else-if=\"onSale\">...</p>\n<p v-else>...</p>\n```\n\n#### Toggles the display: none CSS property\n```html\n<p v-show=\"showProductDetails\">...</p>\n```\n\n#### Two-way data binding\n```html\n<input v-model=\"firstName\" >\n```\n\n| Method | Description |\n| --- | --- |\n| `v-model.lazy=\"...\"` | Syncs input after change event |\n| `v-model.number=\"...\"` | Always returns a number |\n| `v-model.trim=\"...\"` | Strips whitespace |\n\nSee: [Directives](https://vuejs.org/v2/api/#Directives)\n\n### Actions/Events\n\n#### Calls addToCart method on component\n```html\n<button v-on:click=\"addToCart\">...\n```\n\n#### Shorthand syntax\n```html\n<button @click=\"addToCart\">...\n```\n{: data-line=\"1\"}\n\n#### Arguments can be passed\n```html\n<button @click=\"addToCart(product)\">...\n```\n\n#### To prevent default behavior (e.g. page reload)\n```html\n<form @submit.prevent=\"addProduct\">...\n```\n\n#### Only trigger once\n```html\n<img @mouseover.once=\"showImage\">...\n```\n\n| Method | Description |\n| --- | --- |\n| `.stop` | Stop all event propagation |\n| `.self ` | Only trigger if event.target is element itself |\n\n#### Keyboard entry example\n```html\n<input @keyup.enter=\"submit\">\n```\n\n#### Call onCopy when control-c is pressed\n```html\n<input @keyup.ctrl.c=\"onCopy\">\n```\n\nSee: [Events](https://vuejs.org/v2/guide/events.html)\n\n### List rendering\n\n#### The `:key` is always recommended\n```html\n<li v-for=\"item in items\"\n    :key=\"item.id\">\n  {{ item }}\n</li>\n```\n{: data-line=\"2\"}\n\n#### To access the position in the array\n```html\n<li v-for=\"(item, index) in items\">...\n```\n\n#### To iterate through objects\n```html\n<li v-for=\"(value, key) in object\">...\n```\n\n#### Using `v-for` with a component\n```html\n<cart-product v-for=\"item in products\"\n              :product=\"item\"\n              :key=\"item.id\">\n```\n\nSee: [List Rendering](https://vuejs.org/v2/guide/list.html)\n\n\nComponent\n--------\n\n### Component anatomy\n\n```js\nVue.component('my-component', {\n  components: {\n    // Components that can be used in the template\n    ProductComponent,\n    ReviewComponent\n  },\n  props: {\n    // The parameters the component accepts\n    message: String,\n    product: Object,\n    email: {\n      type: String,\n      required: true,\n      default: \"none\"\n      validator: function (value) {\n        // Should return true if value is valid\n      }\n    }\n  },\n  data: function() {\n    // `data` must be a function\n    return {\n      firstName: 'Vue',\n      lastName: 'Mastery'\n    }\n  },\n  computed: {\n    // Return cached values until dependencies change\n    fullName: function () {\n      return this.firstName + ' ' + this.lastName\n    }\n  },\n  watch: {\n    // Called when firstName changes value\n    firstName: function (value, oldValue) { ... }\n  },\n  methods: { ... },\n  template: '<span>{{ message }}</span>',\n  // Can also use backticks in `template` for multi-line\n})\n```\n{: data-line=\"3, 8, 16, 21, 28, 34, 39\"}\n\nSee: [Components Basics](https://vuejs.org/v2/guide/components.html)\n\n### Lifecycle hooks\n\n| Method | Description |\n| --- | --- |\n| `beforeCreate` | After the instance has been initialized [#](https://vuejs.org/v2/api/#beforeCreate) |\n| `created` | After the instance is created [#](https://vuejs.org/v2/api/#created) |\n| `beforeMount` | Before the first render [#](https://vuejs.org/v2/api/#beforeMount) |\n| `mounted` | After the instance has been mounted [#](https://vuejs.org/v2/api/#mounted) |\n| `beforeUpdate` | When data changes, before the DOM is patched [#](https://vuejs.org/v2/api/#beforeUpdate) |\n| `updated` | After a data change [#](https://vuejs.org/v2/api/#updated) |\n| `beforeDestroy` | Before the instance is destroyed [#](https://vuejs.org/v2/api/#beforeDestroy) |\n| `destroyed` | After a Vue instance has been destroyed [#](https://vuejs.org/v2/api/#destroyed) |\n\nSee: [Lifecycle Hooks](https://vuejs.org/v2/api/#Options-Lifecycle-Hooks)\n\n### Custom events\n\n#### Set listener on component, within its parent\n```html\n<button-counter v-on:incrementBy=\"incWithVal\">\n```\n\n#### Inside parent component\n```js\nmethods: {\n  incWithVal: function (toAdd) { ... }\n}\n```\n\n#### Inside button-counter template\n```js\nthis.$emit(\n    'incrementBy', // Custom event name\n    5 // Data sent up to parent\n  )\n```\n\nUse props to pass data into child components,\ncustom events to pass data to parent elements.\n\nSee: [Custom Events](https://vuejs.org/v2/guide/components-custom-events.html)\n\nSingle file components\n--------\n\n### Single file\n```html\n<template>\n  <p>{{ greeting }} World!</p>\n</template>\n\n<script>\nmodule.exports = {\n  data: function () {\n    return {\n      greeting: 'Hello'\n    }\n  }\n}\n</script>\n\n<style scoped>\np {\n  font-size: 2em;\n  text-align: center;\n}\n</style>\n```\n\nSee: [Single File Components](https://vuejs.org/v2/guide/single-file-components.html)\n\n### Separation\n```html\n<template>\n  <div>This will be pre-compiled</div>\n</template>\n<script src=\"./my-component.js\"></script>\n<style src=\"./my-component.css\"></style>\n```\n\nSee: [What About Separation of Concerns?](https://vuejs.org/v2/guide/single-file-components.html#What-About-Separation-of-Concerns)\n\nSlots\n--------\n\n### Using a single slot\n\n#### Component template\n```html\n<div>\n  <h2>I'm a title</h2>\n  <slot>\n    Only displayed if no slot content\n  </slot>\n</div>\n```\n{: data-line=\"3,4,5\"}\n\n#### Use of component with data for slot\n```html\n<my-component>\n  <p>This will go in the slot</p>\n</my-component>\n```\n{: data-line=\"2\"}\n\nSee: [Slots](https://vuejs.org/v2/guide/components-slots.html)\n\n### Multiple slots\n\n#### Component template\n```html\n<div class=\"container\">\n  <header>\n    <slot name=\"header\"></slot>\n  </header>\n  <main>\n    <slot>Default content</slot>\n  </main>\n  <footer>\n    <slot name=\"footer\"></slot>\n  </footer>\n</div>\n```\n{: data-line=\"3,6,9\"}\n\n#### Use of component with data for slots\n```html\n<app-layout>\n  <h1 slot=\"header\">Page title</h1>\n  <p>the main content.</p>\n  <p slot=\"footer\">Contact info</p>\n</app-layout>\n```\n{: data-line=\"2,3,4\"}\n\nSee: [Slots](https://vuejs.org/v2/guide/components-slots.html)\n\nAlso see\n--------\n\n* [Vue CLI](https://cli.vuejs.org/) _(cli.vuejs.org)_\n* [Vue Router](https://router.vuejs.org/) _(router.vuejs.org)_\n* [Vue DevTools](https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd?hl=en) _(chrome.google.com)_\n* [Nuxt.js](https://nuxtjs.org/) _(nuxtjs.org)_\n* [Vue.js v1.0.28 cheatsheet](vue@1.0.28/) _Legacy version_\n\n{%endraw%}"}

field_intro:
[Vue.js](https://vuejs.org/) is an open-source Model–view–viewmodel JavaScript framework for building user interfaces and single-page applications.

field_body:
{%raw%}

Expressions
----------
{: .-three-column}

### Expressions

```html
<div id="app">
  <p>I have a {{ product }}</p>
  <p>{{ product + 's' }}</p>
  <p>{{ isWorking ? 'YES' : 'NO' }}</p>
  <p>{{ product.getSalePrice() }}</p>
</div>
```

See: [Delimiters](https://vuejs.org/v2/api/#delimiters)

### Binding

```html
<a v-bind:href="url">...</a>
```

#### Shorthand syntax
```html
<a :href="url">...</a>
```
{: data-line="1"}

#### True or false will add or remove attribute
```html
<button :disabled="isButtonDisabled">...
```

#### If isActive is truthy, the class ‘active’ will appear
```html
<div :class="{ active: isActive }">...
```

#### Style color set to value of activeColor
```html
<div :style="{ color: activeColor }">
```

See: [v-bind](https://vuejs.org/v2/api/#v-bind)

### Directives

#### Element inserted/removed based on truthiness
```html
<p v-if="inStock">{{ product }}</p>
```
```html
<p v-else-if="onSale">...</p>
<p v-else>...</p>
```

#### Toggles the display: none CSS property
```html
<p v-show="showProductDetails">...</p>
```

#### Two-way data binding
```html
<input v-model="firstName" >
```

| Method | Description |
| --- | --- |
| `v-model.lazy="..."` | Syncs input after change event |
| `v-model.number="..."` | Always returns a number |
| `v-model.trim="..."` | Strips whitespace |

See: [Directives](https://vuejs.org/v2/api/#Directives)

### Actions/Events

#### Calls addToCart method on component
```html
<button v-on:click="addToCart">...
```

#### Shorthand syntax
```html
<button @click="addToCart">...
```
{: data-line="1"}

#### Arguments can be passed
```html
<button @click="addToCart(product)">...
```

#### To prevent default behavior (e.g. page reload)
```html
<form @submit.prevent="addProduct">...
```

#### Only trigger once
```html
<img @mouseover.once="showImage">...
```

| Method | Description |
| --- | --- |
| `.stop` | Stop all event propagation |
| `.self ` | Only trigger if event.target is element itself |

#### Keyboard entry example
```html
<input @keyup.enter="submit">
```

#### Call onCopy when control-c is pressed
```html
<input @keyup.ctrl.c="onCopy">
```

See: [Events](https://vuejs.org/v2/guide/events.html)

### List rendering

#### The `:key` is always recommended
```html
<li v-for="item in items"
    :key="item.id">
  {{ item }}
</li>
```
{: data-line="2"}

#### To access the position in the array
```html
<li v-for="(item, index) in items">...
```

#### To iterate through objects
```html
<li v-for="(value, key) in object">...
```

#### Using `v-for` with a component
```html
<cart-product v-for="item in products"
              :product="item"
              :key="item.id">
```

See: [List Rendering](https://vuejs.org/v2/guide/list.html)


Component
--------

### Component anatomy

```js
Vue.component('my-component', {
  components: {
    // Components that can be used in the template
    ProductComponent,
    ReviewComponent
  },
  props: {
    // The parameters the component accepts
    message: String,
    product: Object,
    email: {
      type: String,
      required: true,
      default: "none"
      validator: function (value) {
        // Should return true if value is valid
      }
    }
  },
  data: function() {
    // `data` must be a function
    return {
      firstName: 'Vue',
      lastName: 'Mastery'
    }
  },
  computed: {
    // Return cached values until dependencies change
    fullName: function () {
      return this.firstName + ' ' + this.lastName
    }
  },
  watch: {
    // Called when firstName changes value
    firstName: function (value, oldValue) { ... }
  },
  methods: { ... },
  template: '<span>{{ message }}</span>',
  // Can also use backticks in `template` for multi-line
})
```
{: data-line="3, 8, 16, 21, 28, 34, 39"}

See: [Components Basics](https://vuejs.org/v2/guide/components.html)

### Lifecycle hooks

| Method | Description |
| --- | --- |
| `beforeCreate` | After the instance has been initialized [#](https://vuejs.org/v2/api/#beforeCreate) |
| `created` | After the instance is created [#](https://vuejs.org/v2/api/#created) |
| `beforeMount` | Before the first render [#](https://vuejs.org/v2/api/#beforeMount) |
| `mounted` | After the instance has been mounted [#](https://vuejs.org/v2/api/#mounted) |
| `beforeUpdate` | When data changes, before the DOM is patched [#](https://vuejs.org/v2/api/#beforeUpdate) |
| `updated` | After a data change [#](https://vuejs.org/v2/api/#updated) |
| `beforeDestroy` | Before the instance is destroyed [#](https://vuejs.org/v2/api/#beforeDestroy) |
| `destroyed` | After a Vue instance has been destroyed [#](https://vuejs.org/v2/api/#destroyed) |

See: [Lifecycle Hooks](https://vuejs.org/v2/api/#Options-Lifecycle-Hooks)

### Custom events

#### Set listener on component, within its parent
```html
<button-counter v-on:incrementBy="incWithVal">
```

#### Inside parent component
```js
methods: {
  incWithVal: function (toAdd) { ... }
}
```

#### Inside button-counter template
```js
this.$emit(
    'incrementBy', // Custom event name
    5 // Data sent up to parent
  )
```

Use props to pass data into child components,
custom events to pass data to parent elements.

See: [Custom Events](https://vuejs.org/v2/guide/components-custom-events.html)

Single file components
--------

### Single file
```html
<template>
  <p>{{ greeting }} World!</p>
</template>

<script>
module.exports = {
  data: function () {
    return {
      greeting: 'Hello'
    }
  }
}
</script>

<style scoped>
p {
  font-size: 2em;
  text-align: center;
}
</style>
```

See: [Single File Components](https://vuejs.org/v2/guide/single-file-components.html)

### Separation
```html
<template>
  <div>This will be pre-compiled</div>
</template>
<script src="./my-component.js"></script>
<style src="./my-component.css"></style>
```

See: [What About Separation of Concerns?](https://vuejs.org/v2/guide/single-file-components.html#What-About-Separation-of-Concerns)

Slots
--------

### Using a single slot

#### Component template
```html
<div>
  <h2>I'm a title</h2>
  <slot>
    Only displayed if no slot content
  </slot>
</div>
```
{: data-line="3,4,5"}

#### Use of component with data for slot
```html
<my-component>
  <p>This will go in the slot</p>
</my-component>
```
{: data-line="2"}

See: [Slots](https://vuejs.org/v2/guide/components-slots.html)

### Multiple slots

#### Component template
```html
<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot>Default content</slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>
```
{: data-line="3,6,9"}

#### Use of component with data for slots
```html
<app-layout>
  <h1 slot="header">Page title</h1>
  <p>the main content.</p>
  <p slot="footer">Contact info</p>
</app-layout>
```
{: data-line="2,3,4"}

See: [Slots](https://vuejs.org/v2/guide/components-slots.html)

Also see
--------

* [Vue CLI](https://cli.vuejs.org/) _(cli.vuejs.org)_
* [Vue Router](https://router.vuejs.org/) _(router.vuejs.org)_
* [Vue DevTools](https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd?hl=en) _(chrome.google.com)_
* [Nuxt.js](https://nuxtjs.org/) _(nuxtjs.org)_
* [Vue.js v1.0.28 cheatsheet](vue@1.0.28/) _Legacy version_

{%endraw%}


id: vscode
git_filename: ./vscode.md
format: md
field_title: Visual Studio Code
field_category: Apps
field_updated: 2018-02-01
field_updated___timezone: UTC
data:
{"title": "Visual Studio Code", "category": "Apps", "updated": "2018-02-01", "weight": -5, "keywords": ["\u2318P: Show files", "\u2318B: Toggle sidebar", "\u2318J: Toggle panel", "F5: Debug"], "intro": "[Visual Studio Code](https://code.visualstudio.com/), or VSCode, is an open-source code editor. This guide targets VSCode v1.19.\n", "body": "## Shortcuts\n{: .-three-column}\n\n### Command palette\n\n| Key   | Description       |\n| ----- | ----------------- |\n| `\u21e7\u2318P` | Show all commands |\n| `\u2318P`  | Show files        |\n{: .-shortcuts}\n\n### Sidebars\n\n| Key   | Description    |\n| ----- | -------------- |\n| `\u2318B`  | Toggle sidebar |\n| ----  | ----           |\n| `\u21e7\u2318E` | Explorer       |\n| `\u21e7\u2318F` | Search         |\n| `\u21e7\u2318D` | Debug          |\n| `\u21e7\u2318X` | Extensions     |\n| `\u21e7^G` | Git (SCM)      |\n{: .-shortcuts}\n\n### Search\n\n| Key   | Description      |\n| ----- | ---------------- |\n| `\u2318F`  | Find             |\n| `\u2325\u2318F` | Replace          |\n| ----  | ----             |\n| `\u21e7\u2318F` | Find in files    |\n| `\u21e7\u2318H` | Replace in files |\n{: .-shortcuts}\n\n### Panel\n\n| Key                        | Description   |\n| -------------------------- | ------------- |\n| `\u2318J`                       | Toggle panel  |\n| ----                       | ----          |\n| `\u21e7\u2318M`                      | Problems      |\n| `\u21e7\u2318U`                      | Output        |\n| `\u21e7\u2318Y`                      | Debug console |\n| <code>^`</code>            | Terminal      |\n{: .-shortcuts}\n\n### View\n\n| Key      | Description      |\n| -------- | ---------------- |\n| `\u2318k` `z` | Zen mode         |\n| ----     | ----             |\n| `\u2318k` `u` | Close unmodified |\n| `\u2318k` `w` | Close all        |\n{: .-shortcuts}\n\n### Debug\n\n| Key    | Description             |\n| ------ | ----------------------- |\n| `F5`   | Start                   |\n| `\u21e7F5`  | Stop                    |\n| `\u21e7\u2318F5` | Restart                 |\n| ----   | ----                    |\n| `^F5`  | Start without debugging |\n| ----   | ----                    |\n| `F9`   | Toggle breakpoint       |\n| ----   | ----                    |\n| `F10`  | Step over               |\n| `F11`  | Step into               |\n| `\u21e7F11` | Step out                |\n| ----   | ----                    |\n| `\u21e7\u2318D`  | Debug sidebar           |\n| `\u21e7\u2318Y`  | Debug panel             |\n{: .-shortcuts}\n\n## References\n\n* [Keyboard shortcuts (MacOS)](https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf) _(code.visualstudio.com)_\n* [Keyboard shortcuts (Windows)](https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf) _(code.visualstudio.com)_\n* [Keyboard shortcuts (Linux)](https://code.visualstudio.com/shortcuts/keyboard-shortcuts-linux.pdf) _(code.visualstudio.com)_"}

field_intro:
[Visual Studio Code](https://code.visualstudio.com/), or VSCode, is an open-source code editor. This guide targets VSCode v1.19.

field_body:
## Shortcuts
{: .-three-column}

### Command palette

| Key   | Description       |
| ----- | ----------------- |
| `⇧⌘P` | Show all commands |
| `⌘P`  | Show files        |
{: .-shortcuts}

### Sidebars

| Key   | Description    |
| ----- | -------------- |
| `⌘B`  | Toggle sidebar |
| ----  | ----           |
| `⇧⌘E` | Explorer       |
| `⇧⌘F` | Search         |
| `⇧⌘D` | Debug          |
| `⇧⌘X` | Extensions     |
| `⇧^G` | Git (SCM)      |
{: .-shortcuts}

### Search

| Key   | Description      |
| ----- | ---------------- |
| `⌘F`  | Find             |
| `⌥⌘F` | Replace          |
| ----  | ----             |
| `⇧⌘F` | Find in files    |
| `⇧⌘H` | Replace in files |
{: .-shortcuts}

### Panel

| Key                        | Description   |
| -------------------------- | ------------- |
| `⌘J`                       | Toggle panel  |
| ----                       | ----          |
| `⇧⌘M`                      | Problems      |
| `⇧⌘U`                      | Output        |
| `⇧⌘Y`                      | Debug console |
| <code>^`</code>            | Terminal      |
{: .-shortcuts}

### View

| Key      | Description      |
| -------- | ---------------- |
| `⌘k` `z` | Zen mode         |
| ----     | ----             |
| `⌘k` `u` | Close unmodified |
| `⌘k` `w` | Close all        |
{: .-shortcuts}

### Debug

| Key    | Description             |
| ------ | ----------------------- |
| `F5`   | Start                   |
| `⇧F5`  | Stop                    |
| `⇧⌘F5` | Restart                 |
| ----   | ----                    |
| `^F5`  | Start without debugging |
| ----   | ----                    |
| `F9`   | Toggle breakpoint       |
| ----   | ----                    |
| `F10`  | Step over               |
| `F11`  | Step into               |
| `⇧F11` | Step out                |
| ----   | ----                    |
| `⇧⌘D`  | Debug sidebar           |
| `⇧⌘Y`  | Debug panel             |
{: .-shortcuts}

## References

* [Keyboard shortcuts (MacOS)](https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf) _(code.visualstudio.com)_
* [Keyboard shortcuts (Windows)](https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf) _(code.visualstudio.com)_
* [Keyboard shortcuts (Linux)](https://code.visualstudio.com/shortcuts/keyboard-shortcuts-linux.pdf) _(code.visualstudio.com)_


id: vows
git_filename: ./vows.md
format: md
field_title: Vows
field_category: JavaScript libraries
data:
{"title": "Vows", "category": "JavaScript libraries", "body": "### About vows\n\n  * [Vowsjs.org](http://vowsjs.org/)\n\n### CoffeeScript usage\n\n    vows = require \"vows\"\n    assert = require \"assert\"\n\n    vows\n      .describe('My tests')\n      .addBatch\n        'context':\n          topic: ->\n            100\n          'should work': (number) ->\n            assert.equal number, 100\n\n      .export(module)\n\n### Running\n\n    vows test/*-test.* --spec\n\n### Assertions\n\n    assert.equal a, b\n    assert.notEqual a, b\n    assert.strictEqual a, b\n\n    assert.isNaN(number)\n    assert.instanceOf(object, klass)\n    assert.isUndefined(object)\n    assert.isFunction(func)\n    assert.isNull(object)\n    assert.isNotZero(object)\n    assert.isObject(object)\n    assert.isString(object)\n\n### Async\n\n    .addBatch\n      topic: ->\n        doStuff()\n        @callback 2\n      'check things': (n) ->\n        assert.equal 2, n"}

field_body:
### About vows

  * [Vowsjs.org](http://vowsjs.org/)

### CoffeeScript usage

    vows = require "vows"
    assert = require "assert"

    vows
      .describe('My tests')
      .addBatch
        'context':
          topic: ->
            100
          'should work': (number) ->
            assert.equal number, 100

      .export(module)

### Running

    vows test/*-test.* --spec

### Assertions

    assert.equal a, b
    assert.notEqual a, b
    assert.strictEqual a, b

    assert.isNaN(number)
    assert.instanceOf(object, klass)
    assert.isUndefined(object)
    assert.isFunction(func)
    assert.isNull(object)
    assert.isNotZero(object)
    assert.isObject(object)
    assert.isString(object)

### Async

    .addBatch
      topic: ->
        doStuff()
        @callback 2
      'check things': (n) ->
        assert.equal 2, n


id: virtual-dom
git_filename: ./virtual-dom.md
format: md
field_title: Virtual-dom
field_category: JavaScript libraries
data:
{"title": "Virtual-dom", "category": "JavaScript libraries", "body": "### About\n\nSee <https://www.npmjs.com/package/virtual-dom>\n\n### Example\n\n```js\nvar h = require('virtual-dom/h')\nvar diff = require('virtual-dom/diff')\nvar patch = require('virtual-dom/patch')\nvar createElement = require('virtual-dom/create-element')\n```\n\n### Rendering\n\n```js\ntree = h('div', { style: { color: 'blue' } }, [ 'hello' ])\nel = createElement(tree)\ndocument.body.appendChild(root)\n```\n\n### Updating\n\n```js\ntree2 = h('div', { style: { color: 'blue' } }, [ 'hello world' ])\ndelta = diff(tree, tree2)\nel = patch(el, delta) // patch() modifies el\n```"}

field_body:
### About

See <https://www.npmjs.com/package/virtual-dom>

### Example

```js
var h = require('virtual-dom/h')
var diff = require('virtual-dom/diff')
var patch = require('virtual-dom/patch')
var createElement = require('virtual-dom/create-element')
```

### Rendering

```js
tree = h('div', { style: { color: 'blue' } }, [ 'hello' ])
el = createElement(tree)
document.body.appendChild(root)
```

### Updating

```js
tree2 = h('div', { style: { color: 'blue' } }, [ 'hello world' ])
delta = diff(tree, tree2)
el = patch(el, delta) // patch() modifies el
```


id: vimscript
git_filename: ./vimscript.md
format: md
field_title: Vim scripting
field_category: Vim
field_tags: Featurable
field_prism_languages: vim
field_updated: 2020-07-05
field_updated___timezone: UTC
data:
{"title": "Vim scripting", "category": "Vim", "prism_languages": ["vim"], "updated": "2020-07-05", "weight": -10, "tags": ["Featurable"], "body": "### Start hacking\n\n```vim\nlet name = \"John\"\necho \"Hello, \" . name\n```\n\nYou can either put this in a script (`script.vim`) and run it (`:source script.vim`), or you can type the commands individually in normal mode as `:let` and `:echo`.\n\n### Learn by example\n\n```vim\nfunction! SuperTab()\n  let l:part = strpart(getline('.'),col('.')-2,1)\n  if (l:part =~ '^\\W\\?$')\n      return \"\\<Tab>\"\n  else\n      return \"\\<C-n>\"\n  endif\nendfunction\n\nimap <Tab> <C-R>=SuperTab()<CR>\n```\n\n[Here](http://www.vimbits.com/bits/46)'s another example with [functions](#functions), [variables](#variables) and [mapping](#mapping).\n\nVariables\n---------\n\n### Defining\n{: .-prime}\n\n```vim\nlet var = \"hello\"\n```\n\n### Variable prefixes\n\n```vim\nlet g:ack_options = '-s -H'    \" g: global\nlet s:ack_program = 'ack'      \" s: local (to script)\nlet l:foo = 'bar'              \" l: local (to function)\n```\n\nThe `s:` prefix is also available in function names. See `:help local-variables`\n\n### Other prefixes\n\n```vim\nlet w:foo = 'bar'    \" w: window\nlet b:state = 'on'   \" b: buffer\nlet t:state = 'off'  \" t: tab\necho v:var           \" v: vim special\n```\n\n```vim\nlet @/ = ''          \" @  register (this clears last search pattern)\necho $PATH           \" $  env\n```\n\n### Vim options\n\n```vim\necho 'tabstop is ' . &tabstop\nif &insertmode\necho &g:option\necho &l:option\n```\n\nPrefix Vim options with `&`\n\n### Operators\n\n```vim\na + b             \" numbers only!\n'hello ' . name   \" concat\n```\n\n```vim\nlet var -= 2\nlet var += 5\nlet var .= 'string'   \" concat\n```\n\n## Strings\n\n### Strings\n\n```vim\nlet str = \"String\"\nlet str = \"String with \\n newline\"\n\nlet literal = 'literal, no \\ escaping'\nlet literal = 'that''s enough'  \" double '' => '\n\necho \"result = \" . re   \" concatenation\n```\n\nAlso see `:help literal-string` and `:help expr-quote`.\nSee: [Strings](http://learnvimscriptthehardway.stevelosh.com/chapters/26.html)\n\n### String functions\n\n```vim\nstrlen(str)    \" length\nlen(str)       \" same\nstrchars(str)  \" character length\n\nsplit(\"one two three\")       \"=> ['one', 'two', 'three']\nsplit(\"one.two.three\", '.')  \"=> ['one', 'two', 'three']\n\njoin(['a', 'b'], ',')  \"=> 'a,b'\n\ntolower('Hello')\ntoupper('Hello')\n```\n\nAlso see `:help functions`\nSee: [String functions](http://learnvimscriptthehardway.stevelosh.com/chapters/27.html)\n\nFunctions\n---------\n\n### Functions\n{: .-prime}\n\n```vim\n\" prefix with s: for local script-only functions\nfunction! s:Initialize(cmd, args)\n  \" a: prefix for arguments\n  echo \"Command: \" . a:cmd\n\n  return 1\nendfunction\n```\n\nSee: [Functions](http://learnvimscriptthehardway.stevelosh.com/chapters/23.html)\n\n### Overwriting\n```vim\nfunction f1()\n  echo \"f1\"\nendfunction\n\n\nfunction! f1()\n  echo \"f1 overridden\"\nendfunction\n```\n\nIf you define two functions with the same name, Vim will throw an error complaining that the function `f1` already exists. To overwrite the previous function with the same name, add a `!` after the function keyword.\n\n### Namespacing\n\n```vim\nfunction! myplugin#hello()\n```\n\n### Calling functions\n\n```vim\ncall s:Initialize()\ncall s:Initialize(\"hello\")\n```\n\n### Consuming return values\n\n```vim\necho \"Result: \" . s:Initialize()\n```\n\n### Abortable\n\n```vim\nfunction! myfunction() abort\nendfunction\n```\n\nAborts when an error occurs.\n\n### Var arguments\n\n```vim\nfunction! infect(...)\n  echo a:0    \"=> 2\n  echo a:1    \"=> jake\n  echo a:2    \"=> bella\n\n  for s in a:000  \" a list\n    echon ' ' . s\n  endfor\nendfunction\n\ninfect('jake', 'bella')\n```\n\nSee `:help function-argument`.  See: [Var arguments](http://learnvimscriptthehardway.stevelosh.com/chapters/24.html)\n\nLoops\n-----\n\n```vim\nfor s in list\n  echo s\n  continue  \" jump to start of loop\n  break     \" breaks out of a loop\nendfor\n```\n\n```vim\nwhile x < 5\nendwhile\n```\n\nCustom commands\n---------------\n\n### Custom commands\n{: .-prime}\n\n```vim\ncommand! Save :set fo=want tw=80 nowrap\n```\n\nCustom commands start with uppercase letters. The `!` redefines a command if it already exists.\n\n### Commands calling functions\n\n```vim\ncommand! Save call <SID>foo()\n```\n{: .-setup}\n\n```vim\nfunction! s:foo()\n  ...\nendfunction\n```\n\n### Commands with arguments\n\n```vim\ncommand! -nargs=? Save call script#foo(<args>)\n```\n{: .-setup}\n\n| What | What |\n| ---- | ---- |\n| `-nargs=0` | 0 arguments, default |\n| `-nargs=1` | 1 argument, includes spaces |\n| `-nargs=?` | 0 or 1 argument |\n| `-nargs=*` | 0+ arguments, space separated |\n| `-nargs=+` | 1+ arguments, space reparated |\n\nFlow\n----\n\n### Conditionals\n\n```vim\nlet char = getchar()\nif char == \"\\<LeftMouse>\"\n  \" ...\nelseif char == \"\\<RightMouse>\"\n  \" ...\nelse\n  \" ...\nendif\n```\n\n### Truthiness\n\n```vim\nif 1 | echo \"true\"  | endif\nif 0 | echo \"false\" | endif\n```\n\n```vim\nif 1       \"=> 1 (true)\nif 0       \"=> 0 (false)\nif \"1\"     \"=> 1 (true)\nif \"456\"   \"=> 1 (true)\nif \"xfz\"   \"=> 0 (false)\n```\n\nNo booleans. `0` is false, `1` is true.\nSee: [Truthiness](http://learnvimscriptthehardway.stevelosh.com/chapters/21.html)\n\n### Operators\n\n```vim\nif 3 > 2\nif a && b\nif (a && b) || (c && d)\nif !c\n```\n\nSee `:help expression-syntax`.\nSee: [Operators](http://learnvimscriptthehardway.stevelosh.com/chapters/22.html)\n\n### Strings\n\n```vim\nif name ==# 'John'     \" case-sensitive\nif name ==? 'John'     \" case-insensitive\nif name == 'John'      \" depends on :set ignorecase\n\n\" also: is#, is?, >=#, >=?, and so on\n```\n\n### Identity operators\n\n```vim\na is b\na isnot b\n```\n\nChecks if it's the same instance object.\n\n### Regexp matches\n\n```vim\n\"hello\" =~ 'xx*'\n\"hello\" !~ 'xx*'\n\"hello\" =~ '\\v<\\d+>'\n```\n\n`\\v` enables \"extended\" regex mode which allows word boundary (`<>`), `+`, and more.\n\n### Single line\n\n```vim\nif empty(a:path) | return [] | endif\na ? b : c\n```\n\nUse `|` to join lines together.\n\n### Boolean logic\n\n```vim\nif g:use_dispatch && s:has_dispatch\n  \u00b7\u00b7\u00b7\nendif\n```\n\nLists\n-----\n\n### Lists\n\n```vim\nlet mylist = [1, two, 3, \"four\"]\n\nlet first = mylist[0]\nlet last  = mylist[-1]\n\n\" Suppresses errors\nlet second = get(mylist, 1)\nlet second = get(mylist, 1, \"NONE\")\n```\n\n### Functions\n\n```vim\nlen(mylist)\nempty(mylist)\n\nsort(list)\nlet sortedlist = sort(copy(list))\n\nsplit('hello there world', ' ')\n```\n\n### Concatenation\n\n```vim\nlet longlist = mylist + [5, 6]\nlet mylist += [7, 8]\n```\n\n### Sublists\n\n```vim\nlet shortlist = mylist[2:-1]\nlet shortlist = mylist[2:]     \" same\n\nlet shortlist = mylist[2:2]    \" one item\n```\n\n### Push\n\n```vim\nlet alist = [1, 2, 3]\nlet alist = add(alist, 4)\n```\n\n### Map\n\n```vim\ncall map(files, \"bufname(v:val)\")  \" use v:val for value\ncall filter(files, 'v:val != \"\"')\n```\n\nDictionaries\n------------\n\n### Dictionaries\n\n```vim\nlet colors = {\n  \\ \"apple\": \"red\",\n  \\ \"banana\": \"yellow\"\n}\n\necho colors[\"a\"]\necho get(colors, \"apple\")   \" suppress error\n```\n\nSee `:help dict`\n\n### Using dictionaries\n\n```vim\nremove(colors, \"apple\")\n```\n\n```vim\n\" :help E715\nif has_key(dict, 'foo')\nif empty(dict)\nkeys(dict)\nlen(dict)\n```\n\n```vim\nmax(dict)\nmin(dict)\n```\n\n```vim\ncount(dict, 'x')\nstring(dict)\n```\n\n```vim\nmap(dict, '<>> \" . v:val')\n```\n\n### Iteration\n\n```vim\nfor key in keys(mydict)\n  echo key . ': ' . mydict[key]\nendfor\n```\n\n### Prefixes\n\n```vim\nkeys(s:)\n```\n\nPrefixes (`s:`, `g:`, `l:`, etc) are actually dictionaries.\n\n### Extending\n\n```vim\n\" Extending with more\nlet extend(s:fruits, { ... })\n```\n\nCasting\n-------\n\n```vim\nstr2float(\"2.3\")\nstr2nr(\"3\")\nfloat2nr(\"3.14\")\n```\n\nNumbers\n-------\n\n### Numbers\n{: .-prime}\n\n```vim\nlet int = 1000\nlet int = 0xff\nlet int = 0755   \" octal\n```\n\nSee `:help Number`.\nSee: [Numbers](http://learnvimscriptthehardway.stevelosh.com/chapters/25.html)\n\n### Floats\n\n```vim\nlet fl = 100.1\nlet fl = 5.4e4\n```\n\nSee `:help Float`\n\n### Arithmetic\n\n```vim\n3 / 2     \"=> 1, integer division\n3 / 2.0   \"=> 1.5\n3 * 2.0   \"=> 6.0\n```\n\n### Math functions\n\n```vim\nsqrt(100)\nfloor(3.5)\nceil(3.3)\nabs(-3.4)\n\nsin() cos() tan()\nsinh() cosh() tanh()\nasin() acos() atan()\n```\n\nVim-isms\n--------\n\n### Execute a command\n\n```vim\nexecute \"vsplit\"\nexecute \"e \" . fnameescape(filename)\n```\n\nRuns an ex command you typically run with `:`. Also see `:help execute`.\nSee: [Execute a command](http://learnvimscriptthehardway.stevelosh.com/chapters/28.html)\n\n### Running keystrokes\n\n```vim\nnormal G\nnormal! G   \" skips key mappings\n\nexecute \"normal! gg/foo\\<cr>dd\"\n```\n\nUse `:normal` to execute keystrokes as if you're typing them in normal mode. Combine with `:execute` for special keystrokes.\nSee: [Running keystrokes](http://learnvimscriptthehardway.stevelosh.com/chapters/29.html)\n\n### Getting filenames\n\n```vim\necho expand(\"%\")      \" path/file.txt\necho expand(\"%:t\")    \" file.txt\necho expand(\"%:p:h\")  \" /home/you/path/file.txt\necho expand(\"%:r\")    \" path/file\necho expand(\"%:e\")    \" txt\n```\n\nSee `:help expand`\n\n### Silencing\n\n```vim\nsilent g/Aap/p\n```\n\nSuppresses output. See `:help silent`\n\n### Echo\n\n```vim\nechoerr 'oh it failed'\nechomsg 'hello there'\necho 'hello'\n\nechohl WarningMsg | echomsg \"=> \" . a:msg | echohl None\n```\n\n\n### Settings\n\n```vim\nset number\nset nonumber\nset number!     \" toggle\nset numberwidth=5\nset guioptions+=e\n```\n\n### Prompts\n\n```vim\nlet result = confirm(\"Sure?\")\nexecute \"confirm q\"\n```\n\n### Built-ins\n\n```vim\nhas(\"feature\")  \" :h feature-list\nexecutable(\"python\")\nglobpath(&rtp, \"syntax/c.vim\")\n\nexists(\"$ENV\")\nexists(\":command\")\nexists(\"variable\")\nexists(\"+option\")\nexists(\"g:...\")\n```\n\nMapping\n-------\n{: .-three-column}\n\n### Mapping commands\n\n```vim\nnmap\nvmap\nimap\nxmap\nnnoremap\nvnoremap\ninoremap\nxnoremap\n...\n```\n\n### Explanation\n\n```vim\n[nvixso](nore)map\n```\n\n```\n \u2502       \u2514 don't recurse\n \u2502\n \u2514 normal, visual, insert,\n   eX mode, select, operator-pending\n```\n{: .-setup}\n\n### Arguments\n\n| `<buffer>` | only in current buffer |\n| `<silent>` | no echo |\n| `<nowait>` | |\n\nSyntax\n------\n\n### Highlights\n\n```vim\nhi Comment\n  term=bold,underline\n  gui=bold\n  ctermfg=4\n  guifg=#80a0ff\n```\n\n### Filetype detection\n\n```vim\naugroup filetypedetect\n  au! BufNewFile,BufRead *.json setf javascript\naugroup END\n\nau Filetype markdown setlocal spell\n```\n\n### Conceal\n\n```vim\nset conceallevel=2\nsyn match newLine \"<br>\" conceal cchar=}\nhi newLine guifg=green\n```\n\n### Region conceal\n\n```vim\nsyn region inBold concealends matchgroup=bTag start=\"<b>\" end=\"</b>\"\nhi inBold gui=bold\nhi bTag guifg=blue\n```\n\n### Syntax\n\n```vim\nsyn match :name \":regex\" :flags\n\nsyn region Comment  start=\"/\\*\"  end=\"\\*/\"\nsyn region String   start=+\"+    end=+\"+\t skip=+\\\\\"+\n\nsyn cluster :name contains=:n1,:n2,:n3...\n\nflags:\n  keepend\n  oneline\n  nextgroup=\n  contains=\n  contained\n\nhi def link markdownH1 htmlH1\n```\n\n### Include guards\n\n```vim\nif exists('g:loaded_myplugin')\n  finish\nendif\n\n\" ...\n\nlet g:loaded_myplugin = 1\n```"}

field_body:
### Start hacking

```vim
let name = "John"
echo "Hello, " . name
```

You can either put this in a script (`script.vim`) and run it (`:source script.vim`), or you can type the commands individually in normal mode as `:let` and `:echo`.

### Learn by example

```vim
function! SuperTab()
  let l:part = strpart(getline('.'),col('.')-2,1)
  if (l:part =~ '^\W\?$')
      return "\<Tab>"
  else
      return "\<C-n>"
  endif
endfunction

imap <Tab> <C-R>=SuperTab()<CR>
```

[Here](http://www.vimbits.com/bits/46)'s another example with [functions](#functions), [variables](#variables) and [mapping](#mapping).

Variables
---------

### Defining
{: .-prime}

```vim
let var = "hello"
```

### Variable prefixes

```vim
let g:ack_options = '-s -H'    " g: global
let s:ack_program = 'ack'      " s: local (to script)
let l:foo = 'bar'              " l: local (to function)
```

The `s:` prefix is also available in function names. See `:help local-variables`

### Other prefixes

```vim
let w:foo = 'bar'    " w: window
let b:state = 'on'   " b: buffer
let t:state = 'off'  " t: tab
echo v:var           " v: vim special
```

```vim
let @/ = ''          " @  register (this clears last search pattern)
echo $PATH           " $  env
```

### Vim options

```vim
echo 'tabstop is ' . &tabstop
if &insertmode
echo &g:option
echo &l:option
```

Prefix Vim options with `&`

### Operators

```vim
a + b             " numbers only!
'hello ' . name   " concat
```

```vim
let var -= 2
let var += 5
let var .= 'string'   " concat
```

## Strings

### Strings

```vim
let str = "String"
let str = "String with \n newline"

let literal = 'literal, no \ escaping'
let literal = 'that''s enough'  " double '' => '

echo "result = " . re   " concatenation
```

Also see `:help literal-string` and `:help expr-quote`.
See: [Strings](http://learnvimscriptthehardway.stevelosh.com/chapters/26.html)

### String functions

```vim
strlen(str)    " length
len(str)       " same
strchars(str)  " character length

split("one two three")       "=> ['one', 'two', 'three']
split("one.two.three", '.')  "=> ['one', 'two', 'three']

join(['a', 'b'], ',')  "=> 'a,b'

tolower('Hello')
toupper('Hello')
```

Also see `:help functions`
See: [String functions](http://learnvimscriptthehardway.stevelosh.com/chapters/27.html)

Functions
---------

### Functions
{: .-prime}

```vim
" prefix with s: for local script-only functions
function! s:Initialize(cmd, args)
  " a: prefix for arguments
  echo "Command: " . a:cmd

  return 1
endfunction
```

See: [Functions](http://learnvimscriptthehardway.stevelosh.com/chapters/23.html)

### Overwriting
```vim
function f1()
  echo "f1"
endfunction


function! f1()
  echo "f1 overridden"
endfunction
```

If you define two functions with the same name, Vim will throw an error complaining that the function `f1` already exists. To overwrite the previous function with the same name, add a `!` after the function keyword.

### Namespacing

```vim
function! myplugin#hello()
```

### Calling functions

```vim
call s:Initialize()
call s:Initialize("hello")
```

### Consuming return values

```vim
echo "Result: " . s:Initialize()
```

### Abortable

```vim
function! myfunction() abort
endfunction
```

Aborts when an error occurs.

### Var arguments

```vim
function! infect(...)
  echo a:0    "=> 2
  echo a:1    "=> jake
  echo a:2    "=> bella

  for s in a:000  " a list
    echon ' ' . s
  endfor
endfunction

infect('jake', 'bella')
```

See `:help function-argument`.  See: [Var arguments](http://learnvimscriptthehardway.stevelosh.com/chapters/24.html)

Loops
-----

```vim
for s in list
  echo s
  continue  " jump to start of loop
  break     " breaks out of a loop
endfor
```

```vim
while x < 5
endwhile
```

Custom commands
---------------

### Custom commands
{: .-prime}

```vim
command! Save :set fo=want tw=80 nowrap
```

Custom commands start with uppercase letters. The `!` redefines a command if it already exists.

### Commands calling functions

```vim
command! Save call <SID>foo()
```
{: .-setup}

```vim
function! s:foo()
  ...
endfunction
```

### Commands with arguments

```vim
command! -nargs=? Save call script#foo(<args>)
```
{: .-setup}

| What | What |
| ---- | ---- |
| `-nargs=0` | 0 arguments, default |
| `-nargs=1` | 1 argument, includes spaces |
| `-nargs=?` | 0 or 1 argument |
| `-nargs=*` | 0+ arguments, space separated |
| `-nargs=+` | 1+ arguments, space reparated |

Flow
----

### Conditionals

```vim
let char = getchar()
if char == "\<LeftMouse>"
  " ...
elseif char == "\<RightMouse>"
  " ...
else
  " ...
endif
```

### Truthiness

```vim
if 1 | echo "true"  | endif
if 0 | echo "false" | endif
```

```vim
if 1       "=> 1 (true)
if 0       "=> 0 (false)
if "1"     "=> 1 (true)
if "456"   "=> 1 (true)
if "xfz"   "=> 0 (false)
```

No booleans. `0` is false, `1` is true.
See: [Truthiness](http://learnvimscriptthehardway.stevelosh.com/chapters/21.html)

### Operators

```vim
if 3 > 2
if a && b
if (a && b) || (c && d)
if !c
```

See `:help expression-syntax`.
See: [Operators](http://learnvimscriptthehardway.stevelosh.com/chapters/22.html)

### Strings

```vim
if name ==# 'John'     " case-sensitive
if name ==? 'John'     " case-insensitive
if name == 'John'      " depends on :set ignorecase

" also: is#, is?, >=#, >=?, and so on
```

### Identity operators

```vim
a is b
a isnot b
```

Checks if it's the same instance object.

### Regexp matches

```vim
"hello" =~ 'xx*'
"hello" !~ 'xx*'
"hello" =~ '\v<\d+>'
```

`\v` enables "extended" regex mode which allows word boundary (`<>`), `+`, and more.

### Single line

```vim
if empty(a:path) | return [] | endif
a ? b : c
```

Use `|` to join lines together.

### Boolean logic

```vim
if g:use_dispatch && s:has_dispatch
  ···
endif
```

Lists
-----

### Lists

```vim
let mylist = [1, two, 3, "four"]

let first = mylist[0]
let last  = mylist[-1]

" Suppresses errors
let second = get(mylist, 1)
let second = get(mylist, 1, "NONE")
```

### Functions

```vim
len(mylist)
empty(mylist)

sort(list)
let sortedlist = sort(copy(list))

split('hello there world', ' ')
```

### Concatenation

```vim
let longlist = mylist + [5, 6]
let mylist += [7, 8]
```

### Sublists

```vim
let shortlist = mylist[2:-1]
let shortlist = mylist[2:]     " same

let shortlist = mylist[2:2]    " one item
```

### Push

```vim
let alist = [1, 2, 3]
let alist = add(alist, 4)
```

### Map

```vim
call map(files, "bufname(v:val)")  " use v:val for value
call filter(files, 'v:val != ""')
```

Dictionaries
------------

### Dictionaries

```vim
let colors = {
  \ "apple": "red",
  \ "banana": "yellow"
}

echo colors["a"]
echo get(colors, "apple")   " suppress error
```

See `:help dict`

### Using dictionaries

```vim
remove(colors, "apple")
```

```vim
" :help E715
if has_key(dict, 'foo')
if empty(dict)
keys(dict)
len(dict)
```

```vim
max(dict)
min(dict)
```

```vim
count(dict, 'x')
string(dict)
```

```vim
map(dict, '<>> " . v:val')
```

### Iteration

```vim
for key in keys(mydict)
  echo key . ': ' . mydict[key]
endfor
```

### Prefixes

```vim
keys(s:)
```

Prefixes (`s:`, `g:`, `l:`, etc) are actually dictionaries.

### Extending

```vim
" Extending with more
let extend(s:fruits, { ... })
```

Casting
-------

```vim
str2float("2.3")
str2nr("3")
float2nr("3.14")
```

Numbers
-------

### Numbers
{: .-prime}

```vim
let int = 1000
let int = 0xff
let int = 0755   " octal
```

See `:help Number`.
See: [Numbers](http://learnvimscriptthehardway.stevelosh.com/chapters/25.html)

### Floats

```vim
let fl = 100.1
let fl = 5.4e4
```

See `:help Float`

### Arithmetic

```vim
3 / 2     "=> 1, integer division
3 / 2.0   "=> 1.5
3 * 2.0   "=> 6.0
```

### Math functions

```vim
sqrt(100)
floor(3.5)
ceil(3.3)
abs(-3.4)

sin() cos() tan()
sinh() cosh() tanh()
asin() acos() atan()
```

Vim-isms
--------

### Execute a command

```vim
execute "vsplit"
execute "e " . fnameescape(filename)
```

Runs an ex command you typically run with `:`. Also see `:help execute`.
See: [Execute a command](http://learnvimscriptthehardway.stevelosh.com/chapters/28.html)

### Running keystrokes

```vim
normal G
normal! G   " skips key mappings

execute "normal! gg/foo\<cr>dd"
```

Use `:normal` to execute keystrokes as if you're typing them in normal mode. Combine with `:execute` for special keystrokes.
See: [Running keystrokes](http://learnvimscriptthehardway.stevelosh.com/chapters/29.html)

### Getting filenames

```vim
echo expand("%")      " path/file.txt
echo expand("%:t")    " file.txt
echo expand("%:p:h")  " /home/you/path/file.txt
echo expand("%:r")    " path/file
echo expand("%:e")    " txt
```

See `:help expand`

### Silencing

```vim
silent g/Aap/p
```

Suppresses output. See `:help silent`

### Echo

```vim
echoerr 'oh it failed'
echomsg 'hello there'
echo 'hello'

echohl WarningMsg | echomsg "=> " . a:msg | echohl None
```


### Settings

```vim
set number
set nonumber
set number!     " toggle
set numberwidth=5
set guioptions+=e
```

### Prompts

```vim
let result = confirm("Sure?")
execute "confirm q"
```

### Built-ins

```vim
has("feature")  " :h feature-list
executable("python")
globpath(&rtp, "syntax/c.vim")

exists("$ENV")
exists(":command")
exists("variable")
exists("+option")
exists("g:...")
```

Mapping
-------
{: .-three-column}

### Mapping commands

```vim
nmap
vmap
imap
xmap
nnoremap
vnoremap
inoremap
xnoremap
...
```

### Explanation

```vim
[nvixso](nore)map
```

```
 │       └ don't recurse
 │
 └ normal, visual, insert,
   eX mode, select, operator-pending
```
{: .-setup}

### Arguments

| `<buffer>` | only in current buffer |
| `<silent>` | no echo |
| `<nowait>` | |

Syntax
------

### Highlights

```vim
hi Comment
  term=bold,underline
  gui=bold
  ctermfg=4
  guifg=#80a0ff
```

### Filetype detection

```vim
augroup filetypedetect
  au! BufNewFile,BufRead *.json setf javascript
augroup END

au Filetype markdown setlocal spell
```

### Conceal

```vim
set conceallevel=2
syn match newLine "<br>" conceal cchar=}
hi newLine guifg=green
```

### Region conceal

```vim
syn region inBold concealends matchgroup=bTag start="<b>" end="</b>"
hi inBold gui=bold
hi bTag guifg=blue
```

### Syntax

```vim
syn match :name ":regex" :flags

syn region Comment  start="/\*"  end="\*/"
syn region String   start=+"+    end=+"+	 skip=+\\"+

syn cluster :name contains=:n1,:n2,:n3...

flags:
  keepend
  oneline
  nextgroup=
  contains=
  contained

hi def link markdownH1 htmlH1
```

### Include guards

```vim
if exists('g:loaded_myplugin')
  finish
endif

" ...

let g:loaded_myplugin = 1
```


id: vimscript-snippets
git_filename: ./vimscript-snippets.md
format: md
field_title: Vimscript snippets
field_category: Vim
data:
{"title": "Vimscript snippets", "category": "Vim", "body": "### Bind function to key and command\n\n    command! YoFunctionHere call s:YoFunctionHere()\n    nnoremap <silent> x :call <SID>FunctionHere()<CR>\n    function! s:FunctionHere()\n    endfunction\n\n### Call a function in insert mode\n\n    inoremap X <C-R>=script#myfunction()<CR>\n    inoremap <F2> <C-R>=MyVimFunc()?'':''<CR>\n\n### Checking plugins\n\n    if globpath(&rtp, \"plugin/commentary.vim\") != \"\"\n\n## Autoload\n\n    \" autoload/hello.vim\n    if exists(\"g:hello_loaded\") | finish | endif\n    let g:hello_loaded=1\n\n    function hello#method()\n    endfunction\n\n    \" calling hello#method() will load only if autoload()\n\n## Misc\n\n### Version check\n\n    if version < 704\n      echom \"requires vim >= 7.4\"\n    endif"}

field_body:
### Bind function to key and command

    command! YoFunctionHere call s:YoFunctionHere()
    nnoremap <silent> x :call <SID>FunctionHere()<CR>
    function! s:FunctionHere()
    endfunction

### Call a function in insert mode

    inoremap X <C-R>=script#myfunction()<CR>
    inoremap <F2> <C-R>=MyVimFunc()?'':''<CR>

### Checking plugins

    if globpath(&rtp, "plugin/commentary.vim") != ""

## Autoload

    " autoload/hello.vim
    if exists("g:hello_loaded") | finish | endif
    let g:hello_loaded=1

    function hello#method()
    endfunction

    " calling hello#method() will load only if autoload()

## Misc

### Version check

    if version < 704
      echom "requires vim >= 7.4"
    endif


id: vimscript-functions
git_filename: ./vimscript-functions.md
format: md
field_title: Vimscript functions
field_category: Vim
data:
{"title": "Vimscript functions", "category": "Vim", "body": "## Dictionaries and lists\n\n### Dictionaries\n\n```vim\nlet colors = {\n  \\ \"apple\": \"red\",\n  \\ \"banana\": \"yellow\"\n}\n\necho colors[\"a\"]\necho get(colors, \"apple\")   \" suppress error\n\nremove(colors, \"apple\")\n\n\" :help E715\nif has_key(dict, 'foo')\nif empty(dict)\nkeys(dict)\nlen(dict)\n\nmax(dict)\nmin(dict)\n\ncount(dict, 'x')\nstring(dict)\n\nmap(dict, '<>> \" . v:val')\nextend(s:fruits, { ... })\n```\n\n```vim\nfor key in keys(mydict)\n  echo key . ': ' . mydict(key)\nendfor\n```\n\n### Lists\n\n```vim\nlet mylist = [1, two, 3, \"four\"]\n\nlet first = mylist[0]\nlet last  = mylist[-1]\n\n\" Suppresses errors\nlet second = get(mylist, 1)\nlet second = get(mylist, 1, \"NONE\")\n```\n\nFunctions\n---------\n\n### Buffer\n\n    line('.')             \" current line number\n    col('.')\n    col('$')\n\n    getline('.')          \" current line as a string\n    getline(1)            \" get line 1\n    getline(1, 5)         \" get lines 1-5\n    search('^$')          \" next blank line, returns line number\n    search('^$','n')      \" but don't move cursor\n\n    getcurpos()           \" [bufnum, lnum, col, off, curswant]\n    getpos('.')           \" [bufnum, lnum, col, off]\n\n    nextnonblank(1)       \" next non-blank line after line1\n    prevnonblank()\n\n### Marks\n\n    getpos(\"'a\")          \" position of a mark\n    setpos(\"'a\",...)\n\n    getpos(\"'<\")          \" position of selection start\n\n### Cursor\n\n    cursor(line,col)      \" moves cursor\n    cursor(line,col,off,curswant)\n\n    getcurpos()           \" returns [bufnum,line,col,off,curswant]\n\n### Expand\n\n    expand('<cword>')      \" word under cursor\n    expand('%')            \" current file\n\n    \" <cword>  current word on cursor\n    \" :p    full path\n    \" :h    head\n    \" :p:h  dirname   (/Users/rsc/project)\n    \" :t    tail      (file.txt)\n    \" :r    root      (file)\n    \" :e    extension (.txt)\n    \" see :h cmdline-special\n\n### Files\n\n    fnameescape('string')\n    fnamemodify('main.c', ':p:h')\n    fnamemodify(fname, ':e')   \" current file extension - see expand()\n    filereadable(fname)\n    getfsize('file.txt')\n    getcwd()\n\n    globpath(&rtp, \"plugin/commentary.vim\")\n\n### Math\n\n    fmod(9, 2)  \" modulus\n    abs(-0.5)\n    sqrt(9)\n\n    trunc(1.84)\n    floor(1.84)\n    ceil(1.84)\n    float2nr(3.14)\n\n### Casting\n\n    str2float('0.2')\n    str2nr('240')\n    str2nr('ff', '16')\n\n    string(0.3)\n\n### Type checking\n\n    type(var) == type(0)\n    type(var) == type(\"\")\n    type(var) == type(function(\"tr\"))\n    type(var) == type([])\n    type(var) == type({})\n    type(var) == type(0.0)\n\n### Date/time\n\n    strftime('%c')\n    strftime('%c',getftime('file.c'))\n\n### Strings\n\n    if a =~ '\\s*'\n    substitute(str, '.', 'x', 'g')\n    strpart(\"abcdef\", 3, 2)    \" == \"de\" (substring)\n    strpart(\"abcdef\", 3)       \" == \"def\"\n    stridx(\"abcdef\", \"e\")      \" == 4\n    strridx()                  \" reverse\n\n    matchstr('testing','test')  \" == 'test' (or '')\n    match('testing','test')     \" == 0\n    matchend('testing','test')  \" == 4\n    match('testing','\\ctest')   \" ignore case\n\n    split(str, '\\zs')           \" split into characters\n\n    strlen(str)\n    strchars()                  \" accounts for composing chars\n    strwidth()                  \" accounts for ambig characters\n    strdisplaywidth()           \" accounts for tab stops\n\n    toupper(str)\n    tolower(str)\n    tr('foo', '_-', '  ')\n\n### Syntax\n\n    synstack(line('.'),col('.'))   \" returns many\n    synID(line('.'),col('.'),1)    \" only one\n\n    synIDattr(id,\"bg\")\n    synIDattr(id,\"name\")\n    synIDtrans()\n\n    \" syntax stack\n    map(synstack(line('.'), col('.')), 'synIDattr(v:val, \"name\")')\n\n### Shell\n\n    system('ls '.shellescape(expand('%:h')))\n\n### Registers\n\n    getreg('*')\n    getregtype('*')     \" v(char), V(line) <ctrl-v>(block)\n\nComparisons\n-----------\n\n    if name ==# 'John'     \" case-sensitive\n    if name ==? 'John'     \" case-insensitive\n    if name == 'John'      \" depends on :set ignorecase\n    \" also: is#, is?, >=#, >=?, and so on\n\n    if \"hello\" =~ '.*'\n    if \"hello\" !~ '.*'\n\nExecuting\n---------\n\n### Running commands\n\n    normal 'ddahello'\n    exe 'normal ^C'  \" with expansions\n    wincmd J"}

field_body:
## Dictionaries and lists

### Dictionaries

```vim
let colors = {
  \ "apple": "red",
  \ "banana": "yellow"
}

echo colors["a"]
echo get(colors, "apple")   " suppress error

remove(colors, "apple")

" :help E715
if has_key(dict, 'foo')
if empty(dict)
keys(dict)
len(dict)

max(dict)
min(dict)

count(dict, 'x')
string(dict)

map(dict, '<>> " . v:val')
extend(s:fruits, { ... })
```

```vim
for key in keys(mydict)
  echo key . ': ' . mydict(key)
endfor
```

### Lists

```vim
let mylist = [1, two, 3, "four"]

let first = mylist[0]
let last  = mylist[-1]

" Suppresses errors
let second = get(mylist, 1)
let second = get(mylist, 1, "NONE")
```

Functions
---------

### Buffer

    line('.')             " current line number
    col('.')
    col('$')

    getline('.')          " current line as a string
    getline(1)            " get line 1
    getline(1, 5)         " get lines 1-5
    search('^$')          " next blank line, returns line number
    search('^$','n')      " but don't move cursor

    getcurpos()           " [bufnum, lnum, col, off, curswant]
    getpos('.')           " [bufnum, lnum, col, off]

    nextnonblank(1)       " next non-blank line after line1
    prevnonblank()

### Marks

    getpos("'a")          " position of a mark
    setpos("'a",...)

    getpos("'<")          " position of selection start

### Cursor

    cursor(line,col)      " moves cursor
    cursor(line,col,off,curswant)

    getcurpos()           " returns [bufnum,line,col,off,curswant]

### Expand

    expand('<cword>')      " word under cursor
    expand('%')            " current file

    " <cword>  current word on cursor
    " :p    full path
    " :h    head
    " :p:h  dirname   (/Users/rsc/project)
    " :t    tail      (file.txt)
    " :r    root      (file)
    " :e    extension (.txt)
    " see :h cmdline-special

### Files

    fnameescape('string')
    fnamemodify('main.c', ':p:h')
    fnamemodify(fname, ':e')   " current file extension - see expand()
    filereadable(fname)
    getfsize('file.txt')
    getcwd()

    globpath(&rtp, "plugin/commentary.vim")

### Math

    fmod(9, 2)  " modulus
    abs(-0.5)
    sqrt(9)

    trunc(1.84)
    floor(1.84)
    ceil(1.84)
    float2nr(3.14)

### Casting

    str2float('0.2')
    str2nr('240')
    str2nr('ff', '16')

    string(0.3)

### Type checking

    type(var) == type(0)
    type(var) == type("")
    type(var) == type(function("tr"))
    type(var) == type([])
    type(var) == type({})
    type(var) == type(0.0)

### Date/time

    strftime('%c')
    strftime('%c',getftime('file.c'))

### Strings

    if a =~ '\s*'
    substitute(str, '.', 'x', 'g')
    strpart("abcdef", 3, 2)    " == "de" (substring)
    strpart("abcdef", 3)       " == "def"
    stridx("abcdef", "e")      " == 4
    strridx()                  " reverse

    matchstr('testing','test')  " == 'test' (or '')
    match('testing','test')     " == 0
    matchend('testing','test')  " == 4
    match('testing','\ctest')   " ignore case

    split(str, '\zs')           " split into characters

    strlen(str)
    strchars()                  " accounts for composing chars
    strwidth()                  " accounts for ambig characters
    strdisplaywidth()           " accounts for tab stops

    toupper(str)
    tolower(str)
    tr('foo', '_-', '  ')

### Syntax

    synstack(line('.'),col('.'))   " returns many
    synID(line('.'),col('.'),1)    " only one

    synIDattr(id,"bg")
    synIDattr(id,"name")
    synIDtrans()

    " syntax stack
    map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")')

### Shell

    system('ls '.shellescape(expand('%:h')))

### Registers

    getreg('*')
    getregtype('*')     " v(char), V(line) <ctrl-v>(block)

Comparisons
-----------

    if name ==# 'John'     " case-sensitive
    if name ==? 'John'     " case-insensitive
    if name == 'John'      " depends on :set ignorecase
    " also: is#, is?, >=#, >=?, and so on

    if "hello" =~ '.*'
    if "hello" !~ '.*'

Executing
---------

### Running commands

    normal 'ddahello'
    exe 'normal ^C'  " with expansions
    wincmd J


id: vim
git_filename: ./vim.md
format: md
field_title: Vim
field_category: Vim
field_tags: Featured
field_updated: 2020-07-05
field_updated___timezone: UTC
data:
{"title": "Vim", "category": "Vim", "tags": ["Featured"], "updated": "2020-07-05", "weight": -10, "body": "## Getting started\n{: .-three-column}\n\n### Introduction\n\n [Vim](http://www.vim.org/) is a very efficient text editor. This reference was made for Vim 8.0.   \n\n For shortcut notation, see `:help key-notation`.\n\n### Exiting\n{: .-prime}\n\n| Shortcut       | Description                      |\n| -------------- | -------------------------------- |\n| `:q`           | Close file                       |\n| `:qa`          | Close all files                  |\n| ---            | ---                              |\n| `:w`           | Save                             |\n| `:wq` _/_ `:x` | Save and close file              |\n| ---            | ---                              |\n| `ZZ`           | Save and quit                    |\n| `:q!` _/_ `ZQ`           | Quit without checking changes    |\n{: .-shortcuts}\n\n### Exiting insert mode\n\n| Shortcut          | Description |\n| ---               | ---         |\n| `Esc` _/_ `<C-[>` | Exit insert mode |\n| `<C-C>`           | Exit insert mode, and abort current command |\n{: .-shortcuts}\n\n## Editing\n{: .-three-column}\n\n### Editing\n\n| Shortcut | Description                         |\n| ---      | ---                                 |\n| `a`      | Append                              |\n| `A`      | Append from end of line             |\n| `i`      | Insert                              |\n| `o`      | Next line                           |\n| `O`      | Previous line                       |\n| ---      | ---                                 |\n| `s`      | Delete char and insert              |\n| `S`      | Delete line and insert              |\n| `C`      | Delete until end of line and insert |\n| ---      | ---                                 |\n| `r`      | Replace one character               |\n| `R`      | Enter Replace mode                  |\n| ---      | ---                                 |\n| `u`      | Undo changes                        |\n| `<C-R>`  | Redo changes                        |\n{: .-shortcuts}\n\n### Clipboard\n\n| Shortcut        | Description                 |\n| ---             | ---                         |\n| `x`             | Delete character            |\n| ---             | ---                         |\n| `dd`            | Delete line _(Cut)_         |\n| `yy`            | Yank line _(Copy)_          |\n| ---             | ---                         |\n| `p`             | Paste                       |\n| `P`             | Paste before                |\n| ---             | ---                         |\n| `\"*p` _/_ `\"+p` | Paste from system clipboard |\n| `\"*y` _/_ `\"+y` | Paste to system clipboard   |\n{: .-shortcuts}\n\n### Visual mode\n\n| Shortcut | Description             |\n| ---      | ---                     |\n| `v`      | Enter visual mode       |\n| `V`      | Enter visual line mode  |\n| `<C-V>`  | Enter visual block mode |\n{: .-shortcuts}\n\n#### In visual mode\n\n| Shortcut    | Description             |\n| ---         | ---                     |\n| `d` _/_ `x` | Delete selection        |\n| `s`         | Replace selection       |\n| `y`         | Yank selection _(Copy)_ |\n{: .-shortcuts}\n\nSee [Operators](#operators) for other things you can do.\n\n### Find & Replace\n\n| Shortcut      | Description                            |\n| ---           | ---                                    |\n| :%s/foo/bar/g | Replace foo with bar in whole document |\n\n## Navigating\n{: .-three-column}\n\n### Directions\n\n| Shortcut            | Description       |\n| ---                 | ---               |\n| `h` `j` `k` `l`     | Arrow keys        |\n| `<C-U>` _/_ `<C-D>` | Half-page up/down |\n| `<C-B>` _/_ `<C-F>` | Page up/down      |\n{: .-shortcuts}\n\n### Words\n\n| Shortcut     | Description               |\n| ---          | ---                       |\n| `b` _/_ `w`  | Previous/next word        |\n| `ge` _/_ `e` | Previous/next end of word |\n{: .-shortcuts}\n\n### Line\n\n| Shortcut     | Description                        |\n| ---          | ---                                |\n| `0` _(zero)_ | Start of line                      |\n| `^`          | Start of line _(after whitespace)_ |\n| `$`          | End of line                        |\n{: .-shortcuts}\n\n### Character\n\n| `fc`  | Go forward to character `c`  |\n| `Fc`  | Go backward to character `c` |\n{: .-shortcuts}\n\n### Document\n\n| Shortcut    | Description              |\n| ---         | ---                      |\n| `gg`        | First line               |\n| `G`         | Last line                |\n| `:{number}` | Go to line `{number}`    |\n| `{number}G` | Go to line `{number}`    |\n| `{number}j` | Go down `{number}` lines |\n| `{number}k` | Go up `{number}` lines   |\n{: .-shortcuts}\n\n### Window\n\n| Shortcut | Description              |\n| ---      | ---                      |\n| `zz`     | Center this line         |\n| `zt`     | Top this line            |\n| `zb`     | Bottom this line         |\n| `H`      | Move to top of screen    |\n| `M`      | Move to middle of screen |\n| `L`      | Move to bottom of screen |\n{: .-shortcuts}\n\n### Search\n\n| Shortcut  | Description                         |\n| ---       | ---                                 |\n| `n`       | Next matching search pattern        |\n| `N`       | Previous match                      |\n| `*`       | Next whole word under cursor        |\n| `#`       | Previous whole word under cursor    |\n{: .-shortcuts}\n\nOperators\n---------\n{: .-three-column}\n\n### Usage\n{: .-prime}\n\nOperators let you operate in a range of text (defined by *motion*). These are performed in normal mode.\n{: .-setup}\n\n| `d`      | `w`    |\n| Operator | Motion |\n{: .-css-breakdown}\n\n### Operators list\n\n| Shortcut | Description                     |\n| ---      | ---                             |\n| `d`      | Delete                          |\n| `y`      | Yank _(copy)_                   |\n| `c`      | Change _(delete then insert)_   |\n| ---      | ---                             |\n| `>`      | Indent right                    |\n| `<`      | Indent left                     |\n| `=`      | Autoindent                      |\n| ---      | ---                             |\n| `g~`     | Swap case                       |\n| `gU`     | Uppercase                       |\n| `gu`     | Lowercase                       |\n| ---      | ---                             |\n| `!`      | Filter through external program |\n{: .-shortcuts}\n\nSee `:help operator`\n\n### Examples\n\nCombine operators with *motions* to use them.\n{: .-setup}\n\n| Shortcut               | Description                               |\n| ---                    | ---                                       |\n| `d`_d_                 | _(repeat the letter)_ Delete current line |\n| `d`_w_                 | Delete to next word                       |\n| `d`_b_                 | Delete to beginning of word               |\n| _2_`dd`                | Delete 2 lines                            |\n| `d`_ip_                | Delete a text object _(inside paragraph)_ |\n| _(in visual mode)_ `d` | Delete selection                          |\n\nSee: `:help motion.txt`\n\nText objects\n------------\n{: .-three-column}\n\n### Usage\n{: .-prime}\n\nText objects let you operate (with an *operator*) in or around text blocks (*objects*).\n{: .-setup}\n\n| `v`      | `i`                  | `p`         |\n| Operator | [i]nside or [a]round | Text object |\n{: .-css-breakdown}\n\n### Text objects\n\n| Shortcut               | Description           |\n| ---                    | ---                   |\n| `p`                    | Paragraph             |\n| `w`                    | Word                  |\n| `s`                    | Sentence              |\n| ---                    | ---                   |\n| `[` `(` `{` `<`        | A [], (), or {} block |\n| `'` `\"` <code>`</code> | A quoted string       |\n| ---                    | ---                   |\n| `b`                    | A block [(            |\n| `B`                    | A block in [{         |\n| `t`                    | A XML tag block       |\n{: .-shortcuts}\n\n### Examples\n\n| Shortcut    | Description                        |\n| ---         | ---                                |\n| `vip`       | Select paragraph                   |\n| `vipipipip` | Select more                        |\n| ---         | ---                                |\n| `yip`       | Yank inner paragraph               |\n| `yap`       | Yank paragraph (including newline) |\n| ---         | ---                                |\n| `dip`       | Delete inner paragraph             |\n| `cip`       | Change inner paragraph             |\n{: .-shortcuts}\n\nSee [Operators](#operators) for other things you can do.\n\n### Diff\n \n| Shortcut                             | Description                              |\n| ---                                  | ---                                      |\n| `gvimdiff file1 file2 [file3]`       | See differences between files, in HMI    |\n \n\nMisc\n----\n\n### Tab pages\n\n| Shortcut              | Description                     |\n| ---                   | ---                             |\n| `:tabedit [file]`     | Edit file in a new tab          |\n| `:tabfind [file]`     | Open file if exists in new tab  |\n| `:tabclose`           | Close current tab               |\n| `:tabs`               | List all tabs                   | \n| `:tabfirst`           | Go to first tab                 |\n| `:tablast`            | Go to last tab                  |\n| `:tabn    `           | Go to next tab                  |\n| `:tabp    `           | Go to previous tab              |\n\n### Folds\n\n| Shortcut      | Description                  |\n| ---           | ---                          |\n| `zo` _/_ `zO` | Open                         |\n| `zc` _/_ `zC` | Close                        |\n| `za` _/_ `zA` | Toggle                       |\n| ---           | ---                          |\n| `zv`          | Open folds for this line     |\n| ---           | ---                          |\n| `zM`          | Close all                    |\n| `zR`          | Open all                     |\n| ---           | ---                          |\n| `zm`          | Fold more _(foldlevel += 1)_ |\n| `zr`          | Fold less _(foldlevel -= 1)_ |\n| ---           | ---                          |\n| `zx`          | Update folds                 |\n{: .-shortcuts}\n\nUppercase ones are recursive (eg, `zO` is open recursively).\n\n### Navigation\n\n| Shortcut            | Description                |\n| ---                 | ---                        |\n| `%`                 | Nearest/matching `{[()]}`  |\n| `[(` `[{` `[<`      | Previous `(` or `{` or `<` |\n| `])`                | Next                       |\n| ---                 | ---                        |\n| `[m`                | Previous method start      |\n| `[M`                | Previous method end        |\n{: .-shortcuts}\n\n### Jumping\n\n| Shortcut | Description                  |\n| ---      | ---                          |\n| `<C-O>`  | Go back to previous location |\n| `<C-I>`  | Go forward                   |\n| ---      | ---                          |\n| `gf`     | Go to file in cursor         |\n{: .-shortcuts}\n\n### Counters\n\n| Shortcut | Description      |\n| ---      | ---              |\n| `<C-A>`  | Increment number |\n| `<C-X>`  | Decrement        |\n{: .-shortcuts}\n\n### Windows\n\n| `z{height}<Cr>` | Resize pane to `{height}` lines tall |\n\n### Tags\n\n| Shortcut              | Description                                     |\n| ---                   | ---                                             |\n| `:tag Classname`      | Jump to first definition of Classname           |\n| ---                   | ---                                             |\n| `<C-]>`               | Jump to definition                              |\n| `g]`                  | See all definitions                             |\n| `<C-T>`               | Go back to last tag                             |\n| `<C-O> <C-I>`         | Back/forward                                    |\n| ---                   | ---                                             |\n| `:tselect Classname`  | Find definitions of Classname                   |\n| `:tjump Classname`    | Find definitions of Classname (auto-select 1st) |\n{: .-shortcuts}\n\n### Case\n\n| Shortcut | Description                          |\n| ---      | ---                                  |\n| `~`      | Toggle case (Case => cASE)           |\n| `gU`     | Uppercase                            |\n| `gu`     | Lowercase                            |\n| ---      | ---                                  |\n| `gUU`    | Uppercase current line (also `gUgU`) |\n| `guu`    | Lowercase current line (also `gugu`) |\n{: .-shortcuts}\n\nDo these in visual or normal mode.\n\n### Marks\n\n| Shortcut           | Description                                          |\n| ---                | ---                                                  |\n| <code>`^</code>    | Last position of cursor in insert mode               |\n| <code>`.</code>    | Last change in current buffer                        |\n| <code>`\"</code>    | Last exited current buffer                           |\n| <code>`0</code>    | In last file edited                                  |\n| <code>''</code>    | Back to line in current buffer where jumped from     |\n| <code>``</code>    | Back to position in current buffer where jumped from |\n| <code>`[</code>    | To beginning of previously changed or yanked text    |\n| <code>`]</code>    | To end of previously changed or yanked text          |\n| <code>`&lt;</code> | To beginning of last visual selection                |\n| <code>`&gt;</code> | To end of last visual selection                      |\n| ---                | ---                                                  |\n| `ma`               | Mark this cursor position as `a`                     |\n| <code>`a</code>    | Jump to the cursor position `a`                      |\n| `'a`               | Jump to the beginning of the line with position `a`  |\n| <code>d'a</code>   | Delete from current line to line of mark `a`         |\n| <code>d`a</code>   | Delete from current position to position of mark `a` |\n| <code>c'a</code>   | Change text from current line to line of `a`         |\n| <code>y`a</code>   | Yank text from current position to position of `a`   |\n| ---                | ---                                                  |\n| `:marks`           | List all current marks                               |\n| `:delm a`          | Delete mark `a`                                      |\n| `:delm a-d`        | Delete marks `a`, `b`, `c`, `d`                      |\n| `:delm abc`        | Delete marks `a`, `b`, `c`                           |\n{: .-shortcuts}\n\n### Misc\n\n| Shortcut   | Description                                       |\n| ---        | ---                                               |\n| `.`        | Repeat last command                               |\n| `]p`       | Paste under the current indentation level         |\n| ---        | ---                                               |\n| `:set ff=unix` | Convert Windows line endings to Unix line endings |\n{: .-shortcuts}\n\n### Command line\n\n| Shortcut     | Description                               |\n| ---          | ---                                       |\n| `<C-R><C-W>` | Insert current word into the command line |\n| `<C-R>\"`     | Paste from \" register                     |\n| `<C-X><C-F>` | Auto-completion of path in insert mode    |\n{: .-shortcuts}\n\n### Text alignment\n\n    :center [width]\n    :right [width]\n    :left\n\nSee `:help formatting`\n\n### Calculator\n\n| Shortcut      | Description                               |\n| ---           | ---                                       |\n| `<C-R>=128/2` | Shows the result of the division : '64'   |\n\nDo this in insert mode.\n\n### Exiting with an error\n\n    :cq\n    :cquit\n\nWorks like `:qa`, but throws an error. Great for aborting Git commands.\n\n\n### Spell checking\n\n| Shortcut                     | Description                                             |\n| ---                          | ---                                                     |\n| `:set spell spelllang=en_us` | Turn on US English spell checking                       |\n| `]s`                         | Move to next misspelled word after the cursor           |\n| `[s`                         | Move to previous misspelled word before the cursor      |\n| `z=`                         | Suggest spellings for the word under/after the cursor   |\n| `zg`                         | Add word to spell list                                  |\n| `zw`                         | Mark word as bad/misspelling                            |\n| `zu` / `C-X (Insert Mode)`   | Suggest words for bad word under cursor from spellfile  |\n{: .-shortcuts}\n\nSee `:help spell`\n\n\nAlso see\n--------\n\n- [Vim cheatsheet](https://vim.rtorr.com/) _(vim.rotrr.com)_\n- [Vim documentation](http://vimdoc.sourceforge.net/htmldoc/) _(vimdoc.sourceforge.net)_\n- [Interactive Vim tutorial](http://openvim.com/) _(openvim.com)_"}

field_body:
## Getting started
{: .-three-column}

### Introduction

 [Vim](http://www.vim.org/) is a very efficient text editor. This reference was made for Vim 8.0.   

 For shortcut notation, see `:help key-notation`.

### Exiting
{: .-prime}

| Shortcut       | Description                      |
| -------------- | -------------------------------- |
| `:q`           | Close file                       |
| `:qa`          | Close all files                  |
| ---            | ---                              |
| `:w`           | Save                             |
| `:wq` _/_ `:x` | Save and close file              |
| ---            | ---                              |
| `ZZ`           | Save and quit                    |
| `:q!` _/_ `ZQ`           | Quit without checking changes    |
{: .-shortcuts}

### Exiting insert mode

| Shortcut          | Description |
| ---               | ---         |
| `Esc` _/_ `<C-[>` | Exit insert mode |
| `<C-C>`           | Exit insert mode, and abort current command |
{: .-shortcuts}

## Editing
{: .-three-column}

### Editing

| Shortcut | Description                         |
| ---      | ---                                 |
| `a`      | Append                              |
| `A`      | Append from end of line             |
| `i`      | Insert                              |
| `o`      | Next line                           |
| `O`      | Previous line                       |
| ---      | ---                                 |
| `s`      | Delete char and insert              |
| `S`      | Delete line and insert              |
| `C`      | Delete until end of line and insert |
| ---      | ---                                 |
| `r`      | Replace one character               |
| `R`      | Enter Replace mode                  |
| ---      | ---                                 |
| `u`      | Undo changes                        |
| `<C-R>`  | Redo changes                        |
{: .-shortcuts}

### Clipboard

| Shortcut        | Description                 |
| ---             | ---                         |
| `x`             | Delete character            |
| ---             | ---                         |
| `dd`            | Delete line _(Cut)_         |
| `yy`            | Yank line _(Copy)_          |
| ---             | ---                         |
| `p`             | Paste                       |
| `P`             | Paste before                |
| ---             | ---                         |
| `"*p` _/_ `"+p` | Paste from system clipboard |
| `"*y` _/_ `"+y` | Paste to system clipboard   |
{: .-shortcuts}

### Visual mode

| Shortcut | Description             |
| ---      | ---                     |
| `v`      | Enter visual mode       |
| `V`      | Enter visual line mode  |
| `<C-V>`  | Enter visual block mode |
{: .-shortcuts}

#### In visual mode

| Shortcut    | Description             |
| ---         | ---                     |
| `d` _/_ `x` | Delete selection        |
| `s`         | Replace selection       |
| `y`         | Yank selection _(Copy)_ |
{: .-shortcuts}

See [Operators](#operators) for other things you can do.

### Find & Replace

| Shortcut      | Description                            |
| ---           | ---                                    |
| :%s/foo/bar/g | Replace foo with bar in whole document |

## Navigating
{: .-three-column}

### Directions

| Shortcut            | Description       |
| ---                 | ---               |
| `h` `j` `k` `l`     | Arrow keys        |
| `<C-U>` _/_ `<C-D>` | Half-page up/down |
| `<C-B>` _/_ `<C-F>` | Page up/down      |
{: .-shortcuts}

### Words

| Shortcut     | Description               |
| ---          | ---                       |
| `b` _/_ `w`  | Previous/next word        |
| `ge` _/_ `e` | Previous/next end of word |
{: .-shortcuts}

### Line

| Shortcut     | Description                        |
| ---          | ---                                |
| `0` _(zero)_ | Start of line                      |
| `^`          | Start of line _(after whitespace)_ |
| `$`          | End of line                        |
{: .-shortcuts}

### Character

| `fc`  | Go forward to character `c`  |
| `Fc`  | Go backward to character `c` |
{: .-shortcuts}

### Document

| Shortcut    | Description              |
| ---         | ---                      |
| `gg`        | First line               |
| `G`         | Last line                |
| `:{number}` | Go to line `{number}`    |
| `{number}G` | Go to line `{number}`    |
| `{number}j` | Go down `{number}` lines |
| `{number}k` | Go up `{number}` lines   |
{: .-shortcuts}

### Window

| Shortcut | Description              |
| ---      | ---                      |
| `zz`     | Center this line         |
| `zt`     | Top this line            |
| `zb`     | Bottom this line         |
| `H`      | Move to top of screen    |
| `M`      | Move to middle of screen |
| `L`      | Move to bottom of screen |
{: .-shortcuts}

### Search

| Shortcut  | Description                         |
| ---       | ---                                 |
| `n`       | Next matching search pattern        |
| `N`       | Previous match                      |
| `*`       | Next whole word under cursor        |
| `#`       | Previous whole word under cursor    |
{: .-shortcuts}

Operators
---------
{: .-three-column}

### Usage
{: .-prime}

Operators let you operate in a range of text (defined by *motion*). These are performed in normal mode.
{: .-setup}

| `d`      | `w`    |
| Operator | Motion |
{: .-css-breakdown}

### Operators list

| Shortcut | Description                     |
| ---      | ---                             |
| `d`      | Delete                          |
| `y`      | Yank _(copy)_                   |
| `c`      | Change _(delete then insert)_   |
| ---      | ---                             |
| `>`      | Indent right                    |
| `<`      | Indent left                     |
| `=`      | Autoindent                      |
| ---      | ---                             |
| `g~`     | Swap case                       |
| `gU`     | Uppercase                       |
| `gu`     | Lowercase                       |
| ---      | ---                             |
| `!`      | Filter through external program |
{: .-shortcuts}

See `:help operator`

### Examples

Combine operators with *motions* to use them.
{: .-setup}

| Shortcut               | Description                               |
| ---                    | ---                                       |
| `d`_d_                 | _(repeat the letter)_ Delete current line |
| `d`_w_                 | Delete to next word                       |
| `d`_b_                 | Delete to beginning of word               |
| _2_`dd`                | Delete 2 lines                            |
| `d`_ip_                | Delete a text object _(inside paragraph)_ |
| _(in visual mode)_ `d` | Delete selection                          |

See: `:help motion.txt`

Text objects
------------
{: .-three-column}

### Usage
{: .-prime}

Text objects let you operate (with an *operator*) in or around text blocks (*objects*).
{: .-setup}

| `v`      | `i`                  | `p`         |
| Operator | [i]nside or [a]round | Text object |
{: .-css-breakdown}

### Text objects

| Shortcut               | Description           |
| ---                    | ---                   |
| `p`                    | Paragraph             |
| `w`                    | Word                  |
| `s`                    | Sentence              |
| ---                    | ---                   |
| `[` `(` `{` `<`        | A [], (), or {} block |
| `'` `"` <code>`</code> | A quoted string       |
| ---                    | ---                   |
| `b`                    | A block [(            |
| `B`                    | A block in [{         |
| `t`                    | A XML tag block       |
{: .-shortcuts}

### Examples

| Shortcut    | Description                        |
| ---         | ---                                |
| `vip`       | Select paragraph                   |
| `vipipipip` | Select more                        |
| ---         | ---                                |
| `yip`       | Yank inner paragraph               |
| `yap`       | Yank paragraph (including newline) |
| ---         | ---                                |
| `dip`       | Delete inner paragraph             |
| `cip`       | Change inner paragraph             |
{: .-shortcuts}

See [Operators](#operators) for other things you can do.

### Diff
 
| Shortcut                             | Description                              |
| ---                                  | ---                                      |
| `gvimdiff file1 file2 [file3]`       | See differences between files, in HMI    |
 

Misc
----

### Tab pages

| Shortcut              | Description                     |
| ---                   | ---                             |
| `:tabedit [file]`     | Edit file in a new tab          |
| `:tabfind [file]`     | Open file if exists in new tab  |
| `:tabclose`           | Close current tab               |
| `:tabs`               | List all tabs                   | 
| `:tabfirst`           | Go to first tab                 |
| `:tablast`            | Go to last tab                  |
| `:tabn    `           | Go to next tab                  |
| `:tabp    `           | Go to previous tab              |

### Folds

| Shortcut      | Description                  |
| ---           | ---                          |
| `zo` _/_ `zO` | Open                         |
| `zc` _/_ `zC` | Close                        |
| `za` _/_ `zA` | Toggle                       |
| ---           | ---                          |
| `zv`          | Open folds for this line     |
| ---           | ---                          |
| `zM`          | Close all                    |
| `zR`          | Open all                     |
| ---           | ---                          |
| `zm`          | Fold more _(foldlevel += 1)_ |
| `zr`          | Fold less _(foldlevel -= 1)_ |
| ---           | ---                          |
| `zx`          | Update folds                 |
{: .-shortcuts}

Uppercase ones are recursive (eg, `zO` is open recursively).

### Navigation

| Shortcut            | Description                |
| ---                 | ---                        |
| `%`                 | Nearest/matching `{[()]}`  |
| `[(` `[{` `[<`      | Previous `(` or `{` or `<` |
| `])`                | Next                       |
| ---                 | ---                        |
| `[m`                | Previous method start      |
| `[M`                | Previous method end        |
{: .-shortcuts}

### Jumping

| Shortcut | Description                  |
| ---      | ---                          |
| `<C-O>`  | Go back to previous location |
| `<C-I>`  | Go forward                   |
| ---      | ---                          |
| `gf`     | Go to file in cursor         |
{: .-shortcuts}

### Counters

| Shortcut | Description      |
| ---      | ---              |
| `<C-A>`  | Increment number |
| `<C-X>`  | Decrement        |
{: .-shortcuts}

### Windows

| `z{height}<Cr>` | Resize pane to `{height}` lines tall |

### Tags

| Shortcut              | Description                                     |
| ---                   | ---                                             |
| `:tag Classname`      | Jump to first definition of Classname           |
| ---                   | ---                                             |
| `<C-]>`               | Jump to definition                              |
| `g]`                  | See all definitions                             |
| `<C-T>`               | Go back to last tag                             |
| `<C-O> <C-I>`         | Back/forward                                    |
| ---                   | ---                                             |
| `:tselect Classname`  | Find definitions of Classname                   |
| `:tjump Classname`    | Find definitions of Classname (auto-select 1st) |
{: .-shortcuts}

### Case

| Shortcut | Description                          |
| ---      | ---                                  |
| `~`      | Toggle case (Case => cASE)           |
| `gU`     | Uppercase                            |
| `gu`     | Lowercase                            |
| ---      | ---                                  |
| `gUU`    | Uppercase current line (also `gUgU`) |
| `guu`    | Lowercase current line (also `gugu`) |
{: .-shortcuts}

Do these in visual or normal mode.

### Marks

| Shortcut           | Description                                          |
| ---                | ---                                                  |
| <code>`^</code>    | Last position of cursor in insert mode               |
| <code>`.</code>    | Last change in current buffer                        |
| <code>`"</code>    | Last exited current buffer                           |
| <code>`0</code>    | In last file edited                                  |
| <code>''</code>    | Back to line in current buffer where jumped from     |
| <code>``</code>    | Back to position in current buffer where jumped from |
| <code>`[</code>    | To beginning of previously changed or yanked text    |
| <code>`]</code>    | To end of previously changed or yanked text          |
| <code>`&lt;</code> | To beginning of last visual selection                |
| <code>`&gt;</code> | To end of last visual selection                      |
| ---                | ---                                                  |
| `ma`               | Mark this cursor position as `a`                     |
| <code>`a</code>    | Jump to the cursor position `a`                      |
| `'a`               | Jump to the beginning of the line with position `a`  |
| <code>d'a</code>   | Delete from current line to line of mark `a`         |
| <code>d`a</code>   | Delete from current position to position of mark `a` |
| <code>c'a</code>   | Change text from current line to line of `a`         |
| <code>y`a</code>   | Yank text from current position to position of `a`   |
| ---                | ---                                                  |
| `:marks`           | List all current marks                               |
| `:delm a`          | Delete mark `a`                                      |
| `:delm a-d`        | Delete marks `a`, `b`, `c`, `d`                      |
| `:delm abc`        | Delete marks `a`, `b`, `c`                           |
{: .-shortcuts}

### Misc

| Shortcut   | Description                                       |
| ---        | ---                                               |
| `.`        | Repeat last command                               |
| `]p`       | Paste under the current indentation level         |
| ---        | ---                                               |
| `:set ff=unix` | Convert Windows line endings to Unix line endings |
{: .-shortcuts}

### Command line

| Shortcut     | Description                               |
| ---          | ---                                       |
| `<C-R><C-W>` | Insert current word into the command line |
| `<C-R>"`     | Paste from " register                     |
| `<C-X><C-F>` | Auto-completion of path in insert mode    |
{: .-shortcuts}

### Text alignment

    :center [width]
    :right [width]
    :left

See `:help formatting`

### Calculator

| Shortcut      | Description                               |
| ---           | ---                                       |
| `<C-R>=128/2` | Shows the result of the division : '64'   |

Do this in insert mode.

### Exiting with an error

    :cq
    :cquit

Works like `:qa`, but throws an error. Great for aborting Git commands.


### Spell checking

| Shortcut                     | Description                                             |
| ---                          | ---                                                     |
| `:set spell spelllang=en_us` | Turn on US English spell checking                       |
| `]s`                         | Move to next misspelled word after the cursor           |
| `[s`                         | Move to previous misspelled word before the cursor      |
| `z=`                         | Suggest spellings for the word under/after the cursor   |
| `zg`                         | Add word to spell list                                  |
| `zw`                         | Mark word as bad/misspelling                            |
| `zu` / `C-X (Insert Mode)`   | Suggest words for bad word under cursor from spellfile  |
{: .-shortcuts}

See `:help spell`


Also see
--------

- [Vim cheatsheet](https://vim.rtorr.com/) _(vim.rotrr.com)_
- [Vim documentation](http://vimdoc.sourceforge.net/htmldoc/) _(vimdoc.sourceforge.net)_
- [Interactive Vim tutorial](http://openvim.com/) _(openvim.com)_


id: vim-unite
git_filename: ./vim-unite.md
format: md
field_title: Vim-Unite
field_category: Vim
data:
{"title": "Vim-Unite", "category": "Vim", "body": "### Usage\n\n``` vim\n:Unite file\n:Unite file_rec/async:!\n:Unite tag\n:Unite buffer\n```\n\n### Sources\n\n* `file/new`\n* `file/async`\n* `file_rec/async`\n* `file_rec/git`\n* `buffer`\n* `buffer_tab` (current tab only)\n* `tab`\n* `register`\n* `bookmark`\n* `source`\n\n### Options\n\n| Option                     | Description                                                 |\n| -------------------------- | ----------------------------------------------------------- |\n| `-start-insert`            |                                                             |\n| `-no-quit`                 |                                                             |\n| `-winheight=10`            |                                                             |\n| `-quick-match`             | select by pressing asdf keys                                |\n| `-winwidth=40`             | use with vertical                                           |\n| `-no-split`                | open in current buffer                                      |\n| `-auto-preview`            | great for outline                                           |\n| `-vertical`                | open as sidebar                                             |\n| `-buffer-name=xxx -resume` | resume the next time it's called (faster)                   |\n| `-input=`                  | reset input (use with -resume)                              |\n| `-unique`                  | remove duplicates (eg, if using `file_rec` with `file_mru`) |"}

field_body:
### Usage

``` vim
:Unite file
:Unite file_rec/async:!
:Unite tag
:Unite buffer
```

### Sources

* `file/new`
* `file/async`
* `file_rec/async`
* `file_rec/git`
* `buffer`
* `buffer_tab` (current tab only)
* `tab`
* `register`
* `bookmark`
* `source`

### Options

| Option                     | Description                                                 |
| -------------------------- | ----------------------------------------------------------- |
| `-start-insert`            |                                                             |
| `-no-quit`                 |                                                             |
| `-winheight=10`            |                                                             |
| `-quick-match`             | select by pressing asdf keys                                |
| `-winwidth=40`             | use with vertical                                           |
| `-no-split`                | open in current buffer                                      |
| `-auto-preview`            | great for outline                                           |
| `-vertical`                | open as sidebar                                             |
| `-buffer-name=xxx -resume` | resume the next time it's called (faster)                   |
| `-input=`                  | reset input (use with -resume)                              |
| `-unique`                  | remove duplicates (eg, if using `file_rec` with `file_mru`) |


id: vim-rails
git_filename: ./vim-rails.md
format: md
field_title: Vim-rails
field_category: Vim
data:
{"title": "Vim-rails", "category": "Vim", "html_class": "key-codes", "body": "Alternate files\n---------------\n\n### Alternate files\n\n| Command | Description |\n| --- | --- |\n| `:A` |  alternate file (test)          |\n| `:R` |  related file (controller/view) |\n\n### What it does\n\n| .                     | :A                | :R              |\n| ----                  | ---               | ---             |\n| **Model**             | test/models/      | db/schema.rb    |\n| **Controller method** | test/controllers/ | app/views/      |\n| **View template**     | test/views/       | app/controllers |\n\nAbbreviations\n-------------\n\nType `:Rabbrev` for a full list.\n\n| Abbrev  | Expansion        |\n| ---     | ---              |\n| `AC::`  | ActionController |\n| `AR::`  | ActiveRecord     |\n| `AV::`  | ActionView       |\n| `...`   | ...              |\n| ---     | ---              |\n| `logd(` | logger.debug     |\n| `logi(` | logger.info      |\n| `...`   | ...              |\n{:.no-head.greycode}\n\n### Model\n\n| Abbrev   | Expansion                 |\n| ---      | ---                       |\n| `bt(`    | `belongs_to`              |\n| `hm(`    | `has_many`                |\n| `ho(`    | `has_one`                 |\n| `habtm(` | `has_and_belongs_to_many` |\n{:.no-head.greycode}\n\n### Controllers\n\n| Abbrev  | Expansion        |\n| ---     | ---              |\n| `pa[`   | params           |\n| `re(`   | redirect_to      |\n| `rp(`   | render partial:  |\n| `rst(`  | respond_to       |\n{:.no-head.greycode}\n\n### Views\n\n| Abbrev  | Expansion                   |\n| ---     | ---                         |\n| `dotiw` | `distance_of_time_in_words` |\n| `taiw`  | `time_ago_in_words`         |\n{:.no-head.greycode}\n\nExtracting partials\n-------------------\n\n```rb\n# from view => app/views/home/_foo_partial.haml\n  :Rextract home/foo_partial\n\n# from model => app/models/concerns/foo_concern.rb\n  :Rextract FooConcern\n```\n\nLoading files\n-------------\n\n### App\n\n    :Econtroller <file>     # app/controllers/*_controller.rb\n    :Ehelper                # app/helpers/*_helper.rb\n    :Emodel <file>          # app/models/*.rb\n    :Ejob <file>            # app/jobs/*_job.rb\n    :Emailer <file>         # app/mailers/*.rb\n\n### DB\n\n    :Emigration <file>     # db/migrations/*.rb\n    :Eschema               # db/schema.rb\n    \n### Lib\n\n    :Elib <file>      # lib/*.rb\n    :Elib             # Gemfile\n    :Etask <file>     # lib/tasks/*.rake\n\n### Assets\n\n    :Estylesheet\n    :Ejavascript\n\n### Views\n\n    :Eview\n    :Elayout\n\n### Test\n\n    :Espec\n    :Eunittest\n      # test/{unit,models,helpers}/*_test.rb\n      # spec/{unit,models,helpers}/*_spec.rb\n\n    :Efunctionaltest\n      # test/{functional,controllers,mailers}/*_test.rb\n      # spec/{functional,controllers,mailers}/*_spec.rb\n\n    :Eintegrationtest\n      # test/integration/*_test.rb\n      # spec/{features,requests,integration}/*_spec.rb\n      # features/*.feature\n\n    :Efixtures\n    :Efunctionaltest\n\n### Config\n\n    :Einitializer <file>          # config/initializers/*.rb\n    :Elocale                      # config/locales/*.yml\n    :Eenvironment                 # application.rb\n    :Eenvironment development     # config/environments/*.rb\n\n## Reference\n\n * [vim-rails](https://github.com/tpope/vim-rails)"}

field_body:
Alternate files
---------------

### Alternate files

| Command | Description |
| --- | --- |
| `:A` |  alternate file (test)          |
| `:R` |  related file (controller/view) |

### What it does

| .                     | :A                | :R              |
| ----                  | ---               | ---             |
| **Model**             | test/models/      | db/schema.rb    |
| **Controller method** | test/controllers/ | app/views/      |
| **View template**     | test/views/       | app/controllers |

Abbreviations
-------------

Type `:Rabbrev` for a full list.

| Abbrev  | Expansion        |
| ---     | ---              |
| `AC::`  | ActionController |
| `AR::`  | ActiveRecord     |
| `AV::`  | ActionView       |
| `...`   | ...              |
| ---     | ---              |
| `logd(` | logger.debug     |
| `logi(` | logger.info      |
| `...`   | ...              |
{:.no-head.greycode}

### Model

| Abbrev   | Expansion                 |
| ---      | ---                       |
| `bt(`    | `belongs_to`              |
| `hm(`    | `has_many`                |
| `ho(`    | `has_one`                 |
| `habtm(` | `has_and_belongs_to_many` |
{:.no-head.greycode}

### Controllers

| Abbrev  | Expansion        |
| ---     | ---              |
| `pa[`   | params           |
| `re(`   | redirect_to      |
| `rp(`   | render partial:  |
| `rst(`  | respond_to       |
{:.no-head.greycode}

### Views

| Abbrev  | Expansion                   |
| ---     | ---                         |
| `dotiw` | `distance_of_time_in_words` |
| `taiw`  | `time_ago_in_words`         |
{:.no-head.greycode}

Extracting partials
-------------------

```rb
# from view => app/views/home/_foo_partial.haml
  :Rextract home/foo_partial

# from model => app/models/concerns/foo_concern.rb
  :Rextract FooConcern
```

Loading files
-------------

### App

    :Econtroller <file>     # app/controllers/*_controller.rb
    :Ehelper                # app/helpers/*_helper.rb
    :Emodel <file>          # app/models/*.rb
    :Ejob <file>            # app/jobs/*_job.rb
    :Emailer <file>         # app/mailers/*.rb

### DB

    :Emigration <file>     # db/migrations/*.rb
    :Eschema               # db/schema.rb
    
### Lib

    :Elib <file>      # lib/*.rb
    :Elib             # Gemfile
    :Etask <file>     # lib/tasks/*.rake

### Assets

    :Estylesheet
    :Ejavascript

### Views

    :Eview
    :Elayout

### Test

    :Espec
    :Eunittest
      # test/{unit,models,helpers}/*_test.rb
      # spec/{unit,models,helpers}/*_spec.rb

    :Efunctionaltest
      # test/{functional,controllers,mailers}/*_test.rb
      # spec/{functional,controllers,mailers}/*_spec.rb

    :Eintegrationtest
      # test/integration/*_test.rb
      # spec/{features,requests,integration}/*_spec.rb
      # features/*.feature

    :Efixtures
    :Efunctionaltest

### Config

    :Einitializer <file>          # config/initializers/*.rb
    :Elocale                      # config/locales/*.yml
    :Eenvironment                 # application.rb
    :Eenvironment development     # config/environments/*.rb

## Reference

 * [vim-rails](https://github.com/tpope/vim-rails)


id: vim-help
git_filename: ./vim-help.md
format: md
field_title: Vim helpfiles
field_category: Vim
field_updated: 2017-09-09
field_updated___timezone: UTC
data:
{"title": "Vim helpfiles", "category": "Vim", "updated": "2017-09-09", "body": "## Writing help files\n{: .-left-reference}\n\n### Creating a document\n\n```nohighlight\n:e doc/potion.txt\n:set ft=help\n:set ft=text\n```\n\nUse `ft=help` to preview it, and `ft=text` to edit it.\n\n### Example\n\n```nohighlight\n*ack.txt*   Plugin that integrates ack with Vim\n\n==============================================================================\nUSAGE INSTRUCTIONS                                                 *ack-usage*\n\n:Ack[!] {pattern}                                                       *:Ack*\n\n    Search recursively for {pattern}. See |:AckAdd|.\n    Also see http://beyondgrep.com for more information.\n\nvim:tw=78:ts=8:ft=help:norl:\n```\n\nThis is a cheatsheet for writing Vim help files. See: `:help help-writing`\n\n## Syntax\n\n### Reference\n\n| Code                 | Description    | Example             |\n| -----                | -----          | -----               |\n| *Inline items*                                              |\n| -----                | -----          | -----               |\n| `*tags*`             | Tags           |                     |\n| `|link-to-tags|`     | Links to tags  | `|:command|`        |\n| `'vimoption'`        | Vim option     | `'textwidth'`       |\n| -----                | -----          | -----               |\n| `{code-text}`        | Code text      | `{Visual}gf`        |\n| `<code-text>`        | Code text      | `<PageDown>`        |\n| `` `code-text` ``    | Code text      | `` `set fo=want` `` |\n| `CTRL-X`             | Code text      |                     |\n| -----                | -----          | -----               |\n| *Block items*                                               |\n| -----                | -----          | -----               |\n| `INTRODUCTION *tag*` | Section header |                     |\n| `Column heading~`    | Highlighting   |                     |\n| `www.url.com`        | Web URL        |                     |\n| -----                | -----          | -----               |\n| `=====`              | Separator      |                     |\n| `-----`              | Separator      |                     |\n\n### Tags\n\n * Tags are created with asterisks, eg, `*potion-usage*`\n * Links to tags are `|potion-usage|`\n * Press `^]` to jump to a tag\n\n### Code blocks\n\n```\nExample: >\n xyz\n<\n```\n\nSurround with `>` and `<` characters\n\n### File header\n\n```\n*potion.txt*  functionality for the potion programming language\n```\n\nIt's customary to start a file with a tag of the filename, plus a description.\n\n### Heading\n\n```\n==============================================================================\nCONTENTS                                                     *potion-contents*\n```\n\nStarts with `ALL CAPS`, ends with `*a-tag*`\n\n### Notes\nUsing `*Todo` and `*Error` will highlight your notes.\n\n```\n\t*Todo something to do\n\t*Error something wrong\n```\n\n### Final modeline\n\n```nohighlight\nvim:tw=78:ts=8:ft=help:norl:\n```\n\n## Conventions\n\n### Table of contents\n\n```nohighlight\n|rails-introduction|            Introduction and Feature Summary\n|rails-commands|                General Commands\n|rails-navigation|              Navigation\n```\n\n```nohighlight\n    1.Intro...................................|ergonomic|\n    2.Note to use..............................|CAPSLOCK|\n    3.Insert Mode Remappings............|ergonomicInsert|\n```\n\n### Author lines\n\n```nohighlight\nAuthor:  Jack Hackness <captain@time.com>         *xyz-author*\nLicense: Same terms as Vim itself (see |license|)\n```"}

field_body:
## Writing help files
{: .-left-reference}

### Creating a document

```nohighlight
:e doc/potion.txt
:set ft=help
:set ft=text
```

Use `ft=help` to preview it, and `ft=text` to edit it.

### Example

```nohighlight
*ack.txt*   Plugin that integrates ack with Vim

==============================================================================
USAGE INSTRUCTIONS                                                 *ack-usage*

:Ack[!] {pattern}                                                       *:Ack*

    Search recursively for {pattern}. See |:AckAdd|.
    Also see http://beyondgrep.com for more information.

vim:tw=78:ts=8:ft=help:norl:
```

This is a cheatsheet for writing Vim help files. See: `:help help-writing`

## Syntax

### Reference

| Code                 | Description    | Example             |
| -----                | -----          | -----               |
| *Inline items*                                              |
| -----                | -----          | -----               |
| `*tags*`             | Tags           |                     |
| `|link-to-tags|`     | Links to tags  | `|:command|`        |
| `'vimoption'`        | Vim option     | `'textwidth'`       |
| -----                | -----          | -----               |
| `{code-text}`        | Code text      | `{Visual}gf`        |
| `<code-text>`        | Code text      | `<PageDown>`        |
| `` `code-text` ``    | Code text      | `` `set fo=want` `` |
| `CTRL-X`             | Code text      |                     |
| -----                | -----          | -----               |
| *Block items*                                               |
| -----                | -----          | -----               |
| `INTRODUCTION *tag*` | Section header |                     |
| `Column heading~`    | Highlighting   |                     |
| `www.url.com`        | Web URL        |                     |
| -----                | -----          | -----               |
| `=====`              | Separator      |                     |
| `-----`              | Separator      |                     |

### Tags

 * Tags are created with asterisks, eg, `*potion-usage*`
 * Links to tags are `|potion-usage|`
 * Press `^]` to jump to a tag

### Code blocks

```
Example: >
 xyz
<
```

Surround with `>` and `<` characters

### File header

```
*potion.txt*  functionality for the potion programming language
```

It's customary to start a file with a tag of the filename, plus a description.

### Heading

```
==============================================================================
CONTENTS                                                     *potion-contents*
```

Starts with `ALL CAPS`, ends with `*a-tag*`

### Notes
Using `*Todo` and `*Error` will highlight your notes.

```
	*Todo something to do
	*Error something wrong
```

### Final modeline

```nohighlight
vim:tw=78:ts=8:ft=help:norl:
```

## Conventions

### Table of contents

```nohighlight
|rails-introduction|            Introduction and Feature Summary
|rails-commands|                General Commands
|rails-navigation|              Navigation
```

```nohighlight
    1.Intro...................................|ergonomic|
    2.Note to use..............................|CAPSLOCK|
    3.Insert Mode Remappings............|ergonomicInsert|
```

### Author lines

```nohighlight
Author:  Jack Hackness <captain@time.com>         *xyz-author*
License: Same terms as Vim itself (see |license|)
```


id: vim-easyalign
git_filename: ./vim-easyalign.md
format: md
field_title: Vim Easyalign
field_category: Vim
data:
{"title": "Vim Easyalign", "html_class": "key-codes", "hljs_languages": ["vim"], "category": "Vim", "body": "## Command mode\n\n### Align by delimiters\n\n```vim\n:EasyAlign :       \" preset characters (\\=:.,&#|)\n:EasyAlign |\n:EasyAlign \\       \" \\ means space\n```\n\n### Align by regexp\n\n```vim\n:EasyAlign /[:;]+/\n```\n\n### Specify which\n\n```vim\n:EasyAlign |       \" align by 1st `|`\n:EasyAlign 3 |     \" align by 3rd `|`\n:EasyAlign * |     \" align by all `|`s\n```\n\n### Add options\n\n```vim\n:EasyAlign * | l4r1\n\n  l4     \" lN - left_margin\n  r1     \" rN - right_margin\n         \"    spaces to the left/right of `|`\n  ar     \" a[lrc] - align\n         \"    align left/right/center\n  dr     \" d[lrc] - delimiter_align\n         \"    alignment of the delimiter itself\n```\n\n### Spaces are optional\n\n```vim\n:EasyAlign * /[;:]+/ l3\n:EasyAlign*/[;:]+/l3\n```\n\n## Examples\n\n### `:EasyAlign = dr` (delimiter_align right)\n\n```\napple    = 1\nbanana  += apple\ncake   ||= banana\n```\n\n### `:EasyAlign :` (for json or yaml)\n\n```\nurl:      jdbc:mysql://localhost/test\ndatabase: test\n```\n\n### `:EasyAlign *|` (markdown tables)\n\n```nohighlight\n| `<Enter>` | right align                   |\n| `1`       | on 1st occurrence             |\n| `2`       | on 2nd occurrence (and so on) |\n```\n\n## Interactive mode\n\n| `{Visual}` `\u23ce` | activate for selection |\n| `ga` `{motion}` | activate for motion/text object |\n{:.greycode}\n\nThen press options (if available), then a delimiter.\n\n### Interactive mode options\n\n| `\u23ce` | Set `alignment` |\n| `<ctrl-l>` `4 \u23ce` | Set `left_margin` (to the left of the delimiter) |\n| `<ctrl-r>` `4 \u23ce` | Set `right_margin` |\n| `\u2193` | no margin |\n{:.greycode}\n\n### Example\n\n- `gaip` `<ctrl-l>` `8\u23ce` `=` - puts 8 spaces before the equal sign\n\n## Also see\n\n- [vim-easy-align](https://github.com/junegunn/vim-easy-align)\n- [Examples](https://github.com/junegunn/vim-easy-align#examples)\n- [Alignment options](https://github.com/junegunn/vim-easy-align#alignment-options)"}

field_body:
## Command mode

### Align by delimiters

```vim
:EasyAlign :       " preset characters (\=:.,&#|)
:EasyAlign |
:EasyAlign \       " \ means space
```

### Align by regexp

```vim
:EasyAlign /[:;]+/
```

### Specify which

```vim
:EasyAlign |       " align by 1st `|`
:EasyAlign 3 |     " align by 3rd `|`
:EasyAlign * |     " align by all `|`s
```

### Add options

```vim
:EasyAlign * | l4r1

  l4     " lN - left_margin
  r1     " rN - right_margin
         "    spaces to the left/right of `|`
  ar     " a[lrc] - align
         "    align left/right/center
  dr     " d[lrc] - delimiter_align
         "    alignment of the delimiter itself
```

### Spaces are optional

```vim
:EasyAlign * /[;:]+/ l3
:EasyAlign*/[;:]+/l3
```

## Examples

### `:EasyAlign = dr` (delimiter_align right)

```
apple    = 1
banana  += apple
cake   ||= banana
```

### `:EasyAlign :` (for json or yaml)

```
url:      jdbc:mysql://localhost/test
database: test
```

### `:EasyAlign *|` (markdown tables)

```nohighlight
| `<Enter>` | right align                   |
| `1`       | on 1st occurrence             |
| `2`       | on 2nd occurrence (and so on) |
```

## Interactive mode

| `{Visual}` `⏎` | activate for selection |
| `ga` `{motion}` | activate for motion/text object |
{:.greycode}

Then press options (if available), then a delimiter.

### Interactive mode options

| `⏎` | Set `alignment` |
| `<ctrl-l>` `4 ⏎` | Set `left_margin` (to the left of the delimiter) |
| `<ctrl-r>` `4 ⏎` | Set `right_margin` |
| `↓` | no margin |
{:.greycode}

### Example

- `gaip` `<ctrl-l>` `8⏎` `=` - puts 8 spaces before the equal sign

## Also see

- [vim-easy-align](https://github.com/junegunn/vim-easy-align)
- [Examples](https://github.com/junegunn/vim-easy-align#examples)
- [Alignment options](https://github.com/junegunn/vim-easy-align#alignment-options)


id: vim-digraphs
git_filename: ./vim-digraphs.md
format: md
field_title: Vim digraphs
field_category: Vim
data:
{"title": "Vim digraphs", "category": "Vim", "body": "### Typing digraphs in insert mode\n\n```\n<Ctrl-K>OK\n```\n{:.light}\n\n### Listing digraphs\n\n\n```\n:dig\n:digraphs\n```\n{:.lights}\n\n## Reference\n\n### Symbols\n\n| \u2120  | \u2122  | \u00a9  | \u00ae  | \u00b6  | \u2020  | \u2021  | &ndash; | \u00b1  |\n| SM | TM | Co | Rg | PI | /- | /= | --      | +- |\n\n| \u00a7  | \u00b5  | \u00a3  | \u00a2  | \u00a5  | \u00a4  |\n| SE | My | $$ | Ct | Ye | Cu |\n\n| \u2605  | \u2606  | \u2661  | \u25c6  | \u25c7  |\n| *2 | *1 | cH | Db | Dw |\n\n| \u2713  | \u2717  |\n| OK | XX |\n\n### Dots and bullets\n\n| \u22c5  | \u00b7  | \u25cb  | \u2219  | \u2218  | \u2234  | \u2235  | \u2236  | \u2237  |\n| .P | .M | 0m | Sb | Ob | .: | :. | :R | :: |\n\n| \u2299  | \u229a  | \u25ce   | \u25a1  | \u25aa  |\n| 0. | 02 | 0o  | OS | sB |\n\n### Math\n\n| \u00f8  | \u2243  | \u2245  | \u2265  | \u2264  | \u2261  | \u226e  | \u226f  | \u2260  |\n| o/ | ?- | ?= | >= | =< | =3 | !< | !> | != |\n\n| \u221a         | \u00d7          | \u00f7           |\n| RT *root* | /\\ *times* | -: *divide* |\n\n\n| \u00bc  | \u00bd  | \u00be  | \u2083  | \u2082  | \u00b3  | \u00b2  |\n| 14 | 12 | 34 | 3s | 2s | 3S | 2S |\n\n### Set Theory\n\n| \u2200         | \u2203          | \u2208              | \u2205             | \u2286                    | \u2287                     |\n| FA *forall* | TE *exists* | (- *element of* | /0 *empty set* | (_ *subset or equal* | )_ *superset or equal* |\n\n| \u2229                 | \u222a          | \u2282           | \u2283             |\n| (U *intersection* | )U *union* | (C *subset* | )C *superset* |\n\n### Greek\n\n| \u0391  | \u03b1  | \u0392  | \u03b2  | \u0393  | \u03b3  | \u0394  | \u03b4  | \u0395  | \u03b5  | \u0396  | \u03b6  |\n| A* | a* | B* | b* | G* | g* | D* | d* | E* | e* | Z* | z* |\n\n| \u0397  | \u03b7  | \u0398  | \u03b8  | \u0399  | \u03b9  | \u039a  | \u03ba  | \u039b  | \u03bb  | \u039c  | \u03bc  |\n| Y* | y* | H* | h* | I* | i* | K* | k* | L* | l* | M* | m* |\n\n| \u039d  | \u03bd  | \u039e  | \u03be  | \u039f  | \u03bf  | \u03a0  | \u03c0  | \u03a1  | \u03c1  | \u03a3  | \u03c3  | \u03c2  |\n| N* | n* | C* | c* | O* | o* | P* | p* | R* | r* | S* | s* | *s |\n\n| \u03a4  | \u03c4  | \u03a5  | \u03c5  | \u03a6  | \u03c6  | \u03a7  | \u03c7  | \u03a8  | \u03c8  | \u03a9  | \u03c9  |\n| T* | t* | U* | u* | F* | f* | X* | x* | Q* | q* | W* | w* |\n\n### Triangles\n\n| \u25b2  | \u25b3  | \u25bc  | \u25bd  |\n| UT | uT | Dt | dT |\n\n| \u25b6  | \u25b7  | \u25c0  | \u25c1  |\n| PR | Tr | PL | Tl |\n\n| \u00bb  | \u00ab  | \u2329 | \u232a | \u2039  | \u203a  |\n| >> | << | </ | /> | <1 | >1 |\n\n### Arrows\n\n| \u2190  | \u2192  | \u2191  | \u2193  | \u2195 | \u2194 |\n| <- | -> | -! | -v | UD | <> |\n\n| \u21d0  | \u21d2  | \u21d4  |\n| <= | => | == |\n\n<style>\n.all table tr td { text-align: center; }\n.all table tr:first-child td { font-size: 1.3em; padding-bottom: 0; }\n.all table tr:first-child+tr td { font-size: 0.9em; color: dodgerblue; border-top: 0; padding-top: 0; font-family: fira mono, monospace; }\n.all table em { color: #aaa; font-size: 0.9em; font-style: normal; font-family: roboto, sans-serif; }\n</style>"}

field_body:
### Typing digraphs in insert mode

```
<Ctrl-K>OK
```
{:.light}

### Listing digraphs


```
:dig
:digraphs
```
{:.lights}

## Reference

### Symbols

| ℠  | ™  | ©  | ®  | ¶  | †  | ‡  | &ndash; | ±  |
| SM | TM | Co | Rg | PI | /- | /= | --      | +- |

| §  | µ  | £  | ¢  | ¥  | ¤  |
| SE | My | $$ | Ct | Ye | Cu |

| ★  | ☆  | ♡  | ◆  | ◇  |
| *2 | *1 | cH | Db | Dw |

| ✓  | ✗  |
| OK | XX |

### Dots and bullets

| ⋅  | ·  | ○  | ∙  | ∘  | ∴  | ∵  | ∶  | ∷  |
| .P | .M | 0m | Sb | Ob | .: | :. | :R | :: |

| ⊙  | ⊚  | ◎   | □  | ▪  |
| 0. | 02 | 0o  | OS | sB |

### Math

| ø  | ≃  | ≅  | ≥  | ≤  | ≡  | ≮  | ≯  | ≠  |
| o/ | ?- | ?= | >= | =< | =3 | !< | !> | != |

| √         | ×          | ÷           |
| RT *root* | /\ *times* | -: *divide* |


| ¼  | ½  | ¾  | ₃  | ₂  | ³  | ²  |
| 14 | 12 | 34 | 3s | 2s | 3S | 2S |

### Set Theory

| ∀         | ∃          | ∈              | ∅             | ⊆                    | ⊇                     |
| FA *forall* | TE *exists* | (- *element of* | /0 *empty set* | (_ *subset or equal* | )_ *superset or equal* |

| ∩                 | ∪          | ⊂           | ⊃             |
| (U *intersection* | )U *union* | (C *subset* | )C *superset* |

### Greek

| Α  | α  | Β  | β  | Γ  | γ  | Δ  | δ  | Ε  | ε  | Ζ  | ζ  |
| A* | a* | B* | b* | G* | g* | D* | d* | E* | e* | Z* | z* |

| Η  | η  | Θ  | θ  | Ι  | ι  | Κ  | κ  | Λ  | λ  | Μ  | μ  |
| Y* | y* | H* | h* | I* | i* | K* | k* | L* | l* | M* | m* |

| Ν  | ν  | Ξ  | ξ  | Ο  | ο  | Π  | π  | Ρ  | ρ  | Σ  | σ  | ς  |
| N* | n* | C* | c* | O* | o* | P* | p* | R* | r* | S* | s* | *s |

| Τ  | τ  | Υ  | υ  | Φ  | φ  | Χ  | χ  | Ψ  | ψ  | Ω  | ω  |
| T* | t* | U* | u* | F* | f* | X* | x* | Q* | q* | W* | w* |

### Triangles

| ▲  | △  | ▼  | ▽  |
| UT | uT | Dt | dT |

| ▶  | ▷  | ◀  | ◁  |
| PR | Tr | PL | Tl |

| »  | «  | 〈 | 〉 | ‹  | ›  |
| >> | << | </ | /> | <1 | >1 |

### Arrows

| ←  | →  | ↑  | ↓  | ↕ | ↔ |
| <- | -> | -! | -v | UD | <> |

| ⇐  | ⇒  | ⇔  |
| <= | => | == |

<style>
.all table tr td { text-align: center; }
.all table tr:first-child td { font-size: 1.3em; padding-bottom: 0; }
.all table tr:first-child+tr td { font-size: 0.9em; color: dodgerblue; border-top: 0; padding-top: 0; font-family: fira mono, monospace; }
.all table em { color: #aaa; font-size: 0.9em; font-style: normal; font-family: roboto, sans-serif; }
</style>


id: vim-diff
git_filename: ./vim-diff.md
format: md
field_title: Vimdiff
field_category: Vim
field_intro: [Vim](https://www.vim.org/) is a very efficient text editor. This reference was made for Vim 8.0.
field_updated: 2018-12-06
field_updated___timezone: UTC
data:
{"title": "Vimdiff", "category": "Vim", "updated": "2018-12-06", "weight": -10, "intro": "[Vim](https://www.vim.org/) is a very efficient text editor. This reference was made for Vim 8.0.\n", "body": "Getting started\n---------------\n{: .-three-column}\n\n### Navigating\n{: .-prime}\n\n| Shortcut       | Description                      |\n| ---            | ---                              |\n| `]c`           | Next difference                  |\n| `[c`           | Previous difference              |\n{: .-shortcuts}\n\n### Editing\n\n| Shortcut | Description                         |\n| ---            | ---                              |\n| `do`           | Diff Obtain! <br>Pull the changes to the current file. |\n| `dp`           | Diff Put! <br>Push the changes to the other file. |\n| ---            | ---                              |\n| `:diffupdate`  | Re-scan the files for differences.                    |\n| `ZQ`           | Quit without checking changes    |\n{: .-shortcuts}\n\n### Folds\n\n| Shortcut      | Description                  |\n| ---           | ---                          |\n| `zo` _/_ `zO` | Open                         |\n| `zc` _/_ `zC` | Close                        |\n| `za` _/_ `zA` | Toggle                       |\n| ---           | ---                          |\n| `zv`          | Open folds for this line     |\n| ---           | ---                          |\n| `zM`          | Close all                    |\n| `zR`          | Open all                     |\n| ---           | ---                          |\n| `zm`          | Fold more _(foldlevel += 1)_ |\n| `zr`          | Fold less _(foldlevel -= 1)_ |\n| ---           | ---                          |\n| `zx`          | Update folds                 |\n{: .-shortcuts}\n\n\nAlso see\n--------\n\n- [Vim cheatsheet](https://vim.rtorr.com/) _(vim.rotrr.com)_\n- [Vim documentation](https://vimdoc.sourceforge.net/htmldoc/) _(vimdoc.sourceforge.net)_\n- [Interactive Vim tutorial](https://openvim.com/) _(openvim.com)_"}

field_body:
Getting started
---------------
{: .-three-column}

### Navigating
{: .-prime}

| Shortcut       | Description                      |
| ---            | ---                              |
| `]c`           | Next difference                  |
| `[c`           | Previous difference              |
{: .-shortcuts}

### Editing

| Shortcut | Description                         |
| ---            | ---                              |
| `do`           | Diff Obtain! <br>Pull the changes to the current file. |
| `dp`           | Diff Put! <br>Push the changes to the other file. |
| ---            | ---                              |
| `:diffupdate`  | Re-scan the files for differences.                    |
| `ZQ`           | Quit without checking changes    |
{: .-shortcuts}

### Folds

| Shortcut      | Description                  |
| ---           | ---                          |
| `zo` _/_ `zO` | Open                         |
| `zc` _/_ `zC` | Close                        |
| `za` _/_ `zA` | Toggle                       |
| ---           | ---                          |
| `zv`          | Open folds for this line     |
| ---           | ---                          |
| `zM`          | Close all                    |
| `zR`          | Open all                     |
| ---           | ---                          |
| `zm`          | Fold more _(foldlevel += 1)_ |
| `zr`          | Fold less _(foldlevel -= 1)_ |
| ---           | ---                          |
| `zx`          | Update folds                 |
{: .-shortcuts}


Also see
--------

- [Vim cheatsheet](https://vim.rtorr.com/) _(vim.rotrr.com)_
- [Vim documentation](https://vimdoc.sourceforge.net/htmldoc/) _(vimdoc.sourceforge.net)_
- [Interactive Vim tutorial](https://openvim.com/) _(openvim.com)_


id: vainglory
git_filename: ./vainglory.md
format: md
field_title: Vainglory
data:
{"title": "Vainglory", "body": "## T3 items by use\n{: .-one-column}\n\n### Items by use\n\n| Use                    | CP                                | WP                           | Util                                                                           |\n| ---                    | ---                               | ---                          | ---                                                                            |\n| __Anti-armor/shield__  | [Myth][BM]                        | [Bonesaw][BS], [Tension][TB] |                                                                                |\n| __Stacking damage__    | [Myth][BM]                        | [Break][BP]                  |                                                                                |\n| __Lifesteal__          | [Eve][Eve]                        | [Serpent][SM], [Shiv][PS]    |                                                                                |\n| __Raw power__          | [Shatterglass][SG]                | [Sorrowblade][SB]            |                                                                                |\n| __Burst damage__       | [Aftershock][AS]                  | [Tension][TB]                |                                                                                |\n| __Attack speed__       | [AC][AC]                          | [Tornado][TT], [Break][BP]   |                                                                                |\n| __Critical__           |                                   | [Monocle][TM]                |                                                                                |\n| __Auto-attack damage__ | [AC][AC], [Aftershock][AS]        | _everything_                 | [Stormcrown][SC]                                                               |\n| __Cooldown__           | [Clockwork][CW], [Aftershock][AS] | Spellsword                   | [Stormcrown][SC], [Contraption][Con], [Nullwave][Null], [Halcyon Boots][HBoot] |\n| __Slow__               | [Frostburn][FB]                   |                              | [Shiversteel][SS]                                                              |\n| __Reflex block__       |                                   |                              | [Aegis][Aegis] (self/shield) <br> [Crucible][Cru] (team/HP)                    |\n| __Ability repeat__     | [Echo][Echo]                      |                              |                                                                                |\n{: .-left-align.-headers}\n\n## Tier 3 items\n{: .-one-column}\n\n### Crystal power\n\n| Item                          | Cost  | CP      | Use                                                                                    |\n| ----                          | ---   | ---     | ---                                                                                    |\n| AS: [Aftershock][AS]          | 2400  | +35 cp  | __Basic dmg, atk speed__ <br> *+basic dmg after ability*, +25% cooldown, +2.5 recharge |\n| EoH: [Eve of Harvest][Eve]    | 2600  | +55 cp  | __Lifesteal__            <br> *+10% lifesteal*, +250 energy, +5 recharge               |\n| AC: [Alternating Current][AC] | 2800  | +60 cp  | __Basic dmg__            <br> *+basic dmg based on CP*, +65% atk speed                 |\n| BM: [Broken Myth][BM]         | 2150  | +70 cp  | __Stack dmg__            <br> +10% shield pierce, stacking dmg                         |\n| FB: [Frostburn][FB]           | 2600  | +100 cp | __Slow__                 <br> *slow for 1.5s* at (10% + 1% per 10CP)                   |\n| SG: [Shatterglass][SG]        | 3000  | +150 cp | __Raw power__            <br> -                                                        |\n| CW: [Clockwork][CW]           | 2500  | +30% cp | __Cooldown__             <br> *+40% cooldown*, +250 energy, +7.5 recharge              |\n| [Echo][Echo]                  | 2500? |         | __Ability repeat__       <br> +250 energy, +4 recharge                                 |\n{: .-left-align.-headers}\n\n[AS]: http://www.vaingloryfire.com/vainglory/wiki/items/aftershock\n[AC]: http://www.vaingloryfire.com/vainglory/wiki/items/alternating-current\n[Eve]: http://www.vaingloryfire.com/vainglory/wiki/items/eve-of-harvest\n[SG]: http://www.vaingloryfire.com/vainglory/wiki/items/shatterglass\n[BM]: http://www.vaingloryfire.com/vainglory/wiki/items/broken-myth\n[CW]: http://www.vaingloryfire.com/vainglory/wiki/items/clockwork\n[FB]: http://www.vaingloryfire.com/vainglory/wiki/items/frostburn\n[Echo]: http://www.vaingloryfire.com/vainglory/wiki/items/echo\n\n### Weapon power\n\n| Item                       | Cost | WP      | Other                                                                         |\n| ----                       | ---  | ---     | ---                                                                           |\n| TT: [Tornado Trigger][TT]  | 2600 |         | __Atk speed__     <br> *+75% atk speed*, +20% crit change, +20% crit dmg      |\n| BS: [Bonesaw][BS]          | 2700 | +15 wp  | __Armor shred__   <br> *stacking armor shred*                                 |\n| TB: [Tension Bow][TB]      | 2300 | +45 wp  | __Bonus dmg__     <br> *bonus dmg every 6s*, +8% armor pierce                 |\n| TM: [Tyrant's Monocle][TM] | 2750 | +50 wp  | __Crit__          <br> *+40% crit chance*, +20% crit dmg                      |\n| BP: [Breaking Point][BP]   | 2600 | +55 wp  | __Stacking dmg__  <br> *stacking weapon dmg*, +35% atk speed                  |\n| SM: [Serpent Mask][SM]     | 2800 | +85 wp  | __Lifesteal__     <br> *stacking lifesteal*, +10% lifesteal                   |\n| SB: [Sorrowblade][SB]      | 3100 | +150 wp | __Raw power__     <br> -                                                      |\n| PS: [Poisoned Shiv][PS]    | 2250 | +30 wp  | __Mortal wounds__ <br> *mortal wounds for 2s*, +10% lifesteal, +30% atk speed |\n| SS: Spellsword             | ?    | +90 wp  | __Cooldown__      <br> ?                                                      |\n{: .-left-align.-headers}\n\n[BS]: http://www.vaingloryfire.com/vainglory/wiki/items/bonesaw\n[BP]: http://www.vaingloryfire.com/vainglory/wiki/items/breaking-point\n[SM]: http://www.vaingloryfire.com/vainglory/wiki/items/serpent-mask\n[SB]: http://www.vaingloryfire.com/vainglory/wiki/items/sorrowblade\n[TB]: http://www.vaingloryfire.com/vainglory/wiki/items/tension-bow\n[TT]: http://www.vaingloryfire.com/vainglory/wiki/items/tornado-trigger\n[TM]: http://www.vaingloryfire.com/vainglory/wiki/items/tyrants-monocle\n[PS]: http://www.vaingloryfire.com/vainglory/wiki/items/poisoned-shiv\n\n### Utilities\n\n| Item                            | Cost | HP      | Use                                                                    |\n| ---                             | ---  | ---     | ---                                                                    |\n| [Halcyon Chargers][HBoot]       | 2300 | +200 hp | \ud83d\udc5f __Boots__        <br> +15% cooldown, +250 energy, +4 recharge       |\n| [Stormcrown][SC]                | 2200 | +200 hp | \ud83d\udd34 __Bonus dmg__    <br> +30% cooldown, +4 recharge, bonus true damage |\n| [Journey Boots][JBoot]          | 1900 | +250 hp | \ud83d\udc5f __Boots__        <br> damaging heroes resets sprint cooldown        |\n| [Nullwave Gauntlet][Null] (2.0) | 2250 | +300 hp | \ud83d\ude36 __Item silence__ <br> +25% cooldown                                 |\n| [Contraption][Con]              | 2100 | +350 hp | \ud83d\udc40 __Vision__       <br> traps/flares, +40% cooldown, +3 recharge      |\n| [Shiversteel][SS]               | 1450 | +500 hp | \ud83d\udc0c __Slow__         <br> active: slow targets                          |\n| [War Treads][WBoot]             | 2500 | +600 hp | \ud83d\udc5f __Boots__        <br> gives sprint to nearby teammates              |\n{: .-left-align.-headers}\n\n### Defense\n\n| Item                            | Cost | HP      | Armor   | Shield  | Use                                    |\n| ---                             | ---  | ---     | ---     | ---     | ---                                    |\n| [Aegis][Aegis]                  | 2250 |         | +30 ar  | +125 sh | \u270a__Reflex block__ (self)              |\n| [Fountain of Renewal][Fountain] | 2300 | +200 hp | +30 ar  | +75 sh  | \u2764 __Heal__ allies                      |\n| [Atlas Pauldron][Atlas]         | 1900 |         | +85 ar  | +35 sh  | \ud83d\udc0c __Slow__ target attack speed        |\n| [Metal Jacket][Metal]           | 2100 |         | +170 ar | +35 sh  |                                        |\n| [Crucible][Cru]                 | 1850 | +600 hp |         |         | \u270a __Reflex block__ (team)             |\n| [Slumbering Husk][Husk] (2.0)   | 1600 | +400 hp |         |         | __Fortification__ against burst damage |\n{: .-left-align.-headers}\n\n[Fountain]: http://www.vaingloryfire.com/vainglory/wiki/items/fountain-of-renewal\n[Cru]: http://www.vaingloryfire.com/vainglory/wiki/items/aegis\n[Aegis]: http://www.vaingloryfire.com/vainglory/wiki/items/aegis\n[Atlas]: http://www.vaingloryfire.com/vainglory/wiki/items/atlas-pauldron\n[Metal]: http://www.vaingloryfire.com/vainglory/wiki/items/metal-jacket\n[Husk]: http://www.vaingloryfire.com/vainglory/wiki/items/slumbering-husk\n[Null]: http://www.vaingloryfire.com/vainglory/wiki/items/nullwave-gauntlet\n\n### Boots\n\n| Item                      | Movement speed | HP      | Sprint                                          | Use            |\n| ---                       | ---            | ---     | ---                                             | ---            |\n| [War Treads][WBoot]       | +0.4           | +600 hp | 2s (60s cooldown) <br> incl. nearby teammates   | __HP, assist__ |\n| [Halcyon Chargers][HBoot] | +0.5           |         | 3s (50s cooldown)                               | __Energy__     |\n| [Journey Boots][JBoot]    | +0.6           | +250 hp | 2s (60s cooldown) <br> damaging resets cooldown | __Gap close__  |\n{: .-left-align.-headers}\n\n[Con]: http://www.vaingloryfire.com/vainglory/wiki/items/contraption\n[HBoot]: http://www.vaingloryfire.com/vainglory/wiki/items/halcyon-chargers\n[WBoot]: http://www.vaingloryfire.com/vainglory/wiki/items/war-treads\n[JBoot]: http://www.vaingloryfire.com/vainglory/wiki/items/journey-boots\n[SC]: http://www.vaingloryfire.com/vainglory/wiki/items/stormcrown\n[SS]: http://www.vaingloryfire.com/vainglory/wiki/items/shiversteel\n\n## Skill tier names\n\n### Skill tier names\n\n| Just Beginning | 1 |\n| Getting There | 2 |\n| Rock Solid | 3 |\n| Worthy Foe |4 |\n| Got Swagger | 5 |\n| Credible Threat | 6 |\n| The Hotness | 7 |\n| Simply Amazing | 8 |\n| Pinnacle of Awesome | 9 |\n| Vainglorious | 10 |\n\nSee: [Skill tier names](http://www.vaingloryfire.com/vainglory/forum/general-discussion/bronze-silver-gold-rankings-5312)\n\n## References\n\n- Last updated for Vainglory 1.22 with some 2.0 stuff.\n- [Vaingloryfire.com](http://www.vaingloryfire.com/)\n- [Version history](http://forums.vainglorygame.com/index.php?threads/41129/) (forums.vainglorygame.com)\n- [Skill tier points](http://brokenmyth.net/skill-tier-point-far-next-tier/#more-10043) (brokenmyth.net)"}

field_body:
## T3 items by use
{: .-one-column}

### Items by use

| Use                    | CP                                | WP                           | Util                                                                           |
| ---                    | ---                               | ---                          | ---                                                                            |
| __Anti-armor/shield__  | [Myth][BM]                        | [Bonesaw][BS], [Tension][TB] |                                                                                |
| __Stacking damage__    | [Myth][BM]                        | [Break][BP]                  |                                                                                |
| __Lifesteal__          | [Eve][Eve]                        | [Serpent][SM], [Shiv][PS]    |                                                                                |
| __Raw power__          | [Shatterglass][SG]                | [Sorrowblade][SB]            |                                                                                |
| __Burst damage__       | [Aftershock][AS]                  | [Tension][TB]                |                                                                                |
| __Attack speed__       | [AC][AC]                          | [Tornado][TT], [Break][BP]   |                                                                                |
| __Critical__           |                                   | [Monocle][TM]                |                                                                                |
| __Auto-attack damage__ | [AC][AC], [Aftershock][AS]        | _everything_                 | [Stormcrown][SC]                                                               |
| __Cooldown__           | [Clockwork][CW], [Aftershock][AS] | Spellsword                   | [Stormcrown][SC], [Contraption][Con], [Nullwave][Null], [Halcyon Boots][HBoot] |
| __Slow__               | [Frostburn][FB]                   |                              | [Shiversteel][SS]                                                              |
| __Reflex block__       |                                   |                              | [Aegis][Aegis] (self/shield) <br> [Crucible][Cru] (team/HP)                    |
| __Ability repeat__     | [Echo][Echo]                      |                              |                                                                                |
{: .-left-align.-headers}

## Tier 3 items
{: .-one-column}

### Crystal power

| Item                          | Cost  | CP      | Use                                                                                    |
| ----                          | ---   | ---     | ---                                                                                    |
| AS: [Aftershock][AS]          | 2400  | +35 cp  | __Basic dmg, atk speed__ <br> *+basic dmg after ability*, +25% cooldown, +2.5 recharge |
| EoH: [Eve of Harvest][Eve]    | 2600  | +55 cp  | __Lifesteal__            <br> *+10% lifesteal*, +250 energy, +5 recharge               |
| AC: [Alternating Current][AC] | 2800  | +60 cp  | __Basic dmg__            <br> *+basic dmg based on CP*, +65% atk speed                 |
| BM: [Broken Myth][BM]         | 2150  | +70 cp  | __Stack dmg__            <br> +10% shield pierce, stacking dmg                         |
| FB: [Frostburn][FB]           | 2600  | +100 cp | __Slow__                 <br> *slow for 1.5s* at (10% + 1% per 10CP)                   |
| SG: [Shatterglass][SG]        | 3000  | +150 cp | __Raw power__            <br> -                                                        |
| CW: [Clockwork][CW]           | 2500  | +30% cp | __Cooldown__             <br> *+40% cooldown*, +250 energy, +7.5 recharge              |
| [Echo][Echo]                  | 2500? |         | __Ability repeat__       <br> +250 energy, +4 recharge                                 |
{: .-left-align.-headers}

[AS]: http://www.vaingloryfire.com/vainglory/wiki/items/aftershock
[AC]: http://www.vaingloryfire.com/vainglory/wiki/items/alternating-current
[Eve]: http://www.vaingloryfire.com/vainglory/wiki/items/eve-of-harvest
[SG]: http://www.vaingloryfire.com/vainglory/wiki/items/shatterglass
[BM]: http://www.vaingloryfire.com/vainglory/wiki/items/broken-myth
[CW]: http://www.vaingloryfire.com/vainglory/wiki/items/clockwork
[FB]: http://www.vaingloryfire.com/vainglory/wiki/items/frostburn
[Echo]: http://www.vaingloryfire.com/vainglory/wiki/items/echo

### Weapon power

| Item                       | Cost | WP      | Other                                                                         |
| ----                       | ---  | ---     | ---                                                                           |
| TT: [Tornado Trigger][TT]  | 2600 |         | __Atk speed__     <br> *+75% atk speed*, +20% crit change, +20% crit dmg      |
| BS: [Bonesaw][BS]          | 2700 | +15 wp  | __Armor shred__   <br> *stacking armor shred*                                 |
| TB: [Tension Bow][TB]      | 2300 | +45 wp  | __Bonus dmg__     <br> *bonus dmg every 6s*, +8% armor pierce                 |
| TM: [Tyrant's Monocle][TM] | 2750 | +50 wp  | __Crit__          <br> *+40% crit chance*, +20% crit dmg                      |
| BP: [Breaking Point][BP]   | 2600 | +55 wp  | __Stacking dmg__  <br> *stacking weapon dmg*, +35% atk speed                  |
| SM: [Serpent Mask][SM]     | 2800 | +85 wp  | __Lifesteal__     <br> *stacking lifesteal*, +10% lifesteal                   |
| SB: [Sorrowblade][SB]      | 3100 | +150 wp | __Raw power__     <br> -                                                      |
| PS: [Poisoned Shiv][PS]    | 2250 | +30 wp  | __Mortal wounds__ <br> *mortal wounds for 2s*, +10% lifesteal, +30% atk speed |
| SS: Spellsword             | ?    | +90 wp  | __Cooldown__      <br> ?                                                      |
{: .-left-align.-headers}

[BS]: http://www.vaingloryfire.com/vainglory/wiki/items/bonesaw
[BP]: http://www.vaingloryfire.com/vainglory/wiki/items/breaking-point
[SM]: http://www.vaingloryfire.com/vainglory/wiki/items/serpent-mask
[SB]: http://www.vaingloryfire.com/vainglory/wiki/items/sorrowblade
[TB]: http://www.vaingloryfire.com/vainglory/wiki/items/tension-bow
[TT]: http://www.vaingloryfire.com/vainglory/wiki/items/tornado-trigger
[TM]: http://www.vaingloryfire.com/vainglory/wiki/items/tyrants-monocle
[PS]: http://www.vaingloryfire.com/vainglory/wiki/items/poisoned-shiv

### Utilities

| Item                            | Cost | HP      | Use                                                                    |
| ---                             | ---  | ---     | ---                                                                    |
| [Halcyon Chargers][HBoot]       | 2300 | +200 hp | 👟 __Boots__        <br> +15% cooldown, +250 energy, +4 recharge       |
| [Stormcrown][SC]                | 2200 | +200 hp | 🔴 __Bonus dmg__    <br> +30% cooldown, +4 recharge, bonus true damage |
| [Journey Boots][JBoot]          | 1900 | +250 hp | 👟 __Boots__        <br> damaging heroes resets sprint cooldown        |
| [Nullwave Gauntlet][Null] (2.0) | 2250 | +300 hp | 😶 __Item silence__ <br> +25% cooldown                                 |
| [Contraption][Con]              | 2100 | +350 hp | 👀 __Vision__       <br> traps/flares, +40% cooldown, +3 recharge      |
| [Shiversteel][SS]               | 1450 | +500 hp | 🐌 __Slow__         <br> active: slow targets                          |
| [War Treads][WBoot]             | 2500 | +600 hp | 👟 __Boots__        <br> gives sprint to nearby teammates              |
{: .-left-align.-headers}

### Defense

| Item                            | Cost | HP      | Armor   | Shield  | Use                                    |
| ---                             | ---  | ---     | ---     | ---     | ---                                    |
| [Aegis][Aegis]                  | 2250 |         | +30 ar  | +125 sh | ✊__Reflex block__ (self)              |
| [Fountain of Renewal][Fountain] | 2300 | +200 hp | +30 ar  | +75 sh  | ❤ __Heal__ allies                      |
| [Atlas Pauldron][Atlas]         | 1900 |         | +85 ar  | +35 sh  | 🐌 __Slow__ target attack speed        |
| [Metal Jacket][Metal]           | 2100 |         | +170 ar | +35 sh  |                                        |
| [Crucible][Cru]                 | 1850 | +600 hp |         |         | ✊ __Reflex block__ (team)             |
| [Slumbering Husk][Husk] (2.0)   | 1600 | +400 hp |         |         | __Fortification__ against burst damage |
{: .-left-align.-headers}

[Fountain]: http://www.vaingloryfire.com/vainglory/wiki/items/fountain-of-renewal
[Cru]: http://www.vaingloryfire.com/vainglory/wiki/items/aegis
[Aegis]: http://www.vaingloryfire.com/vainglory/wiki/items/aegis
[Atlas]: http://www.vaingloryfire.com/vainglory/wiki/items/atlas-pauldron
[Metal]: http://www.vaingloryfire.com/vainglory/wiki/items/metal-jacket
[Husk]: http://www.vaingloryfire.com/vainglory/wiki/items/slumbering-husk
[Null]: http://www.vaingloryfire.com/vainglory/wiki/items/nullwave-gauntlet

### Boots

| Item                      | Movement speed | HP      | Sprint                                          | Use            |
| ---                       | ---            | ---     | ---                                             | ---            |
| [War Treads][WBoot]       | +0.4           | +600 hp | 2s (60s cooldown) <br> incl. nearby teammates   | __HP, assist__ |
| [Halcyon Chargers][HBoot] | +0.5           |         | 3s (50s cooldown)                               | __Energy__     |
| [Journey Boots][JBoot]    | +0.6           | +250 hp | 2s (60s cooldown) <br> damaging resets cooldown | __Gap close__  |
{: .-left-align.-headers}

[Con]: http://www.vaingloryfire.com/vainglory/wiki/items/contraption
[HBoot]: http://www.vaingloryfire.com/vainglory/wiki/items/halcyon-chargers
[WBoot]: http://www.vaingloryfire.com/vainglory/wiki/items/war-treads
[JBoot]: http://www.vaingloryfire.com/vainglory/wiki/items/journey-boots
[SC]: http://www.vaingloryfire.com/vainglory/wiki/items/stormcrown
[SS]: http://www.vaingloryfire.com/vainglory/wiki/items/shiversteel

## Skill tier names

### Skill tier names

| Just Beginning | 1 |
| Getting There | 2 |
| Rock Solid | 3 |
| Worthy Foe |4 |
| Got Swagger | 5 |
| Credible Threat | 6 |
| The Hotness | 7 |
| Simply Amazing | 8 |
| Pinnacle of Awesome | 9 |
| Vainglorious | 10 |

See: [Skill tier names](http://www.vaingloryfire.com/vainglory/forum/general-discussion/bronze-silver-gold-rankings-5312)

## References

- Last updated for Vainglory 1.22 with some 2.0 stuff.
- [Vaingloryfire.com](http://www.vaingloryfire.com/)
- [Version history](http://forums.vainglorygame.com/index.php?threads/41129/) (forums.vainglorygame.com)
- [Skill tier points](http://brokenmyth.net/skill-tier-point-far-next-tier/#more-10043) (brokenmyth.net)


id: vagrantfile
git_filename: ./vagrantfile.md
format: md
field_title: Vagrantfile
field_category: Devops
data:
{"title": "Vagrantfile", "category": "Devops", "body": "## Vagrantfile\n{: .-one-column}\n\n```rb\nVagrant.configure(\"2\") do |config|\n  # All Vagrant configuration is done here. The most common configuration\n  # options are documented and commented below. For a complete reference,\n  # please see the online documentation at vagrantup.com.\n\n  # Every Vagrant virtual environment requires a box to build off of.\n  config.vm.box = \"precise64\"\n\n  # The url from where the 'config.vm.box' box will be fetched if it\n  # doesn't already exist on the user's system.\n  # config.vm.box_url = \"http://domain.com/path/to/above.box\"\n\n  # Create a forwarded port mapping which allows access to a specific port\n  # within the machine from a port on the host machine. In the example below,\n  # accessing \"localhost:8080\" will access port 80 on the guest machine.\n  # config.vm.network :forwarded_port, guest: 80, host: 8080\n\n  # Create a private network, which allows host-only access to the machine\n  # using a specific IP.\n  # config.vm.network :private_network, ip: \"192.168.33.10\"\n\n  # Create a public network, which generally matched to bridged network.\n  # Bridged networks make the machine appear as another physical device on\n  # your network.\n  # config.vm.network :public_network\n\n  # If true, then any SSH connections made will enable agent forwarding.\n  # Default value: false\n  # config.ssh.forward_agent = true\n\n  # Share an additional folder to the guest VM. The first argument is\n  # the path on the host to the actual folder. The second argument is\n  # the path on the guest to mount the folder. And the optional third\n  # argument is a set of non-required options.\n  # config.vm.synced_folder \"../data\", \"/vagrant_data\"\n\n  # Provider-specific configuration so you can fine-tune various\n  # backing providers for Vagrant. These expose provider-specific options.\n  # Example for VirtualBox:\n  #\n  # config.vm.provider :virtualbox do |vb|\n  #   # Don't boot with headless mode\n  #   vb.gui = true\n  #\n  #   # Use VBoxManage to customize the VM. For example to change memory:\n  #   vb.customize [\"modifyvm\", :id, \"--memory\", \"1024\"]\n  # end\n  #\n  # View the documentation for the provider you're using for more\n  # information on available options.\n\n  # Enable provisioning with Puppet stand alone.  Puppet manifests\n  # are contained in a directory path relative to this Vagrantfile.\n  # You will need to create the manifests directory and a manifest in\n  # the file precise64.pp in the manifests_path directory.\n  #\n  # An example Puppet manifest to provision the message of the day:\n  #\n  # # group { \"puppet\":\n  # #   ensure => \"present\",\n  # # }\n  # #\n  # # File { owner => 0, group => 0, mode => 0644 }\n  # #\n  # # file { '/etc/motd':\n  # #   content => \"Welcome to your Vagrant-built virtual machine!\n  # #               Managed by Puppet.\\n\"\n  # # }\n  #\n  # config.vm.provision :puppet do |puppet|\n  #   puppet.manifests_path = \"manifests\"\n  #   puppet.manifest_file  = \"init.pp\"\n  # end\n\n  # Enable provisioning with chef solo, specifying a cookbooks path, roles\n  # path, and data_bags path (all relative to this Vagrantfile), and adding\n  # some recipes and/or roles.\n  #\n  # config.vm.provision :chef_solo do |chef|\n  #   chef.cookbooks_path = \"../my-recipes/cookbooks\"\n  #   chef.roles_path = \"../my-recipes/roles\"\n  #   chef.data_bags_path = \"../my-recipes/data_bags\"\n  #   chef.add_recipe \"mysql\"\n  #   chef.add_role \"web\"\n  #\n  #   # You may also specify custom JSON attributes:\n  #   chef.json = { :mysql_password => \"foo\" }\n  # end\n\n  # Enable provisioning with chef server, specifying the chef server URL,\n  # and the path to the validation key (relative to this Vagrantfile).\n  #\n  # The Opscode Platform uses HTTPS. Substitute your organization for\n  # ORGNAME in the URL and validation key.\n  #\n  # If you have your own Chef Server, use the appropriate URL, which may be\n  # HTTP instead of HTTPS depending on your configuration. Also change the\n  # validation key to validation.pem.\n  #\n  # config.vm.provision :chef_client do |chef|\n  #   chef.chef_server_url = \"https://api.opscode.com/organizations/ORGNAME\"\n  #   chef.validation_key_path = \"ORGNAME-validator.pem\"\n  # end\n  #\n  # If you're using the Opscode platform, your validator client is\n  # ORGNAME-validator, replacing ORGNAME with your organization name.\n  #\n  # If you have your own Chef Server, the default validation client name is\n  # chef-validator, unless you changed the configuration.\n  #\n  #   chef.validation_client_name = \"ORGNAME-validator\"\nend\n```\n\n## Also see\n\n* [Vagrant cheatsheet](./vagrant)"}

field_body:
## Vagrantfile
{: .-one-column}

```rb
Vagrant.configure("2") do |config|
  # All Vagrant configuration is done here. The most common configuration
  # options are documented and commented below. For a complete reference,
  # please see the online documentation at vagrantup.com.

  # Every Vagrant virtual environment requires a box to build off of.
  config.vm.box = "precise64"

  # The url from where the 'config.vm.box' box will be fetched if it
  # doesn't already exist on the user's system.
  # config.vm.box_url = "http://domain.com/path/to/above.box"

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
  # config.vm.network :forwarded_port, guest: 80, host: 8080

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  # config.vm.network :private_network, ip: "192.168.33.10"

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  # config.vm.network :public_network

  # If true, then any SSH connections made will enable agent forwarding.
  # Default value: false
  # config.ssh.forward_agent = true

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options.
  # config.vm.synced_folder "../data", "/vagrant_data"

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  # config.vm.provider :virtualbox do |vb|
  #   # Don't boot with headless mode
  #   vb.gui = true
  #
  #   # Use VBoxManage to customize the VM. For example to change memory:
  #   vb.customize ["modifyvm", :id, "--memory", "1024"]
  # end
  #
  # View the documentation for the provider you're using for more
  # information on available options.

  # Enable provisioning with Puppet stand alone.  Puppet manifests
  # are contained in a directory path relative to this Vagrantfile.
  # You will need to create the manifests directory and a manifest in
  # the file precise64.pp in the manifests_path directory.
  #
  # An example Puppet manifest to provision the message of the day:
  #
  # # group { "puppet":
  # #   ensure => "present",
  # # }
  # #
  # # File { owner => 0, group => 0, mode => 0644 }
  # #
  # # file { '/etc/motd':
  # #   content => "Welcome to your Vagrant-built virtual machine!
  # #               Managed by Puppet.\n"
  # # }
  #
  # config.vm.provision :puppet do |puppet|
  #   puppet.manifests_path = "manifests"
  #   puppet.manifest_file  = "init.pp"
  # end

  # Enable provisioning with chef solo, specifying a cookbooks path, roles
  # path, and data_bags path (all relative to this Vagrantfile), and adding
  # some recipes and/or roles.
  #
  # config.vm.provision :chef_solo do |chef|
  #   chef.cookbooks_path = "../my-recipes/cookbooks"
  #   chef.roles_path = "../my-recipes/roles"
  #   chef.data_bags_path = "../my-recipes/data_bags"
  #   chef.add_recipe "mysql"
  #   chef.add_role "web"
  #
  #   # You may also specify custom JSON attributes:
  #   chef.json = { :mysql_password => "foo" }
  # end

  # Enable provisioning with chef server, specifying the chef server URL,
  # and the path to the validation key (relative to this Vagrantfile).
  #
  # The Opscode Platform uses HTTPS. Substitute your organization for
  # ORGNAME in the URL and validation key.
  #
  # If you have your own Chef Server, use the appropriate URL, which may be
  # HTTP instead of HTTPS depending on your configuration. Also change the
  # validation key to validation.pem.
  #
  # config.vm.provision :chef_client do |chef|
  #   chef.chef_server_url = "https://api.opscode.com/organizations/ORGNAME"
  #   chef.validation_key_path = "ORGNAME-validator.pem"
  # end
  #
  # If you're using the Opscode platform, your validator client is
  # ORGNAME-validator, replacing ORGNAME with your organization name.
  #
  # If you have your own Chef Server, the default validation client name is
  # chef-validator, unless you changed the configuration.
  #
  #   chef.validation_client_name = "ORGNAME-validator"
end
```

## Also see

* [Vagrant cheatsheet](./vagrant)


id: vagrant
git_filename: ./vagrant.md
format: md
field_title: Vagrant
field_category: Devops
field_intro: [Vagrant](http://vagrantup.com) lets you build isolated virtual environments for your apps.
data:
{"title": "Vagrant", "category": "Devops", "intro": "[Vagrant](http://vagrantup.com) lets you build isolated virtual environments for your apps.\n", "body": "### Get started\n\nAdd some base boxes:\n{: .-setup}\n\n```bash\nvagrant box add precise64 http://files.vagrantup.com/precise64.box\n```\n\nWork it:\n\n```bash\nmkdir test_box\ncd test_box\nvagrant init precise64\n```\n\nRun it:\n\n```bash\nvagrant up\nvagrant ssh\n```\n\nTo stop, use one of the following:\n\n```bash\nvagrant ssh        # then: sudo shutdown -h now\nvagrant suspend\nvagrant destroy    # !!\n```\n\n### Also see\n\n* [Vagrant website](http://vagrantup.com) _(vagrantup.com)_\n* [Vagrantfile cheatsheet](./vagrantfile)"}

field_body:
### Get started

Add some base boxes:
{: .-setup}

```bash
vagrant box add precise64 http://files.vagrantup.com/precise64.box
```

Work it:

```bash
mkdir test_box
cd test_box
vagrant init precise64
```

Run it:

```bash
vagrant up
vagrant ssh
```

To stop, use one of the following:

```bash
vagrant ssh        # then: sudo shutdown -h now
vagrant suspend
vagrant destroy    # !!
```

### Also see

* [Vagrant website](http://vagrantup.com) _(vagrantup.com)_
* [Vagrantfile cheatsheet](./vagrantfile)


id: unicode
git_filename: ./unicode.md
format: md
field_title: Unicode symbols
data:
{"title": "Unicode symbols", "body": "### Symbols\n\n    \u2708   \\u2708 airplane\n    \u2744   \\u2744 snowflake\n    \u2691   \\u2691 flag\n    \u262f   \\u262f yinyang\n    \u265e   \\u265e horse\n    \u2600   \\u2600 rays\n    \u26a0   \\u26a0 warning\n\n    \u2605   star\n    \u2606   star2\n\n    \u2690   \\u2690 flag\n    \u2691   \\u2691 flag\n\n### Bullets\n\n    \u2022   \\u2022\n    \u00b7   \\u00b7\n    \u2504   \\u2504\n    \u2014   \\u2014 (mdash)\n    \u2013   \\u2013 (ndash)\n    \u25e6   \\u25e6 circle\n\n### Checks\n\n    \u2713   \\u2713 check\n    \u2715   \\u2715\n    \u2717   \\u2717 x mark\n    \u2718   \\u2718 x mark bold\n    \u274f   \\u274f checkbox\n    \u00d7   times\n\n\n### Spinners\n\n      \u25dc\u25e0\u25dd\u25de\u25e1\u25df\n      \u2758\u2759\u275a\n\n### Triangles and arrows\n\n    \u25b2\n    \u25bc\n    \u25b6\n\n    \u2b05   \\u2b05\n    \u2b06   \\u2b06\n    \u2b07   \\u2b07\n\n    \u25e2\n    \u25e3\n    \u25e4\n    \u25e5\n\n    \u00ab   &laquo;\n    \u00bb   &raquo;\n    \u2039   &lsaquo;\n    \u203a   &rsaquo;\n    \u2022   &middot;\n\n    \u2318 \u2013 &#x2318; \u2013 &#8984; \u2013 Command Key\n    \u2325 \u2013 &#x2325; \u2013 &#8997; \u2013 Option Key\n    \u21e7 \u2013 &#x21E7; \u2013 &#8679; \u2013 Shift Key\n    \u238b \u2013 &#x238B; \u2013 &#9099; \u2013 ESC Key\n    \u21ea \u2013 &#x21ea; \u2013 &#8682; \u2013 Capslock\n    \u23ce \u2013 &#x23ce; \u2013 &#9166; \u2013 Return\n    \u232b \u2013 &#x232b; \u2013 &#9003; \u2013 Delete / Backspace\n\n    \u25b8   \\u25b8 right arrow\n    \u25b9\n\n    \u25c7   \\u25c7\n    \u25c6\n\n    \u25d0\n    \u25d1\n    \u25d2\n    \u25d3\n\n\n    \u2660   \\u2660\n    \u2663   \\u2663\n    \u2665   \\u2665\n    \u2666   \\u2666\n\n\n    \u2702  scissors\n    \u2139 information &#008505;\n    \u2661 heart &#009825;\n    \u2699 cog or gear &#009881;\n    \u2709 envelope &#009993;\n    \u270e pencil &#009998;\n\n### JavaScript\n\n    \"x\".charCodeAt(0)\n    \"x\".charCodeAt(0).toString(16)\n\n    http://www.danshort.com/HTMLentities/index.php?w=dingb"}

field_body:
### Symbols

    ✈   \u2708 airplane
    ❄   \u2744 snowflake
    ⚑   \u2691 flag
    ☯   \u262f yinyang
    ♞   \u265e horse
    ☀   \u2600 rays
    ⚠   \u26a0 warning

    ★   star
    ☆   star2

    ⚐   \u2690 flag
    ⚑   \u2691 flag

### Bullets

    •   \u2022
    ·   \u00b7
    ┄   \u2504
    —   \u2014 (mdash)
    –   \u2013 (ndash)
    ◦   \u25e6 circle

### Checks

    ✓   \u2713 check
    ✕   \u2715
    ✗   \u2717 x mark
    ✘   \u2718 x mark bold
    ❏   \u274f checkbox
    ×   times


### Spinners

      ◜◠◝◞◡◟
      ❘❙❚

### Triangles and arrows

    ▲
    ▼
    ▶

    ⬅   \u2b05
    ⬆   \u2b06
    ⬇   \u2b07

    ◢
    ◣
    ◤
    ◥

    «   &laquo;
    »   &raquo;
    ‹   &lsaquo;
    ›   &rsaquo;
    •   &middot;

    ⌘ – &#x2318; – &#8984; – Command Key
    ⌥ – &#x2325; – &#8997; – Option Key
    ⇧ – &#x21E7; – &#8679; – Shift Key
    ⎋ – &#x238B; – &#9099; – ESC Key
    ⇪ – &#x21ea; – &#8682; – Capslock
    ⏎ – &#x23ce; – &#9166; – Return
    ⌫ – &#x232b; – &#9003; – Delete / Backspace

    ▸   \u25b8 right arrow
    ▹

    ◇   \u25c7
    ◆

    ◐
    ◑
    ◒
    ◓


    ♠   \u2660
    ♣   \u2663
    ♥   \u2665
    ♦   \u2666


    ✂  scissors
    ℹ information &#008505;
    ♡ heart &#009825;
    ⚙ cog or gear &#009881;
    ✉ envelope &#009993;
    ✎ pencil &#009998;

### JavaScript

    "x".charCodeAt(0)
    "x".charCodeAt(0).toString(16)

    http://www.danshort.com/HTMLentities/index.php?w=dingb


id: underscore-string
git_filename: ./underscore-string.md
format: md
field_title: Underscore-string
field_category: JavaScript libraries
data:
{"title": "Underscore-string", "category": "JavaScript libraries", "body": "### Usage\n\n    // Use it like so:\n    _.str.trim(\"hey\");\n    _s.trim(\"hey\");\n\n    // Unless you do:\n    _.mixin(_.string.exports());\n\n    // So you can:\n    _.trim(\"hey\");\n    _(\"hey\").trim();\n\n### Trimming\n\n    _.truncate(\"Hello world\", 4) // => \"Hell...\"\n    _.prune(\"Hello world\", 5)    // => \"Hello...\"\n\n    _.trim(\" foo \")              // => \"foo\"\n    _.trim(\"-foo-\", '-')         // => \"foo\"\n    _.ltrim\n    _.rtrim\n\n### Numbers\n\n    _.numberFormat(1000, 2)  // => \"1,000.00\"\n\n### Caps\n\n    _.capitalize(\"foo bar\")       // => \"Foo Bar\"\n    _.humanize(\"hey-there foo\")   // => \"Hey there foo\"\n    _.titleize('My name is hi')   // => \"My Name Is Hi\"\n\n    _.dasherize('MozTransform')   // => \"-moz-transform\"\n    _.underscored('MozTransform') // => \"moz_transform\"\n    _.classify('-moz-transform')  // => \"MozTransform\"\n    _.camelize('moz_transform')   // => \"MozTransform\"\n\n    _.slugify(\"hey there\")        // => \"hey-there\"\n\n    _.swapCase(\"hELLO\")           // => \"Hello\"\n\n### Checks\n\n    _.startsWith('image.gif', 'image') // => true\n    _.endsWith('image.gif', '.gif')    // => true\n    _.isBlank(\" \")                     // => true (also for \"\\n\", \"\")\n\n### HTML\n\n    _.escapeHTML(\"<div>\")\n    _.unescapeHTML(\"&lt;div&gt;\")\n    _.stripTags(\"<div>hi</div>\")\n\n### Quote\n\n    _.quote(\"hi\", '\"') // => '\"hi\"'\n    _.unquote('\"hi\"')  // => \"hi\"\n\n### Splits\n\n    _.lines(\"hi\\nthere\")     // => [\"hi\",\"there\"]\n    _.words(\"hi  there you\") // => [\"hi\",\"there\",\"you\"]\n\n### Sprintf\n\n    _.sprintf(\"%.1f\", 1.17)\n\n### Pad\n\n    _.pad(\"1\", 8)               // => \"       1\"\n    _.pad(\"1\", 8, \"0\")          // => \"00000001\"\n    _.pad(\"1\", 8, \" \", \"right\") // => \"1       \"\n    _.pad(\"1\", 8, \" \", \"both\")  // => \"    1   \"\n\n    _.lpad(..)  // same as _.pad(.., 'left')\n    _.rpad(..)  // same as _.pad(.., 'right')\n    _.lrpad(..) // same as _.pad(.., 'both')\n\n### References\n\n* https://github.com/epeli/underscore.string"}

field_body:
### Usage

    // Use it like so:
    _.str.trim("hey");
    _s.trim("hey");

    // Unless you do:
    _.mixin(_.string.exports());

    // So you can:
    _.trim("hey");
    _("hey").trim();

### Trimming

    _.truncate("Hello world", 4) // => "Hell..."
    _.prune("Hello world", 5)    // => "Hello..."

    _.trim(" foo ")              // => "foo"
    _.trim("-foo-", '-')         // => "foo"
    _.ltrim
    _.rtrim

### Numbers

    _.numberFormat(1000, 2)  // => "1,000.00"

### Caps

    _.capitalize("foo bar")       // => "Foo Bar"
    _.humanize("hey-there foo")   // => "Hey there foo"
    _.titleize('My name is hi')   // => "My Name Is Hi"

    _.dasherize('MozTransform')   // => "-moz-transform"
    _.underscored('MozTransform') // => "moz_transform"
    _.classify('-moz-transform')  // => "MozTransform"
    _.camelize('moz_transform')   // => "MozTransform"

    _.slugify("hey there")        // => "hey-there"

    _.swapCase("hELLO")           // => "Hello"

### Checks

    _.startsWith('image.gif', 'image') // => true
    _.endsWith('image.gif', '.gif')    // => true
    _.isBlank(" ")                     // => true (also for "\n", "")

### HTML

    _.escapeHTML("<div>")
    _.unescapeHTML("&lt;div&gt;")
    _.stripTags("<div>hi</div>")

### Quote

    _.quote("hi", '"') // => '"hi"'
    _.unquote('"hi"')  // => "hi"

### Splits

    _.lines("hi\nthere")     // => ["hi","there"]
    _.words("hi  there you") // => ["hi","there","you"]

### Sprintf

    _.sprintf("%.1f", 1.17)

### Pad

    _.pad("1", 8)               // => "       1"
    _.pad("1", 8, "0")          // => "00000001"
    _.pad("1", 8, " ", "right") // => "1       "
    _.pad("1", 8, " ", "both")  // => "    1   "

    _.lpad(..)  // same as _.pad(.., 'left')
    _.rpad(..)  // same as _.pad(.., 'right')
    _.lrpad(..) // same as _.pad(.., 'both')

### References

* https://github.com/epeli/underscore.string


id: umdjs
git_filename: ./umdjs.md
format: md
field_title: Universal JS module loader
field_category: JavaScript libraries
data:
{"title": "Universal JS module loader", "category": "JavaScript libraries", "body": "### Reference\n\n * <https://github.com/umdjs/umd>\n\n### [With dependency](https://github.com/umdjs/umd/blob/master/amdWebGlobal.js)\n\n~~~ js\n;(function (root, factory) {\n\n  if (typeof define === 'function' && define.amd) {\n    define(['jquery'], factory);\n  } else if (typeof exports === 'object') {\n    module.exports = factory(require('jquery'));\n  } else {\n    root.YourModule = factory(root.jQuery);\n  }\n\n}(this, function (jquery) {\n  return {};\n}));\n~~~\n\n### No dependencies\n\n~~~ js\n;(function (root, factory) {\n\n  if (typeof define === 'function' && define.amd) {\n    define(factory);\n  } else if (typeof exports === 'object') {\n    module.exports = factory();\n  } else {\n    root.YourModule = factory();\n  }\n\n}(this, function () {\n  return {};\n}));\n~~~\n\n### [Supports circular references](https://github.com/umdjs/umd/blob/master/commonjsStrict.js)\n\n~~~ js\n(function (root, factory) {\n\n  if (typeof define === 'function' && define.amd) {\n    define(['exports', 'jquery'], factory);\n  } else if (typeof exports === 'object') {\n    factory(exports, require('jquery'));\n  } else {\n    factory((root.YourModule = {}), root.jQuery);\n  }\n\n}(this, function (exports, jQuery) {\n  exports.action = function () {};\n}));\n~~~"}

field_body:
### Reference

 * <https://github.com/umdjs/umd>

### [With dependency](https://github.com/umdjs/umd/blob/master/amdWebGlobal.js)

~~~ js
;(function (root, factory) {

  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory(require('jquery'));
  } else {
    root.YourModule = factory(root.jQuery);
  }

}(this, function (jquery) {
  return {};
}));
~~~

### No dependencies

~~~ js
;(function (root, factory) {

  if (typeof define === 'function' && define.amd) {
    define(factory);
  } else if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    root.YourModule = factory();
  }

}(this, function () {
  return {};
}));
~~~

### [Supports circular references](https://github.com/umdjs/umd/blob/master/commonjsStrict.js)

~~~ js
(function (root, factory) {

  if (typeof define === 'function' && define.amd) {
    define(['exports', 'jquery'], factory);
  } else if (typeof exports === 'object') {
    factory(exports, require('jquery'));
  } else {
    factory((root.YourModule = {}), root.jQuery);
  }

}(this, function (exports, jQuery) {
  exports.action = function () {};
}));
~~~


id: ubuntu
git_filename: ./ubuntu.md
format: md
field_title: Ubuntu
data:
{"title": "Ubuntu", "body": "### Aptitude stuff\n\n    aptitude search mysql       # Look for something\n    dpkg -S `which tsclient`    # What package does it belong to?\n    dpkg -L aria2c              # What does this package provide?\n    dpkg -i *.deb               # Install a deb file\n    dpkg -s nodejs              # Show info\n\n    dpkg --get-selections       # list installed packages\n\n### Apt archives path\n\n    /var/cache/apt/archives\n\n### List services\n\n    service --status-all"}

field_body:
### Aptitude stuff

    aptitude search mysql       # Look for something
    dpkg -S `which tsclient`    # What package does it belong to?
    dpkg -L aria2c              # What does this package provide?
    dpkg -i *.deb               # Install a deb file
    dpkg -s nodejs              # Show info

    dpkg --get-selections       # list installed packages

### Apt archives path

    /var/cache/apt/archives

### List services

    service --status-all


id: typescript
git_filename: ./typescript.md
format: md
field_title: TypeScript
field_category: JavaScript libraries
data:
{"title": "TypeScript", "category": "JavaScript libraries", "body": "### About\n\nTypeScript is just like ES2015 with type-checking. All ES2015 (classes, etc) should work.\n\n### Basic types\n\n```ts\nany\nvoid\n\nboolean\nnumber\nstring\n\nnull\nundefined\n\nbigint\nsymbol\n\nstring[]          /* or Array<string> */\n[string, number]  /* tuple */\n\nstring | null | undefined   /* union */\n\nnever  /* unreachable */\nunknown\n```\n\n```ts\nenum Color {\n  Red,\n  Green,\n  Blue = 4\n};\n\nlet c: Color = Color.Green\n```\n\n### Declarations\n\n```ts\nlet isDone: boolean\nlet isDone: boolean = false\n```\n\n```ts\nfunction add (a: number, b: number): number {\n  return a + b\n}\n\n// Return type is optional\nfunction add (a: number, b: number) { ... }\n```\n\n## Type assertions\n\n#### Variables\n```ts\nlet len: number = (input as string).length\nlet len: number = (<string> input).length  /* not allowed in JSX */\n```\n\n#### Functions\n```ts\nfunction object(this: {a: number, b: number}, a: number, b: number) {\n  this.a = a;\n  this.b = b;\n  return this;\n}\n\n// this is used only for type declaration\nlet a = object(1,2);\n// a has type {a: number, b: number}\n```\n\n\n## Interfaces\n\n### Inline\n\n```ts\nfunction printLabel (options: { label: string }) {\n  console.log(options.label)\n}\n\n// Note the semicolon\nfunction getUser (): { name: string; age?: number } {\n}\n```\n\n### Explicit\n\n```ts\ninterface LabelOptions {\n  label: string\n}\n\nfunction printLabel(options: LabelOptions) { ... }\n```\n\n### Optional properties\n\n```ts\ninterface User {\n  name: string;\n  age?: number;\n}\n```\n\n### Read only\n\n```ts\ninterface User {\n  readonly name: string\n}\n```\n\n### Dynamic keys\n\n```ts\n{\n  [key: string]: Object[]\n}\n```\n\n## Type aliases\n\n### Type aliases\n\n```ts\ntype Name = string | string[]\n```\n\n### Intersection\n\n```ts\ninterface Colorful { ... }\n\ninterface Circle { ... }\n \ntype ColorfulCircle = Colorful & Circle;\n```\n\n## Function types\n\n```ts\ninterface User { ... }\n\nfunction getUser(callback: (user: User) => any) { callback({...}) }\n\ngetUser(function (user: User) { ... })\n```\n\n## Classes\n\n```ts\nclass Point {\n  x: number\n  y: number\n  static instances = 0\n  constructor(x: number, y: number) {\n    this.x = x\n    this.y = y\n  }\n}\n```\n\n#### Inheritance\n\n```ts\nclass Point {...}\n\nclass Point3D extends Point {...}\n\ninterface Colored {...}\n\nclass Pixel extends Point implements Colored {...}\n```\n\n#### Short fields initialisation\n\n```ts\nclass Point {\n  static instances = 0;\n  constructor(\n    public x: number,\n    public y: number,\n  ){}\n}\n```\n\n#### Fields which do not require initialisation\n```ts\nclass Point {\n  public someUselessValue!: number;\n  ...\n}\n```\n\n## Generics\n\n```ts\nclass Greeter<T> {\n  greeting: T\n  constructor(message: T) {\n    this.greeting = message\n  }\n}\n\nlet greeter = new Greeter<string>('Hello, world')\n```\n\n## Modules\n\n```ts\nexport interface User { ... }\n```\n\n## Type extraction\n\n```ts\ninterface Building {\n  room: {\n    door: string;\n    walls: string[];\n  };\n}\n\ntype Walls = Building['room']['walls']; // string[]\n```\n\n## Keyof Type Operator\n\n```ts\ntype Point = { x: number; y: number };\n\ntype P = keyof Point; // x | y\n```\n\n## Conditional Types\n\n```ts\n// SomeType extends OtherType ? TrueType : FalseType;\n\ntype ToArray<T> = T extends any ? T[] : never;\n\ntype StrArrOrNumArr = ToArray<string | number>; // string[] | number[]\n```\n\n### Inferring\n\n```ts\ntype GetReturnType<T> = T extends (...args: unknown[]) => infer R\n  ? R\n  : never;\n\ntype Num = GetReturnType<() => number>; // number\n```\n\n```ts\ntype First<T extends Array<any>> = T extends [infer F, ...infer Rest] ? F : never;\n\ntype Str = First<['hello', 1, false]>; // 'hello'\n```\n\n## Literal Type\n\n```ts\nconst point = { x: 4, y: 2 }; // { x: number, y: number }\n\nconst literalPoint = { x: 4, y: 2 } as const; // { readonly x: 4, readonly y: 2 };\n```\n\n## Template Literal Types\n\n```ts\ntype SpaceChar = ' ' | '\\n' | '\\t';\n\ntype TrimLeft<S extends string> = S extends `${SpaceChar}${infer Rest}` ? TrimLeft<Rest> : S;\n\ntype Str = TrimLeft<'    hello'>; // 'hello'\n```"}

field_body:
### About

TypeScript is just like ES2015 with type-checking. All ES2015 (classes, etc) should work.

### Basic types

```ts
any
void

boolean
number
string

null
undefined

bigint
symbol

string[]          /* or Array<string> */
[string, number]  /* tuple */

string | null | undefined   /* union */

never  /* unreachable */
unknown
```

```ts
enum Color {
  Red,
  Green,
  Blue = 4
};

let c: Color = Color.Green
```

### Declarations

```ts
let isDone: boolean
let isDone: boolean = false
```

```ts
function add (a: number, b: number): number {
  return a + b
}

// Return type is optional
function add (a: number, b: number) { ... }
```

## Type assertions

#### Variables
```ts
let len: number = (input as string).length
let len: number = (<string> input).length  /* not allowed in JSX */
```

#### Functions
```ts
function object(this: {a: number, b: number}, a: number, b: number) {
  this.a = a;
  this.b = b;
  return this;
}

// this is used only for type declaration
let a = object(1,2);
// a has type {a: number, b: number}
```


## Interfaces

### Inline

```ts
function printLabel (options: { label: string }) {
  console.log(options.label)
}

// Note the semicolon
function getUser (): { name: string; age?: number } {
}
```

### Explicit

```ts
interface LabelOptions {
  label: string
}

function printLabel(options: LabelOptions) { ... }
```

### Optional properties

```ts
interface User {
  name: string;
  age?: number;
}
```

### Read only

```ts
interface User {
  readonly name: string
}
```

### Dynamic keys

```ts
{
  [key: string]: Object[]
}
```

## Type aliases

### Type aliases

```ts
type Name = string | string[]
```

### Intersection

```ts
interface Colorful { ... }

interface Circle { ... }
 
type ColorfulCircle = Colorful & Circle;
```

## Function types

```ts
interface User { ... }

function getUser(callback: (user: User) => any) { callback({...}) }

getUser(function (user: User) { ... })
```

## Classes

```ts
class Point {
  x: number
  y: number
  static instances = 0
  constructor(x: number, y: number) {
    this.x = x
    this.y = y
  }
}
```

#### Inheritance

```ts
class Point {...}

class Point3D extends Point {...}

interface Colored {...}

class Pixel extends Point implements Colored {...}
```

#### Short fields initialisation

```ts
class Point {
  static instances = 0;
  constructor(
    public x: number,
    public y: number,
  ){}
}
```

#### Fields which do not require initialisation
```ts
class Point {
  public someUselessValue!: number;
  ...
}
```

## Generics

```ts
class Greeter<T> {
  greeting: T
  constructor(message: T) {
    this.greeting = message
  }
}

let greeter = new Greeter<string>('Hello, world')
```

## Modules

```ts
export interface User { ... }
```

## Type extraction

```ts
interface Building {
  room: {
    door: string;
    walls: string[];
  };
}

type Walls = Building['room']['walls']; // string[]
```

## Keyof Type Operator

```ts
type Point = { x: number; y: number };

type P = keyof Point; // x | y
```

## Conditional Types

```ts
// SomeType extends OtherType ? TrueType : FalseType;

type ToArray<T> = T extends any ? T[] : never;

type StrArrOrNumArr = ToArray<string | number>; // string[] | number[]
```

### Inferring

```ts
type GetReturnType<T> = T extends (...args: unknown[]) => infer R
  ? R
  : never;

type Num = GetReturnType<() => number>; // number
```

```ts
type First<T extends Array<any>> = T extends [infer F, ...infer Rest] ? F : never;

type Str = First<['hello', 1, false]>; // 'hello'
```

## Literal Type

```ts
const point = { x: 4, y: 2 }; // { x: number, y: number }

const literalPoint = { x: 4, y: 2 } as const; // { readonly x: 4, readonly y: 2 };
```

## Template Literal Types

```ts
type SpaceChar = ' ' | '\n' | '\t';

type TrimLeft<S extends string> = S extends `${SpaceChar}${infer Rest}` ? TrimLeft<Rest> : S;

type Str = TrimLeft<'    hello'>; // 'hello'
```


id: travis
git_filename: ./travis.md
format: md
field_title: Travis.yml
field_category: Devops
field_prism_languages: yaml
data:
{"title": "Travis.yml", "category": "Devops", "prism_languages": ["yaml"], "intro": "Quick reference for [Travis CI](https://travis-ci.org) yaml configuration. See [official documentation](https://docs.travis-ci.com/user/customizing-the-build/).\n", "body": "## Reference\n{:.-three-column}\n\n### Node.js\n\n```yaml\nlanguage: node_js\nnode_js:\n  - '4'\n```\n\nDefaults install to `npm install`, and defaults test to `npm test`.\n\n### Ruby\n\n```yaml\nlanguage: ruby\nrvm:\n  - 2.0.0\n  - 1.9.3\n  - 1.8.7\n```\n\nDefaults install to `bundle install`, defaults test to `rake`.\n\n### Build lifecycle\n\n| Lifecycle                          |\n| ---------------------------------- |\n| `before_install`                   |\n| `install`                          |\n| ---                                |\n| `before_script`                    |\n| `script`                           |\n| ---                                |\n| `after_success` or `after_failure` |\n| `after_script`                     |\n| ---                                |\n| `before_deploy` (optional)         |\n| `deploy` (optional)                |\n| `after_deploy` (optional)          |\n\n### Branches\n\n```yaml\nbranches:\n  except: ['..']\n  only: ['master']\n```\n\n### Environment vars\n\n```yaml\nenv:\n  - 'rack=master'\n  - 'rack=1.3.4'\n```\n\n### Custom test command\n\n```yaml\nscript: make test\nbefore_script: make pretest\nafter_script:  make clean\n\nbefore_script:\n  - make pretest1\n  - make pretest2\n```\n\n### Branches\n\n```yaml\nbranches:\n  except:\n    - legacy\n\n  only:\n    - gh-pages\n    - /^deploy/\n```\n\n### Apt packages\n\n```yaml\nbefore_install:\n  - sudo apt-get update -q\n  - sudo apt-get install gcc-4.8 -y\n```\n\n<https://docs.travis-ci.com/user/installing-dependencies/>\n\n### Etc\n\n```yaml\ngemfile:\n  - gemfiles/Gemfile.rails-2.3.x\n  - gemfiles/Gemfile.rails-3.0.x\n```\n\n### References\n\n- https://about.travis-ci.org/docs/user/build-configuration/\n- https://about.travis-ci.org/docs/user/languages/javascript-with-nodejs/\n- https://about.travis-ci.org/docs/user/languages/ruby/"}

field_intro:
Quick reference for [Travis CI](https://travis-ci.org) yaml configuration. See [official documentation](https://docs.travis-ci.com/user/customizing-the-build/).

field_body:
## Reference
{:.-three-column}

### Node.js

```yaml
language: node_js
node_js:
  - '4'
```

Defaults install to `npm install`, and defaults test to `npm test`.

### Ruby

```yaml
language: ruby
rvm:
  - 2.0.0
  - 1.9.3
  - 1.8.7
```

Defaults install to `bundle install`, defaults test to `rake`.

### Build lifecycle

| Lifecycle                          |
| ---------------------------------- |
| `before_install`                   |
| `install`                          |
| ---                                |
| `before_script`                    |
| `script`                           |
| ---                                |
| `after_success` or `after_failure` |
| `after_script`                     |
| ---                                |
| `before_deploy` (optional)         |
| `deploy` (optional)                |
| `after_deploy` (optional)          |

### Branches

```yaml
branches:
  except: ['..']
  only: ['master']
```

### Environment vars

```yaml
env:
  - 'rack=master'
  - 'rack=1.3.4'
```

### Custom test command

```yaml
script: make test
before_script: make pretest
after_script:  make clean

before_script:
  - make pretest1
  - make pretest2
```

### Branches

```yaml
branches:
  except:
    - legacy

  only:
    - gh-pages
    - /^deploy/
```

### Apt packages

```yaml
before_install:
  - sudo apt-get update -q
  - sudo apt-get install gcc-4.8 -y
```

<https://docs.travis-ci.com/user/installing-dependencies/>

### Etc

```yaml
gemfile:
  - gemfiles/Gemfile.rails-2.3.x
  - gemfiles/Gemfile.rails-3.0.x
```

### References

- https://about.travis-ci.org/docs/user/build-configuration/
- https://about.travis-ci.org/docs/user/languages/javascript-with-nodejs/
- https://about.travis-ci.org/docs/user/languages/ruby/


id: top
git_filename: ./top.md
format: md
field_title: top
field_category: CLI
field_intro: See the processes in your Unix machine.
field_updated: 2020-01-01
field_updated___timezone: UTC
data:
{"title": "top", "category": "CLI", "updated": "2020-01-01", "intro": "See the processes in your Unix machine.", "body": "### Shortcuts\n\n| Shortcut  | Description           |\n| --------- | --------------------- |\n| `h`       | shows help            |\n| `q`       | quits the program     |\n| `m`       | switches memory view  |\n| `1`       | switches cpu view     |\n| `k`       | kills process         |\n| `Shift+p` | sorts by CPU usage    |\n| `Shift+m` | sorts by memory usage |\n| `Shift+r` | reverses sorting      |\n| `Shift+l` | searches for string   |\n| `o`       | adds a filter         |\n| `u`       | filter user           |\n| `=`       | clears filters        |\n| `V`       | Forest view           |\n| `c`       | show full path        |\n{: .-shortcuts}"}

field_body:
### Shortcuts

| Shortcut  | Description           |
| --------- | --------------------- |
| `h`       | shows help            |
| `q`       | quits the program     |
| `m`       | switches memory view  |
| `1`       | switches cpu view     |
| `k`       | kills process         |
| `Shift+p` | sorts by CPU usage    |
| `Shift+m` | sorts by memory usage |
| `Shift+r` | reverses sorting      |
| `Shift+l` | searches for string   |
| `o`       | adds a filter         |
| `u`       | filter user           |
| `=`       | clears filters        |
| `V`       | Forest view           |
| `c`       | show full path        |
{: .-shortcuts}


id: tomdoc
git_filename: ./tomdoc.md
format: md
field_title: Tomdoc
field_category: Markup
data:
{"title": "Tomdoc", "category": "Markup", "body": "### Tomdoc\n{: .-prime}\n\n```ruby\n# Public: Duplicate some text an arbitrary number of times.\n#\n# text  - The String to be duplicated.\n# count - The Integer number of times to duplicate the text.\n#\n# Examples\n#\n#   multiplex('Tom', 4)\n#   # => 'TomTomTomTom'\n#\n# Returns the duplicated String.\ndef multiplex(text, count)\n  text * count\nend\n```\n\nSee [tomdoc.org](http://tomdoc.org/).\n\n### Tags\n\n- `Deprecated`\n- `Internal`\n- `Public`\n\n### Options\n\n```ruby\n# options - The Hash options used to refine the selection (default: {}):\n#           :color  - The String color to restrict by (optional).\n#           :weight - The Float weight to restrict by. The weight should\n#                     be specified in grams (optional).\n```\n\n### Yields\n\n```ruby\n# Yields the Integer index of the iteration.\n```\n\n```ruby\n# Returns the duplicated String.\n```\n\n```ruby\n# Returns nothing.\n```\n\n```ruby\n# Raises Errno::ENOENT if the file can't be found.\n```\n\n```ruby\n# Returns something else and this is a wrapped\n#   multi-line comment.\n```\n\n### Signatures\n\n```ruby\n# Signature\n#\n#   find_by_<field>[_and_<field>...](args)\n#\n```"}

field_body:
### Tomdoc
{: .-prime}

```ruby
# Public: Duplicate some text an arbitrary number of times.
#
# text  - The String to be duplicated.
# count - The Integer number of times to duplicate the text.
#
# Examples
#
#   multiplex('Tom', 4)
#   # => 'TomTomTomTom'
#
# Returns the duplicated String.
def multiplex(text, count)
  text * count
end
```

See [tomdoc.org](http://tomdoc.org/).

### Tags

- `Deprecated`
- `Internal`
- `Public`

### Options

```ruby
# options - The Hash options used to refine the selection (default: {}):
#           :color  - The String color to restrict by (optional).
#           :weight - The Float weight to restrict by. The weight should
#                     be specified in grams (optional).
```

### Yields

```ruby
# Yields the Integer index of the iteration.
```

```ruby
# Returns the duplicated String.
```

```ruby
# Returns nothing.
```

```ruby
# Raises Errno::ENOENT if the file can't be found.
```

```ruby
# Returns something else and this is a wrapped
#   multi-line comment.
```

### Signatures

```ruby
# Signature
#
#   find_by_<field>[_and_<field>...](args)
#
```


id: tmux
git_filename: ./tmux.md
format: md
field_title: tmux
field_category: CLI
field_updated: 2024-04-08
field_updated___timezone: UTC
data:
{"title": "tmux", "category": "CLI", "updated": "2024-04-08", "body": "### Commands\n\n    $ tmux\n      -u        # UTF8 mode\n      -S ~/.tmux.socket\n\n#### Sessions\n\n    $ tmux new\n    $ tmux new -s session_name\n\n    $ tmux attach # Default session\n    $ tmux attach -t session_name\n\n    $ tmux switch -t session_name\n\n    $ tmux ls     # List sessions\n\n    $ tmux detach\n\n#### Windows\n\n    $ tmux new-window\n\n### Help\n\n    C-b ?\n\n### Scrolling\n\n    C-b [       # Enter scroll mode then press up and down, you can also scroll with mouse support enabled (`set -g mouse on` in `~/.tmux.conf`)\n\n### Copy/paste\n\n    C-b [       # 1. Enter scroll mode first\n    Space       # 2. Start selecting and move around\n    Enter       # 3. Press enter to copy\n    C-b ]       # Paste\n\n### Panes\n\n    C-b %       # vert\n    C-b \"       # horiz\n    C-b hkjl    # navigation\n    C-b HJKL    # resize\n    C-b o       # next window\n    C-b q       # show pane numbers\n    C-b x       # close pane\n\n    C-b { or }  # move windows around\n\n### Windows\n\n    C-b c       # New window\n    C-b 1       # Go to window 1\n    C-b n       # Go to next window\n    C-b p       # Go to previous window\n    C-b w       # List all window\n\n### Detach/attach\n\n    C-b d       # Detach\n    C-b ( )     # Switch through sessions\n    $ tmux attach\n\n### Search in buffer\n\n    C-b [       # 1. Enter scroll mode first, you can also scroll with mouse support enabled\n    C-s         # 2. Enter search mode, type pattern then press Enter to start search\n    n or N      # 3. Go to the previous or next match\n    C-c         # 4. Exit search and scroll mode\n\n### Niceties\n\n    C-b t       # Display a clock, press any key to quit\n\n## Status formats\n\n```\nsetw -g window-status-format `#[fg=8,bg=default]#I`\n```\n\nSee `message-command-style` in the man page.\n\n### Attribute/colors\n\n| Key | Description |\n| --- | --- |\n| `#[fg=1]` | standard color |\n| `#[fg=yellow]` | yellow |\n| `#[bold]` | bold |\n| `#[fg=colour240]` | 256 color |\n| `#[fg=default]` | default |\n| `#[fg=1,bg=2]` | combinations |\n| `#[default]` | reset |\n\n### Colors\n\n * `black` `red` `green` `yellow` `blue` `magenta` `cyan` `white`\n * `brightred` (and so on)\n * `colour0` ... `colour255`\n * `#333` (rgb hex)\n\n### Attributes\n\n * `bold` `underscore` `blink` `noreverse` `hidden` `dim` `italics`\n\n### Variables\n\n| Key | Description |\n| --- | --- |\n| `#(date)` | shell command |\n| `#I` | window index |\n| `#S` | session name |\n| `#W` | window name |\n| `#F` | window flags |\n| `#H` | Hostname |\n| `#h` | Hostname, short |\n| `#D` | pane id |\n| `#P` | pane index |\n| `#T` | pane title |\n\n## Options\n\n    set -g status-justify [left|centre|right]\n    set -g status-left '...'\n\n    setw -g window-status-style\n    setw -g window-status-activity-style\n    setw -g window-status-bell-style\n    setw -g window-status-content-style\n    setw -g window-status-current-style\n    setw -g window-status-last-style\n\n    setw -g window-status-format\n    setw -g window-status-current-format\n\n    setw -g window-status-separator"}

field_body:
### Commands

    $ tmux
      -u        # UTF8 mode
      -S ~/.tmux.socket

#### Sessions

    $ tmux new
    $ tmux new -s session_name

    $ tmux attach # Default session
    $ tmux attach -t session_name

    $ tmux switch -t session_name

    $ tmux ls     # List sessions

    $ tmux detach

#### Windows

    $ tmux new-window

### Help

    C-b ?

### Scrolling

    C-b [       # Enter scroll mode then press up and down, you can also scroll with mouse support enabled (`set -g mouse on` in `~/.tmux.conf`)

### Copy/paste

    C-b [       # 1. Enter scroll mode first
    Space       # 2. Start selecting and move around
    Enter       # 3. Press enter to copy
    C-b ]       # Paste

### Panes

    C-b %       # vert
    C-b "       # horiz
    C-b hkjl    # navigation
    C-b HJKL    # resize
    C-b o       # next window
    C-b q       # show pane numbers
    C-b x       # close pane

    C-b { or }  # move windows around

### Windows

    C-b c       # New window
    C-b 1       # Go to window 1
    C-b n       # Go to next window
    C-b p       # Go to previous window
    C-b w       # List all window

### Detach/attach

    C-b d       # Detach
    C-b ( )     # Switch through sessions
    $ tmux attach

### Search in buffer

    C-b [       # 1. Enter scroll mode first, you can also scroll with mouse support enabled
    C-s         # 2. Enter search mode, type pattern then press Enter to start search
    n or N      # 3. Go to the previous or next match
    C-c         # 4. Exit search and scroll mode

### Niceties

    C-b t       # Display a clock, press any key to quit

## Status formats

```
setw -g window-status-format `#[fg=8,bg=default]#I`
```

See `message-command-style` in the man page.

### Attribute/colors

| Key | Description |
| --- | --- |
| `#[fg=1]` | standard color |
| `#[fg=yellow]` | yellow |
| `#[bold]` | bold |
| `#[fg=colour240]` | 256 color |
| `#[fg=default]` | default |
| `#[fg=1,bg=2]` | combinations |
| `#[default]` | reset |

### Colors

 * `black` `red` `green` `yellow` `blue` `magenta` `cyan` `white`
 * `brightred` (and so on)
 * `colour0` ... `colour255`
 * `#333` (rgb hex)

### Attributes

 * `bold` `underscore` `blink` `noreverse` `hidden` `dim` `italics`

### Variables

| Key | Description |
| --- | --- |
| `#(date)` | shell command |
| `#I` | window index |
| `#S` | session name |
| `#W` | window name |
| `#F` | window flags |
| `#H` | Hostname |
| `#h` | Hostname, short |
| `#D` | pane id |
| `#P` | pane index |
| `#T` | pane title |

## Options

    set -g status-justify [left|centre|right]
    set -g status-left '...'

    setw -g window-status-style
    setw -g window-status-activity-style
    setw -g window-status-bell-style
    setw -g window-status-content-style
    setw -g window-status-current-style
    setw -g window-status-last-style

    setw -g window-status-format
    setw -g window-status-current-format

    setw -g window-status-separator


id: tig
git_filename: ./tig.md
format: md
field_title: Tig
field_category: Git
field_updated: 2022-12-08
field_updated___timezone: UTC
data:
{"title": "Tig", "category": "Git", "updated": "2022-12-08", "weight": -3, "body": "### Installing\n\n```bash\n# MacOS + Homebrew\n$ brew install tig --HEAD\n```\n\n```bash\n# Ubuntu\n$ sudo apt install tig\n```\n\n### Invocation\n\n| Command             | Description                                  |\n| ------------------- | -------------------------------------------- |\n| `tig`               | Logs                                         |\n| ---                 | ---                                          |\n| `tig status`        | Status                                       |\n| `tig blame FILE`    | Blame                                        |\n| ---                 | ---                                          |\n| `tig master`        | Show a branch                                |\n| `tig test..master`  | Show difference between two branches         |\n| `tig FILE`          | Show history of file                         |\n| `tig v0.0.3:README` | Show contents of file in a specific revision |\n| `tig -C /repo/path` | Run in dir `/repo/path` (like `git -C`)      |\n\nYou can substitute `git log` \u2192 `tig`.\n\n## Shortcut keys\n{: .-three-column}\n\n### Switching views\n\n| Shortcut | Description  |\n| -------- | ------------ |\n| `m`      | Main view    |\n| `d`      | Diff         |\n| `t`      | Tree (files) |\n| `b`      | Blame        |\n| `s`      | Status       |\n| `c`      | Stage        |\n| `y`      | Stash        |\n| `g`      | Grep         |\n| `h`      | Help         |\n{: .-shortcuts}\n\n### All views\n\n| Shortcut  | Description                  |\n| ---       | ---                          |\n| `<enter>` | Enter and open selected line |\n| `<`       | Back to previous view state  |\n| `<tab>`   | Move focus to next view      |\n| `R`       | Refresh                      |\n| `q`       | Close view                   |\n| `Q`       | Close all (quit)             |\n| `,`       | Parent commit                |\n{: .-shortcuts}\n\n### Cursor navigation\n\n| Shortcut  | Description                  |\n| ---       | ---                          |\n| `/`       | Search                       |\n| `?`       | Search backwards             |\n| `j`  `k`  | Up/down                      |\n| `J`  `K`  | Next/previous                |\n| `<space>` | Page down                    |\n| `-`       | Page up                      |\n| `^D`      | Half page down               |\n| `^U`      | Half page up                 |\n{: .-shortcuts}\n\n### Option toggles\n\n| Shortcut  | Description                  |\n| ---       | ---                          |\n| `I`       | Toggle sort order modes      |\n| `i`       | Change sort header           |\n| `D`       | Toggle date display modes    |\n| `A`       | Toggle author display modes  |\n| `#`       | Toggle line numbers          |\n| `~`       | Toggle line graphics         |\n| `F`       | Toggle file names            |\n| `W`       | Toggle ignore space          |\n{: .-shortcuts}\n\n### `m` - Main view\n\n| Shortcut  | Description                  |\n| ---       | ---                          |\n| `X`       | Toggle commit sha            |\n| `C`       | Cherry pick a commit         |\n{: .-shortcuts}\n\n### `s` - Status view\n\n| Shortcut  | Description                        |\n| ---       | ---                                |\n| `u`       | Stage/unstage file or chunk        |\n| `!`       | Revert file or chunk               |\n| `C`       | Commit                             |\n| `M`       | Merge with external tool           |\n{: .-shortcuts}\n\n### `c` - Stage view\n\n| Shortcut  | Description                        |\n| ---       | ---                                |\n| `u`       | Stage/unstage file or chunk        |\n| `!`       | Revert file or chunk               |\n| `1`       | Stage line                         |\n| `\\`       | Split current diff hunk            |\n| `[` `]`   | Increase/decrease the diff context |\n{: .-shortcuts}\n\n### `d` - Diff view\n\n| Shortcut  | Description                        |\n| ---       | ---                                |\n| `[` `]`   | Increase/decrease the diff context |\n{: .-shortcuts}\n\n### `y` - Stash view\n\n| Shortcut  | Description                        |\n| ---       | ---                                |\n| `A`       | Apply selected stash               |\n| `P`       | Pop selected stash                 |\n| `!`       | Drop selected stash                |\n{: .-shortcuts}"}

field_body:
### Installing

```bash
# MacOS + Homebrew
$ brew install tig --HEAD
```

```bash
# Ubuntu
$ sudo apt install tig
```

### Invocation

| Command             | Description                                  |
| ------------------- | -------------------------------------------- |
| `tig`               | Logs                                         |
| ---                 | ---                                          |
| `tig status`        | Status                                       |
| `tig blame FILE`    | Blame                                        |
| ---                 | ---                                          |
| `tig master`        | Show a branch                                |
| `tig test..master`  | Show difference between two branches         |
| `tig FILE`          | Show history of file                         |
| `tig v0.0.3:README` | Show contents of file in a specific revision |
| `tig -C /repo/path` | Run in dir `/repo/path` (like `git -C`)      |

You can substitute `git log` → `tig`.

## Shortcut keys
{: .-three-column}

### Switching views

| Shortcut | Description  |
| -------- | ------------ |
| `m`      | Main view    |
| `d`      | Diff         |
| `t`      | Tree (files) |
| `b`      | Blame        |
| `s`      | Status       |
| `c`      | Stage        |
| `y`      | Stash        |
| `g`      | Grep         |
| `h`      | Help         |
{: .-shortcuts}

### All views

| Shortcut  | Description                  |
| ---       | ---                          |
| `<enter>` | Enter and open selected line |
| `<`       | Back to previous view state  |
| `<tab>`   | Move focus to next view      |
| `R`       | Refresh                      |
| `q`       | Close view                   |
| `Q`       | Close all (quit)             |
| `,`       | Parent commit                |
{: .-shortcuts}

### Cursor navigation

| Shortcut  | Description                  |
| ---       | ---                          |
| `/`       | Search                       |
| `?`       | Search backwards             |
| `j`  `k`  | Up/down                      |
| `J`  `K`  | Next/previous                |
| `<space>` | Page down                    |
| `-`       | Page up                      |
| `^D`      | Half page down               |
| `^U`      | Half page up                 |
{: .-shortcuts}

### Option toggles

| Shortcut  | Description                  |
| ---       | ---                          |
| `I`       | Toggle sort order modes      |
| `i`       | Change sort header           |
| `D`       | Toggle date display modes    |
| `A`       | Toggle author display modes  |
| `#`       | Toggle line numbers          |
| `~`       | Toggle line graphics         |
| `F`       | Toggle file names            |
| `W`       | Toggle ignore space          |
{: .-shortcuts}

### `m` - Main view

| Shortcut  | Description                  |
| ---       | ---                          |
| `X`       | Toggle commit sha            |
| `C`       | Cherry pick a commit         |
{: .-shortcuts}

### `s` - Status view

| Shortcut  | Description                        |
| ---       | ---                                |
| `u`       | Stage/unstage file or chunk        |
| `!`       | Revert file or chunk               |
| `C`       | Commit                             |
| `M`       | Merge with external tool           |
{: .-shortcuts}

### `c` - Stage view

| Shortcut  | Description                        |
| ---       | ---                                |
| `u`       | Stage/unstage file or chunk        |
| `!`       | Revert file or chunk               |
| `1`       | Stage line                         |
| `\`       | Split current diff hunk            |
| `[` `]`   | Increase/decrease the diff context |
{: .-shortcuts}

### `d` - Diff view

| Shortcut  | Description                        |
| ---       | ---                                |
| `[` `]`   | Increase/decrease the diff context |
{: .-shortcuts}

### `y` - Stash view

| Shortcut  | Description                        |
| ---       | ---                                |
| `A`       | Apply selected stash               |
| `P`       | Pop selected stash                 |
| `!`       | Drop selected stash                |
{: .-shortcuts}


id: textile
git_filename: ./textile.md
format: md
field_title: Textile
field_category: Markup
field_updated: 2017-09-20
field_updated___timezone: UTC
data:
{"title": "Textile", "category": "Markup", "updated": "2017-09-20", "weight": -1, "body": "## Reference\n{: .-three-column}\n\n### Inlines\n\n| Code | Description |\n| --- | --- |\n| `_em_` | |\n| `*strong*` | |\n| `__bold-italic__` | |\n| `@code@` | |\n| `??citation??` | |\n| --- | --- |\n| `-strikethrough-` | |\n| `+insertion+` | |\n| --- | --- |\n| `%span%` | HTML tag |\n| `%{color:red}formatting%` | CSS styles |\n| --- | --- |\n\n### Blocks\n\n```textile\nh1. Header 1\n```\n\n```textile\nh2. Header 2\n```\n\n```textile\nbq. Blockquote\n```\n\n```textile\np(classname). Class.\n```\n\n```textile\np(#id). ID.\n```\n\n### Lists\n\n```textile\n## ordered list\n```\n\n```textile\n* unordered list\n```\n\n### Links\n\n| Code | Description |\n| --- | --- |\n| `\"Hypertext\":index.html` | Link |\n| --- | --- |\n| `\"Text link\":link` <br> `[link]http://link.com` | Link via reference |\n\n### Images\n\n| Code | Description |\n| --- | --- |\n| `!image.jpg!` | Image |\n| `!image.jpg(title text)!` | |\n| `!image.jpg!:link.html` | |\n| `!>right.jpg!` | |\n\n### Escaped HTML\n\n```html\n<pre>\nI am <b>very serious.</b> -- this\nwill get escaped.\n</pre>\n```\n\n### Line breaks\n\n```textile\nLine breaks.\nJust break the lines.\n```\n\n### Entities\n\n```textile\none(TM), two(R), three(C).\n```\n\n### Horizontal line\n\n```textile\n--\n```\n\n### Footnotes\n\n```textile\nFootnotes[1].\n```\n\n```textile\nfn1. Something.\n```"}

field_body:
## Reference
{: .-three-column}

### Inlines

| Code | Description |
| --- | --- |
| `_em_` | |
| `*strong*` | |
| `__bold-italic__` | |
| `@code@` | |
| `??citation??` | |
| --- | --- |
| `-strikethrough-` | |
| `+insertion+` | |
| --- | --- |
| `%span%` | HTML tag |
| `%{color:red}formatting%` | CSS styles |
| --- | --- |

### Blocks

```textile
h1. Header 1
```

```textile
h2. Header 2
```

```textile
bq. Blockquote
```

```textile
p(classname). Class.
```

```textile
p(#id). ID.
```

### Lists

```textile
## ordered list
```

```textile
* unordered list
```

### Links

| Code | Description |
| --- | --- |
| `"Hypertext":index.html` | Link |
| --- | --- |
| `"Text link":link` <br> `[link]http://link.com` | Link via reference |

### Images

| Code | Description |
| --- | --- |
| `!image.jpg!` | Image |
| `!image.jpg(title text)!` | |
| `!image.jpg!:link.html` | |
| `!>right.jpg!` | |

### Escaped HTML

```html
<pre>
I am <b>very serious.</b> -- this
will get escaped.
</pre>
```

### Line breaks

```textile
Line breaks.
Just break the lines.
```

### Entities

```textile
one(TM), two(R), three(C).
```

### Horizontal line

```textile
--
```

### Footnotes

```textile
Footnotes[1].
```

```textile
fn1. Something.
```


id: tar
git_filename: ./tar.md
format: md
field_title: tar
field_category: CLI
field_intro: Concatenate, Deflate, Inflate files
field_updated: 2022-08-11
field_updated___timezone: UTC
data:
{"title": "tar", "category": "CLI", "updated": "2022-08-11", "intro": "Concatenate, Deflate, Inflate files", "body": "## Reference\n{:.-two-column}\n\n### Deflate / Inflate / Concatenate\n```shell\n# Deflate / Compress\ntar -czf archive.tar.gz /path/files\n```\n\n```shell\n# Inflate / Uncompress\ntar -xzf archive.tar.gz\n```\n\n```shell\n# Concatenate files into a single tar\ntar -cf archive.tar /path/files\n```\n\n```shell\n# Extract file to a defined directory\ntar -xzf archive.tar.gz -C /target/directory\n```\n\n```shell\n# Append a file to an existing archive\ntar -zu archive.tar.gz -C /target/file\n```\n\n```shell\n# List files in archive\n# Add -v for additional details\ntar -tzf archive.tar.gz\n```\n\n### Common options\n\n| Option | Description                                                             |\n|--------|-------------------------------------------------------------------------|\n| `z`    | compress with gzip                                                      |\n| `c`    | create an archive                                                       |\n| `u`    | append files which are newer than the corresponding copy in the archive |\n| `f`    | filename of the archive                                                 |\n| `v`    | verbose, display what is inflated or deflated                           |\n| `a`    | unlike of `z`, determine compression based on file extension            |"}

field_body:
## Reference
{:.-two-column}

### Deflate / Inflate / Concatenate
```shell
# Deflate / Compress
tar -czf archive.tar.gz /path/files
```

```shell
# Inflate / Uncompress
tar -xzf archive.tar.gz
```

```shell
# Concatenate files into a single tar
tar -cf archive.tar /path/files
```

```shell
# Extract file to a defined directory
tar -xzf archive.tar.gz -C /target/directory
```

```shell
# Append a file to an existing archive
tar -zu archive.tar.gz -C /target/file
```

```shell
# List files in archive
# Add -v for additional details
tar -tzf archive.tar.gz
```

### Common options

| Option | Description                                                             |
|--------|-------------------------------------------------------------------------|
| `z`    | compress with gzip                                                      |
| `c`    | create an archive                                                       |
| `u`    | append files which are newer than the corresponding copy in the archive |
| `f`    | filename of the archive                                                 |
| `v`    | verbose, display what is inflated or deflated                           |
| `a`    | unlike of `z`, determine compression based on file extension            |


id: tape
git_filename: ./tape.md
format: md
field_title: Tape
field_category: JavaScript libraries
data:
{"title": "Tape", "category": "JavaScript libraries", "body": "### Example\n\n```js\ntest('things', (t) => {\n  t.plan(1)\n\n  t.equal('actual', 'expected')\n  t.equal('actual', 'expected', 'should be equal') // messages are optional\n\n  t.end(err)\n  t.fail('msg')\n  t.pass('msg')\n  t.timeoutAfter(2000)\n  t.skip('msg')\n\n  t.ok(value, 'is truthy')\n  t.notOk(value, 'is falsy')\n  t.error(err, 'is falsy (print err.message)')\n\n  t.equal(actual, expected, 'is equal')\n  t.notEqual\n\n  t.deepEqual(actual, expected, 'is equal (use node's deepEqual)')\n  t.notDeepEqual\n\n  t.looseEqual(actual, expected, 'is equal (use node's deepEqual with ==)')\n  t.notLooseEqual\n\n  t.throws(fn, /FooError/)\n  t.throws(fn, FooError /* class */)\n  t.doesNotThrow\n\n  t.comment('message')\n})\n```\n\n```js\ntest.only((t) => { ... })\n```"}

field_body:
### Example

```js
test('things', (t) => {
  t.plan(1)

  t.equal('actual', 'expected')
  t.equal('actual', 'expected', 'should be equal') // messages are optional

  t.end(err)
  t.fail('msg')
  t.pass('msg')
  t.timeoutAfter(2000)
  t.skip('msg')

  t.ok(value, 'is truthy')
  t.notOk(value, 'is falsy')
  t.error(err, 'is falsy (print err.message)')

  t.equal(actual, expected, 'is equal')
  t.notEqual

  t.deepEqual(actual, expected, 'is equal (use node's deepEqual)')
  t.notDeepEqual

  t.looseEqual(actual, expected, 'is equal (use node's deepEqual with ==)')
  t.notLooseEqual

  t.throws(fn, /FooError/)
  t.throws(fn, FooError /* class */)
  t.doesNotThrow

  t.comment('message')
})
```

```js
test.only((t) => { ... })
```


id: tabular
git_filename: ./tabular.md
format: md
field_title: Tabular
field_category: Vim
field_intro: [Tabular](https://github.com/godlygeek/tabular) is a Vim script for text alignment.
field_updated: 2017-10-11
field_updated___timezone: UTC
data:
{"title": "Tabular", "category": "Vim", "updated": "2017-10-11", "weight": -1, "intro": "[Tabular](https://github.com/godlygeek/tabular) is a Vim script for text alignment.\n", "body": "## Common usage\n{: .-three-column}\n\n### Tables\n\n```\n:Tab /|\n```\n{: .-setup}\n\n```\n| Fruit  | Color  |\n| -----  | -----  |\n| Apple  | Red    |\n| Banana | Yellow |\n| Kiwi   | Green  |\n```\n\n### Variables\n\n```\n:Tab /=\n```\n{: .-setup}\n\n```\ntitle = \"Hello\"\nsrc   = \"image.jpg\"\nwidth = 640\n```\n\n### Colons\n\n```\n:Tab /:\\zs/l0l1\n```\n{: .-setup}\n\n```\ntitle:       \"Hello world\"\ndescription: \"This is a description\"\nsrc:         \"image.jpg\"\nheight:      320\nwidth:       640\n```\n\n## Tab command\n{: .-three-column}\n\n### Basic example\n\n```\n:Tab /:\n```\n{: .-setup}\n\n```bash\ntitle : My picture\nsrc   : img.jpg\n```\n\n### Right align\n\n```\n:Tab /:/r0\n```\n{: .-setup}\n\n```bash\ntitle:My picture\n  src:   img.jpg\n```\n\n### The \\zs atom\n\n```\n:Tab /:\\zs\n```\n{: .-setup}\n\n```\ntitle:  My picture\nsrc:    img.jpg\n```\n\nThe `\\zs` atom will exclude the `:` from the search match.\n\n### Specifier\n\n```\n:Tab /:/r1c1l0\n```\n{: .-setup}\n\n```bash\ntitle : My picture\n  src : img.jpg\n```\n\n#### Explanation\n\n- `r1` -- Right align with 1 space\n- `c1` -- Center align the comma with 1 space\n- `l0` -- Left align with 0 spaces\n\n### Regexp\n\n```\n:Tab /^[^,]*\\zs,/r0\n```\n{: .-setup}\n\n```bash\nabc,hello\n  c,hi there\n  a,yo\n```\n\n### Specifiers\n\n| Specifier | Description |\n| --- | --- |\n| `r1c1l0` |  multiple specifiers, one per column<br>(the separator counts as a column) |\n| --- | --- |\n| `lN` | Left-align (with N spaces padding) |\n| `rN` | Right-align (with N spaces padding) |\n| `cN` | Center-align (with N spaces padding) |\n\n## Also see\n\n- [godlygeek/tabular](https://github.com/godlygeek/tabular) _(github.com)_\n- [Aligning text with Tabular.vim](http://vimcasts.org/episodes/aligning-text-with-tabular-vim/) _(vimcasts.org)_"}

field_body:
## Common usage
{: .-three-column}

### Tables

```
:Tab /|
```
{: .-setup}

```
| Fruit  | Color  |
| -----  | -----  |
| Apple  | Red    |
| Banana | Yellow |
| Kiwi   | Green  |
```

### Variables

```
:Tab /=
```
{: .-setup}

```
title = "Hello"
src   = "image.jpg"
width = 640
```

### Colons

```
:Tab /:\zs/l0l1
```
{: .-setup}

```
title:       "Hello world"
description: "This is a description"
src:         "image.jpg"
height:      320
width:       640
```

## Tab command
{: .-three-column}

### Basic example

```
:Tab /:
```
{: .-setup}

```bash
title : My picture
src   : img.jpg
```

### Right align

```
:Tab /:/r0
```
{: .-setup}

```bash
title:My picture
  src:   img.jpg
```

### The \zs atom

```
:Tab /:\zs
```
{: .-setup}

```
title:  My picture
src:    img.jpg
```

The `\zs` atom will exclude the `:` from the search match.

### Specifier

```
:Tab /:/r1c1l0
```
{: .-setup}

```bash
title : My picture
  src : img.jpg
```

#### Explanation

- `r1` -- Right align with 1 space
- `c1` -- Center align the comma with 1 space
- `l0` -- Left align with 0 spaces

### Regexp

```
:Tab /^[^,]*\zs,/r0
```
{: .-setup}

```bash
abc,hello
  c,hi there
  a,yo
```

### Specifiers

| Specifier | Description |
| --- | --- |
| `r1c1l0` |  multiple specifiers, one per column<br>(the separator counts as a column) |
| --- | --- |
| `lN` | Left-align (with N spaces padding) |
| `rN` | Right-align (with N spaces padding) |
| `cN` | Center-align (with N spaces padding) |

## Also see

- [godlygeek/tabular](https://github.com/godlygeek/tabular) _(github.com)_
- [Aligning text with Tabular.vim](http://vimcasts.org/episodes/aligning-text-with-tabular-vim/) _(vimcasts.org)_


id: superagent
git_filename: ./superagent.md
format: md
field_title: Superagent
field_category: JavaScript libraries
field_tags: WIP
field_updated: 2018-04-21
field_updated___timezone: UTC
data:
{"title": "Superagent", "category": "JavaScript libraries", "updated": "2018-04-21", "tags": ["WIP"], "body": "### Response object\n```javascript\n  res: {\n    // The HTTP Status Code (see: httpstatuses.com for definitions on HTTP status codes)\n    status: 202,\n    // True when res.status is 2xx\n    ok: true,\n    // True when res.status is 4xx or 5xx\n    error: false,\n    // True when res.status is 4xx\n    clientError: false,\n    // True when res.status is 5xx\n    serverError: false,\n\n    // True when res.status == 202\n    accepted: true,\n    // True when res.status == 204 || res.status == 1223 \n    noContent: false,\n    // True when res.status == 400\n    badRequest: false,\n    // True when res.status == 401\n    unauthorized: false,\n    // True when res.status == 406\n    notAcceptable: false,\n    // True when res.status == 404\n    notFound: false,\n    // True when res.status == 403\n    forbidden: false,\n\n    // Unparsed response text\n    text: '{\"user\":{\"username\":\"JohnDoe\",\"role\":\"admin\"}}'\n\n    // Parsed response text (only if response is 'application/json' or 'application/x-www-form-urlencoded'\n    body: {\n      // Example of parsed object from res.text\n      user: {\n        username: 'JohnDoe',\n        role: 'admin'\n      }\n    }\n\n    // The content-type (parsed from headers)\n    type: 'application/json'\n    // The charset (parsed from headers)\n    charset: 'UTF-8'\n    // Header object with each header field as a property\n    headers: {\n      'content-type': 'application/json; charset=UTF-8',\n      ...\n    }\n}\n```"}

field_body:
### Response object
```javascript
  res: {
    // The HTTP Status Code (see: httpstatuses.com for definitions on HTTP status codes)
    status: 202,
    // True when res.status is 2xx
    ok: true,
    // True when res.status is 4xx or 5xx
    error: false,
    // True when res.status is 4xx
    clientError: false,
    // True when res.status is 5xx
    serverError: false,

    // True when res.status == 202
    accepted: true,
    // True when res.status == 204 || res.status == 1223 
    noContent: false,
    // True when res.status == 400
    badRequest: false,
    // True when res.status == 401
    unauthorized: false,
    // True when res.status == 406
    notAcceptable: false,
    // True when res.status == 404
    notFound: false,
    // True when res.status == 403
    forbidden: false,

    // Unparsed response text
    text: '{"user":{"username":"JohnDoe","role":"admin"}}'

    // Parsed response text (only if response is 'application/json' or 'application/x-www-form-urlencoded'
    body: {
      // Example of parsed object from res.text
      user: {
        username: 'JohnDoe',
        role: 'admin'
      }
    }

    // The content-type (parsed from headers)
    type: 'application/json'
    // The charset (parsed from headers)
    charset: 'UTF-8'
    // Header object with each header field as a property
    headers: {
      'content-type': 'application/json; charset=UTF-8',
      ...
    }
}
```


id: sublime-text
git_filename: ./sublime-text.md
format: md
field_title: Sublime Text
field_category: Apps
data:
{"title": "Sublime Text", "category": "Apps", "body": "### Select & Expand\n\n| `\u2318 D`       | select current word (repeat to include next instance of word) |\n| `\u2318 L`       | select current line (repeat to include next line) |\n| `\u2318 \u21e7 L`     | split selection into multiple lines |\n| `\u2318 \u21e7 A`     | select text inside tag (repeat to expand) |\n| `Ctrl \u21e7 M`  | select to curly or angle brackets (repeat to expand) |\n{: .-shortcuts}\n\nReplace \u2318 with Ctrl on Windows and Linux.\n\n### Code Folding\n\n| `\u2318 Alt [`         | fold closest block                     |\n| `\u2318 Alt ]`         | unfold closest block                   |\n| `\u2318 K` `\u2318 1`       | fold all first level code blocks       |\n| `\u2318 K` `\u2318 2`       | fold all second level code blocks      |\n| `\u2318 K` `\u2318 3 (etc)` | fold all third level code blocks (etc) |\n| `\u2318 K` `\u2318 T`       | fold all HTML attributes               |\n| `\u2318 K` `\u2318 0`       | unfold everything                      |\n{: .-shortcuts}\n\n### Editing\n\n| `\u2318 \u21e7 D` | duplicate current line/selection |\n| `\u2318 \u21e7 K` | delete current line/selection |\n| `\u21e7 del` | delete current line/selection |\n| `\u2318 \u21e7 \u2191` | move line up   |\n| `\u2318 \u21e7 \u2193` | move line down |\n{: .-shortcuts}\n\n### Goto\n\n| `\u2318 P`         | goto anything |\n| `\u2318 G`         | goto line number |\n| `\u2318 R`         | goto symbol |\n| `\u2318 P, :`      | goto line number (enter number after `:`) |\n| `\u2318 P, #`      | goto and list fuzzy-matches of string (enter characters after `#`) |\n| `\u2318 P, @`      | goto and list symbol (begin typing symbol name after `@`) |\n{: .-shortcuts}\n\n### Command line\n\n```sh\n$ subl .\n$ subl README.md\n```\n\nUse `subl` to open files in Sublime from the terminal."}

field_body:
### Select & Expand

| `⌘ D`       | select current word (repeat to include next instance of word) |
| `⌘ L`       | select current line (repeat to include next line) |
| `⌘ ⇧ L`     | split selection into multiple lines |
| `⌘ ⇧ A`     | select text inside tag (repeat to expand) |
| `Ctrl ⇧ M`  | select to curly or angle brackets (repeat to expand) |
{: .-shortcuts}

Replace ⌘ with Ctrl on Windows and Linux.

### Code Folding

| `⌘ Alt [`         | fold closest block                     |
| `⌘ Alt ]`         | unfold closest block                   |
| `⌘ K` `⌘ 1`       | fold all first level code blocks       |
| `⌘ K` `⌘ 2`       | fold all second level code blocks      |
| `⌘ K` `⌘ 3 (etc)` | fold all third level code blocks (etc) |
| `⌘ K` `⌘ T`       | fold all HTML attributes               |
| `⌘ K` `⌘ 0`       | unfold everything                      |
{: .-shortcuts}

### Editing

| `⌘ ⇧ D` | duplicate current line/selection |
| `⌘ ⇧ K` | delete current line/selection |
| `⇧ del` | delete current line/selection |
| `⌘ ⇧ ↑` | move line up   |
| `⌘ ⇧ ↓` | move line down |
{: .-shortcuts}

### Goto

| `⌘ P`         | goto anything |
| `⌘ G`         | goto line number |
| `⌘ R`         | goto symbol |
| `⌘ P, :`      | goto line number (enter number after `:`) |
| `⌘ P, #`      | goto and list fuzzy-matches of string (enter characters after `#`) |
| `⌘ P, @`      | goto and list symbol (begin typing symbol name after `@`) |
{: .-shortcuts}

### Command line

```sh
$ subl .
$ subl README.md
```

Use `subl` to open files in Sublime from the terminal.


id: stylus
git_filename: ./stylus.md
format: md
field_title: Stylus
field_category: CSS
field_tags: Featurable
field_prism_languages: stylus
field_updated: 2017-10-30
field_updated___timezone: UTC
data:
{"title": "Stylus", "category": "CSS", "prism_languages": ["stylus"], "weight": -3, "updated": "2017-10-30", "tags": ["Featurable"], "body": "Getting started\n---------------\n{: .-three-column}\n\n### CSS syntax\n\n```stylus\n.box {\n  color: blue;\n\n  .button {\n    color: red;\n  }\n}\n```\n\nStylus is a CSS pre-processor.\n\nSee: [stylus-lang.com](http://stylus-lang.com/)\n\n### Indent syntax\n\n```stylus\n.box\n  color: blue\n\n  .button\n    color: red\n```\n\nAlso works! The colon is optional, as well. This is typically the syntax used with Stylus documents.\n\n### Mixins\n\n```stylus\ncaps-type()\n  text-transform: uppercase\n  letter-spacing: 0.05em\n```\n{: data-line=\"1\"}\n\n```stylus\nh5\n  caps-type()\n```\n{: data-line=\"2\"}\n\nSee [Mixins](#mixins-1) below.\n\n### Variables\n\n```stylus\nroyal-blue = #36a\n```\n{: data-line=\"1\"}\n\n```stylus\ndiv\n  color: royal-blue\n```\n\nMixins\n------\n{: .-three-column}\n\n### Without arguments\n\n```stylus\nred-border()\n  border: solid 2px red\n```\n{: data-line=\"1\"}\n\n```stylus\ndiv\n  red-border()\n```\n{: data-line=\"2\"}\n\nSee: [Mixins](http://stylus-lang.com/docs/mixins.html)\n\n### With arguments\n\n```stylus\nborder-radius(n)\n  -webkit-border-radius: n\n  border-radius: n\n```\n{: data-line=\"1\"}\n\n```stylus\ndiv\n  border-radius: 2px\n  border-radius(2px)\n```\n{: data-line=\"2,3\"}\n\nMixins can be applied in two different ways.\n\n### Argument defaults\n\n```stylus\nborder-radius(n = 2px)\n  -webkit-border-radius: n\n```\n{: data-line=\"1\"}\n\n### Block mixins\n\n```stylus\nmobile()\n  @media (max-width: 480px)\n    {block}\n```\n{: data-line=\"3\"}\n\n```stylus\n+mobile()\n  width: 10px\n```\n{: data-line=\"1\"}\n\nSee: [Block mixins](http://stylus-lang.com/docs/mixins.html#block-mixins)\n\n### Rest params\n\n```stylus\nshadow(offset-x, args...)\n  box-shadow: offset-x args\n  margin-top: offset-x\n```\n{: data-line=\"1\"}\n\n```stylus\n#login\n  shadow: 1px 2px 5px #eee\n```\n\nSee: [Rest params](http://stylus-lang.com/docs/vargs.html)\n\nFunctions\n---------\n{: .-three-column}\n\n### Functions\n\n```stylus\nadd(a, b)\n  a + b\n```\n{: data-line=\"1\"}\n\n```stylus\nbody\n  padding: add(10px, 5)\n```\n{: data-line=\"2\"}\n\nSee: [Functions](http://stylus-lang.com/docs/functions.html)\n\n### Argument defaults\n\n```stylus\nadd(a, b = 2)\n  a + b\n```\n{: data-line=\"1\"}\n\nSee: [Argument defaults](http://stylus-lang.com/docs/functions.html#argument-defaults)\n\n### Named parameters\n\n```stylus\nshadow(x, y)\n  x y (y * 1.5) #000\n```\n\n```stylus\n.button\n  box-shadow: shadow(x: 2, y: 4)\n```\n{: data-line=\"2\"}\n\nSee: [Named parameters](http://stylus-lang.com/docs/functions.html#named-parameters)\n\n### Multiple return values\n\n```stylus\nsizes()\n  8px 16px\n```\n{: data-line=\"2\"}\n\n```stylus\nsizes()[0]  // \u2192 8px\nsizes()[1]  // \u2192 16px\n```\n\nSee: [Multiple return values](http://stylus-lang.com/docs/functions.html#multiple-return-values)\n\nValues\n------\n{: .-three-column}\n\n### Conditional assignment\n\n```stylus\nroyal-blue = #36a\nroyal-blue ?= #89f\n```\n{: data-line=\"2\"}\n\n```stylus\ndiv\n  color: royal-blue  // #36a\n```\n\n`?=` will only set a variable if it's previously unset.\n\nSee: [Conditional assignment](https://stylus-lang.com/docs/operators.html#conditional-assignment--)\n\n### Property lookup\n\n```stylus\n.logo\n  width: w = 150\n  margin-left: -(w / 2)\n  // or\n  height: 80px\n  margin-top: -(@height / 2)\n```\n{: data-line=\"2,3\"}\n\nSee: [Property lookup](https://stylus-lang.com/docs/variables.html#property-lookup)\n\n### Interpolation\n\n```stylus\n-{prefix}-border-radius: 2px\n```\n\nSee: [Interpolation](https://stylus-lang.com/docs/interpolation.html)\n\n### Color operators\n\n```stylus\n#888 + 50%    // \u2192 #c3c3c3 (lighten)\n#888 - 50%    // \u2192 #444 (darken)\n#f00 + 50deg  // \u2192 #ffd500 (hue)\n```\n\n### Casting\n\n```stylus\nn = 5px\n```\n\n```stylus\nfoo: (n)em\nfoo: (n * 5)%\n```\n{: data-line=\"1,2\"}\n\n### Lookup\n\n```stylus\nlight-blue = #3bd\nname = 'blue'\nlookup('light-' + name)\n```\n{: data-line=\"3\"}\n\nSee: [lookup](https://stylus-lang.com/docs/bifs.html#lookupname)\n\nAdvanced features\n-----------------\n{: .-three-column}\n\n### Conditional\n\n```stylus\nif color == blue\n  display: block\nelse if true and true\n  display: inline\nelse if 'hey' is not 'bye'\n  display: flex\nelse\n  display: none\n```\n\nAliases:\n\n\n| `==` | `is` |\n| `!=` | `is not` |\n| `!=` | `isnt` |\n\nSee: [Conditionals](https://stylus-lang.com/docs/functions.html#conditionals)\n\n### For loops\n\n```stylus\nfont-size-1 = 10px\nfont-size-2 = 20px\nfont-size-3 = 30px\n\nfor i in 1..3\n  .text-{i}\n    font-size: lookup('font-size-' + i)\n```\n{: data-line=\"5\"}\n\n### Definition check\n\n```stylus\nif ohnoes is defined\n  color: blue\n```\n{: data-line=\"1\"}\n\nSee: [is defined](https://stylus-lang.com/docs/operators.html#variable-definition-is-defined)\n\n### False values\n\n```stylus\n0\nnull\nfalse\n''\n```\n\n### Type check\n\n```stylus\nif val is a 'string'\nif val is a 'ident'\nif #fff is a 'rgba'    // \u2192 true\n```\n\nSee: [Instance check](https://stylus-lang.com/docs/operators.html#instance-check-is-a)\n\nBuilt-in functions\n------------------\n{: .-three-column}\n\n### Color functions\n\n```stylus\nalpha(#fff)   //\u2192 1\nalpha(rgba(0, 0, 0, 0.2))   //\u2192 0.2\n```\n\n```stylus\ndark(black)  //\u2192 true\nlight(black) //\u2192 false\n```\n\n```stylus\nhue(#0a0)         //\u2192 50deg\nsaturation(#f00)  //\u2192 100%\nlightness(#f00)   //\u2192 50%\nluminosity(#f00)  //\u2192 0.2126\n```\n\n```stylus\nhue(#0a0, 0deg)\nsaturation(#f00, 50%)\nlightness(#f00)\n```\n\n```stylus\nlighten(color, 10%)\ndarken(color, 10%)\nsaturate(color, 10%)\ndesaturate(color, 10%)\ninvert(color)\n```\n\n```stylus\ntint(color, 50%)  // mix with white\nshade(color, 50%) // mix with black\n```\n\n```stylus\nunquote(string)\n```\n\nSee: [Built-in functions](http://stylus-lang.com/docs/bifs.html)\n\n### Image size\n\n```stylus\nwidth:  image-size('tux.png')[0]\nheight: image-size('tux.png')[1]\n```\n\nReturns the width and height of a given image.\n\nSee: [image-size](http://stylus-lang.com/docs/bifs.html#image-sizepath)\n\n### Caching\n\n```stylus\nsize($width)\n  +cache('w' + $width)\n    width: $width\n.a { size: 10px }\n.b { size: 10px }\n```\n\n```stylus\n// yields: .a, b { width: 10px }\n```\n\nApplies its contents to the given selector on the first call, but would @extend the first call\u2019s selector at the second call with the same params.\n\nSee: [cache](http://stylus-lang.com/docs/bifs.html#cachekeys)\n\n### Add Property\n\n```stylus\ngradient(color)\n  add-property('background-image', linear-gradient(top, color, darken(color, 20%)))\n  color\n```\n\n```stylus\nbody\n  background: gradient(red)\n```\n\nSee: [add-property](http://stylus-lang.com/docs/bifs.html#add-propertyname-expr)\n\n### sprintf\n\n```stylus\n'-webkit-gradient(%s, %s, %s)' % (linear (0 0) (0 100%))\n// \u2192 -webkit-gradient(linear, 0 0, 0 100%)\n```\n\n```stylus\ns(\"rgba(0, 0, 0, %s)\", 0.3)\n```\n\nSee: [s](http://stylus-lang.com/docs/bifs.html#sfmt-)\n\n### Embed URL\n\n```\nbackground: embedurl('logo.png')\n// \u2192 background: url(\"data:image/png;base64,\u2026\")\n```\n\nSee: [embedurl](http://stylus-lang.com/docs/bifs.html#embedurlpath-encoding)"}

field_body:
Getting started
---------------
{: .-three-column}

### CSS syntax

```stylus
.box {
  color: blue;

  .button {
    color: red;
  }
}
```

Stylus is a CSS pre-processor.

See: [stylus-lang.com](http://stylus-lang.com/)

### Indent syntax

```stylus
.box
  color: blue

  .button
    color: red
```

Also works! The colon is optional, as well. This is typically the syntax used with Stylus documents.

### Mixins

```stylus
caps-type()
  text-transform: uppercase
  letter-spacing: 0.05em
```
{: data-line="1"}

```stylus
h5
  caps-type()
```
{: data-line="2"}

See [Mixins](#mixins-1) below.

### Variables

```stylus
royal-blue = #36a
```
{: data-line="1"}

```stylus
div
  color: royal-blue
```

Mixins
------
{: .-three-column}

### Without arguments

```stylus
red-border()
  border: solid 2px red
```
{: data-line="1"}

```stylus
div
  red-border()
```
{: data-line="2"}

See: [Mixins](http://stylus-lang.com/docs/mixins.html)

### With arguments

```stylus
border-radius(n)
  -webkit-border-radius: n
  border-radius: n
```
{: data-line="1"}

```stylus
div
  border-radius: 2px
  border-radius(2px)
```
{: data-line="2,3"}

Mixins can be applied in two different ways.

### Argument defaults

```stylus
border-radius(n = 2px)
  -webkit-border-radius: n
```
{: data-line="1"}

### Block mixins

```stylus
mobile()
  @media (max-width: 480px)
    {block}
```
{: data-line="3"}

```stylus
+mobile()
  width: 10px
```
{: data-line="1"}

See: [Block mixins](http://stylus-lang.com/docs/mixins.html#block-mixins)

### Rest params

```stylus
shadow(offset-x, args...)
  box-shadow: offset-x args
  margin-top: offset-x
```
{: data-line="1"}

```stylus
#login
  shadow: 1px 2px 5px #eee
```

See: [Rest params](http://stylus-lang.com/docs/vargs.html)

Functions
---------
{: .-three-column}

### Functions

```stylus
add(a, b)
  a + b
```
{: data-line="1"}

```stylus
body
  padding: add(10px, 5)
```
{: data-line="2"}

See: [Functions](http://stylus-lang.com/docs/functions.html)

### Argument defaults

```stylus
add(a, b = 2)
  a + b
```
{: data-line="1"}

See: [Argument defaults](http://stylus-lang.com/docs/functions.html#argument-defaults)

### Named parameters

```stylus
shadow(x, y)
  x y (y * 1.5) #000
```

```stylus
.button
  box-shadow: shadow(x: 2, y: 4)
```
{: data-line="2"}

See: [Named parameters](http://stylus-lang.com/docs/functions.html#named-parameters)

### Multiple return values

```stylus
sizes()
  8px 16px
```
{: data-line="2"}

```stylus
sizes()[0]  // → 8px
sizes()[1]  // → 16px
```

See: [Multiple return values](http://stylus-lang.com/docs/functions.html#multiple-return-values)

Values
------
{: .-three-column}

### Conditional assignment

```stylus
royal-blue = #36a
royal-blue ?= #89f
```
{: data-line="2"}

```stylus
div
  color: royal-blue  // #36a
```

`?=` will only set a variable if it's previously unset.

See: [Conditional assignment](https://stylus-lang.com/docs/operators.html#conditional-assignment--)

### Property lookup

```stylus
.logo
  width: w = 150
  margin-left: -(w / 2)
  // or
  height: 80px
  margin-top: -(@height / 2)
```
{: data-line="2,3"}

See: [Property lookup](https://stylus-lang.com/docs/variables.html#property-lookup)

### Interpolation

```stylus
-{prefix}-border-radius: 2px
```

See: [Interpolation](https://stylus-lang.com/docs/interpolation.html)

### Color operators

```stylus
#888 + 50%    // → #c3c3c3 (lighten)
#888 - 50%    // → #444 (darken)
#f00 + 50deg  // → #ffd500 (hue)
```

### Casting

```stylus
n = 5px
```

```stylus
foo: (n)em
foo: (n * 5)%
```
{: data-line="1,2"}

### Lookup

```stylus
light-blue = #3bd
name = 'blue'
lookup('light-' + name)
```
{: data-line="3"}

See: [lookup](https://stylus-lang.com/docs/bifs.html#lookupname)

Advanced features
-----------------
{: .-three-column}

### Conditional

```stylus
if color == blue
  display: block
else if true and true
  display: inline
else if 'hey' is not 'bye'
  display: flex
else
  display: none
```

Aliases:


| `==` | `is` |
| `!=` | `is not` |
| `!=` | `isnt` |

See: [Conditionals](https://stylus-lang.com/docs/functions.html#conditionals)

### For loops

```stylus
font-size-1 = 10px
font-size-2 = 20px
font-size-3 = 30px

for i in 1..3
  .text-{i}
    font-size: lookup('font-size-' + i)
```
{: data-line="5"}

### Definition check

```stylus
if ohnoes is defined
  color: blue
```
{: data-line="1"}

See: [is defined](https://stylus-lang.com/docs/operators.html#variable-definition-is-defined)

### False values

```stylus
0
null
false
''
```

### Type check

```stylus
if val is a 'string'
if val is a 'ident'
if #fff is a 'rgba'    // → true
```

See: [Instance check](https://stylus-lang.com/docs/operators.html#instance-check-is-a)

Built-in functions
------------------
{: .-three-column}

### Color functions

```stylus
alpha(#fff)   //→ 1
alpha(rgba(0, 0, 0, 0.2))   //→ 0.2
```

```stylus
dark(black)  //→ true
light(black) //→ false
```

```stylus
hue(#0a0)         //→ 50deg
saturation(#f00)  //→ 100%
lightness(#f00)   //→ 50%
luminosity(#f00)  //→ 0.2126
```

```stylus
hue(#0a0, 0deg)
saturation(#f00, 50%)
lightness(#f00)
```

```stylus
lighten(color, 10%)
darken(color, 10%)
saturate(color, 10%)
desaturate(color, 10%)
invert(color)
```

```stylus
tint(color, 50%)  // mix with white
shade(color, 50%) // mix with black
```

```stylus
unquote(string)
```

See: [Built-in functions](http://stylus-lang.com/docs/bifs.html)

### Image size

```stylus
width:  image-size('tux.png')[0]
height: image-size('tux.png')[1]
```

Returns the width and height of a given image.

See: [image-size](http://stylus-lang.com/docs/bifs.html#image-sizepath)

### Caching

```stylus
size($width)
  +cache('w' + $width)
    width: $width
.a { size: 10px }
.b { size: 10px }
```

```stylus
// yields: .a, b { width: 10px }
```

Applies its contents to the given selector on the first call, but would @extend the first call’s selector at the second call with the same params.

See: [cache](http://stylus-lang.com/docs/bifs.html#cachekeys)

### Add Property

```stylus
gradient(color)
  add-property('background-image', linear-gradient(top, color, darken(color, 20%)))
  color
```

```stylus
body
  background: gradient(red)
```

See: [add-property](http://stylus-lang.com/docs/bifs.html#add-propertyname-expr)

### sprintf

```stylus
'-webkit-gradient(%s, %s, %s)' % (linear (0 0) (0 100%))
// → -webkit-gradient(linear, 0 0, 0 100%)
```

```stylus
s("rgba(0, 0, 0, %s)", 0.3)
```

See: [s](http://stylus-lang.com/docs/bifs.html#sfmt-)

### Embed URL

```
background: embedurl('logo.png')
// → background: url("data:image/png;base64,…")
```

See: [embedurl](http://stylus-lang.com/docs/bifs.html#embedurlpath-encoding)


id: strftime
git_filename: ./strftime.md
format: md
field_title: strftime format
field_tags: Featurable
field_intro: The strftime format is the standard date formatting for UNIX. It's used in C, Ruby, and more.
field_updated: 2017-11-27
field_updated___timezone: UTC
field_body: {% include common/strftime_format.md title="strftime" %}
data:
{"title": "strftime format", "weight": -5, "updated": "2017-11-27", "tags": ["Featurable"], "intro": "The strftime format is the standard date formatting for UNIX. It's used in C, Ruby, and more.\n", "body": "{% include common/strftime_format.md title=\"strftime\" %}"}


id: stimulus-reflex
git_filename: ./stimulus-reflex.md
format: md
field_title: StimulusReflex
field_category: Ruby
field_updated: 2021-01-07
field_updated___timezone: UTC
data:
{"title": "StimulusReflex", "category": "Ruby", "updated": "2021-01-07", "body": "### via Data Attributes\n\nTrigger reflexes without writing any javascript with the `data-reflex` attribute.\n\n#### index.html.erb\n\n```html\n<a\n  href=\"#\"\n  data-reflex=\"click->CounterReflex#increment\"\n  data-step=\"1\"\n  data-count=\"<%= @count.to_i %>\"\n  >Increment <%= @count.to_i %></a\n>\n```\n\n#### counter_reflex.rb\n\n```ruby\nclass CounterReflex < StimulusReflex::Reflex\n  def increment\n    @count = element.dataset[:count].to_i + element.dataset[:step].to_i\n  end\nend\n```\n\n### from Stimulus.js Controller\n\nStimulus.js controllers registered with StimulusReflex can use the `stimulate` method to trigger reflexes\n\n#### index.html.erb\n\n```html\n<a href=\"#\"\n  data-controller=\"counter\"\n  data-action=\"click->counter#increment\"\n>Increment <%= @count %></a>\n```\n\n#### counter_controller.js\n\n```javascript\nimport { Controller } from 'stimulus'\nimport StimulusReflex from 'stimulus_reflex'\n\nexport default class extends Controller {\n  connect() {\n    StimulusReflex.register(this)\n  }\n\n  increment(event) {\n    event.preventDefault()\n    this.stimulate('Counter#increment', 1)\n  }\n}\n```\n\n#### counter_reflex.rb\n\n```ruby\nclass CounterReflex < StimulusReflex::Reflex\n  def increment(step = 1)\n    session[:count] = session[:count].to_i + step\n   end\nend\n```\n\n## Morphs\n\n### Selector morphs\n\nInstead of refreshing the entire page, you can specify a portion of the page to update with `morph(selector, content)`\n\n```html\n<!-- show.html.erb -->\n<header data-reflex=\"click->Example#change\">\n  <%= render partial: \"path/to/foo\", locals: {message: \"Am I the medium or the massage?\"} %>\n</header>\n```\n\n```html\n<!-- _foo.html.erb -->\n<div id=\"foo\">\n  <span class=\"spa\"><%= message %></span>\n</div>\n```\n\n```ruby\n# example_reflex.rb\nclass ExampleReflex < ApplicationReflex\n  def change\n    morph \"#foo\", \"Your muscles... they are so tight.\"\n  end\nend\n```\n\n### Nothing morph\n\nUse `morph :nothing` in reflexes that do something on the server without updating the client.\n\n```ruby\n# example_reflex.rb\nclass ExampleReflex < ApplicationReflex\n  def change\n    LongRunningJob.perform_later\n    morph :nothing\n  end\nend\n```\n\n## Lifecycle\n\n### Server-side callbacks\n\nReflex classes can use the following callbacks. [Full Docs](http://docs.stimulusreflex.com/lifecycle#server-side-reflex-callbacks)\n\n- `before_reflex`\n- `around_reflex`\n- `after_reflex`\n\n### Client-side callbacks (generic)\n\nStimulusReflex controllers automatically support five generic lifecycle callback methods.\n\n- `beforeReflex(element, reflex, noop, reflexId)` prior to sending a request over the web socket\n- `reflexSuccess(element, reflex, noop, reflexId)` after the server side Reflex succeeds and the DOM has been updated\n- `reflexError(element, reflex, error, reflexId)` whenever the server side Reflex raises an error\n- `reflexHalted(element, reflex, noop, reflexId)` reflex canceled with throw :abort in the before_reflex callback\n- `afterReflex(element, reflex, noop, reflexId)` after both success and error\n- `finalizeReflex(element, reflex, noop, reflexId)` after both success and error\n\n### Client-side callbacks (custom)\n\nStimulusReflex controllers can define up to five custom lifecycle callback methods for each Reflex action. These methods use a naming convention based on the name of the Reflex. e.g. for the `add_one` reflex:\n\n- `beforeAddOne(element, reflex, noop, reflexId)`\n- `addOneSuccess(element, reflex, noop, reflexId)`\n- `addOneError(element, reflex, error, reflexId)`\n- `addOneHalted(element, reflex, noop, reflexId)`\n- `afterAddOne(element, reflex, noop, reflexId)`\n- `finalizeAddOne(element, reflex, noop, reflexId)`\n\n### Client-side events\n\nIf you need to know when a Reflex method is called, but you're working outside of the Stimulus controller that initiated it, you can subscribe to receive DOM events\n\n- `stimulus-reflex:before`\n- `stimulus-reflex:success`\n- `stimulus-reflex:error`\n- `stimulus-reflex:halted`\n- `stimulus-reflex:after`\n\nThere are also events related to the StimulusReflex library setting up and connecting to ActionCable\n\n- `stimulus-reflex:connected`\n- `stimulus-reflex:disconnected`\n- `stimulus-reflex:rejected`\n- `stimulus-reflex:ready`\n\n## Helpful tips\n\n### Forms\n\nIf a Reflex is called on a form element - or a child of that form element - then the data for the whole form will be properly serialized and made available to the Reflex action method as the `params` accessor. [Read more](http://docs.stimulusreflex.com/working-with-forms)\n\n### Promises\n\n`stimulate()` method returns a promise\n\n```javascript\nthis.stimulate('Comments#create')\n  .then(() => this.doSomething())\n  .catch(() => this.handleError())\n```\n\n### Inheriting data-attributes from parent elements\n\nYou can use the `data-reflex-dataset=\"combined\"` directive to scoop all data attributes up the DOM hierarchy and pass them as part of the Reflex payload.\n\n```html\n<!-- new.html.erb -->\n<div data-post-id=\"<%= @post.id %>\">\n  <div data-category-id=\"<%= @category.id %>\">\n    <button data-reflex=\"click->Comment#create\" data-reflex-dataset=\"combined\">Create</button>\n  </div>\n</div>\n```\n\n```html\n# comment_reflex.rb\nclass CommentReflex < ApplicationReflex\n  def create\n    puts element.dataset[\"post-id\"]\n    puts element.dataset[\"category-id\"]\n  end\nend\n```\n\n### Reflex root\n\nInstead of updating your entire page, you can specify exactly which parts of the DOM will be updated using the `data-reflex-root` attribute. [Full docs](http://docs.stimulusreflex.com/morph-modes#scoping-page-morphs)\n\n```text\n<!-- index.html.erb -->\n<div data-reflex-root=\"[forward],[backward]\">\n  <input type=\"text\" value=\"<%= @words %>\" data-reflex=\"keyup->Example#words\">\n  <div forward><%= @words %></div>\n  <div backward><%= @words&.reverse %></div>\n</div>\n```\n\n```ruby\n# example_reflex.rb\n  def words\n    @words = element[:value]\n  end\n```\n\n### Permanent elements\n\nAdd data-reflex-permanent to any element in your DOM, and it will be left unchanged by full-page Reflex updates and morph calls that re-render partials.\n\n```erb\n<!-- index.html.erb -->\n<div data-reflex-permanent>\n  <iframe src=\"https://ghbtns.com/github-btn.html?user=hopsoft&repo=stimulus_reflex&type=star&count=true\" frameborder=\"0\" scrolling=\"0\" class=\"ghbtn\"></iframe>\n  <iframe src=\"https://ghbtns.com/github-btn.html?user=hopsoft&repo=stimulus_reflex&type=fork&count=true\" frameborder=\"0\" scrolling=\"0\" class=\"ghbtn\"></iframe>\n</div>\n```\n\n### Aborting a reflex\n\ncall `raise :abort` within a reflex method to cancel it.\n\n```ruby\n# comment_reflex.rb\nclass CommentReflex < ApplicationReflex\n  def create\n    raise :abort\n  end\nend\n```"}

field_body:
### via Data Attributes

Trigger reflexes without writing any javascript with the `data-reflex` attribute.

#### index.html.erb

```html
<a
  href="#"
  data-reflex="click->CounterReflex#increment"
  data-step="1"
  data-count="<%= @count.to_i %>"
  >Increment <%= @count.to_i %></a
>
```

#### counter_reflex.rb

```ruby
class CounterReflex < StimulusReflex::Reflex
  def increment
    @count = element.dataset[:count].to_i + element.dataset[:step].to_i
  end
end
```

### from Stimulus.js Controller

Stimulus.js controllers registered with StimulusReflex can use the `stimulate` method to trigger reflexes

#### index.html.erb

```html
<a href="#"
  data-controller="counter"
  data-action="click->counter#increment"
>Increment <%= @count %></a>
```

#### counter_controller.js

```javascript
import { Controller } from 'stimulus'
import StimulusReflex from 'stimulus_reflex'

export default class extends Controller {
  connect() {
    StimulusReflex.register(this)
  }

  increment(event) {
    event.preventDefault()
    this.stimulate('Counter#increment', 1)
  }
}
```

#### counter_reflex.rb

```ruby
class CounterReflex < StimulusReflex::Reflex
  def increment(step = 1)
    session[:count] = session[:count].to_i + step
   end
end
```

## Morphs

### Selector morphs

Instead of refreshing the entire page, you can specify a portion of the page to update with `morph(selector, content)`

```html
<!-- show.html.erb -->
<header data-reflex="click->Example#change">
  <%= render partial: "path/to/foo", locals: {message: "Am I the medium or the massage?"} %>
</header>
```

```html
<!-- _foo.html.erb -->
<div id="foo">
  <span class="spa"><%= message %></span>
</div>
```

```ruby
# example_reflex.rb
class ExampleReflex < ApplicationReflex
  def change
    morph "#foo", "Your muscles... they are so tight."
  end
end
```

### Nothing morph

Use `morph :nothing` in reflexes that do something on the server without updating the client.

```ruby
# example_reflex.rb
class ExampleReflex < ApplicationReflex
  def change
    LongRunningJob.perform_later
    morph :nothing
  end
end
```

## Lifecycle

### Server-side callbacks

Reflex classes can use the following callbacks. [Full Docs](http://docs.stimulusreflex.com/lifecycle#server-side-reflex-callbacks)

- `before_reflex`
- `around_reflex`
- `after_reflex`

### Client-side callbacks (generic)

StimulusReflex controllers automatically support five generic lifecycle callback methods.

- `beforeReflex(element, reflex, noop, reflexId)` prior to sending a request over the web socket
- `reflexSuccess(element, reflex, noop, reflexId)` after the server side Reflex succeeds and the DOM has been updated
- `reflexError(element, reflex, error, reflexId)` whenever the server side Reflex raises an error
- `reflexHalted(element, reflex, noop, reflexId)` reflex canceled with throw :abort in the before_reflex callback
- `afterReflex(element, reflex, noop, reflexId)` after both success and error
- `finalizeReflex(element, reflex, noop, reflexId)` after both success and error

### Client-side callbacks (custom)

StimulusReflex controllers can define up to five custom lifecycle callback methods for each Reflex action. These methods use a naming convention based on the name of the Reflex. e.g. for the `add_one` reflex:

- `beforeAddOne(element, reflex, noop, reflexId)`
- `addOneSuccess(element, reflex, noop, reflexId)`
- `addOneError(element, reflex, error, reflexId)`
- `addOneHalted(element, reflex, noop, reflexId)`
- `afterAddOne(element, reflex, noop, reflexId)`
- `finalizeAddOne(element, reflex, noop, reflexId)`

### Client-side events

If you need to know when a Reflex method is called, but you're working outside of the Stimulus controller that initiated it, you can subscribe to receive DOM events

- `stimulus-reflex:before`
- `stimulus-reflex:success`
- `stimulus-reflex:error`
- `stimulus-reflex:halted`
- `stimulus-reflex:after`

There are also events related to the StimulusReflex library setting up and connecting to ActionCable

- `stimulus-reflex:connected`
- `stimulus-reflex:disconnected`
- `stimulus-reflex:rejected`
- `stimulus-reflex:ready`

## Helpful tips

### Forms

If a Reflex is called on a form element - or a child of that form element - then the data for the whole form will be properly serialized and made available to the Reflex action method as the `params` accessor. [Read more](http://docs.stimulusreflex.com/working-with-forms)

### Promises

`stimulate()` method returns a promise

```javascript
this.stimulate('Comments#create')
  .then(() => this.doSomething())
  .catch(() => this.handleError())
```

### Inheriting data-attributes from parent elements

You can use the `data-reflex-dataset="combined"` directive to scoop all data attributes up the DOM hierarchy and pass them as part of the Reflex payload.

```html
<!-- new.html.erb -->
<div data-post-id="<%= @post.id %>">
  <div data-category-id="<%= @category.id %>">
    <button data-reflex="click->Comment#create" data-reflex-dataset="combined">Create</button>
  </div>
</div>
```

```html
# comment_reflex.rb
class CommentReflex < ApplicationReflex
  def create
    puts element.dataset["post-id"]
    puts element.dataset["category-id"]
  end
end
```

### Reflex root

Instead of updating your entire page, you can specify exactly which parts of the DOM will be updated using the `data-reflex-root` attribute. [Full docs](http://docs.stimulusreflex.com/morph-modes#scoping-page-morphs)

```text
<!-- index.html.erb -->
<div data-reflex-root="[forward],[backward]">
  <input type="text" value="<%= @words %>" data-reflex="keyup->Example#words">
  <div forward><%= @words %></div>
  <div backward><%= @words&.reverse %></div>
</div>
```

```ruby
# example_reflex.rb
  def words
    @words = element[:value]
  end
```

### Permanent elements

Add data-reflex-permanent to any element in your DOM, and it will be left unchanged by full-page Reflex updates and morph calls that re-render partials.

```erb
<!-- index.html.erb -->
<div data-reflex-permanent>
  <iframe src="https://ghbtns.com/github-btn.html?user=hopsoft&repo=stimulus_reflex&type=star&count=true" frameborder="0" scrolling="0" class="ghbtn"></iframe>
  <iframe src="https://ghbtns.com/github-btn.html?user=hopsoft&repo=stimulus_reflex&type=fork&count=true" frameborder="0" scrolling="0" class="ghbtn"></iframe>
</div>
```

### Aborting a reflex

call `raise :abort` within a reflex method to cancel it.

```ruby
# comment_reflex.rb
class CommentReflex < ApplicationReflex
  def create
    raise :abort
  end
end
```


id: stencil
git_filename: ./stencil.md
format: md
field_title: Stencil
field_category: JavaScript libraries
field_updated: 2019-05-08
field_updated___timezone: UTC
data:
{"title": "Stencil", "category": "JavaScript libraries", "updated": "2019-05-08", "keywords": ["@Component", "@Prop()", "@State()", "render()", "componentWillLoad()", "componentWillUpdate()", "Templating", "Lifecycle"], "intro": "[Stencil](https://github.com/ionic-team/stencil) is a compiler for web components made by the Ionic team. This guide targets Stencil v0.0.5.\n", "body": "## Quick-start guide\n{: .-three-column}\n\n### Getting started\n{: .-prime}\n\n#### JavaScript\n\n```js\nimport { Component, Prop, State } from '@stencil/core'\n\n@Component({\n  tag: 'my-component',\n  styleUrl: 'my-component.scss'\n})\nexport class MyComponent {\n  @Prop() name: string\n  @State() isVisible: boolean = true\n\n  render () {\n    return <p>I am {this.name}!</p>\n    )\n  }\n}\n```\n\n#### HTML\n\n```html\n<my-component name='Groot' />\n```\n\nThat's the same example in the [Readme](https://github.com/ionic-team/stencil), that's as simple as you can get! Just use `<my-component>` like you would use any other HTML tag.\n\n### DOM events\n\n```js\nexport class MyComponent {\n  render () {\n    return (\n      <input\n        onChange={(event: UIEvent) => this.inputChanged(event)}\n      />\n    )\n  }\n\n  inputChanged (event) {\n    console.log('input changed:', event.target.value)\n  }\n}\n```\n{: data-line=\"5,10,11\"}\n\nStencil uses DOM events.\n\nSee: [Handling user input](https://stenciljs.com/docs/templating/#handling-user-input)\n\n### Multiple children\n\n```js\nrender () {\n  return [\n    <h1>Hello there</h1>,\n    <p>This component returns multiple nodes</p>\n  ]\n}\n```\n{: data-line=\"3,4\"}\n\n`render()` can return an array of elements.\n\nSee: [Complex template content](https://stenciljs.com/docs/templating#complex-template-content)\n\n## State\n\n### Managing state\n\n```js\nexport class MyComponent {\n  @State() isVisible: boolean\n\n  show () {\n    this.isVisible = true\n  }\n}\n```\n{: data-line=\"4,5\"}\n\nJust do assignments. You can't do mutations though, see next section.\n\nSee: [Managing component state](https://stenciljs.com/docs/decorators#managing-component-state)\n\n### Updating arrays and objects\n\n#### \u2717 Bad\n```js\nthis.names.push('Larry')  // \u26a0\ufe0f\nthis.options.show = true  // \u26a0\ufe0f\n```\n\n#### \u2713 OK\n\n```js\nthis.names = [ ...this.names, 'Larry' ]\nthis.options = { ...this.options, show: true }\n```\n\nMutable operations such as `push()` won't work. You'll need to assign a new copy.\n\nSee: [Updating arrays](https://stenciljs.com/docs/reactive-data/#updating-arrays)\n\n## Slots\n\n### Using slot\n\n```html\n<my-component>\n  <span>Hello, friends</span>\n</my-component>\n```\n{: data-line=\"2\"}\n\n#### Component\n\n```js\nrender() {\n  return <h1><slot /></h1>\n}\n```\n{: data-line=\"2\"}\n\nYou can pass JSX/HTML as child elements. Use the `slot` tag to use them inside your component.\n\nSee: [Slots](https://stenciljs.com/docs/templating#slots)\n\n### Multiple slots\n\n```html\n<my-component>\n  <p slot='my-header'>Hello</p>\n  <p slot='my-footer'>Thanks</p>\n</my-component>\n```\n{: data-line=\"2,3\"}\n\n#### Component\n\n```js\nrender () {\n  return <div>\n    <header><slot name='my-header' /></header>\n    <footer><slot name='my-footer' /></footer>\n  </div>\n}\n```\n{: data-line=\"3,4\"}\n\nSee: [Slots](https://stenciljs.com/docs/templating#slots)\n\n## Lifecycle\n\n### Lifecycle hooks\n\n| Event                   | Description      |\n| ---                     | ---              |\n| `componentWillLoad()`   | Before rendering |\n| `componentDidLoad()`    | After rendering  |\n| ---                     | ---              |\n| `componentWillUpdate()` | Before updating  |\n| `componentDidUpdate()`  | After updating   |\n| ---                     | ---              |\n| `componentDidUnload()`  | After unmounting |\n\nSee: [Component lifecycle](https://stenciljs.com/docs/component-lifecycle)\n\n### Example\n\n```js\nexport class MyComponent {\n  componentWillUpdate () {\n    console.log('updating')\n  }\n}\n```\n\n## References\n\n- [Stencil docs](https://stenciljs.com/docs/) _(stenciljs.com)_"}

field_intro:
[Stencil](https://github.com/ionic-team/stencil) is a compiler for web components made by the Ionic team. This guide targets Stencil v0.0.5.

field_body:
## Quick-start guide
{: .-three-column}

### Getting started
{: .-prime}

#### JavaScript

```js
import { Component, Prop, State } from '@stencil/core'

@Component({
  tag: 'my-component',
  styleUrl: 'my-component.scss'
})
export class MyComponent {
  @Prop() name: string
  @State() isVisible: boolean = true

  render () {
    return <p>I am {this.name}!</p>
    )
  }
}
```

#### HTML

```html
<my-component name='Groot' />
```

That's the same example in the [Readme](https://github.com/ionic-team/stencil), that's as simple as you can get! Just use `<my-component>` like you would use any other HTML tag.

### DOM events

```js
export class MyComponent {
  render () {
    return (
      <input
        onChange={(event: UIEvent) => this.inputChanged(event)}
      />
    )
  }

  inputChanged (event) {
    console.log('input changed:', event.target.value)
  }
}
```
{: data-line="5,10,11"}

Stencil uses DOM events.

See: [Handling user input](https://stenciljs.com/docs/templating/#handling-user-input)

### Multiple children

```js
render () {
  return [
    <h1>Hello there</h1>,
    <p>This component returns multiple nodes</p>
  ]
}
```
{: data-line="3,4"}

`render()` can return an array of elements.

See: [Complex template content](https://stenciljs.com/docs/templating#complex-template-content)

## State

### Managing state

```js
export class MyComponent {
  @State() isVisible: boolean

  show () {
    this.isVisible = true
  }
}
```
{: data-line="4,5"}

Just do assignments. You can't do mutations though, see next section.

See: [Managing component state](https://stenciljs.com/docs/decorators#managing-component-state)

### Updating arrays and objects

#### ✗ Bad
```js
this.names.push('Larry')  // ⚠️
this.options.show = true  // ⚠️
```

#### ✓ OK

```js
this.names = [ ...this.names, 'Larry' ]
this.options = { ...this.options, show: true }
```

Mutable operations such as `push()` won't work. You'll need to assign a new copy.

See: [Updating arrays](https://stenciljs.com/docs/reactive-data/#updating-arrays)

## Slots

### Using slot

```html
<my-component>
  <span>Hello, friends</span>
</my-component>
```
{: data-line="2"}

#### Component

```js
render() {
  return <h1><slot /></h1>
}
```
{: data-line="2"}

You can pass JSX/HTML as child elements. Use the `slot` tag to use them inside your component.

See: [Slots](https://stenciljs.com/docs/templating#slots)

### Multiple slots

```html
<my-component>
  <p slot='my-header'>Hello</p>
  <p slot='my-footer'>Thanks</p>
</my-component>
```
{: data-line="2,3"}

#### Component

```js
render () {
  return <div>
    <header><slot name='my-header' /></header>
    <footer><slot name='my-footer' /></footer>
  </div>
}
```
{: data-line="3,4"}

See: [Slots](https://stenciljs.com/docs/templating#slots)

## Lifecycle

### Lifecycle hooks

| Event                   | Description      |
| ---                     | ---              |
| `componentWillLoad()`   | Before rendering |
| `componentDidLoad()`    | After rendering  |
| ---                     | ---              |
| `componentWillUpdate()` | Before updating  |
| `componentDidUpdate()`  | After updating   |
| ---                     | ---              |
| `componentDidUnload()`  | After unmounting |

See: [Component lifecycle](https://stenciljs.com/docs/component-lifecycle)

### Example

```js
export class MyComponent {
  componentWillUpdate () {
    console.log('updating')
  }
}
```

## References

- [Stencil docs](https://stenciljs.com/docs/) _(stenciljs.com)_


id: sql-join
git_filename: ./sql-join.md
format: md
field_title: SQL joins
field_category: Databases
field_updated: 2018-12-06
field_updated___timezone: UTC
data:
{"title": "SQL joins", "category": "Databases", "updated": "2018-12-06", "weight": -1, "body": "### Example\n\n```\nSELECT * FROM order_items \\\n  LEFT OUTER JOIN orders \\\n  ON order_items.order_id = orders.id\n```\n{: .-wrap}\n\nJoins are typically added to `SELECT` statements to add more columns and records.\n\n### Diagram\n\n```\nSELECT * FROM `A` INNER JOIN `B`\n```\n{: .-setup}\n\n```\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502 A  \u250c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2510\n\u2502    \u2502 \u2229 \u2502    \u2502\n\u2514\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2518  B \u2502\n     \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n```\n{: .-box-chars.-setup}\n\n| Join             | What            |\n| ----             | ----            |\n| Inner join       | `\u2229`             |\n| Left outer join  | `A` + `\u2229`       |\n| Right outer join | `\u2229` + `B`       |\n| Full outer join  | `A` + `\u2229` + `B` |"}

field_body:
### Example

```
SELECT * FROM order_items \
  LEFT OUTER JOIN orders \
  ON order_items.order_id = orders.id
```
{: .-wrap}

Joins are typically added to `SELECT` statements to add more columns and records.

### Diagram

```
SELECT * FROM `A` INNER JOIN `B`
```
{: .-setup}

```
┌────────┐
│ A  ┌───┼────┐
│    │ ∩ │    │
└────┼───┘  B │
     └────────┘
```
{: .-box-chars.-setup}

| Join             | What            |
| ----             | ----            |
| Inner join       | `∩`             |
| Left outer join  | `A` + `∩`       |
| Right outer join | `∩` + `B`       |
| Full outer join  | `A` + `∩` + `B` |


id: spreadsheet
git_filename: ./spreadsheet.md
format: md
field_title: Spreadsheet functions
field_tags: WIP
data:
{"title": "Spreadsheet functions", "tags": ["WIP"], "body": "### If\n\n```\n=IF(test, then, else)\n=IF(EQ(A1, \"paid\"), \"true\", \"false\")\n```\n\n### Comparators\n\n```\n=EQ(a,b)\n=NE(a,b)\n=GT(a,b)\n=GTE(a,b)\n=LT(a,b)\n=LTE(a,b)\n```\n\n### Math\n\n```\n=POW(2, 32)   # 2^32\n=SIN() ACOS() etc\n=CEILING(n,sig,mode)\n=FLOOR(n,sig,mode)\n=INT(n)\n```\n\n```\n=SUM(range)\n```\n\n```\n=SUMIF(range, criteria, sum_range)\n=SUMIF(A1:A5, \">300\", B1:B5)          # if A# is >300, use B#\n```\n\n### Core\n\n```\n=TO_DATE(number)\n```\n\n### Vlook\n\n```\n=VLOOKUP(value, range, column_index)\n```"}

field_body:
### If

```
=IF(test, then, else)
=IF(EQ(A1, "paid"), "true", "false")
```

### Comparators

```
=EQ(a,b)
=NE(a,b)
=GT(a,b)
=GTE(a,b)
=LT(a,b)
=LTE(a,b)
```

### Math

```
=POW(2, 32)   # 2^32
=SIN() ACOS() etc
=CEILING(n,sig,mode)
=FLOOR(n,sig,mode)
=INT(n)
```

```
=SUM(range)
```

```
=SUMIF(range, criteria, sum_range)
=SUMIF(A1:A5, ">300", B1:B5)          # if A# is >300, use B#
```

### Core

```
=TO_DATE(number)
```

### Vlook

```
=VLOOKUP(value, range, column_index)
```


id: spine
git_filename: ./spine.md
format: md
field_title: Spine
field_category: JavaScript libraries
field_tags: Outdated
data:
{"title": "Spine", "category": "JavaScript libraries", "tags": ["Outdated"], "body": "## Models\n\n### About\n{: .-intro}\n\nSpine is an MVC framework for JavaScript.\n\n- <https://spine.github.io/>\n\n### Models\n\n    class User extends Spine.Model\n      @configure \"User\", \"name\", \"address\"\n\n      fullName: ->\n        [@first, @last].join ' '\n\n### JavaScript\n\n    // Subclassing\n    User = Spine.Model.sub()\n\n### Class methods\n\n    .configure 'modelname', attributes...\n\n    # Inheritance\n    .include(Module)\n    .extend(Module)\n\n    .create(name: \"John\")\n\n    .count()\n\n    # Events\n    .on 'refresh change', (user) -> ...\n    .trigger 'event'\n\n    .change (user) -> ...  # same as on('change')\n    .fetch (user) -> ...   # same as on('fetch')\n\n    # JSON\n    .toJSON()         # all records\n    .fromJSON(json)   # from json string\n    .fromForm(el)\n\n    # Data\n    .records     # Hash of instances\n    .attributes  # array of attributes (from .configure)\n\n    # Convenience\n    .toString()  #=> \"User\"\n\n    # Find by ID\n    .exists(1)\n    .find(1)     # throws error\n\n    # Find by something\n    .select (u) u.name == 'bob'\n    .findByAttribute 'name', 'bob'\n    .findAllByAttribute 'name', 'bob'\n\n    .all()\n    .slice(6, 13)  # cloned copies of instances\n\n    # Iterating\n    .each (user) ->\n\n    # Ends\n    .first()\n    .last()\n\n    # Deleting\n    .deleteAll()\n    .destroyAll()\n    .destroyAll({ ..options.. })\n    .destroy(2)\n\n### Instance methods\n\n    user = new User();\n\n    user\n    .isNew()\n    .exists()\n\n    # Validation\n    .isValid()\n    .validate()    # validate = (-> \"Name required\" unless @name)\n\n    .attributes()  # hash of attr values\n    .eql(other)    # equality check\n\n    # Update\n    .load(attrs)\n    .reload()\n    .fromForm(form)\n    .updateAttribute(\"name\", \"john\")\n    .updateAttributes(name: \"John\")\n\n    # Event\n    .on 'event', -> ...\n    .trigger 'event'\n\n    # Retrieve\n    .toJSON()\n\n    # Persistence\n    .save()\n\n    .destroy()\n    .dup()         # clone as unsaved\n\n### Mixins\n\n    class User extends Spine.Model\n      @include MyModule\n      @extend MyModule\n\n### Events\n\n    .on 'create'\n    .on 'update'\n    .on 'destroy'\n\n    .on 'save'    # create / update\n    .on 'change'  # create / update / destroy\n\n    .on 'refresh'\n    .on 'error'    # validation error\n\n## Ajax\n\n### Ajax\n\n    class User extends Spine.Model\n      @extend Spine.Model.Ajax\n\n      @url: '/users'\n      @url: -> '/users'\n      scope: '2013'\n\n### Using\n\n    User.fetch()\n    user = new User()\n\n    user.url()            #=> \"/users\"\n    user.url('bands')     #=> \"/users/bands\"\n\n    user.scope = 'admin'\n    user.url()            #=> \"/admin/users\"\n\n### Host\n\n    Spine.Model.host = 'http://endpoint'\n\n### Ajax mapping\n\n    read    \u2192 GET    /collection\n    create  \u2192 POST   /collection (201 created)\n    update  \u2192 PUT    /collection/id\n    destroy \u2192 DELETE /collection/id\n\n### Associations\n\n    class Photo extends Spine.Model\n      @belongsTo 'album', 'Album'          # window['Album']\n      @belongsTo 'album', 'models/album'   # via require.js\n\n    class Album\n      @hasMany 'photos', 'models/photo'\n\n    album.photos().all()\n    album.photos().create(name: \"Vacation\")\n    album.photos().find(id)\n\n    photo = Photo.create(album: album)\n    photo.album()\n    photo.album_id"}

field_body:
## Models

### About
{: .-intro}

Spine is an MVC framework for JavaScript.

- <https://spine.github.io/>

### Models

    class User extends Spine.Model
      @configure "User", "name", "address"

      fullName: ->
        [@first, @last].join ' '

### JavaScript

    // Subclassing
    User = Spine.Model.sub()

### Class methods

    .configure 'modelname', attributes...

    # Inheritance
    .include(Module)
    .extend(Module)

    .create(name: "John")

    .count()

    # Events
    .on 'refresh change', (user) -> ...
    .trigger 'event'

    .change (user) -> ...  # same as on('change')
    .fetch (user) -> ...   # same as on('fetch')

    # JSON
    .toJSON()         # all records
    .fromJSON(json)   # from json string
    .fromForm(el)

    # Data
    .records     # Hash of instances
    .attributes  # array of attributes (from .configure)

    # Convenience
    .toString()  #=> "User"

    # Find by ID
    .exists(1)
    .find(1)     # throws error

    # Find by something
    .select (u) u.name == 'bob'
    .findByAttribute 'name', 'bob'
    .findAllByAttribute 'name', 'bob'

    .all()
    .slice(6, 13)  # cloned copies of instances

    # Iterating
    .each (user) ->

    # Ends
    .first()
    .last()

    # Deleting
    .deleteAll()
    .destroyAll()
    .destroyAll({ ..options.. })
    .destroy(2)

### Instance methods

    user = new User();

    user
    .isNew()
    .exists()

    # Validation
    .isValid()
    .validate()    # validate = (-> "Name required" unless @name)

    .attributes()  # hash of attr values
    .eql(other)    # equality check

    # Update
    .load(attrs)
    .reload()
    .fromForm(form)
    .updateAttribute("name", "john")
    .updateAttributes(name: "John")

    # Event
    .on 'event', -> ...
    .trigger 'event'

    # Retrieve
    .toJSON()

    # Persistence
    .save()

    .destroy()
    .dup()         # clone as unsaved

### Mixins

    class User extends Spine.Model
      @include MyModule
      @extend MyModule

### Events

    .on 'create'
    .on 'update'
    .on 'destroy'

    .on 'save'    # create / update
    .on 'change'  # create / update / destroy

    .on 'refresh'
    .on 'error'    # validation error

## Ajax

### Ajax

    class User extends Spine.Model
      @extend Spine.Model.Ajax

      @url: '/users'
      @url: -> '/users'
      scope: '2013'

### Using

    User.fetch()
    user = new User()

    user.url()            #=> "/users"
    user.url('bands')     #=> "/users/bands"

    user.scope = 'admin'
    user.url()            #=> "/admin/users"

### Host

    Spine.Model.host = 'http://endpoint'

### Ajax mapping

    read    → GET    /collection
    create  → POST   /collection (201 created)
    update  → PUT    /collection/id
    destroy → DELETE /collection/id

### Associations

    class Photo extends Spine.Model
      @belongsTo 'album', 'Album'          # window['Album']
      @belongsTo 'album', 'models/album'   # via require.js

    class Album
      @hasMany 'photos', 'models/photo'

    album.photos().all()
    album.photos().create(name: "Vacation")
    album.photos().find(id)

    photo = Photo.create(album: album)
    photo.album()
    photo.album_id


id: spacemacs
git_filename: ./spacemacs.md
format: md
field_title: Spacemacs
field_category: Apps
field_tags: WIP
field_intro: [Spacemacs](http://spacemacs.org) is a distribution for Emacs.
field_updated: 2020-05-22
field_updated___timezone: UTC
data:
{"title": "Spacemacs", "category": "Apps", "updated": "2020-05-22", "tags": ["WIP"], "intro": "[Spacemacs](http://spacemacs.org) is a distribution for Emacs.\n", "body": "Shortcuts\n---------\n{: .-three-column}\n\n### Layers\n\n| Shortcut  | Description       |\n| ---       | ---               |\n| `SPC` `f` | File              |\n| `SPC` `p` | Project           |\n| `SPC` `t` | Toggle            |\n| `SPC` `b` | Buffer            |\n| ---       | ---               |\n| `SPC` `m` | Major mode        |\n| `,`       | Same as `SPC` `m` |\n| ---       | ---               |\n| `SPC` `g` | Git               |\n| `SPC` `l` | Layout            |\n| `SPC` `a` | Apps              |\n| `SPC` `h` | Help              |\n{: .-shortcuts.-prime}\n\n### More\n\n| Description | Shortcut    |\n| ---         | ---         |\n| **M-x**     | `SPC` `SPC` |\n| Terminal    | `SPC` `'`   |\n| Search      | `SPC` `/`   |\n{: .-shortcuts-right}\n\n### `SPC` `h` - Help\n\n| Description        | Shortcut |\n| ---                | ---      |\n| **Spacemacs help** | `SPC`    |\n| ---                | ---      |\n| Layers             | `l`      |\n| Documentation      | `r`      |\n| FAQ                | `f`      |\n| Vimtutor           | `T`      |\n{: .-shortcuts-right}\n\n### `SPC` `f` - File\n\n| Description   | Shortcut |\n| ---           | ---      |\n| **Save**      | `s`      |\n| Save all      | `S`      |\n| Copy          | `c`      |\n| Delete        | `D`      |\n| ---           | ---      |\n| Show filename | `y`      |\n{: .-shortcuts-right}\n\n### `SPC` `b` - Buffer\n\n| Description                | Shortcut |\n| ---                        | ---      |\n| Next buffer (`:bnext`)     | `n`      |\n| Previous buffer (`:bprev`) | `p`      |\n| Delete buffer (`:bd`)      | `d`      |\n{: .-shortcuts-right}\n\n### `SPC` `f` `e` - Config\n\n| Description              | Shortcut |\n| ---                      | ---      |\n| **Edit config**          | `d`      |\n| Edit config and template | `D`      |\n| ---                      | ---      |\n| Reload config            | `R`      |\n{: .-shortcuts}\n\n### `SPC` `w` - Window\n\n| Description         | Shortcut              |\n| ---                 | ---                   |\n| Help                | `.`                   |\n|                     | ---                   |\n| Select              | `h` / `j` / `k` / `l` |\n| Move                | `H` / `J` / `K` / `L` |\n| ---                 | ---                   |\n| Split               | `s`                   |\n| Split & follow      | `S`                   |\n| ---                 | ---                   |\n| Split vert          | `v`                   |\n| Split vert & follow | `V`                   |\n{: .-shortcuts-right}\n\n### `SPC` `p` - Project\n\n| Description             | Shortcut |\n| ---                     | ---      |\n| **Switch project**      | `l`      |\n| Switch project          | `p`      |\n| ---                     | ---      |\n| **Open files & recent** | `h`      |\n| Open files              | `f`      |\n| ---                     | ---      |\n| **Show tree**           | `t`      |\n| ---                     | ---      |\n| Open terminal           | `'`      |\n| Open terminal in root   | `$` `t`  |\n{: .-shortcuts-right}\n\n### `SPC` `l` `w` - Workspaces\n\n| Description                 | Shortcut    |\n| ---                         | ---         |\n| Help                        | `?`         |\n| ---                         | ---         |\n| Switch previous layout      | `TAB`       |\n| **Switch to nth workspace** | `0` ... `9` |\n| ---                         | ---         |\n| Rename                      | `R`         |\n{: .-shortcuts-right}\n\n### `SPC` `t` - Toggle\n\n| Description  | Shortcut |\n| ---          | ---      |\n| Line numbers | `n`      |\n{: .-shortcuts\n\n### `SPC` `j` - Jump\n\n| Description | Shortcut |\n| ---         | ---      |\n| Character   | `j`      |\n| Line        | `l`      |\n| Word        | `w`      |\n{: .-shortcuts-right}\n\n## Major modes\n\n### Markdown\n\n| Shortcut    | Description            |\n| ---         | ---                    |\n| `,` `-`     | Insert horizontal rule |\n| `,` `h` `1` | Insert H1              |\n{: .-shortcuts}\n\n## Other layers\n\n### version-control\n\n| Shortcut              | Description            |\n| ---                   | ---                    |\n| `SPC` `g` `s`         | **Status**             |\n| ---                   | ---                    |\n| `SPC` `g` `m`         | **Open dispatch menu** |\n| `SPC` `g` `m` `s`     | Stage                  |\n| `SPC` `g` `m` `P` `p` | Push                   |\n| `SPC` `g` `m` `c`     | Commit                 |\n| ---                   | ---                    |\n| `SPC` `g` `t`         | Open time machine      |\n| ---                   | ---                    |\n| `SPC` `g` `l` `l`     | Open in GitHub         |\n| `SPC` `g` `l` `L`     | Show GitHub URL        |\n{: .-shortcuts}\n\nVersion control is provided by Magit.\n\n## Emacs standard\n\n### File\n\n| Description      | Emacs       | Spacemacs     |\n| ---              | ---         | ---           |\n| Save             | `C-x` `C-s` | `SPC` `f` `s` |\n| Open             | `C-x` `C-f` | `SPC` `f` `f` |\n| Close            | `C-x` `C-k` |               |\n| ---              | ---         | ---           |\n| Split horizontal | `C-x` `2`   | `SPC` `w` `h` |\n| Split vertical   | `C-x` `3`   | `SPC` `w` `v` |\n| ---              | ---         | ---           |\n| Confirm          | `C-c` `C-c` |               |\n| Abort            | `C-c` `C-k` |               |\n{: .-shortcuts-right}\n\n## References\n\n- [Spacemacs documentation](https://github.com/syl20bnr/spacemacs/blob/master/doc/DOCUMENTATION.org) _(github.com)_"}

field_body:
Shortcuts
---------
{: .-three-column}

### Layers

| Shortcut  | Description       |
| ---       | ---               |
| `SPC` `f` | File              |
| `SPC` `p` | Project           |
| `SPC` `t` | Toggle            |
| `SPC` `b` | Buffer            |
| ---       | ---               |
| `SPC` `m` | Major mode        |
| `,`       | Same as `SPC` `m` |
| ---       | ---               |
| `SPC` `g` | Git               |
| `SPC` `l` | Layout            |
| `SPC` `a` | Apps              |
| `SPC` `h` | Help              |
{: .-shortcuts.-prime}

### More

| Description | Shortcut    |
| ---         | ---         |
| **M-x**     | `SPC` `SPC` |
| Terminal    | `SPC` `'`   |
| Search      | `SPC` `/`   |
{: .-shortcuts-right}

### `SPC` `h` - Help

| Description        | Shortcut |
| ---                | ---      |
| **Spacemacs help** | `SPC`    |
| ---                | ---      |
| Layers             | `l`      |
| Documentation      | `r`      |
| FAQ                | `f`      |
| Vimtutor           | `T`      |
{: .-shortcuts-right}

### `SPC` `f` - File

| Description   | Shortcut |
| ---           | ---      |
| **Save**      | `s`      |
| Save all      | `S`      |
| Copy          | `c`      |
| Delete        | `D`      |
| ---           | ---      |
| Show filename | `y`      |
{: .-shortcuts-right}

### `SPC` `b` - Buffer

| Description                | Shortcut |
| ---                        | ---      |
| Next buffer (`:bnext`)     | `n`      |
| Previous buffer (`:bprev`) | `p`      |
| Delete buffer (`:bd`)      | `d`      |
{: .-shortcuts-right}

### `SPC` `f` `e` - Config

| Description              | Shortcut |
| ---                      | ---      |
| **Edit config**          | `d`      |
| Edit config and template | `D`      |
| ---                      | ---      |
| Reload config            | `R`      |
{: .-shortcuts}

### `SPC` `w` - Window

| Description         | Shortcut              |
| ---                 | ---                   |
| Help                | `.`                   |
|                     | ---                   |
| Select              | `h` / `j` / `k` / `l` |
| Move                | `H` / `J` / `K` / `L` |
| ---                 | ---                   |
| Split               | `s`                   |
| Split & follow      | `S`                   |
| ---                 | ---                   |
| Split vert          | `v`                   |
| Split vert & follow | `V`                   |
{: .-shortcuts-right}

### `SPC` `p` - Project

| Description             | Shortcut |
| ---                     | ---      |
| **Switch project**      | `l`      |
| Switch project          | `p`      |
| ---                     | ---      |
| **Open files & recent** | `h`      |
| Open files              | `f`      |
| ---                     | ---      |
| **Show tree**           | `t`      |
| ---                     | ---      |
| Open terminal           | `'`      |
| Open terminal in root   | `$` `t`  |
{: .-shortcuts-right}

### `SPC` `l` `w` - Workspaces

| Description                 | Shortcut    |
| ---                         | ---         |
| Help                        | `?`         |
| ---                         | ---         |
| Switch previous layout      | `TAB`       |
| **Switch to nth workspace** | `0` ... `9` |
| ---                         | ---         |
| Rename                      | `R`         |
{: .-shortcuts-right}

### `SPC` `t` - Toggle

| Description  | Shortcut |
| ---          | ---      |
| Line numbers | `n`      |
{: .-shortcuts

### `SPC` `j` - Jump

| Description | Shortcut |
| ---         | ---      |
| Character   | `j`      |
| Line        | `l`      |
| Word        | `w`      |
{: .-shortcuts-right}

## Major modes

### Markdown

| Shortcut    | Description            |
| ---         | ---                    |
| `,` `-`     | Insert horizontal rule |
| `,` `h` `1` | Insert H1              |
{: .-shortcuts}

## Other layers

### version-control

| Shortcut              | Description            |
| ---                   | ---                    |
| `SPC` `g` `s`         | **Status**             |
| ---                   | ---                    |
| `SPC` `g` `m`         | **Open dispatch menu** |
| `SPC` `g` `m` `s`     | Stage                  |
| `SPC` `g` `m` `P` `p` | Push                   |
| `SPC` `g` `m` `c`     | Commit                 |
| ---                   | ---                    |
| `SPC` `g` `t`         | Open time machine      |
| ---                   | ---                    |
| `SPC` `g` `l` `l`     | Open in GitHub         |
| `SPC` `g` `l` `L`     | Show GitHub URL        |
{: .-shortcuts}

Version control is provided by Magit.

## Emacs standard

### File

| Description      | Emacs       | Spacemacs     |
| ---              | ---         | ---           |
| Save             | `C-x` `C-s` | `SPC` `f` `s` |
| Open             | `C-x` `C-f` | `SPC` `f` `f` |
| Close            | `C-x` `C-k` |               |
| ---              | ---         | ---           |
| Split horizontal | `C-x` `2`   | `SPC` `w` `h` |
| Split vertical   | `C-x` `3`   | `SPC` `w` `v` |
| ---              | ---         | ---           |
| Confirm          | `C-c` `C-c` |               |
| Abort            | `C-c` `C-k` |               |
{: .-shortcuts-right}

## References

- [Spacemacs documentation](https://github.com/syl20bnr/spacemacs/blob/master/doc/DOCUMENTATION.org) _(github.com)_


id: social-images
git_filename: ./social-images.md
format: md
field_title: Social media images
data:
{"title": "Social media images", "body": "### Facebook\n\n| What | Dimensions |\n|:---- | ----------:|\n| Cover photo | 851 x 315 |\n| Display picture | 168 x 168 ? |\n| Highlighted image | 1200 x 717 (appears 843 x 504) |\n| Share link (og:image) | 940 x 492 (1.91:1, appears as 470 x 246) |\n| Share link (square) | 1:1, appears as 114 x 114? |\n\n### Twitter\n\n| What | Dimensions |\n|:---- | ----------:|\n| Page header | 1500 x 500 |\n| Display picture | 400 x 400 (shown as 200x200) |\n| In-stream photo preview | 440 x 220 (2:1) |\n\n### References\n\n * <https://developers.facebook.com/docs/plugins/checklist/>"}

field_body:
### Facebook

| What | Dimensions |
|:---- | ----------:|
| Cover photo | 851 x 315 |
| Display picture | 168 x 168 ? |
| Highlighted image | 1200 x 717 (appears 843 x 504) |
| Share link (og:image) | 940 x 492 (1.91:1, appears as 470 x 246) |
| Share link (square) | 1:1, appears as 114 x 114? |

### Twitter

| What | Dimensions |
|:---- | ----------:|
| Page header | 1500 x 500 |
| Display picture | 400 x 400 (shown as 200x200) |
| In-stream photo preview | 440 x 220 (2:1) |

### References

 * <https://developers.facebook.com/docs/plugins/checklist/>


id: slim
git_filename: ./slim.md
format: md
field_title: Slim
field_category: Ruby libraries
field_prism_languages: jade
data:
{"title": "Slim", "category": "Ruby libraries", "prism_languages": ["jade"], "weight": -1, "body": "### Example\n\n```jade\ndoctype html\nhtml\n  head\n    title Slim Examples\n    meta[charset='utf-8']\n    meta(name=\"keywords\" content=\"template language\")\n    meta name=\"author\" content=author\n    meta property='og:image' content=asset_url('foo.png')\n    meta property='og:image' content=(path_to_user user)\n    meta(\n      property='description'\n      content='this is the song that never ends')\n```\n\n### Attributes\n\n```jade\nmeta[charset='utf-8']\nmeta(name=\"keywords\" content=\"template language\")\nmeta name=\"author\" content=author\n```\n\nYou can use parentheses, brackets, or none at all.\n\n### Ruby attributes\n\n```jade\na class=[:menu,:highlight]\n```\n\nYou can use Ruby expressions in attributes.\n\n### Hash attributes\n\n```jade\n.card *{'data-url' => place_path(place)}\n```\n\nYou can destructure Ruby hashes as attributes.\n\n### Inline Ruby\n\n```jade\nruby:\n  def foobar\n    \"hello\"\n  end\n\ndiv= foobar\n```\n\n### Inline Markdown\n\n```jade\nmarkdown:\n  ### On Markdown\n\n  I am *Markdown* _text_!\n  {: .classname}\n```\n\nSlim can handle your [Markdown](https://daringfireball.net/projects/markdown/syntax) content for longer content blocks or `code`.\nDepending on your parser, like [Kramdown](https://kramdown.gettalong.org/quickref.html), other features might work, like assigning attributes or classes.\n\n### Embedded JavaScript\n\n```jade\njavascript:\n  alert('Slim supports embedded javascript!')\n```\n\n\n### Comments\n\n```jade\n/ Comment\n/! HTML comment\n```\n\n### Ruby\n\n```jade\n== yield\n= t('.hello')\n- 3.times do |i|\n  div\n```\n\n### Verbatim text\n\n```jade\ndiv\n  | This is text\n    it is nice\n```\n\n### Advanced whitespaces\n\n```jade\ndiv\n  ' This appends a whitespace\ndiv\n  |  This hackily prepends a whitespace\ndiv\n  => 'This appends a whitespace'\ndiv\n  =< 'This prepends a whitespace'\n```\n\n### Inline HTML\n\n```jade\n<div class='foo'>\n  - if articles.empty?\n    | Nothing here\n</div>\n```\n\n### Inline tags\n\n```jade\nul\n  li: a(href='/') Home\n```\n\n### References\n\n- <http://slim-lang.com/>"}

field_body:
### Example

```jade
doctype html
html
  head
    title Slim Examples
    meta[charset='utf-8']
    meta(name="keywords" content="template language")
    meta name="author" content=author
    meta property='og:image' content=asset_url('foo.png')
    meta property='og:image' content=(path_to_user user)
    meta(
      property='description'
      content='this is the song that never ends')
```

### Attributes

```jade
meta[charset='utf-8']
meta(name="keywords" content="template language")
meta name="author" content=author
```

You can use parentheses, brackets, or none at all.

### Ruby attributes

```jade
a class=[:menu,:highlight]
```

You can use Ruby expressions in attributes.

### Hash attributes

```jade
.card *{'data-url' => place_path(place)}
```

You can destructure Ruby hashes as attributes.

### Inline Ruby

```jade
ruby:
  def foobar
    "hello"
  end

div= foobar
```

### Inline Markdown

```jade
markdown:
  ### On Markdown

  I am *Markdown* _text_!
  {: .classname}
```

Slim can handle your [Markdown](https://daringfireball.net/projects/markdown/syntax) content for longer content blocks or `code`.
Depending on your parser, like [Kramdown](https://kramdown.gettalong.org/quickref.html), other features might work, like assigning attributes or classes.

### Embedded JavaScript

```jade
javascript:
  alert('Slim supports embedded javascript!')
```


### Comments

```jade
/ Comment
/! HTML comment
```

### Ruby

```jade
== yield
= t('.hello')
- 3.times do |i|
  div
```

### Verbatim text

```jade
div
  | This is text
    it is nice
```

### Advanced whitespaces

```jade
div
  ' This appends a whitespace
div
  |  This hackily prepends a whitespace
div
  => 'This appends a whitespace'
div
  =< 'This prepends a whitespace'
```

### Inline HTML

```jade
<div class='foo'>
  - if articles.empty?
    | Nothing here
</div>
```

### Inline tags

```jade
ul
  li: a(href='/') Home
```

### References

- <http://slim-lang.com/>


id: sketch
git_filename: ./sketch.md
format: md
field_title: Sketch
field_category: Apps
field_updated: 2017-08-30
field_updated___timezone: UTC
data:
{"title": "Sketch", "category": "Apps", "updated": "2017-08-30", "body": "## Shortcuts\n{: .-three-column}\n\n### Insert\n\n| Shortcut | Description |\n| ---      | ---         |\n| `V`      | Vector      |\n| `P`      | Pencil      |\n| `T`      | Text        |\n| `L`      | Line        |\n| `R`      | Rectangle   |\n| `O`      | Oval        |\n| `U`      | Rounded     |\n{: .-shortcuts}\n\n### Show\n\n| Shortcut | Description            |\n| ---      | ---                    |\n| `^G`     | Show grid              |\n| `^L`     | Show layout            |\n| `^P`     | Show pixels            |\n| `^H`     | Show selection handles |\n| `^R`     | Show rulers            |\n{: .-shortcuts}\n\n### Sidebars\n\n| Shortcut | Description              |\n| ---      | ---                      |\n| `\u2318\u23251`    | Toggle left (layers)     |\n| `\u2318\u23252`    | Toggle right (inspector) |\n| `\u2318\u23253`    | Toggle both              |\n| `\u2318.`     | Presentation mode        |\n{: .-shortcuts}\n\n### Zoom\n\n| Shortcut | Description             |\n| ---      | ---                     |\n| `\u23180`     | 100%                    |\n| `\u23181`     | Fit to screen           |\n| `\u23182`     | Fit selection to screen |\n| `\u23183`     | Center selection        |\n{: .-shortcuts}\n\n### Arrange\n\n| Shortcut       | Description         |\n| ---            | ---                 |\n| `\u2318\u2325\u2191` _/_ `\u2193`  | Forward or backward |\n| `^\u2318\u2325\u2191` _/_ `\u2193` | Front or back       |\n{: .-shortcuts}\n\n### Distribute\n\n| Shortcut | Description |\n| ---      | ---         |\n| `^\u2318H`    | Horizontal  |\n| `^\u2318V`    | Vertical    |\n{: .-shortcuts}\n\n### Layers\n\n| Shortcut | Description  |\n| ---      | ---          |\n| `\u2318R`     | Rename layer |\n| `\u2318F`     | Find layer   |\n| `\u2318G`     | Group        |\n| `\u2318\u21e7G`    | Ungroup      |\n{: .-shortcuts}\n\n### Font\n\n| Shortcut       | Description    |\n| ---            | ---            |\n| `\u2318\u2325 +` _/_ `-` | Bigger/smaller |\n| `\u2318\u21e7[`          | Left align     |\n| `\u2318\u21e7\\`          | Center align   |\n| `\u2318\u21e7]`          | Right align    |\n{: .-shortcuts}"}

field_body:
## Shortcuts
{: .-three-column}

### Insert

| Shortcut | Description |
| ---      | ---         |
| `V`      | Vector      |
| `P`      | Pencil      |
| `T`      | Text        |
| `L`      | Line        |
| `R`      | Rectangle   |
| `O`      | Oval        |
| `U`      | Rounded     |
{: .-shortcuts}

### Show

| Shortcut | Description            |
| ---      | ---                    |
| `^G`     | Show grid              |
| `^L`     | Show layout            |
| `^P`     | Show pixels            |
| `^H`     | Show selection handles |
| `^R`     | Show rulers            |
{: .-shortcuts}

### Sidebars

| Shortcut | Description              |
| ---      | ---                      |
| `⌘⌥1`    | Toggle left (layers)     |
| `⌘⌥2`    | Toggle right (inspector) |
| `⌘⌥3`    | Toggle both              |
| `⌘.`     | Presentation mode        |
{: .-shortcuts}

### Zoom

| Shortcut | Description             |
| ---      | ---                     |
| `⌘0`     | 100%                    |
| `⌘1`     | Fit to screen           |
| `⌘2`     | Fit selection to screen |
| `⌘3`     | Center selection        |
{: .-shortcuts}

### Arrange

| Shortcut       | Description         |
| ---            | ---                 |
| `⌘⌥↑` _/_ `↓`  | Forward or backward |
| `^⌘⌥↑` _/_ `↓` | Front or back       |
{: .-shortcuts}

### Distribute

| Shortcut | Description |
| ---      | ---         |
| `^⌘H`    | Horizontal  |
| `^⌘V`    | Vertical    |
{: .-shortcuts}

### Layers

| Shortcut | Description  |
| ---      | ---          |
| `⌘R`     | Rename layer |
| `⌘F`     | Find layer   |
| `⌘G`     | Group        |
| `⌘⇧G`    | Ungroup      |
{: .-shortcuts}

### Font

| Shortcut       | Description    |
| ---            | ---            |
| `⌘⌥ +` _/_ `-` | Bigger/smaller |
| `⌘⇧[`          | Left align     |
| `⌘⇧\`          | Center align   |
| `⌘⇧]`          | Right align    |
{: .-shortcuts}


id: sinon
git_filename: ./sinon.md
format: md
field_title: Sinon
field_category: JavaScript libraries
field_updated: 2017-10-27
field_updated___timezone: UTC
data:
{"title": "Sinon", "category": "JavaScript libraries", "weight": -1, "updated": "2017-10-27", "body": "### Creating spies\n\n```js\nfn = sinon.spy()\nfn()\n```\n\n```js\nfn.calledOnce == true\nfn.callCount == 1\n```\n\n### Spying/stubbing\n\n```js\nsinon.spy($, 'ajax')\n```\n\n```js\n$.ajax();\n$.ajax.calledOnce == true\n```\n\n```js\nsinon.stub($, 'ajax', function () { ... }) // function optional\n```\n\n```js\n$.ajax.calledWithMatch({ url: '/x' })\n$.ajax.restore()\n```\n\n### Spy/stub properties\n\n```js\nspy\n  .args        //=> [ [..], [..] ] one per call\n  .thisValues\n  .returnValues\n```\n\n```js\n  .called      //=> true\n  .notCalled\n  .callCount\n  .calledOnce\n  .calledTwice\n  .calledThrice\n```\n\n```js\n  .getCalls()   //=> Array\n  .getCall(0)\n  .firstCall\n```\n\n### Anonymous stub\n\n```js\nstub = sinon.stub().returns(42)\nstub() == 42\n```\n\n```js\nstub\n  .withArgs(42).returns(1)\n  .withArgs(43).throws(\"TypeError\")\n```\n\n```js\nstub\n  .returns(1)\n  .throws(\"TypeError\")\n  .returnsArg(0) // Return 1st argument\n  .callsArg(0)\n```\n\n### Fake date\n\n```js\nsinon.useFakeTimers(+new Date(2011,9,1));\n```\n\n### Fake server\n\n```js\nserver = sinon.fakeServer.create()\n```\n\n```js\n$.get('/file.json', ...)\nserver.requests[0].respond(\n  200,\n  { 'Content-Type': 'application/json' },\n  JSON.stringify({ hello: 'world' })\n)\n```\n\n```js\nserver.restore()\n```\n\n### Fake XHR\n\n```js\nxhr = sinon.useFakeXMLHttpRequest()\nxhr.restore()\n```\n\n### Sandbox\n\n```js\nbeforeEach(function() {\n  global.sinon = require('sinon').sandbox.create()\n})\n```\n\n```js\nafterEach(function() {\n  global.sinon.restore()\n})\n```"}

field_body:
### Creating spies

```js
fn = sinon.spy()
fn()
```

```js
fn.calledOnce == true
fn.callCount == 1
```

### Spying/stubbing

```js
sinon.spy($, 'ajax')
```

```js
$.ajax();
$.ajax.calledOnce == true
```

```js
sinon.stub($, 'ajax', function () { ... }) // function optional
```

```js
$.ajax.calledWithMatch({ url: '/x' })
$.ajax.restore()
```

### Spy/stub properties

```js
spy
  .args        //=> [ [..], [..] ] one per call
  .thisValues
  .returnValues
```

```js
  .called      //=> true
  .notCalled
  .callCount
  .calledOnce
  .calledTwice
  .calledThrice
```

```js
  .getCalls()   //=> Array
  .getCall(0)
  .firstCall
```

### Anonymous stub

```js
stub = sinon.stub().returns(42)
stub() == 42
```

```js
stub
  .withArgs(42).returns(1)
  .withArgs(43).throws("TypeError")
```

```js
stub
  .returns(1)
  .throws("TypeError")
  .returnsArg(0) // Return 1st argument
  .callsArg(0)
```

### Fake date

```js
sinon.useFakeTimers(+new Date(2011,9,1));
```

### Fake server

```js
server = sinon.fakeServer.create()
```

```js
$.get('/file.json', ...)
server.requests[0].respond(
  200,
  { 'Content-Type': 'application/json' },
  JSON.stringify({ hello: 'world' })
)
```

```js
server.restore()
```

### Fake XHR

```js
xhr = sinon.useFakeXMLHttpRequest()
xhr.restore()
```

### Sandbox

```js
beforeEach(function() {
  global.sinon = require('sinon').sandbox.create()
})
```

```js
afterEach(function() {
  global.sinon.restore()
})
```


id: sinon-chai
git_filename: ./sinon-chai.md
format: md
field_title: Sinon-chai
field_category: JavaScript libraries
data:
{"title": "Sinon-chai", "category": "JavaScript libraries", "body": "### About\n{: .-intro}\n\n  * [Sinon-chai](https://github.com/domenic/sinon-chai)\n\n### Initialization\n\n```js\nvar sinon = require('sinon');\nrequire('chai').use(require('sinon-chai'));\n```\n\n### Assert\n\n    expect(spy).called\n    expect(spy).calledOnce\n    expect(spy).calledTwice\n    expect(spy).calledThrice\n    expect(spy).calledBefore\n    expect(spy).calledAfter\n    expect(spy).calledWithNew\n    expect(spy).alwaysCalledWithNew\n    expect(spy).calledOn\n    expect(spy).alwaysCalledOn\n    expect(spy).calledWith\n    expect(spy).alwaysCalledWith\n    expect(spy).calledWithExactly\n    expect(spy).alwaysCalledWithExactly\n    expect(spy).calledWithMatch\n    expect(spy).alwaysCalledWithMatch\n    expect(spy).returned\n    expect(spy).alwaysReturned\n    expect(spy).threw\n    expect(spy).alwaysThrew\n\n### Should\n\n    spy.should.have.been.called\n    spy.should.have.been.calledOnce\n    spy.should.have.been.calledTwice\n    spy.should.have.been.calledThrice\n    spy1.should.have.been.calledBefore(spy2)\n    spy1.should.have.been.calledAfter(spy2)\n    spy.should.have.been.calledWithNew\n    spy.should.always.have.been.calledWithNew\n    spy.should.have.been.calledOn(context)\n    spy.should.always.have.been.calledOn(context)\n    spy.should.have.been.calledWith(...args)\n    spy.should.always.have.been.calledWith(...args)\n    spy.should.always.have.been.calledWithExactly(...args)\n    spy.should.always.have.been.calledWithExactly(...args)\n    spy.should.have.been.calledWithMatch(...args)\n    spy.should.always.have.been.calledWithMatch(...args)\n    spy.should.have.returned(returnVal)\n    spy.should.have.always.returned(returnVal)\n    spy.should.have.thrown(errorObjOrErrorTypeStringOrNothing)\n    spy.should.have.always.thrown(errorObjOrErrorTypeStringOrNothing)"}

field_body:
### About
{: .-intro}

  * [Sinon-chai](https://github.com/domenic/sinon-chai)

### Initialization

```js
var sinon = require('sinon');
require('chai').use(require('sinon-chai'));
```

### Assert

    expect(spy).called
    expect(spy).calledOnce
    expect(spy).calledTwice
    expect(spy).calledThrice
    expect(spy).calledBefore
    expect(spy).calledAfter
    expect(spy).calledWithNew
    expect(spy).alwaysCalledWithNew
    expect(spy).calledOn
    expect(spy).alwaysCalledOn
    expect(spy).calledWith
    expect(spy).alwaysCalledWith
    expect(spy).calledWithExactly
    expect(spy).alwaysCalledWithExactly
    expect(spy).calledWithMatch
    expect(spy).alwaysCalledWithMatch
    expect(spy).returned
    expect(spy).alwaysReturned
    expect(spy).threw
    expect(spy).alwaysThrew

### Should

    spy.should.have.been.called
    spy.should.have.been.calledOnce
    spy.should.have.been.calledTwice
    spy.should.have.been.calledThrice
    spy1.should.have.been.calledBefore(spy2)
    spy1.should.have.been.calledAfter(spy2)
    spy.should.have.been.calledWithNew
    spy.should.always.have.been.calledWithNew
    spy.should.have.been.calledOn(context)
    spy.should.always.have.been.calledOn(context)
    spy.should.have.been.calledWith(...args)
    spy.should.always.have.been.calledWith(...args)
    spy.should.always.have.been.calledWithExactly(...args)
    spy.should.always.have.been.calledWithExactly(...args)
    spy.should.have.been.calledWithMatch(...args)
    spy.should.always.have.been.calledWithMatch(...args)
    spy.should.have.returned(returnVal)
    spy.should.have.always.returned(returnVal)
    spy.should.have.thrown(errorObjOrErrorTypeStringOrNothing)
    spy.should.have.always.thrown(errorObjOrErrorTypeStringOrNothing)


id: simple_form
git_filename: ./simple_form.md
format: md
field_title: SimpleForm
field_tags: WIP
data:
{"title": "SimpleForm", "tags": ["WIP"], "body": "### Inputs\n\n```ruby\n<%= f.input :email, required: false, autofocus: true %>\n<%= f.input :password, required: false %>\n<%= f.input :remember_me, as: :boolean %>\n<%= f.button :submit, \"Sign in\" %>\n```\n\n### Adding a wrapper\n\n```ruby\nsimple_form_for @x, wrapper: :small\n```"}

field_body:
### Inputs

```ruby
<%= f.input :email, required: false, autofocus: true %>
<%= f.input :password, required: false %>
<%= f.input :remember_me, as: :boolean %>
<%= f.button :submit, "Sign in" %>
```

### Adding a wrapper

```ruby
simple_form_for @x, wrapper: :small
```


id: siege
git_filename: ./siege.md
format: md
field_title: Siege
field_category: Others
field_intro: [Siege](https://www.joedog.org/siege-home/) is an HTTP and HTTPS load testing tool.
data:
{"title": "Siege", "category": "Others", "intro": "[Siege](https://www.joedog.org/siege-home/) is an HTTP and HTTPS load testing tool.\n", "body": "### Basic usage\n\n```sh\nsiege -b -c=10 -t=5m \"http://...\"\n```\n\n### Options\n\n#### Repetitions\n\n```\n-c, --concurrent=N\n-t, --time=MINSm\n-r, --reps=N\n```\n\n#### Modes\n\n```\n-i, --internet       Hit URLs randomly\n-b, --benchmark      No delay between requests\n```\n\n#### Configuration\n\n```\n-f, --file=FILE      load urls.txt\n-R, --rc=FILE        load siegerc\n```\n\n#### Headers\n\n```\n-H, --header=\"Cookie: foo=bar\"\n-A, --user-agent=\"Mozilla\"\n-T, --content-type=\"text/html\"\n```\n\n### References\n\nAlso see: [siegerc](https://gist.github.com/stansmet/3067988)"}

field_body:
### Basic usage

```sh
siege -b -c=10 -t=5m "http://..."
```

### Options

#### Repetitions

```
-c, --concurrent=N
-t, --time=MINSm
-r, --reps=N
```

#### Modes

```
-i, --internet       Hit URLs randomly
-b, --benchmark      No delay between requests
```

#### Configuration

```
-f, --file=FILE      load urls.txt
-R, --rc=FILE        load siegerc
```

#### Headers

```
-H, --header="Cookie: foo=bar"
-A, --user-agent="Mozilla"
-T, --content-type="text/html"
```

### References

Also see: [siegerc](https://gist.github.com/stansmet/3067988)


id: shelljs
git_filename: ./shelljs.md
format: md
field_title: Shell.js
field_category: JavaScript libraries
field_updated: 2017-10-27
field_updated___timezone: UTC
data:
{"title": "Shell.js", "category": "JavaScript libraries", "updated": "2017-10-27", "weight": -1, "intro": "[ShellJS](https://github.com/shelljs/shelljs) is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. \n", "body": "### Example\n\n```js\nvar shell = require('shelljs')\n```\n\n```js\nif (!shell.which('git')) {\n  shell.echo('Sorry, this script requires git')\n  shell.exit(1)\n}\n```\n\n```js\n// Copy files to release dir\nshell.rm('-rf', 'out/Release')\nshell.cp('-R', 'stuff/', 'out/Release')\n```\n\n```js\n// Replace macros in each .js file\nshell.cd('lib')\nshell.ls('*.js').forEach(function (file) {\n  shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file)\n  shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file)\n  shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\\n/, shell.cat('macro.js'), file)\n})\nshell.cd('..')\n```\n\n```js\n// Run external tool synchronously\nif (shell.exec('git commit -am \"Auto-commit\"').code !== 0) {\n  shell.echo('Error: Git commit failed')\n  shell.exit(1)\n}\n```\n\nTaken from the [Readme](https://github.com/shelljs/shelljs).\n\n### Require\n\n```js\nconst sh = require('shelljs')\n```\n\n### Paths\n\n```js\nsh.cd('dir')\n```\n\n```js\nsh.mkdir('dir')\nsh.mkdir('-p', 'dir')\n```\n\n### File manipulation\n\n```js\nsh.cp('src', 'dest')\nsh.cp('-rf', 'src', 'dest')\n```\n\n```js\nsh.rm('file')\nsh.rm('-rf', 'file')\n```\n\n```js\nsh.mv('src', 'dest')\nsh.mv(['src1','src2'], 'dest')\n```\n\n```js\nsh.chmod('644', 'file')\nsh.chmod(755, 'file')\nsh.chmod('u+x', 'file')\n```\n\n### Tests\n\n```js\nsh.test('-b', 'path')  // block device\nsh.test('-d', 'path')  // dir\nsh.test('-e', 'path')  // exists\nsh.test('-f', 'path')  // file\nsh.test('-L', 'path')  // symlink\n```\n\n### Cat and output\n\n```js\nsrc = sh.cat('file*.txt')\n```\n\n```js\n'hello'.to('output.txt')\n'hello'.toEnd('append.txt')\n```\n\n```js\nsh.cat('input.txt').to('output.txt')\n```\n\n### Utils\n\n```js\nsh.which('x')\nsh.pwd()\n```\n\n```js\nsh.echo('hi')\n```\n\n```js\nsh.exec('node --version').code\nsh.exec('node --version').output\nsh.exec('node --version', { silent: true }).output\n```\n\n```js\nsh.exec('node --version', (code, output) => {\n  sh.echo(`exit code ${code}`)\n})\n```\n\n```js\nsh.tempdir()\n```\n\n```js\nsh.error()  // null if no error\n```\n\n## Also see\n\n* <https://github.com/shelljs/shelljs>"}

field_intro:
[ShellJS](https://github.com/shelljs/shelljs) is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. 

field_body:
### Example

```js
var shell = require('shelljs')
```

```js
if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git')
  shell.exit(1)
}
```

```js
// Copy files to release dir
shell.rm('-rf', 'out/Release')
shell.cp('-R', 'stuff/', 'out/Release')
```

```js
// Replace macros in each .js file
shell.cd('lib')
shell.ls('*.js').forEach(function (file) {
  shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file)
  shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file)
  shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file)
})
shell.cd('..')
```

```js
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
  shell.echo('Error: Git commit failed')
  shell.exit(1)
}
```

Taken from the [Readme](https://github.com/shelljs/shelljs).

### Require

```js
const sh = require('shelljs')
```

### Paths

```js
sh.cd('dir')
```

```js
sh.mkdir('dir')
sh.mkdir('-p', 'dir')
```

### File manipulation

```js
sh.cp('src', 'dest')
sh.cp('-rf', 'src', 'dest')
```

```js
sh.rm('file')
sh.rm('-rf', 'file')
```

```js
sh.mv('src', 'dest')
sh.mv(['src1','src2'], 'dest')
```

```js
sh.chmod('644', 'file')
sh.chmod(755, 'file')
sh.chmod('u+x', 'file')
```

### Tests

```js
sh.test('-b', 'path')  // block device
sh.test('-d', 'path')  // dir
sh.test('-e', 'path')  // exists
sh.test('-f', 'path')  // file
sh.test('-L', 'path')  // symlink
```

### Cat and output

```js
src = sh.cat('file*.txt')
```

```js
'hello'.to('output.txt')
'hello'.toEnd('append.txt')
```

```js
sh.cat('input.txt').to('output.txt')
```

### Utils

```js
sh.which('x')
sh.pwd()
```

```js
sh.echo('hi')
```

```js
sh.exec('node --version').code
sh.exec('node --version').output
sh.exec('node --version', { silent: true }).output
```

```js
sh.exec('node --version', (code, output) => {
  sh.echo(`exit code ${code}`)
})
```

```js
sh.tempdir()
```

```js
sh.error()  // null if no error
```

## Also see

* <https://github.com/shelljs/shelljs>


id: sh-pipes
git_filename: ./sh-pipes.md
format: md
field_title: Shell: named pipes
field_category: CLI
data:
{"title": "Shell: named pipes", "category": "CLI", "body": "### Named pipes\n\n```sh\ndiff <(ls ./old) <(ls ./new)\n```\n\nThis creates a virtual file with the contents of the output of `ls ./old`.\n\n### References\n\n* [Named pipe](https://en.wikipedia.org/wiki/Named_pipe) _(wikipedia.org)_"}

field_body:
### Named pipes

```sh
diff <(ls ./old) <(ls ./new)
```

This creates a virtual file with the contents of the output of `ls ./old`.

### References

* [Named pipe](https://en.wikipedia.org/wiki/Named_pipe) _(wikipedia.org)_


id: sequelize
git_filename: ./sequelize.md
format: md
field_title: Sequelize
field_category: JavaScript libraries
data:
{"title": "Sequelize", "category": "JavaScript libraries", "body": "### About\n{: .-intro}\n\nSequelize is an ORM for JavaScript.\n\n- <https://sequelize.org/>\n\n### API\n\n    sequelize.sync().done -> ...\n\n### Models\n\n    Project = sequelize.define('Project', {\n      title: Sequelize.STRING,\n      description: Sequelize.TEXT,\n      myDate: { type: Sequelize.DATE, defaultValue: Sequelize.NOW },\n      title: { type: Sequelize.STRING, allowNull: false },\n      id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },\n    }, {\n      classMethods: { ... },\n      instanceMethods: { ... }\n    });\n\n    Project.hasMany(Task)\n\n### Finders\n\n    Project.find(123).success (project) ->\n\n    Project.find({ where: {title: 'Hello'} })\n    Project.find({ where: {id: [1,3,4]} })\n    Project.find({ where: [\"id > ?\", 25] })\n\n    Project.find(\n      where: {title: 'a'}\n      attributes: ['id', ['name', 'title']]\n    )\n\n    .findOrCreate(...)\n\n    .findAll\n    .findAll({ where: ... })\n    .findAll({ order: 'title DESC' })\n    .findAll({ limit: 10 })\n    .findAll({ offset: 10, limit: 2 })\n\n    .count()\n\n\n### Build\n\n    item = Project.build({ ... })\n\n    item.title = '...'\n\n    item.save().success (item) ->\n\n    item.updateAttributes({ title: '...' })\n\n    item.destroy().success ->\n\n    item.values"}

field_body:
### About
{: .-intro}

Sequelize is an ORM for JavaScript.

- <https://sequelize.org/>

### API

    sequelize.sync().done -> ...

### Models

    Project = sequelize.define('Project', {
      title: Sequelize.STRING,
      description: Sequelize.TEXT,
      myDate: { type: Sequelize.DATE, defaultValue: Sequelize.NOW },
      title: { type: Sequelize.STRING, allowNull: false },
      id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
    }, {
      classMethods: { ... },
      instanceMethods: { ... }
    });

    Project.hasMany(Task)

### Finders

    Project.find(123).success (project) ->

    Project.find({ where: {title: 'Hello'} })
    Project.find({ where: {id: [1,3,4]} })
    Project.find({ where: ["id > ?", 25] })

    Project.find(
      where: {title: 'a'}
      attributes: ['id', ['name', 'title']]
    )

    .findOrCreate(...)

    .findAll
    .findAll({ where: ... })
    .findAll({ order: 'title DESC' })
    .findAll({ limit: 10 })
    .findAll({ offset: 10, limit: 2 })

    .count()


### Build

    item = Project.build({ ... })

    item.title = '...'

    item.save().success (item) ->

    item.updateAttributes({ title: '...' })

    item.destroy().success ->

    item.values


id: sequel
git_filename: ./sequel.md
format: md
field_title: Sequel
field_category: Ruby libraries
data:
{"title": "Sequel", "category": "Ruby libraries", "body": "### About\n{: .-intro}\n\nSequel is a database toolkit for Ruby.\n\n- <https://github.com/jeremyevans/sequel>\n\n### Open a database\n\n```\nrequire 'rubygems'\nrequire 'sequel'\n\nDB = Sequel.sqlite('my_blog.db')\nDB = Sequel.connect('postgres://user:password@localhost/my_db')\nDB = Sequel.postgres('my_db', :user => 'user', :password => 'password', :host => 'localhost')\nDB = Sequel.ado('mydb')\n```\n\n### Open an SQLite memory database\n\nWithout a filename argument, the sqlite adapter will setup a new sqlite database in memory.\n\n```\nDB = Sequel.sqlite\n```\n\n### Logging SQL statements\n\n```\nrequire 'logger'\nDB = Sequel.sqlite '', :loggers => [Logger.new($stdout)]\n# or\nDB.loggers << Logger.new(...)\n```\n\n### Using raw SQL\n\n```\nDB.run \"CREATE TABLE users (name VARCHAR(255) NOT NULL, age INT(3) NOT NULL)\"\ndataset = DB[\"SELECT age FROM users WHERE name = ?\", name]\ndataset.map(:age)\nDB.fetch(\"SELECT name FROM users\") do |row|\n  p row[:name]\nend\n```\n\n### Create a dataset\n\n```\ndataset = DB[:items]\ndataset = DB.from(:items)\n```\n\n### Most dataset methods are chainable\n\n```\ndataset = DB[:managers].where(:salary => 5000..10000).order(:name, :department)\n```\n\n### Insert rows\n\n```\ndataset.insert(:name => 'Sharon', :grade => 50)\n```\n\n### Retrieve rows\n\n```\ndataset.each{|r| p r}\ndataset.all # => [{...}, {...}, ...]\ndataset.first # => {...}\n```\n\n### Update/Delete rows\n\n```\ndataset.filter(~:active).delete\ndataset.filter('price < ?', 100).update(:active => true)\n```\n\n### Datasets are Enumerable\n\n```\ndataset.map{|r| r[:name]}\ndataset.map(:name) # same as above\n\ndataset.inject(0){|sum, r| sum + r[:value]}\ndataset.sum(:value) # same as above\n```\n\n### Filtering (see also doc/dataset_filtering.rdoc)\n\n#### Equality\n\n```\ndataset.filter(:name => 'abc')\ndataset.filter('name = ?', 'abc')\n```\n\n#### Inequality\n\n```\ndataset.filter{value > 100}\ndataset.exclude{value <= 100}\n```\n\n#### Inclusion\n\n```\ndataset.filter(:value => 50..100)\ndataset.where{(value >= 50) & (value <= 100)}\n\ndataset.where('value IN ?', [50,75,100])\ndataset.where(:value=>[50,75,100])\n\ndataset.where(:id=>other_dataset.select(:other_id))\n```\n\n#### Subselects as scalar values\n\n```\ndataset.where('price > (SELECT avg(price) + 100 FROM table)')\ndataset.filter{price > dataset.select(avg(price) + 100)}\n```\n\n#### LIKE/Regexp\n\n```\nDB[:items].filter(:name.like('AL%'))\nDB[:items].filter(:name => /^AL/)\n```\n\n#### AND/OR/NOT\n\n```\nDB[:items].filter{(x > 5) & (y > 10)}.sql\n# SELECT * FROM items WHERE ((x > 5) AND (y > 10))\n\nDB[:items].filter({:x => 1, :y => 2}.sql_or & ~{:z => 3}).sql\n# SELECT * FROM items WHERE (((x = 1) OR (y = 2)) AND (z != 3))\n```\n\n#### Mathematical operators\n\n```\nDB[:items].filter((:x + :y) > :z).sql\n# SELECT * FROM items WHERE ((x + y) > z)\n\nDB[:items].filter{price - 100 < avg(price)}.sql\n# SELECT * FROM items WHERE ((price - 100) < avg(price))\n```\n\n### Ordering\n\n```\ndataset.order(:kind)\ndataset.reverse_order(:kind)\ndataset.order(:kind.desc, :name)\n```\n\n### Limit/Offset\n\n```\ndataset.limit(30) # LIMIT 30\ndataset.limit(30, 10) # LIMIT 30 OFFSET 10\n```\n\n### Joins\n\n```\nDB[:items].left_outer_join(:categories, :id => :category_id).sql\n# SELECT * FROM items LEFT OUTER JOIN categories ON categories.id = items.category_id\n\nDB[:items].join(:categories, :id => :category_id).join(:groups, :id => :items__group_id)\n# SELECT * FROM items INNER JOIN categories ON categories.id = items.category_id INNER JOIN groups ON groups.id = items.group_id\n```\n\n### Aggregate functions methods\n\n```\ndataset.count #=> record count\ndataset.max(:price)\ndataset.min(:price)\ndataset.avg(:price)\ndataset.sum(:stock)\n\ndataset.group_and_count(:category)\ndataset.group(:category).select(:category, :AVG.sql_function(:price))\n```\n\n### SQL Functions / Literals\n\n```\ndataset.update(:updated_at => :NOW.sql_function)\ndataset.update(:updated_at => 'NOW()'.lit)\n\ndataset.update(:updated_at => \"DateValue('1/1/2001')\".lit)\ndataset.update(:updated_at => :DateValue.sql_function('1/1/2001'))\n```\n\n### Schema Manipulation\n\n```\nDB.create_table :items do\n  primary_key :id\n  String :name, :unique => true, :null => false\n  TrueClass :active, :default => true\n  foreign_key :category_id, :categories\n  DateTime :created_at\n\n  index :created_at\nend\n\nDB.drop_table :items\n\nDB.create_table :test do\n  String :zipcode\n  enum :system, :elements => ['mac', 'linux', 'windows']\nend\n```\n\n### Aliasing\n\n```\nDB[:items].select(:name.as(:item_name))\nDB[:items].select(:name___item_name)\nDB[:items___items_table].select(:items_table__name___item_name)\n# SELECT items_table.name AS item_name FROM items AS items_table\n```\n\n### Transactions\n\n```\nDB.transaction do\n  dataset.insert(:first_name => 'Inigo', :last_name => 'Montoya')\n  dataset.insert(:first_name => 'Farm', :last_name => 'Boy')\nend # Either both are inserted or neither are inserted\n```\n\nDatabase#transaction is re-entrant:\n\n```\nDB.transaction do # BEGIN issued only here\n  DB.transaction\n    dataset << {:first_name => 'Inigo', :last_name => 'Montoya'}\n  end\nend # COMMIT issued only here\n```\n\nTransactions are aborted if an error is raised:\n\n```\nDB.transaction do\n  raise \"some error occurred\"\nend # ROLLBACK issued and the error is re-raised\n```\n\nTransactions can also be aborted by raising Sequel::Rollback:\n\n```\nDB.transaction do\n  raise(Sequel::Rollback) if something_bad_happened\nend # ROLLBACK issued and no error raised\n```\n\nSavepoints can be used if the database supports it:\n\n```\nDB.transaction do\n  dataset << {:first_name => 'Farm', :last_name => 'Boy'} # Inserted\n  DB.transaction(:savepoint=>true) # This savepoint is rolled back\n    dataset << {:first_name => 'Inigo', :last_name => 'Montoya'} # Not inserted\n    raise(Sequel::Rollback) if something_bad_happened\n  end\n  dataset << {:first_name => 'Prince', :last_name => 'Humperdink'} # Inserted\nend\n```\n\n### Miscellaneous:\n\n```\ndataset.sql # \"SELECT * FROM items\"\ndataset.delete_sql # \"DELETE FROM items\"\ndataset.where(:name => 'sequel').exists # \"EXISTS ( SELECT * FROM items WHERE name = 'sequel' )\"\ndataset.columns #=> array of columns in the result set, does a SELECT\nDB.schema(:items) => [[:id, {:type=>:integer, ...}], [:name, {:type=>:string, ...}], ...]\n```\n\n---\n\n### Documents\n\n```\nhttp://sequel.rubyforge.org/rdoc/files/doc/association_basics_rdoc.html\nhttp://sequel.rubyforge.org/rdoc/classes/Sequel/Schema/Generator.html\nhttp://sequel.rubyforge.org/rdoc/files/doc/validations_rdoc.html\nhttp://sequel.rubyforge.org/rdoc/classes/Sequel/Model.html\n```\n\n### Alter table\n\n```\ndatabase.alter_table :deals do\n  add_column :name, String\n  drop_column :column_name\n  rename_column :from, :to\n\n  add_constraint :valid_name, :name.like('A%')\n  drop_constraint :constraint\n\n  add_full_text_index :body\n  add_spacial_index [columns]\n\n  add_index :price\n  drop_index :index\n\n  add_foreign_key :artist_id, :table\n  add_primary_key :id\n  add_unique_constraint [columns]\n  set_column_allow_null :foo, false\n  set_column_default :title, ''\n\n  set_column_type :price, 'char(10)'\nend\n```\n\n### Model associations\n\n```\nclass Deal < Sequel::Model\n\n  # Us (left) <=> Them (right)\n  many_to_many  :images,\n    left_key:   :deal_id,\n    right_key:  :image_id,\n    join_table: :image_links\n\n  one_to_many   :files,\n    key:        :deal_id,\n    class:      :DataFile,\n\n  many_to_one   :parent, class: self\n  one_to_many   :children, key: :parent_id, class: self\n\n  one_to_many :gold_albums, class: :Album do |ds|\n    ds.filter { copies_sold > 50000 }\n  end\n```\n\nProvided by many_to_many\n\n```\nDeal[1].images\nDeal[1].add_image\nDeal[1].remove_image\nDeal[1].remove_all_images\n```\n\n### Validations\n\n```\ndef validate\n    super\n    errors.add(:name, 'cannot be empty') if !name || name.empty?\n\n    validates_presence [:title, :site]\n    validates_unique :name\n    validates_format /\\Ahttps?:\\/\\//, :website, :message=>'is not a valid URL'\n    validates_includes %w(a b c), :type\n    validates_integer :rating\n    validates_numeric :number\n    validates_type String, [:title, :description]\n\n    validates_integer :rating  if new?\n\n    # options: :message =>, :allow_nil =>, :allow_blank =>,\n    #          :allow_missing =>,\n\n    validates_exact_length 17, :isbn\n    validates_min_length 3, :name\n    validates_max_length 100, :name\n    validates_length_range 3..100, :name\n\n    # Setter override\n    def filename=(name)\n      @values[:filename] = name\n    end\n  end\nend\n\ndeal.errors\n```\n\n### Model stuff\n\n```\ndeal = Deal[1]\ndeal.changed_columns\ndeal.destroy  # Calls hooks\ndeal.delete   # No hooks\ndeal.exists?\ndeal.new?\ndeal.hash  # Only uniques\ndeal.keys  #=> [:id, :name]\ndeal.modified!\ndeal.modified?\n\ndeal.lock!\n```\n\n### Callbacks\n\n```\nbefore_create\nafter_create\n\nbefore_validation\nafter_validation\nbefore_save\nbefore_update\nUPDATE QUERY\nafter_update\nafter_save\n\nbefore_destroy\nDELETE QUERY\nafter_destroy\n```\n\n### Schema\n\n```\nclass Deal < Sequel::Model\n  set_schema do\n    primary_key :id\n    primary_key [:id, :title]\n    String :name, primary_key: true\n\n    String  :title\n    Numeric :price\n    DateTime :expires\n\n    unique :whatever\n    check(:price) { num > 0 }\n\n    foreign_key :artist_id\n    String :artist_name, key: :id\n\n    index :title\n    index [:artist_id, :name]\n    full_text_index :title\n\n    # String, Integer, Fixnum, Bignum, Float, Numeric, BigDecimal,\n    # Date, DateTime, Time, File, TrueClass, FalseClass\n  end\nend\n```\n\n### Unrestrict primary key\n\n```\nCategory.create id: 'travel'   # error\nCategory.unrestrict_primary_key\nCategory.create id: 'travel'   # ok\n```"}

field_body:
### About
{: .-intro}

Sequel is a database toolkit for Ruby.

- <https://github.com/jeremyevans/sequel>

### Open a database

```
require 'rubygems'
require 'sequel'

DB = Sequel.sqlite('my_blog.db')
DB = Sequel.connect('postgres://user:password@localhost/my_db')
DB = Sequel.postgres('my_db', :user => 'user', :password => 'password', :host => 'localhost')
DB = Sequel.ado('mydb')
```

### Open an SQLite memory database

Without a filename argument, the sqlite adapter will setup a new sqlite database in memory.

```
DB = Sequel.sqlite
```

### Logging SQL statements

```
require 'logger'
DB = Sequel.sqlite '', :loggers => [Logger.new($stdout)]
# or
DB.loggers << Logger.new(...)
```

### Using raw SQL

```
DB.run "CREATE TABLE users (name VARCHAR(255) NOT NULL, age INT(3) NOT NULL)"
dataset = DB["SELECT age FROM users WHERE name = ?", name]
dataset.map(:age)
DB.fetch("SELECT name FROM users") do |row|
  p row[:name]
end
```

### Create a dataset

```
dataset = DB[:items]
dataset = DB.from(:items)
```

### Most dataset methods are chainable

```
dataset = DB[:managers].where(:salary => 5000..10000).order(:name, :department)
```

### Insert rows

```
dataset.insert(:name => 'Sharon', :grade => 50)
```

### Retrieve rows

```
dataset.each{|r| p r}
dataset.all # => [{...}, {...}, ...]
dataset.first # => {...}
```

### Update/Delete rows

```
dataset.filter(~:active).delete
dataset.filter('price < ?', 100).update(:active => true)
```

### Datasets are Enumerable

```
dataset.map{|r| r[:name]}
dataset.map(:name) # same as above

dataset.inject(0){|sum, r| sum + r[:value]}
dataset.sum(:value) # same as above
```

### Filtering (see also doc/dataset_filtering.rdoc)

#### Equality

```
dataset.filter(:name => 'abc')
dataset.filter('name = ?', 'abc')
```

#### Inequality

```
dataset.filter{value > 100}
dataset.exclude{value <= 100}
```

#### Inclusion

```
dataset.filter(:value => 50..100)
dataset.where{(value >= 50) & (value <= 100)}

dataset.where('value IN ?', [50,75,100])
dataset.where(:value=>[50,75,100])

dataset.where(:id=>other_dataset.select(:other_id))
```

#### Subselects as scalar values

```
dataset.where('price > (SELECT avg(price) + 100 FROM table)')
dataset.filter{price > dataset.select(avg(price) + 100)}
```

#### LIKE/Regexp

```
DB[:items].filter(:name.like('AL%'))
DB[:items].filter(:name => /^AL/)
```

#### AND/OR/NOT

```
DB[:items].filter{(x > 5) & (y > 10)}.sql
# SELECT * FROM items WHERE ((x > 5) AND (y > 10))

DB[:items].filter({:x => 1, :y => 2}.sql_or & ~{:z => 3}).sql
# SELECT * FROM items WHERE (((x = 1) OR (y = 2)) AND (z != 3))
```

#### Mathematical operators

```
DB[:items].filter((:x + :y) > :z).sql
# SELECT * FROM items WHERE ((x + y) > z)

DB[:items].filter{price - 100 < avg(price)}.sql
# SELECT * FROM items WHERE ((price - 100) < avg(price))
```

### Ordering

```
dataset.order(:kind)
dataset.reverse_order(:kind)
dataset.order(:kind.desc, :name)
```

### Limit/Offset

```
dataset.limit(30) # LIMIT 30
dataset.limit(30, 10) # LIMIT 30 OFFSET 10
```

### Joins

```
DB[:items].left_outer_join(:categories, :id => :category_id).sql
# SELECT * FROM items LEFT OUTER JOIN categories ON categories.id = items.category_id

DB[:items].join(:categories, :id => :category_id).join(:groups, :id => :items__group_id)
# SELECT * FROM items INNER JOIN categories ON categories.id = items.category_id INNER JOIN groups ON groups.id = items.group_id
```

### Aggregate functions methods

```
dataset.count #=> record count
dataset.max(:price)
dataset.min(:price)
dataset.avg(:price)
dataset.sum(:stock)

dataset.group_and_count(:category)
dataset.group(:category).select(:category, :AVG.sql_function(:price))
```

### SQL Functions / Literals

```
dataset.update(:updated_at => :NOW.sql_function)
dataset.update(:updated_at => 'NOW()'.lit)

dataset.update(:updated_at => "DateValue('1/1/2001')".lit)
dataset.update(:updated_at => :DateValue.sql_function('1/1/2001'))
```

### Schema Manipulation

```
DB.create_table :items do
  primary_key :id
  String :name, :unique => true, :null => false
  TrueClass :active, :default => true
  foreign_key :category_id, :categories
  DateTime :created_at

  index :created_at
end

DB.drop_table :items

DB.create_table :test do
  String :zipcode
  enum :system, :elements => ['mac', 'linux', 'windows']
end
```

### Aliasing

```
DB[:items].select(:name.as(:item_name))
DB[:items].select(:name___item_name)
DB[:items___items_table].select(:items_table__name___item_name)
# SELECT items_table.name AS item_name FROM items AS items_table
```

### Transactions

```
DB.transaction do
  dataset.insert(:first_name => 'Inigo', :last_name => 'Montoya')
  dataset.insert(:first_name => 'Farm', :last_name => 'Boy')
end # Either both are inserted or neither are inserted
```

Database#transaction is re-entrant:

```
DB.transaction do # BEGIN issued only here
  DB.transaction
    dataset << {:first_name => 'Inigo', :last_name => 'Montoya'}
  end
end # COMMIT issued only here
```

Transactions are aborted if an error is raised:

```
DB.transaction do
  raise "some error occurred"
end # ROLLBACK issued and the error is re-raised
```

Transactions can also be aborted by raising Sequel::Rollback:

```
DB.transaction do
  raise(Sequel::Rollback) if something_bad_happened
end # ROLLBACK issued and no error raised
```

Savepoints can be used if the database supports it:

```
DB.transaction do
  dataset << {:first_name => 'Farm', :last_name => 'Boy'} # Inserted
  DB.transaction(:savepoint=>true) # This savepoint is rolled back
    dataset << {:first_name => 'Inigo', :last_name => 'Montoya'} # Not inserted
    raise(Sequel::Rollback) if something_bad_happened
  end
  dataset << {:first_name => 'Prince', :last_name => 'Humperdink'} # Inserted
end
```

### Miscellaneous:

```
dataset.sql # "SELECT * FROM items"
dataset.delete_sql # "DELETE FROM items"
dataset.where(:name => 'sequel').exists # "EXISTS ( SELECT * FROM items WHERE name = 'sequel' )"
dataset.columns #=> array of columns in the result set, does a SELECT
DB.schema(:items) => [[:id, {:type=>:integer, ...}], [:name, {:type=>:string, ...}], ...]
```

---

### Documents

```
http://sequel.rubyforge.org/rdoc/files/doc/association_basics_rdoc.html
http://sequel.rubyforge.org/rdoc/classes/Sequel/Schema/Generator.html
http://sequel.rubyforge.org/rdoc/files/doc/validations_rdoc.html
http://sequel.rubyforge.org/rdoc/classes/Sequel/Model.html
```

### Alter table

```
database.alter_table :deals do
  add_column :name, String
  drop_column :column_name
  rename_column :from, :to

  add_constraint :valid_name, :name.like('A%')
  drop_constraint :constraint

  add_full_text_index :body
  add_spacial_index [columns]

  add_index :price
  drop_index :index

  add_foreign_key :artist_id, :table
  add_primary_key :id
  add_unique_constraint [columns]
  set_column_allow_null :foo, false
  set_column_default :title, ''

  set_column_type :price, 'char(10)'
end
```

### Model associations

```
class Deal < Sequel::Model

  # Us (left) <=> Them (right)
  many_to_many  :images,
    left_key:   :deal_id,
    right_key:  :image_id,
    join_table: :image_links

  one_to_many   :files,
    key:        :deal_id,
    class:      :DataFile,

  many_to_one   :parent, class: self
  one_to_many   :children, key: :parent_id, class: self

  one_to_many :gold_albums, class: :Album do |ds|
    ds.filter { copies_sold > 50000 }
  end
```

Provided by many_to_many

```
Deal[1].images
Deal[1].add_image
Deal[1].remove_image
Deal[1].remove_all_images
```

### Validations

```
def validate
    super
    errors.add(:name, 'cannot be empty') if !name || name.empty?

    validates_presence [:title, :site]
    validates_unique :name
    validates_format /\Ahttps?:\/\//, :website, :message=>'is not a valid URL'
    validates_includes %w(a b c), :type
    validates_integer :rating
    validates_numeric :number
    validates_type String, [:title, :description]

    validates_integer :rating  if new?

    # options: :message =>, :allow_nil =>, :allow_blank =>,
    #          :allow_missing =>,

    validates_exact_length 17, :isbn
    validates_min_length 3, :name
    validates_max_length 100, :name
    validates_length_range 3..100, :name

    # Setter override
    def filename=(name)
      @values[:filename] = name
    end
  end
end

deal.errors
```

### Model stuff

```
deal = Deal[1]
deal.changed_columns
deal.destroy  # Calls hooks
deal.delete   # No hooks
deal.exists?
deal.new?
deal.hash  # Only uniques
deal.keys  #=> [:id, :name]
deal.modified!
deal.modified?

deal.lock!
```

### Callbacks

```
before_create
after_create

before_validation
after_validation
before_save
before_update
UPDATE QUERY
after_update
after_save

before_destroy
DELETE QUERY
after_destroy
```

### Schema

```
class Deal < Sequel::Model
  set_schema do
    primary_key :id
    primary_key [:id, :title]
    String :name, primary_key: true

    String  :title
    Numeric :price
    DateTime :expires

    unique :whatever
    check(:price) { num > 0 }

    foreign_key :artist_id
    String :artist_name, key: :id

    index :title
    index [:artist_id, :name]
    full_text_index :title

    # String, Integer, Fixnum, Bignum, Float, Numeric, BigDecimal,
    # Date, DateTime, Time, File, TrueClass, FalseClass
  end
end
```

### Unrestrict primary key

```
Category.create id: 'travel'   # error
Category.unrestrict_primary_key
Category.create id: 'travel'   # ok
```


id: semver
git_filename: ./semver.md
format: md
field_title: Semver
field_updated: 2019-12-31
field_updated___timezone: UTC
data:
{"title": "Semver", "updated": "2019-12-31", "weight": -3, "body": "### Semver\n\nGiven a version number `MAJOR.MINOR.PATCH`:\n{: .-setup}\n\n| `MAJOR` | incompatible API changes                 |\n| `MINOR` | add functionality (backwards-compatible) |\n| `PATCH` | bug fixes (backwards-compatible)         |\n\n### Simple ranges\n\n      1.2.3\n     =1.2.3\n     >1.2.3\n     <1.2.3\n    >=1.2.3\n\nNote that suffixed versions (`1.2.3-rc1`) are not matched.\n\n### Ranges\n\n| Range    | Description         | Notes              |\n| ---      | ---                 | ---                |\n| `~1.2.3` | is `>=1.2.3 <1.3.0` |                    |\n| ---      | ---                 | ---                |\n| `^1.2.3` | is `>=1.2.3 <2.0.0` |                    |\n| `^0.2.3` | is `>=0.2.3 <0.3.0` | (0.x.x is special) |\n| `^0.0.1` | is  `=0.0.1`        | (0.0.x is special) |\n| ---      | ---                 | ---                |\n| `^1.2`   | is `>=1.2.0 <2.0.0` | (like ^1.2.0)      |\n| `~1.2`   | is `>=1.2.0 <1.3.0` | (like ~1.2.0)      |\n| ---      | ---                 | ---                |\n| `^1`     | is `>=1.0.0 <2.0.0` |                    |\n| `~1`     | same                |                    |\n| `1.x`    | same                |                    |\n| `1.*`    | same                |                    |\n| `1`      | same                |                    |\n| ---      | ---                 | ---                |\n| `*`      | any version         |                    |\n| `x`      | same                |                    |\n{: .-shortcuts}\n\n### Hyphenated ranges\n\n| Range              | Description           |\n| ---                | ---                   |\n| `1.2.3 - 2.3.4`    | is `>=1.2.3 <=2.3.4`  |\n\n#### Partial right\n\n| Range              | Description           |\n| ---                | ---                   |\n| `1.2.3 - 2.3`      | is `>=1.2.3 <2.4.0`   |\n| `1.2.3 - 2`        | is `>=1.2.3 <3.0.0`   |\n\n#### Partial left\n\n| Range              | Description           |\n| ---                | ---                   |\n| `1.2 - 2.3.0`      | is `1.2.0 - 2.3.0`    |\n\nWhen the right is partial (eg, `2.3`), missing pieces are assumed to be `x` (eg, `2.3.x`).\n\nWhen the left is partial (eg, `1.2`), missing pieces are assumed to be `0` (eg, `1.2.0`).\n\n### Combining ranges\n\n| Range              | Description           |\n| ---                | ---                   |\n| `>=0.14 <16`       | And (space-separated) |\n| `0.14.x || 15.x.x` | Or (pipe-separated)   |\n\n### Pre-releases\n\n    1.2.3-prerelease+build\n\n### Explanation\n\n| `^` | means \"compatible with\" |\n| `~` | means \"reasonably close to\" |\n| `0.x.x` | is for \"initial development\" |\n| `1.x.x` | means public API is defined |\n{: .-shortcuts}\n\n## References\n{: .-one-column}\n\n * <https://semver.org/>\n * <https://docs.npmjs.com/misc/semver>"}

field_body:
### Semver

Given a version number `MAJOR.MINOR.PATCH`:
{: .-setup}

| `MAJOR` | incompatible API changes                 |
| `MINOR` | add functionality (backwards-compatible) |
| `PATCH` | bug fixes (backwards-compatible)         |

### Simple ranges

      1.2.3
     =1.2.3
     >1.2.3
     <1.2.3
    >=1.2.3

Note that suffixed versions (`1.2.3-rc1`) are not matched.

### Ranges

| Range    | Description         | Notes              |
| ---      | ---                 | ---                |
| `~1.2.3` | is `>=1.2.3 <1.3.0` |                    |
| ---      | ---                 | ---                |
| `^1.2.3` | is `>=1.2.3 <2.0.0` |                    |
| `^0.2.3` | is `>=0.2.3 <0.3.0` | (0.x.x is special) |
| `^0.0.1` | is  `=0.0.1`        | (0.0.x is special) |
| ---      | ---                 | ---                |
| `^1.2`   | is `>=1.2.0 <2.0.0` | (like ^1.2.0)      |
| `~1.2`   | is `>=1.2.0 <1.3.0` | (like ~1.2.0)      |
| ---      | ---                 | ---                |
| `^1`     | is `>=1.0.0 <2.0.0` |                    |
| `~1`     | same                |                    |
| `1.x`    | same                |                    |
| `1.*`    | same                |                    |
| `1`      | same                |                    |
| ---      | ---                 | ---                |
| `*`      | any version         |                    |
| `x`      | same                |                    |
{: .-shortcuts}

### Hyphenated ranges

| Range              | Description           |
| ---                | ---                   |
| `1.2.3 - 2.3.4`    | is `>=1.2.3 <=2.3.4`  |

#### Partial right

| Range              | Description           |
| ---                | ---                   |
| `1.2.3 - 2.3`      | is `>=1.2.3 <2.4.0`   |
| `1.2.3 - 2`        | is `>=1.2.3 <3.0.0`   |

#### Partial left

| Range              | Description           |
| ---                | ---                   |
| `1.2 - 2.3.0`      | is `1.2.0 - 2.3.0`    |

When the right is partial (eg, `2.3`), missing pieces are assumed to be `x` (eg, `2.3.x`).

When the left is partial (eg, `1.2`), missing pieces are assumed to be `0` (eg, `1.2.0`).

### Combining ranges

| Range              | Description           |
| ---                | ---                   |
| `>=0.14 <16`       | And (space-separated) |
| `0.14.x || 15.x.x` | Or (pipe-separated)   |

### Pre-releases

    1.2.3-prerelease+build

### Explanation

| `^` | means "compatible with" |
| `~` | means "reasonably close to" |
| `0.x.x` | is for "initial development" |
| `1.x.x` | means public API is defined |
{: .-shortcuts}

## References
{: .-one-column}

 * <https://semver.org/>
 * <https://docs.npmjs.com/misc/semver>


id: sed
git_filename: ./sed.md
format: md
field_title: sed
field_category: CLI
field_intro: Here's some hints on using sed.
data:
{"title": "sed", "category": "CLI", "intro": "Here's some hints on using sed.\n", "body": "### Replacements\n\n#### In-place replacement (GNU)\n\n```bash\nsed -i -e 's/foo/bar/' example.md\n```\n\nIn GNU sed: use `-i` without arg.\n\n#### In-place replacement (BSD)\n\n```bash\nsed -i '' -e 's/foo/bar/' example.md\n```\n\nIn OSX, `-i ''` is required.\n\n#### In-place Multiple replacements\n\n```bash\nsed -i 's/match1/replace1/g; s/match2/replace2/g' \\\n\n```\n\nreplace different matches with different values\n\n```bash\nsed -i 's/\\(MATCH1\\|MATCH2\\)/VALUE/g' \\\n\n```\n\nreplace multiple matches with the same value\n\n## File regions\n{:.-three-column}\n\n### Print until a certain line is met\n\n```bash\nsed '/begin api/q'\n```\n\n### Print until a certain line is met, but not that line\n\n```bash\nsed '/^# begin/,$d'\n```\n\n### Print everything after a given line\n\n```bash\nsed -n '/end api/,$p'\n```\n\nPrint after a given line is found.\n\n### Print everything except matching\n\n```bash\nsed -n '/regex/!p'\n```\n\nPrint everything except lines matching regex. Useful for printing files with comments.\n\n#### Printing REGEX ranges\n\n```bash\nsed -n -e '/^START$/,/^END$/p'\n```\n\nsuppress output and print REGEX range\ninclude (^START$,^END$) lines.\n\n**OR** without \"-n\" (same result)\n\n```bash\nsed -e '/^START$/,/^END$/p;d'\n```\n\nprint REGEX range and delete other\noutput, the [;] character means run another\nexpression on the input file which is 'd' stands for delete .\n\n### Append a text after a specific line number\n\n```bash\nsed -e \"1a ## HEADING 02:\" README.md\n```\n\nthis appends \"## HEADING 02:\" after the first line in the file README.md\nand print the result to stdout replace -e with -i to write the file .\n\n### Insert text before a specific line number\n\n```bash\nsed -e \"1i # HEADING 01:\" README.md\n```\n\nthe same as appending but before the first line.\n\n### Deleting text\n\n#### With line number\n\n```bash\nsed -e \"1,5d\" README.md\n```\n\ndelete a RANGE (i.e. including lines 1 to 5)\n\n```bash\nsed -e '1,5!d' README.md\n```\n\ndelete everything (i.e. excluding lines 1 to 5)\nit is better to quote sed expressions with single quotes\nespecially when there is a [!] character.\n\n#### With REGEX matching\n\n```bash\nsed -e \"/REGEX/Id\" README.md\n```\n\ndelete lines with /REGEX/ matched\n/I is for insensitive search\n\n```bash\nsed -e '/REGEX/Ip;d' README.md\n```\n\nthis invert the previous sed command\ndelete everything (excluding lines with REGEX)"}

field_body:
### Replacements

#### In-place replacement (GNU)

```bash
sed -i -e 's/foo/bar/' example.md
```

In GNU sed: use `-i` without arg.

#### In-place replacement (BSD)

```bash
sed -i '' -e 's/foo/bar/' example.md
```

In OSX, `-i ''` is required.

#### In-place Multiple replacements

```bash
sed -i 's/match1/replace1/g; s/match2/replace2/g' \

```

replace different matches with different values

```bash
sed -i 's/\(MATCH1\|MATCH2\)/VALUE/g' \

```

replace multiple matches with the same value

## File regions
{:.-three-column}

### Print until a certain line is met

```bash
sed '/begin api/q'
```

### Print until a certain line is met, but not that line

```bash
sed '/^# begin/,$d'
```

### Print everything after a given line

```bash
sed -n '/end api/,$p'
```

Print after a given line is found.

### Print everything except matching

```bash
sed -n '/regex/!p'
```

Print everything except lines matching regex. Useful for printing files with comments.

#### Printing REGEX ranges

```bash
sed -n -e '/^START$/,/^END$/p'
```

suppress output and print REGEX range
include (^START$,^END$) lines.

**OR** without "-n" (same result)

```bash
sed -e '/^START$/,/^END$/p;d'
```

print REGEX range and delete other
output, the [;] character means run another
expression on the input file which is 'd' stands for delete .

### Append a text after a specific line number

```bash
sed -e "1a ## HEADING 02:" README.md
```

this appends "## HEADING 02:" after the first line in the file README.md
and print the result to stdout replace -e with -i to write the file .

### Insert text before a specific line number

```bash
sed -e "1i # HEADING 01:" README.md
```

the same as appending but before the first line.

### Deleting text

#### With line number

```bash
sed -e "1,5d" README.md
```

delete a RANGE (i.e. including lines 1 to 5)

```bash
sed -e '1,5!d' README.md
```

delete everything (i.e. excluding lines 1 to 5)
it is better to quote sed expressions with single quotes
especially when there is a [!] character.

#### With REGEX matching

```bash
sed -e "/REGEX/Id" README.md
```

delete lines with /REGEX/ matched
/I is for insensitive search

```bash
sed -e '/REGEX/Ip;d' README.md
```

this invert the previous sed command
delete everything (excluding lines with REGEX)


