From bab0baf193d78d974ceb22c45bf05fff1741db08 Mon Sep 17 00:00:00 2001 From: Sascha Date: Mon, 18 Apr 2022 17:23:30 +0200 Subject: [PATCH] Added examples on how to add and modify rules (#619) --- docs/examples/renderer_rules.md | 262 ++++++++++++++++++++++++++++++++ 1 file changed, 262 insertions(+) create mode 100644 docs/examples/renderer_rules.md diff --git a/docs/examples/renderer_rules.md b/docs/examples/renderer_rules.md new file mode 100644 index 000000000..7318b7a3b --- /dev/null +++ b/docs/examples/renderer_rules.md @@ -0,0 +1,262 @@ +# Adding or modifying rules +## Default renderer rules +Rules on how to translate markdown content to HTML elements are stored in `renderer.rules`: + +``` +const MarkdownIt = require('markdown-it'); +const md = new MarkdownIt(); + +console.log(Object.keys(md.renderer.rules)) +``` +Output: +``` +[ + 'code_inline', + 'code_block', + 'fence', + 'image', + 'hardbreak', + 'softbreak', + 'text', + 'html_block', + 'html_inline' +] +``` +These are the default renderer rules. For any element that is not explicitly listed in this array its default rule applies. For example the rule `bullet_list_open` is not defined, so when markdown-it tries to parse a list to HTML it defaults to ua generic renderer called `Renderer.prototype.renderToken`. + +## The demo tool + +You can use the [demo tool](https://markdown-it.github.io/) to see which specific rule name corresponds to which HTML tag (switch to the debug tab in the output). + +Let's use a Hello World example: + [Link to Demo](https://markdown-it.github.io/#md3=%7B%22source%22%3A%22-%20Hello%20World%22%2C%22defaults%22%3A%7B%22html%22%3Afalse%2C%22xhtmlOut%22%3Afalse%2C%22breaks%22%3Afalse%2C%22langPrefix%22%3A%22language-%22%2C%22linkify%22%3Afalse%2C%22typographer%22%3Afalse%2C%22_highlight%22%3Afalse%2C%22_strict%22%3Afalse%2C%22_view%22%3A%22debug%22%7D%7D) + +Now take a closer look at the first element in the resulting list: +``` +{ + "type": "bullet_list_open", + "tag": "ul", + "attrs": null, + "map": [ + 0, + 1 + ], + "nesting": 1, + "level": 0, + "children": null, + "content": "", + "markup": "-", + "info": "", + "meta": null, + "block": true, + "hidden": false + } +``` +This is a [Token](https://markdown-it.github.io/markdown-it/#Token). Its corresponding HTML `tag` is `ul` and its nesting is `1`. This means this specific token represents the opening tag of the HTML list we want to generate from markdown. + +* `{ nesting: 1}` is an opening tag: `` +* `{ nesting: 0}` is a self-closing tag: `
` + +## Adding new rules +### To add a default CSS class to an element + +Let's set ourself a goal: +``` +Create a rule to add the CSS class "lorem_ipsum" to every