<NME> plugins.md
<BEF> # Writing plugins

```js
// Abbreviated example:

var stylelint = require("stylelint")

var myPluginRuleName = "plugin/foobar"
var myPluginRule = stylelint.createPlugin(myPluginRuleName, function(expectationKeyword, optionsObject) {
  return function(postcssRoot, postcssResult) {
    // ... some logic ...
    stylelint.utils.report({ .. })
  }
})
```

`stylelint.createPlugin(ruleName, ruleFunction)` ensures that your plugin will be setup properly alongside other rules. *Make sure you document your plugin's rule name for users, because they will need to use it in their config.*

Your plugin's rule name must be namespaced, e.g. `your-namespace/your-rule-name`. If your plugin provides only a single rule or you can't think of a good namespace, you can simply use `plugin/my-rule`. This namespace ensures that plugin rules will never clash with core rules.

In order for your plugin rule to work with the standard configuration format, (e.g. `["tab", { hierarchicalSelectors: true }]`), `ruleFunction` should accept 2 arguments: the expectation keyword (e.g. `"tab"`) and, optionally, an options object (e.g. `{ hierarchicalSelectors: true }`).

`ruleFunction` should return a function that is essentially a little PostCSS plugin: it takes 2 arguments: the PostCSS Root (the parsed AST), and the PostCSS LazyResult. You'll have to [learn about the PostCSS API](https://github.com/postcss/postcss/blob/master/docs/api.md).

## Modules providing multiple rules

To make a single module provide multiple rules, simply export an array of plugin objects (rather than a single object).

## Standard parsers

We recommend using [postcss-value-parser](https://github.com/TrySound/postcss-value-parser) and/or [postcss-selector-parser](https://github.com/postcss/postcss-selector-parser). Use these standard parsers whenever possible, even if there's a performance hit, because there are significant gains in doing so.

## `stylelint.utils`

A few of stylelint's internal utilities are exposed publicly in `stylelint.utils`, to help you write plugin rules. For details about the APIs of these functions, please look at comments in the source code and examples in the standard rules.

You will want to use:

- `report`: Report your linting warnings. *Do not use `node.warn()` directly.* If you use `report`, your plugin will respect disabled ranges and other possible future features of stylelint, so it will fit in better with the standard rules.
- `ruleMessages`: Tailor your messages to look like the messages of other stylelint rules. Currently, this means that the name of the rule is appended, in parentheses, to the end of the message.
- `validateOptions`: Help your user's out by checking that the options they've submitted are valid.

**`stylelint.util.styleSearch` is deprecated and will be removed in v7. Use the external module [style-search](https://github.com/davidtheclark/style-search) instead.**
    });
  };
};

ruleFunction.ruleName = ruleName;
ruleFunction.messages = messages;
ruleFunction.meta = meta;

module.exports = stylelint.createPlugin(ruleName, ruleFunction);
```

Your plugin's rule name must be namespaced, e.g. `your-namespace/your-rule-name`, to ensure it never clashes with the built-in rules. If your plugin provides only a single rule or you can't think of a good namespace, you can use `plugin/my-rule`. _You should document your plugin's rule name (and namespace) because users need to use them in their config._

Use `stylelint.createPlugin(ruleName, ruleFunction)` to ensure that your plugin is set up properly alongside other rules.

For your plugin rule to work with the [standard configuration format](../user-guide/configure.md#rules), `ruleFunction` should accept 2 arguments:

- the primary option
})
```

## Testing plugins

For testing your plugin, you might consider using the same rule-testing function that stylelint uses internally: [`stylelint-test-rule-tape`](https://github.com/stylelint/stylelint-test-rule-tape).

## Sharing plugins

- Use the `stylelint-plugin` keyword within your `package.json`.
- Once your plugin is published, please send us a Pull Request to add your plugin to [the list](/docs/user-guide/plugins.md).
};

const ruleFunction = (primaryOption, secondaryOptionObject) => {
  return (postcssRoot, postcssResult) => {
    const validOptions = stylelint.utils.validateOptions(
      postcssResult,
      ruleName,
      {
        /* .. */
      }
    );

    if (!validOptions) {
      return;
    }

    return new Promise((resolve) => {
      // some async operation
      setTimeout(() => {
        // ... some logic ...
        stylelint.utils.report({
          /* .. */
        });
        resolve();
      }, 1);
    });
  };
};

ruleFunction.ruleName = ruleName;
ruleFunction.messages = messages;
ruleFunction.meta = meta;

module.exports = stylelint.createPlugin(ruleName, ruleFunction);
```

## Testing

You should use [`jest-preset-stylelint`](https://github.com/stylelint/jest-preset-stylelint) to test your plugin. The preset exposes a global `testRule` function that you can use to efficiently test your plugin using a schema.

For example:

```js
// index.test.js
const {
  rule: { ruleName, messages }
} = require(".");

testRule({
  plugins: ["./index.js"],
  ruleName,
  config: true,
  fix: true,

  accept: [
    {
      code: ".class {}"
    },
    {
      code: ".my-class {}"
    }
  ],

  reject: [
    {
      code: ".myClass {}",
      fixed: ".my-class {}",
      message: messages.expected,
      line: 1,
      column: 1,
      endLine: 1,
      endColumn: 9
    }
  ]
});
```

However, if your plugin involves more than just checking syntax you can use Stylelint directly.

For example:

```js
// index.test.js
const { lint } = require("stylelint");

const config = {
  plugins: ["./index.js"],
  rules: {
    "plugin/at-import-no-unresolveable": [true]
  }
};

it("warns for unresolveable import", async () => {
  const {
    results: [{ warnings, parseErrors }]
  } = await lint({
    files: "fixtures/contains-unresolveable-import.css",
    config
  });

  expect(parseErrors).toHaveLength(0);
  expect(warnings).toHaveLength(1);

  const [{ line, column, text }] = warnings;

  expect(text).toBe(
    "Unexpected unresolveable import (plugin/at-import-no-unresolveable)"
  );
  expect(line).toBe(1);
  expect(column).toBe(1);
});

it("doesn't warn for fileless sources", async () => {
  const {
    results: [{ warnings, parseErrors }]
  } = await lint({
    code: "@import url(unknown.css)",
    config
  });
  expect(parseErrors).toHaveLength(0);
  expect(warnings).toHaveLength(0);
});
```

Alternatively, if you don't want to use Jest you'll find more tools in [awesome stylelint](https://github.com/stylelint/awesome-stylelint#tools).

## `stylelint.utils`

Stylelint exposes some useful utilities.

### `stylelint.utils.report`

Adds problems from your plugin to the list of problems that Stylelint will report to the user.

Use `stylelint.utils.report` to ensure your plugin respects disabled ranges and other possible future features of stylelint. _Do not use PostCSS's `node.warn()` method directly._

### `stylelint.utils.ruleMessages`

Tailors your messages to the format of standard Stylelint rules.

### `stylelint.utils.validateOptions`

Validates the options for your rule.

### `stylelint.utils.checkAgainstRule`

Checks CSS against a standard Stylelint rule _within your own rule_. This function provides power and flexibility for plugins authors who wish to modify, constrain, or extend the functionality of existing Stylelint rules.

It accepts an options object and a callback that is invoked with warnings from the specified rule. The options are:

- `ruleName`: the name of the rule you are invoking
- `ruleSettings`: settings for the rule you are invoking
- `root`: the root node to run this rule against

Use the warning to create a _new_ warning _from your plugin rule_ that you report with `stylelint.utils.report`.

For example, imagine you want to create a plugin that runs `at-rule-no-unknown` with a built-in list of exceptions for at-rules provided by your preprocessor-of-choice:

```js
const allowableAtRules = [
  /* .. */
];

function myPluginRule(primaryOption, secondaryOptionObject) {
  return (postcssRoot, postcssResult) => {
    const defaultedOptions = Object.assign({}, secondaryOptionObject, {
      ignoreAtRules: allowableAtRules.concat(options.ignoreAtRules || [])
    });

    stylelint.utils.checkAgainstRule(
      {
        ruleName: "at-rule-no-unknown",
        ruleSettings: [primaryOption, defaultedOptions],
        root: postcssRoot
      },
      (warning) => {
        stylelint.utils.report({
          message: myMessage,
          ruleName: myRuleName,
          result: postcssResult,
          node: warning.node,
          line: warning.line,
          column: warning.column,
          endLine: warning.endLine,
          endColumn: warning.endColumn
        });
      }
    );
  };
}
```

## `stylelint.rules`

All of the rule functions are available at `stylelint.rules`. This allows you to build on top of existing rules for your particular needs.

A typical use-case is to build in more complex conditionals that the rule's options allow for. For example, maybe your codebase uses special comment directives to customize rule options for specific stylesheets. You could build a plugin that checks those directives and then runs the appropriate rules with the right options (or doesn't run them at all).

All rules share a common signature. They are a function that accepts two arguments: a primary option and a secondary options object. And that functions returns a function that has the signature of a PostCSS plugin, expecting a PostCSS root and result as its arguments.

Here's an example of a plugin that runs `declaration-no-important` only if there is a special directive `@@check-declaration-no-important` somewhere in the stylesheet:

```js
module.exports = stylelint.createPlugin(ruleName, (expectation) => {
  const runDeclarationNoImportant =
    stylelint.rules["declaration-no-important"](expectation);

  return (root, result) => {
    if (root.toString().indexOf("@@check-declaration-no-important") === -1) {
      return;
    }

    runDeclarationNoImportant(root, result);
  };
});
```

## Allow primary option arrays

If your plugin can accept an array as its primary option, you must designate this by setting the property `primaryOptionArray = true` on your rule function. For more information, check out the ["Working on rules"](rules.md) doc.

## External helper modules

In addition to the standard parsers mentioned in the ["Working on rules"](rules.md) doc, there are other external modules used within Stylelint that we recommend using. These include:

- [postcss-resolve-nested-selector](https://github.com/davidtheclark/postcss-resolve-nested-selector): given a (nested) selector in a PostCSS AST, return an array of resolved selectors.

Have a look through [Stylelint's internal utils](https://github.com/stylelint/stylelint/tree/main/lib/utils) and if you come across one that you need in your plugin, then please consider helping us extract it out into an external module.

## Peer dependencies

You should express, within the `peerDependencies` key (and **not** within the `dependencies` key) of your plugin's `package.json`, what version(s) of Stylelint your plugin can be used with. This is to ensure that different versions of Stylelint are not unexpectedly installed.

For example, to express that your plugin can be used with Stylelint versions 7 and 8:

```json
{
  "peerDependencies": {
    "stylelint": "^7.0.0 || ^8.0.0"
  }
}
```

## Plugin packs

To make a single module provide multiple rules, export an array of plugin objects (rather than a single object).

## Sharing plugins and plugin packs

Use the `stylelint-plugin` keyword within your `package.json`.

<MSG> Merge pull request #1440 from stylelint/update-plugin-docs

Expand plugin docs
<DFF> @@ -1,35 +1,37 @@
 # Writing plugins
 
-```js
-// Abbreviated example:
+Plugins are rules and sets of rules built by the community. We recommend adhering to stylelint's [conventions for writing rules](/docs/developer-guide/rules.md#come-up-with-a-name), including conventions for: names, options, messages, tests and docs. These will help create a consistent user experience.
+
+## The anatomy of a plugin
 
+```js
+// Abbreviated example
 var stylelint = require("stylelint")
 
-var myPluginRuleName = "plugin/foobar"
-var myPluginRule = stylelint.createPlugin(myPluginRuleName, function(expectationKeyword, optionsObject) {
+var ruleName = "plugin/foobar"
+
+stylelint.utils.ruleMessages(ruleName, {
+  expected: "Expected ...",
+})
+
+var myPluginRule = stylelint.createPlugin(ruleName, function(primaryOption, secondaryOptionObject) {
   return function(postcssRoot, postcssResult) {
+    var validOptions = stylelint.utils.validateOptions(postcssResult, ruleName, { .. })
+    if (!validOptions) { return }
     // ... some logic ...
     stylelint.utils.report({ .. })
   }
 })
 ```
 
-`stylelint.createPlugin(ruleName, ruleFunction)` ensures that your plugin will be setup properly alongside other rules. *Make sure you document your plugin's rule name for users, because they will need to use it in their config.*
+Your plugin's rule name must be namespaced, e.g. `your-namespace/your-rule-name`. If your plugin provides only a single rule or you can't think of a good namespace, you can simply use `plugin/my-rule`. This namespace ensures that plugin rules will never clash with core rules. *Make sure you document your plugin's rule name (and namespace) for users, because they will need to use it in their config.*
 
-Your plugin's rule name must be namespaced, e.g. `your-namespace/your-rule-name`. If your plugin provides only a single rule or you can't think of a good namespace, you can simply use `plugin/my-rule`. This namespace ensures that plugin rules will never clash with core rules.
+`stylelint.createPlugin(ruleName, ruleFunction)` ensures that your plugin will be setup properly alongside other rules.
 
-In order for your plugin rule to work with the standard configuration format, (e.g. `["tab", { hierarchicalSelectors: true }]`), `ruleFunction` should accept 2 arguments: the expectation keyword (e.g. `"tab"`) and, optionally, an options object (e.g. `{ hierarchicalSelectors: true }`).
+In order for your plugin rule to work with the standard configuration format, (e.g. `["tab", { hierarchicalSelectors: true }]`), `ruleFunction` should accept 2 arguments: the primary option (e.g. `"tab"`) and, optionally, an secondary options object (e.g. `{ hierarchicalSelectors: true }`).
 
 `ruleFunction` should return a function that is essentially a little PostCSS plugin: it takes 2 arguments: the PostCSS Root (the parsed AST), and the PostCSS LazyResult. You'll have to [learn about the PostCSS API](https://github.com/postcss/postcss/blob/master/docs/api.md).
 
-## Modules providing multiple rules
-
-To make a single module provide multiple rules, simply export an array of plugin objects (rather than a single object).
-
-## Standard parsers
-
-We recommend using [postcss-value-parser](https://github.com/TrySound/postcss-value-parser) and/or [postcss-selector-parser](https://github.com/postcss/postcss-selector-parser). Use these standard parsers whenever possible, even if there's a performance hit, because there are significant gains in doing so.
-
 ## `stylelint.utils`
 
 A few of stylelint's internal utilities are exposed publicly in `stylelint.utils`, to help you write plugin rules. For details about the APIs of these functions, please look at comments in the source code and examples in the standard rules.
@@ -37,7 +39,7 @@ A few of stylelint's internal utilities are exposed publicly in `stylelint.utils
 You will want to use:
 
 - `report`: Report your linting warnings. *Do not use `node.warn()` directly.* If you use `report`, your plugin will respect disabled ranges and other possible future features of stylelint, so it will fit in better with the standard rules.
-- `ruleMessages`: Tailor your messages to look like the messages of other stylelint rules. Currently, this means that the name of the rule is appended, in parentheses, to the end of the message.
+- `ruleMessages`: Tailor your messages to look like the messages of other stylelint rules.
 - `validateOptions`: Help your user's out by checking that the options they've submitted are valid.
 
 **`stylelint.util.styleSearch` is deprecated and will be removed in v7. Use the external module [style-search](https://github.com/davidtheclark/style-search) instead.**
@@ -62,11 +64,25 @@ export default stylelint.createPlugin(ruleName, function (expectation) {
 })
 ```
 
+## External helper modules
+
+In addition to the standard parsers mentioned in the ["Working on rules"](/docs/developer-guide/rules.md) doc, there are other external modules used within stylelint that we recommend using. These include:
+
+- [normalize-selector](https://github.com/getify/normalize-selector) - Normalize CSS selectors.
+- [postcss-resolve-nested-selector](https://github.com/davidtheclark/postcss-resolve-nested-selector) - Given a (nested) selector in a PostCSS AST, return an array of resolved selectors.
+- [style-search](https://github.com/davidtheclark/style-search) - Search CSS (and CSS-like) strings, with sensitivity to whether matches occur inside strings, comments, and functions.
+
+Have a look through [stylelint's internal utils](https://github.com/stylelint/stylelint/tree/master/src/utils) and if you come across one that you need in your plugin, then please consider helping us extract it out into a external module.
+
 ## Testing plugins
 
 For testing your plugin, you might consider using the same rule-testing function that stylelint uses internally: [`stylelint-test-rule-tape`](https://github.com/stylelint/stylelint-test-rule-tape).
 
-## Sharing plugins
+## Plugin packs
+
+To make a single module provide multiple rules, simply export an array of plugin objects (rather than a single object).
+
+## Sharing plugins and plugin packs
 
 - Use the `stylelint-plugin` keyword within your `package.json`.
 - Once your plugin is published, please send us a Pull Request to add your plugin to [the list](/docs/user-guide/plugins.md).

{'commit': 'diff --git a/docs/developer-guide/plugins.md b/docs/developer-guide/plugins.md\nindex d903e3a3..7192ac62 100644\n--- a/docs/developer-guide/plugins.md\n+++ b/docs/developer-guide/plugins.md\n@@ -1,35 +1,37 @@\n # Writing plugins\n \n-```js\n-// Abbreviated example:\n+Plugins are rules and sets of rules built by the community. We recommend adhering to stylelint\'s [conventions for writing rules](/docs/developer-guide/rules.md#come-up-with-a-name), including conventions for: names, options, messages, tests and docs. These will help create a consistent user experience.\n+\n+## The anatomy of a plugin\n \n+```js\n+// Abbreviated example\n var stylelint = require("stylelint")\n \n-var myPluginRuleName = "plugin/foobar"\n-var myPluginRule = stylelint.createPlugin(myPluginRuleName, function(expectationKeyword, optionsObject) {\n+var ruleName = "plugin/foobar"\n+\n+stylelint.utils.ruleMessages(ruleName, {\n+  expected: "Expected ...",\n+})\n+\n+var myPluginRule = stylelint.createPlugin(ruleName, function(primaryOption, secondaryOptionObject) {\n   return function(postcssRoot, postcssResult) {\n+    var validOptions = stylelint.utils.validateOptions(postcssResult, ruleName, { .. })\n+    if (!validOptions) { return }\n     // ... some logic ...\n     stylelint.utils.report({ .. })\n   }\n })\n ```\n \n-`stylelint.createPlugin(ruleName, ruleFunction)` ensures that your plugin will be setup properly alongside other rules. *Make sure you document your plugin\'s rule name for users, because they will need to use it in their config.*\n+Your plugin\'s rule name must be namespaced, e.g. `your-namespace/your-rule-name`. If your plugin provides only a single rule or you can\'t think of a good namespace, you can simply use `plugin/my-rule`. This namespace ensures that plugin rules will never clash with core rules. *Make sure you document your plugin\'s rule name (and namespace) for users, because they will need to use it in their config.*\n \n-Your plugin\'s rule name must be namespaced, e.g. `your-namespace/your-rule-name`. If your plugin provides only a single rule or you can\'t think of a good namespace, you can simply use `plugin/my-rule`. This namespace ensures that plugin rules will never clash with core rules.\n+`stylelint.createPlugin(ruleName, ruleFunction)` ensures that your plugin will be setup properly alongside other rules.\n \n-In order for your plugin rule to work with the standard configuration format, (e.g. `["tab", { hierarchicalSelectors: true }]`), `ruleFunction` should accept 2 arguments: the expectation keyword (e.g. `"tab"`) and, optionally, an options object (e.g. `{ hierarchicalSelectors: true }`).\n+In order for your plugin rule to work with the standard configuration format, (e.g. `["tab", { hierarchicalSelectors: true }]`), `ruleFunction` should accept 2 arguments: the primary option (e.g. `"tab"`) and, optionally, an secondary options object (e.g. `{ hierarchicalSelectors: true }`).\n \n `ruleFunction` should return a function that is essentially a little PostCSS plugin: it takes 2 arguments: the PostCSS Root (the parsed AST), and the PostCSS LazyResult. You\'ll have to [learn about the PostCSS API](https://github.com/postcss/postcss/blob/master/docs/api.md).\n \n-## Modules providing multiple rules\n-\n-To make a single module provide multiple rules, simply export an array of plugin objects (rather than a single object).\n-\n-## Standard parsers\n-\n-We recommend using [postcss-value-parser](https://github.com/TrySound/postcss-value-parser) and/or [postcss-selector-parser](https://github.com/postcss/postcss-selector-parser). Use these standard parsers whenever possible, even if there\'s a performance hit, because there are significant gains in doing so.\n-\n ## `stylelint.utils`\n \n A few of stylelint\'s internal utilities are exposed publicly in `stylelint.utils`, to help you write plugin rules. For details about the APIs of these functions, please look at comments in the source code and examples in the standard rules.\n@@ -37,7 +39,7 @@ A few of stylelint\'s internal utilities are exposed publicly in `stylelint.utils\n You will want to use:\n \n - `report`: Report your linting warnings. *Do not use `node.warn()` directly.* If you use `report`, your plugin will respect disabled ranges and other possible future features of stylelint, so it will fit in better with the standard rules.\n-- `ruleMessages`: Tailor your messages to look like the messages of other stylelint rules. Currently, this means that the name of the rule is appended, in parentheses, to the end of the message.\n+- `ruleMessages`: Tailor your messages to look like the messages of other stylelint rules.\n - `validateOptions`: Help your user\'s out by checking that the options they\'ve submitted are valid.\n \n **`stylelint.util.styleSearch` is deprecated and will be removed in v7. Use the external module [style-search](https://github.com/davidtheclark/style-search) instead.**\n@@ -62,11 +64,25 @@ export default stylelint.createPlugin(ruleName, function (expectation) {\n })\n ```\n \n+## External helper modules\n+\n+In addition to the standard parsers mentioned in the ["Working on rules"](/docs/developer-guide/rules.md) doc, there are other external modules used within stylelint that we recommend using. These include:\n+\n+- [normalize-selector](https://github.com/getify/normalize-selector) - Normalize CSS selectors.\n+- [postcss-resolve-nested-selector](https://github.com/davidtheclark/postcss-resolve-nested-selector) - Given a (nested) selector in a PostCSS AST, return an array of resolved selectors.\n+- [style-search](https://github.com/davidtheclark/style-search) - Search CSS (and CSS-like) strings, with sensitivity to whether matches occur inside strings, comments, and functions.\n+\n+Have a look through [stylelint\'s internal utils](https://github.com/stylelint/stylelint/tree/master/src/utils) and if you come across one that you need in your plugin, then please consider helping us extract it out into a external module.\n+\n ## Testing plugins\n \n For testing your plugin, you might consider using the same rule-testing function that stylelint uses internally: [`stylelint-test-rule-tape`](https://github.com/stylelint/stylelint-test-rule-tape).\n \n-## Sharing plugins\n+## Plugin packs\n+\n+To make a single module provide multiple rules, simply export an array of plugin objects (rather than a single object).\n+\n+## Sharing plugins and plugin packs\n \n - Use the `stylelint-plugin` keyword within your `package.json`.\n - Once your plugin is published, please send us a Pull Request to add your plugin to [the list](/docs/user-guide/plugins.md).\n', 'commit_subject': 'Merge pull request #1440 from stylelint/update-plugin-docs', 'repo_name': 'stylelint/stylelint', 'committer': {'name': 'GitHub', 'email': '1505422b2465e9a84f6fdfaa161078890c593f06@github.com', 'time_sec': '1465825734', 'tz_offset': '-420', 'date': {'seconds': '1465825734'}}, 'commit_tree': 'b2653c899c246ae1316d1341678b08c5654d0f9d', 'commit_message': 'Merge pull request #1440 from stylelint/update-plugin-docs\n\nExpand plugin docs', 'language_name': 'JavaScript', 'license': 'mit', 'hunks': '@@ -1,35 +1,37 @@\n # Writing plugins\n \n-```js\n-// Abbreviated example:\n+Plugins are rules and sets of rules built by the community. We recommend adhering to stylelint\'s [conventions for writing rules](/docs/developer-guide/rules.md#come-up-with-a-name), including conventions for: names, options, messages, tests and docs. These will help create a consistent user experience.\n+\n+## The anatomy of a plugin\n \n+```js\n+// Abbreviated example\n var stylelint = require("stylelint")\n \n-var myPluginRuleName = "plugin/foobar"\n-var myPluginRule = stylelint.createPlugin(myPluginRuleName, function(expectationKeyword, optionsObject) {\n+var ruleName = "plugin/foobar"\n+\n+stylelint.utils.ruleMessages(ruleName, {\n+  expected: "Expected ...",\n+})\n+\n+var myPluginRule = stylelint.createPlugin(ruleName, function(primaryOption, secondaryOptionObject) {\n   return function(postcssRoot, postcssResult) {\n+    var validOptions = stylelint.utils.validateOptions(postcssResult, ruleName, { .. })\n+    if (!validOptions) { return }\n     // ... some logic ...\n     stylelint.utils.report({ .. })\n   }\n })\n ```\n \n-`stylelint.createPlugin(ruleName, ruleFunction)` ensures that your plugin will be setup properly alongside other rules. *Make sure you document your plugin\'s rule name for users, because they will need to use it in their config.*\n+Your plugin\'s rule name must be namespaced, e.g. `your-namespace/your-rule-name`. If your plugin provides only a single rule or you can\'t think of a good namespace, you can simply use `plugin/my-rule`. This namespace ensures that plugin rules will never clash with core rules. *Make sure you document your plugin\'s rule name (and namespace) for users, because they will need to use it in their config.*\n \n-Your plugin\'s rule name must be namespaced, e.g. `your-namespace/your-rule-name`. If your plugin provides only a single rule or you can\'t think of a good namespace, you can simply use `plugin/my-rule`. This namespace ensures that plugin rules will never clash with core rules.\n+`stylelint.createPlugin(ruleName, ruleFunction)` ensures that your plugin will be setup properly alongside other rules.\n \n-In order for your plugin rule to work with the standard configuration format, (e.g. `["tab", { hierarchicalSelectors: true }]`), `ruleFunction` should accept 2 arguments: the expectation keyword (e.g. `"tab"`) and, optionally, an options object (e.g. `{ hierarchicalSelectors: true }`).\n+In order for your plugin rule to work with the standard configuration format, (e.g. `["tab", { hierarchicalSelectors: true }]`), `ruleFunction` should accept 2 arguments: the primary option (e.g. `"tab"`) and, optionally, an secondary options object (e.g. `{ hierarchicalSelectors: true }`).\n \n `ruleFunction` should return a function that is essentially a little PostCSS plugin: it takes 2 arguments: the PostCSS Root (the parsed AST), and the PostCSS LazyResult. You\'ll have to [learn about the PostCSS API](https://github.com/postcss/postcss/blob/master/docs/api.md).\n \n-## Modules providing multiple rules\n-\n-To make a single module provide multiple rules, simply export an array of plugin objects (rather than a single object).\n-\n-## Standard parsers\n-\n-We recommend using [postcss-value-parser](https://github.com/TrySound/postcss-value-parser) and/or [postcss-selector-parser](https://github.com/postcss/postcss-selector-parser). Use these standard parsers whenever possible, even if there\'s a performance hit, because there are significant gains in doing so.\n-\n ## `stylelint.utils`\n \n A few of stylelint\'s internal utilities are exposed publicly in `stylelint.utils`, to help you write plugin rules. For details about the APIs of these functions, please look at comments in the source code and examples in the standard rules.\n@@ -37,7 +39,7 @@ A few of stylelint\'s internal utilities are exposed publicly in `stylelint.utils\n You will want to use:\n \n - `report`: Report your linting warnings. *Do not use `node.warn()` directly.* If you use `report`, your plugin will respect disabled ranges and other possible future features of stylelint, so it will fit in better with the standard rules.\n-- `ruleMessages`: Tailor your messages to look like the messages of other stylelint rules. Currently, this means that the name of the rule is appended, in parentheses, to the end of the message.\n+- `ruleMessages`: Tailor your messages to look like the messages of other stylelint rules.\n - `validateOptions`: Help your user\'s out by checking that the options they\'ve submitted are valid.\n \n **`stylelint.util.styleSearch` is deprecated and will be removed in v7. Use the external module [style-search](https://github.com/davidtheclark/style-search) instead.**\n@@ -62,11 +64,25 @@ export default stylelint.createPlugin(ruleName, function (expectation) {\n })\n ```\n \n+## External helper modules\n+\n+In addition to the standard parsers mentioned in the ["Working on rules"](/docs/developer-guide/rules.md) doc, there are other external modules used within stylelint that we recommend using. These include:\n+\n+- [normalize-selector](https://github.com/getify/normalize-selector) - Normalize CSS selectors.\n+- [postcss-resolve-nested-selector](https://github.com/davidtheclark/postcss-resolve-nested-selector) - Given a (nested) selector in a PostCSS AST, return an array of resolved selectors.\n+- [style-search](https://github.com/davidtheclark/style-search) - Search CSS (and CSS-like) strings, with sensitivity to whether matches occur inside strings, comments, and functions.\n+\n+Have a look through [stylelint\'s internal utils](https://github.com/stylelint/stylelint/tree/master/src/utils) and if you come across one that you need in your plugin, then please consider helping us extract it out into a external module.\n+\n ## Testing plugins\n \n For testing your plugin, you might consider using the same rule-testing function that stylelint uses internally: [`stylelint-test-rule-tape`](https://github.com/stylelint/stylelint-test-rule-tape).\n \n-## Sharing plugins\n+## Plugin packs\n+\n+To make a single module provide multiple rules, simply export an array of plugin objects (rather than a single object).\n+\n+## Sharing plugins and plugin packs\n \n - Use the `stylelint-plugin` keyword within your `package.json`.\n - Once your plugin is published, please send us a Pull Request to add your plugin to [the list](/docs/user-guide/plugins.md).\n', 'addition_count': 33, 'deletion_count': 17, 'src_file': 'a/docs/developer-guide/plugins.md', 'tgt_file': 'b/docs/developer-guide/plugins.md', 'file_extension': '.md', 'before_file': '# Writing plugins\n\n```js\n// Abbreviated example:\n\nvar stylelint = require("stylelint")\n\nvar myPluginRuleName = "plugin/foobar"\nvar myPluginRule = stylelint.createPlugin(myPluginRuleName, function(expectationKeyword, optionsObject) {\n  return function(postcssRoot, postcssResult) {\n    // ... some logic ...\n    stylelint.utils.report({ .. })\n  }\n})\n```\n\n`stylelint.createPlugin(ruleName, ruleFunction)` ensures that your plugin will be setup properly alongside other rules. *Make sure you document your plugin\'s rule name for users, because they will need to use it in their config.*\n\nYour plugin\'s rule name must be namespaced, e.g. `your-namespace/your-rule-name`. If your plugin provides only a single rule or you can\'t think of a good namespace, you can simply use `plugin/my-rule`. This namespace ensures that plugin rules will never clash with core rules.\n\nIn order for your plugin rule to work with the standard configuration format, (e.g. `["tab", { hierarchicalSelectors: true }]`), `ruleFunction` should accept 2 arguments: the expectation keyword (e.g. `"tab"`) and, optionally, an options object (e.g. `{ hierarchicalSelectors: true }`).\n\n`ruleFunction` should return a function that is essentially a little PostCSS plugin: it takes 2 arguments: the PostCSS Root (the parsed AST), and the PostCSS LazyResult. You\'ll have to [learn about the PostCSS API](https://github.com/postcss/postcss/blob/master/docs/api.md).\n\n## Modules providing multiple rules\n\nTo make a single module provide multiple rules, simply export an array of plugin objects (rather than a single object).\n\n## Standard parsers\n\nWe recommend using [postcss-value-parser](https://github.com/TrySound/postcss-value-parser) and/or [postcss-selector-parser](https://github.com/postcss/postcss-selector-parser). Use these standard parsers whenever possible, even if there\'s a performance hit, because there are significant gains in doing so.\n\n## `stylelint.utils`\n\nA few of stylelint\'s internal utilities are exposed publicly in `stylelint.utils`, to help you write plugin rules. For details about the APIs of these functions, please look at comments in the source code and examples in the standard rules.\n\nYou will want to use:\n\n- `report`: Report your linting warnings. *Do not use `node.warn()` directly.* If you use `report`, your plugin will respect disabled ranges and other possible future features of stylelint, so it will fit in better with the standard rules.\n- `ruleMessages`: Tailor your messages to look like the messages of other stylelint rules. Currently, this means that the name of the rule is appended, in parentheses, to the end of the message.\n- `validateOptions`: Help your user\'s out by checking that the options they\'ve submitted are valid.\n\n**`stylelint.util.styleSearch` is deprecated and will be removed in v7. Use the external module [style-search](https://github.com/davidtheclark/style-search) instead.**\n    });\n  };\n};\n\nruleFunction.ruleName = ruleName;\nruleFunction.messages = messages;\nruleFunction.meta = meta;\n\nmodule.exports = stylelint.createPlugin(ruleName, ruleFunction);\n```\n\nYour plugin\'s rule name must be namespaced, e.g. `your-namespace/your-rule-name`, to ensure it never clashes with the built-in rules. If your plugin provides only a single rule or you can\'t think of a good namespace, you can use `plugin/my-rule`. _You should document your plugin\'s rule name (and namespace) because users need to use them in their config._\n\nUse `stylelint.createPlugin(ruleName, ruleFunction)` to ensure that your plugin is set up properly alongside other rules.\n\nFor your plugin rule to work with the [standard configuration format](../user-guide/configure.md#rules), `ruleFunction` should accept 2 arguments:\n\n- the primary option\n})\n```\n\n## Testing plugins\n\nFor testing your plugin, you might consider using the same rule-testing function that stylelint uses internally: [`stylelint-test-rule-tape`](https://github.com/stylelint/stylelint-test-rule-tape).\n\n## Sharing plugins\n\n- Use the `stylelint-plugin` keyword within your `package.json`.\n- Once your plugin is published, please send us a Pull Request to add your plugin to [the list](/docs/user-guide/plugins.md).\n};\n\nconst ruleFunction = (primaryOption, secondaryOptionObject) => {\n  return (postcssRoot, postcssResult) => {\n    const validOptions = stylelint.utils.validateOptions(\n      postcssResult,\n      ruleName,\n      {\n        /* .. */\n      }\n    );\n\n    if (!validOptions) {\n      return;\n    }\n\n    return new Promise((resolve) => {\n      // some async operation\n      setTimeout(() => {\n        // ... some logic ...\n        stylelint.utils.report({\n          /* .. */\n        });\n        resolve();\n      }, 1);\n    });\n  };\n};\n\nruleFunction.ruleName = ruleName;\nruleFunction.messages = messages;\nruleFunction.meta = meta;\n\nmodule.exports = stylelint.createPlugin(ruleName, ruleFunction);\n```\n\n## Testing\n\nYou should use [`jest-preset-stylelint`](https://github.com/stylelint/jest-preset-stylelint) to test your plugin. The preset exposes a global `testRule` function that you can use to efficiently test your plugin using a schema.\n\nFor example:\n\n```js\n// index.test.js\nconst {\n  rule: { ruleName, messages }\n} = require(".");\n\ntestRule({\n  plugins: ["./index.js"],\n  ruleName,\n  config: true,\n  fix: true,\n\n  accept: [\n    {\n      code: ".class {}"\n    },\n    {\n      code: ".my-class {}"\n    }\n  ],\n\n  reject: [\n    {\n      code: ".myClass {}",\n      fixed: ".my-class {}",\n      message: messages.expected,\n      line: 1,\n      column: 1,\n      endLine: 1,\n      endColumn: 9\n    }\n  ]\n});\n```\n\nHowever, if your plugin involves more than just checking syntax you can use Stylelint directly.\n\nFor example:\n\n```js\n// index.test.js\nconst { lint } = require("stylelint");\n\nconst config = {\n  plugins: ["./index.js"],\n  rules: {\n    "plugin/at-import-no-unresolveable": [true]\n  }\n};\n\nit("warns for unresolveable import", async () => {\n  const {\n    results: [{ warnings, parseErrors }]\n  } = await lint({\n    files: "fixtures/contains-unresolveable-import.css",\n    config\n  });\n\n  expect(parseErrors).toHaveLength(0);\n  expect(warnings).toHaveLength(1);\n\n  const [{ line, column, text }] = warnings;\n\n  expect(text).toBe(\n    "Unexpected unresolveable import (plugin/at-import-no-unresolveable)"\n  );\n  expect(line).toBe(1);\n  expect(column).toBe(1);\n});\n\nit("doesn\'t warn for fileless sources", async () => {\n  const {\n    results: [{ warnings, parseErrors }]\n  } = await lint({\n    code: "@import url(unknown.css)",\n    config\n  });\n  expect(parseErrors).toHaveLength(0);\n  expect(warnings).toHaveLength(0);\n});\n```\n\nAlternatively, if you don\'t want to use Jest you\'ll find more tools in [awesome stylelint](https://github.com/stylelint/awesome-stylelint#tools).\n\n## `stylelint.utils`\n\nStylelint exposes some useful utilities.\n\n### `stylelint.utils.report`\n\nAdds problems from your plugin to the list of problems that Stylelint will report to the user.\n\nUse `stylelint.utils.report` to ensure your plugin respects disabled ranges and other possible future features of stylelint. _Do not use PostCSS\'s `node.warn()` method directly._\n\n### `stylelint.utils.ruleMessages`\n\nTailors your messages to the format of standard Stylelint rules.\n\n### `stylelint.utils.validateOptions`\n\nValidates the options for your rule.\n\n### `stylelint.utils.checkAgainstRule`\n\nChecks CSS against a standard Stylelint rule _within your own rule_. This function provides power and flexibility for plugins authors who wish to modify, constrain, or extend the functionality of existing Stylelint rules.\n\nIt accepts an options object and a callback that is invoked with warnings from the specified rule. The options are:\n\n- `ruleName`: the name of the rule you are invoking\n- `ruleSettings`: settings for the rule you are invoking\n- `root`: the root node to run this rule against\n\nUse the warning to create a _new_ warning _from your plugin rule_ that you report with `stylelint.utils.report`.\n\nFor example, imagine you want to create a plugin that runs `at-rule-no-unknown` with a built-in list of exceptions for at-rules provided by your preprocessor-of-choice:\n\n```js\nconst allowableAtRules = [\n  /* .. */\n];\n\nfunction myPluginRule(primaryOption, secondaryOptionObject) {\n  return (postcssRoot, postcssResult) => {\n    const defaultedOptions = Object.assign({}, secondaryOptionObject, {\n      ignoreAtRules: allowableAtRules.concat(options.ignoreAtRules || [])\n    });\n\n    stylelint.utils.checkAgainstRule(\n      {\n        ruleName: "at-rule-no-unknown",\n        ruleSettings: [primaryOption, defaultedOptions],\n        root: postcssRoot\n      },\n      (warning) => {\n        stylelint.utils.report({\n          message: myMessage,\n          ruleName: myRuleName,\n          result: postcssResult,\n          node: warning.node,\n          line: warning.line,\n          column: warning.column,\n          endLine: warning.endLine,\n          endColumn: warning.endColumn\n        });\n      }\n    );\n  };\n}\n```\n\n## `stylelint.rules`\n\nAll of the rule functions are available at `stylelint.rules`. This allows you to build on top of existing rules for your particular needs.\n\nA typical use-case is to build in more complex conditionals that the rule\'s options allow for. For example, maybe your codebase uses special comment directives to customize rule options for specific stylesheets. You could build a plugin that checks those directives and then runs the appropriate rules with the right options (or doesn\'t run them at all).\n\nAll rules share a common signature. They are a function that accepts two arguments: a primary option and a secondary options object. And that functions returns a function that has the signature of a PostCSS plugin, expecting a PostCSS root and result as its arguments.\n\nHere\'s an example of a plugin that runs `declaration-no-important` only if there is a special directive `@@check-declaration-no-important` somewhere in the stylesheet:\n\n```js\nmodule.exports = stylelint.createPlugin(ruleName, (expectation) => {\n  const runDeclarationNoImportant =\n    stylelint.rules["declaration-no-important"](expectation);\n\n  return (root, result) => {\n    if (root.toString().indexOf("@@check-declaration-no-important") === -1) {\n      return;\n    }\n\n    runDeclarationNoImportant(root, result);\n  };\n});\n```\n\n## Allow primary option arrays\n\nIf your plugin can accept an array as its primary option, you must designate this by setting the property `primaryOptionArray = true` on your rule function. For more information, check out the ["Working on rules"](rules.md) doc.\n\n## External helper modules\n\nIn addition to the standard parsers mentioned in the ["Working on rules"](rules.md) doc, there are other external modules used within Stylelint that we recommend using. These include:\n\n- [postcss-resolve-nested-selector](https://github.com/davidtheclark/postcss-resolve-nested-selector): given a (nested) selector in a PostCSS AST, return an array of resolved selectors.\n\nHave a look through [Stylelint\'s internal utils](https://github.com/stylelint/stylelint/tree/main/lib/utils) and if you come across one that you need in your plugin, then please consider helping us extract it out into an external module.\n\n## Peer dependencies\n\nYou should express, within the `peerDependencies` key (and **not** within the `dependencies` key) of your plugin\'s `package.json`, what version(s) of Stylelint your plugin can be used with. This is to ensure that different versions of Stylelint are not unexpectedly installed.\n\nFor example, to express that your plugin can be used with Stylelint versions 7 and 8:\n\n```json\n{\n  "peerDependencies": {\n    "stylelint": "^7.0.0 || ^8.0.0"\n  }\n}\n```\n\n## Plugin packs\n\nTo make a single module provide multiple rules, export an array of plugin objects (rather than a single object).\n\n## Sharing plugins and plugin packs\n\nUse the `stylelint-plugin` keyword within your `package.json`.\n', 'message': 'Merge pull request #1440 from stylelint/update-plugin-docs\n\nExpand plugin docs', 'author_name': 'GitHub', 'lang': 'md'}