### Inspect Syntax Tree Output
Source: https://github.com/ariabuckles/simple-markdown/blob/master/README.md
Provides an example of how to pretty-print the generated syntax tree using JSON.stringify with 4-space indentation. This helps in understanding the structure of the parsed markdown.
```javascript
// pretty-print this with 4-space indentation:
console.log(JSON.stringify(syntaxTree, null, 4));
```
--------------------------------
### Example Strong Text Rule Definition (JavaScript)
Source: https://github.com/ariabuckles/simple-markdown/blob/master/README.md
Illustrates the structure of a Simple Markdown rule, using the example of a 'strong' (bold) text rule. It defines `match`, `parse`, `react`, and `html` methods, showing how to capture and transform text enclosed in double asterisks.
```javascript
strong: {
match: function(source, state, lookbehind) {
return /^\*\*([\s\S]+?)\*\*(?!\*)/.exec(source);
},
parse: function(capture, recurseParse, state) {
return {
content: recurseParse(capture[1], state)
};
},
react: function(node, recurseOutput) {
return React.DOM.strong(null, recurseOutput(node.content));
},
html: function(node, recurseOutput) {
return '' + recurseOutput(node.content) + '';
},
},
```
--------------------------------
### Create Parsers for Multiple Output Formats in Simple Markdown
Source: https://context7.com/ariabuckles/simple-markdown/llms.txt
Illustrates how to define custom rules in simple-markdown that support multiple output formats, such as React components and plain text. This example shows creating a custom emphasis rule that can be rendered differently depending on the output format.
```javascript
var SimpleMarkdown = require("simple-markdown");
// Define a rule with multiple output methods
var emphasisRule = {
order: SimpleMarkdown.defaultRules.em.order,
match: SimpleMarkdown.inlineRegex(/^\*\*([\s\S]+?)\*\*/),
parse: function(capture, parse, state) {
return { content: parse(capture[1], state) };
},
react: function(node, output, state) {
return SimpleMarkdown.reactElement('strong', state.key, {
children: output(node.content, state)
});
},
html: function(node, output, state) {
return SimpleMarkdown.htmlTag('strong', output(node.content, state));
},
// Custom plain text output
text: function(node, output, state) {
return output(node.content, state).toUpperCase();
}
};
var rules = Object.assign({}, SimpleMarkdown.defaultRules, {
strong: emphasisRule
});
// Add Array handler for text output
rules.Array = Object.assign({}, rules.Array, {
text: function(arr, output, state) {
return arr.map(function(node) {
return output(node, state);
}).join('');
}
});
// Add text handler for text nodes
rules.text = Object.assign({}, rules.text, {
text: function(node, output, state) {
return node.content;
}
});
var parser = SimpleMarkdown.parserFor(rules);
var textOutput = SimpleMarkdown.outputFor(rules, 'text');
var tree = parser("This is **important** text", { inline: true });
console.log(textOutput(tree));
// "This is IMPORTANT text"
```
--------------------------------
### Require SimpleMarkdown in Node.js
Source: https://github.com/ariabuckles/simple-markdown/blob/master/README.md
This snippet shows how to import the SimpleMarkdown library in a Node.js environment. Ensure you have installed the library via npm.
```javascript
var SimpleMarkdown = require("simple-markdown");
```
--------------------------------
### Implement Stateful Parsing for List Nesting Depth in Simple Markdown
Source: https://context7.com/ariabuckles/simple-markdown/llms.txt
This example shows how to use stateful parsing in Simple Markdown to track nesting depth for lists. A custom list rule modifies the default list parsing to increment and decrement a 'listDepth' counter in the state, and adds a depth class to the output HTML. Requires 'simple-markdown'.
```javascript
var SimpleMarkdown = require("simple-markdown");
// Create a rule that tracks nesting depth
var customListRule = Object.assign({}, SimpleMarkdown.defaultRules.list, {
parse: function(capture, parse, state) {
// Track list depth in state
state.listDepth = (state.listDepth || 0) + 1;
var result = SimpleMarkdown.defaultRules.list.parse(capture, parse, state);
result.depth = state.listDepth;
state.listDepth = state.listDepth - 1;
return result;
},
html: function(node, output, state) {
var listTag = node.ordered ? 'ol' : 'ul';
var items = node.items.map(function(item) {
return SimpleMarkdown.htmlTag('li', output(item, state));
}).join('');
var attrs = {
class: 'list-depth-' + node.depth,
start: node.start
};
return SimpleMarkdown.htmlTag(listTag, items, attrs);
}
});
var rules = Object.assign({}, SimpleMarkdown.defaultRules, {
list: customListRule
});
var parser = SimpleMarkdown.parserFor(rules, { listDepth: 0 });
var htmlOutput = SimpleMarkdown.outputFor(rules, 'html');
var markdown = "* Level 1\n * Level 2\n * Level 3\n";
var tree = parser(markdown, { inline: false });
console.log(htmlOutput(tree));
// Lists with depth-specific classes
```
--------------------------------
### Get Default Parsers and Outputter
Source: https://github.com/ariabuckles/simple-markdown/blob/master/README.md
This code retrieves the default block parser and output function provided by SimpleMarkdown for handling generic markdown content. These are used for parsing markdown into a syntax tree and then rendering it.
```javascript
var mdParse = SimpleMarkdown.defaultBlockParse;
var mdOutput = SimpleMarkdown.defaultOutput;
```
--------------------------------
### Create Parser and Renderers from Rules (JavaScript)
Source: https://github.com/ariabuckles/simple-markdown/blob/master/README.md
This snippet shows how to define custom rules, create a parser instance, and then generate output renderers for React and HTML. It includes a helper function to parse and render markdown content, ensuring proper block termination.
```javascript
var rules = {
...SimpleMarkdown.defaultRules,
paragraph: {
...SimpleMarkdown.defaultRules.paragraph,
react: (node, output, state) => {
return
{output(node.content, state)}
;
}
}
};
var parser = SimpleMarkdown.parserFor(rules);
var reactOutput = SimpleMarkdown.outputFor(rules, 'react'));
var htmlOutput = SimpleMarkdown.outputFor(rules, 'html'));
var blockParseAndOutput = function(source) {
// Many rules require content to end in \n\n to be interpreted
// as a block.
var blockSource = source + "\n\n";
var parseTree = parser(blockSource, {inline: false});
var outputResult = htmlOutput(parseTree);
// Or for react output, use:
// var outputResult = reactOutput(parseTree);
return outputResult;
};
```
--------------------------------
### Build Custom Parser and Outputters (JavaScript)
Source: https://github.com/ariabuckles/simple-markdown/blob/master/README.md
Constructs custom parser and output functions using the extended rules. It creates a `rawBuiltParser` and then wrapper functions `parse`, `reactOutput`, and `htmlOutput` for convenience. This enables markdown parsing with the new underline functionality.
```javascript
var rawBuiltParser = SimpleMarkdown.parserFor(rules);
var parse = function (source) {
var blockSource = source + "\n\n";
return rawBuiltParser(blockSource, { inline: false });
};
// You probably only need one of these: choose depending on
// whether you want react nodes or an html string:
var reactOutput = SimpleMarkdown.outputFor(rules, "react");
var htmlOutput = SimpleMarkdown.outputFor(rules, "html");
```
--------------------------------
### Parse and Output Markdown with Underlines (JavaScript)
Source: https://github.com/ariabuckles/simple-markdown/blob/master/README.md
Demonstrates the usage of the custom `parse` and `htmlOutput` functions to process markdown containing underlines. It shows the resulting syntax tree and the generated HTML output.
```javascript
var syntaxTree = parse("__hello underlines__");
console.log(JSON.stringify(syntaxTree, null, 4));
// => [
// {
// "content": [
// {
// "content": [
// {
// "content": "hello underlines",
// "type": "text"
// }
// ],
// "type": "underline"
// }
// ],
// "type": "paragraph"
// }
// ]
// reactOutput(syntaxTree)
// => [ { type: 'div',
// key: null,
// ref: null,
// _owner: null,
// _context: {},
// _store: { validated: false, props: [Object] } } ]
// htmlOutput(syntaxTree)
// => 'hello underlines
'
```
--------------------------------
### Create a Markdown Parser from Custom Rules
Source: https://github.com/ariabuckles/simple-markdown/blob/master/README.md
The `SimpleMarkdown.parserFor` function generates a parser instance from a provided `rules` object. Each rule must have an `order` field, and `match` and `parse` functions. Ties in `order` are broken lexicographically by rule name.
```javascript
const customRules = {
// ... define your custom rules here ...
};
const parser = SimpleMarkdown.parserFor(customRules);
const ast = parser('Input markdown text');
```
--------------------------------
### Output Syntax Tree to React Elements
Source: https://github.com/ariabuckles/simple-markdown/blob/master/README.md
Shows how to convert the parsed syntax tree into an array of React elements using the default output function provided by SimpleMarkdown. This is a common use case for rendering markdown in a React application.
```javascript
mdOutput(syntaxTree)
```
--------------------------------
### Create Custom Parser Rules for Simple-Markdown (JavaScript)
Source: https://context7.com/ariabuckles/simple-markdown/llms.txt
Extends the Simple-Markdown parser with custom syntax rules. Demonstrates creating a rule for highlighted text (`==highlight==`) and integrating it into a custom parser and outputter for HTML. Requires simple-markdown.
```javascript
var SimpleMarkdown = require("simple-markdown");
// Create a custom rule for highlighting text with ==highlight==
var highlightRule = {
order: SimpleMarkdown.defaultRules.em.order - 0.5,
match: function(source) {
return /^==([\s\S]+?)==/.exec(source);
},
parse: function(capture, parse, state) {
return {
content: parse(capture[1], state)
};
},
react: function(node, output, state) {
return SimpleMarkdown.reactElement('mark', state.key, {
children: output(node.content, state)
});
},
html: function(node, output, state) {
return '' + output(node.content, state) + '';
}
};
// Combine with default rules
var rules = Object.assign({}, SimpleMarkdown.defaultRules, {
highlight: highlightRule
});
// Create custom parser and outputter
var parser = SimpleMarkdown.parserFor(rules);
var htmlOutput = SimpleMarkdown.outputFor(rules, 'html');
var parse = function(source) {
return parser(source + "\n\n", { inline: false });
};
var result = parse("This is ==highlighted text==");
console.log(htmlOutput(result));
// This is highlighted text
```
--------------------------------
### Parse Markdown to Syntax Tree
Source: https://github.com/ariabuckles/simple-markdown/blob/master/README.md
Demonstrates parsing a markdown string into a structured syntax tree using the default block parser from SimpleMarkdown. The resulting tree represents the hierarchical structure of the markdown content.
```javascript
var syntaxTree = mdParse("Here is a paragraph and an *em tag*.");
```
--------------------------------
### Create a Markdown Output Function
Source: https://github.com/ariabuckles/simple-markdown/blob/master/README.md
The `SimpleMarkdown.outputFor` function creates a recursive output function based on a `rules` object and a specified output `key` (e.g., 'react' or 'html'). This function is used to render a syntax tree node into the desired output format.
```javascript
const reactOutput = SimpleMarkdown.outputFor(defaultRules, 'react');
const htmlOutput = SimpleMarkdown.outputFor(defaultRules, 'html');
// Assuming 'ast' is a parsed syntax tree node
const reactTree = reactOutput(ast, recurseOutput);
const htmlString = htmlOutput(ast, recurseOutput);
```
--------------------------------
### Sanitize User Input and URLs with Simple Markdown
Source: https://context7.com/ariabuckles/simple-markdown/llms.txt
Demonstrates how to use SimpleMarkdown's built-in sanitization functions to prevent XSS attacks by neutralizing dangerous URLs and escaping HTML entities. It also shows how default rules handle sanitization and how to implement custom sanitization within a link rule.
```javascript
var SimpleMarkdown = require("simple-markdown");
// Built-in sanitization functions
var sanitizeUrl = SimpleMarkdown.sanitizeUrl;
var sanitizeText = SimpleMarkdown.sanitizeText;
// Dangerous URL is neutralized
var safeUrl = sanitizeUrl('javascript:alert("XSS")');
console.log(safeUrl); // null
var safeUrl2 = sanitizeUrl('https://example.com');
console.log(safeUrl2); // "https://example.com"
// HTML entities are escaped
var safeText = sanitizeText('');
console.log(safeText); // "<script>alert(\"XSS\")</script>"
// Default rules already use sanitization
var userMarkdown = '[Click me](javascript:alert("XSS"))';
var tree = SimpleMarkdown.defaultBlockParse(userMarkdown);
var html = SimpleMarkdown.defaultHtmlOutput(tree);
console.log(html);
// Link href will be sanitized to null, preventing XSS
// Custom rule with sanitization
var customLinkRule = Object.assign({}, SimpleMarkdown.defaultRules.link, {
html: function(node, output, state) {
var safeHref = sanitizeUrl(node.target) || '#';
var safeTitle = node.title ? sanitizeText(node.title) : null;
return SimpleMarkdown.htmlTag('a', output(node.content, state), {
href: safeHref,
title: safeTitle,
rel: 'nofollow noopener'
});
}
});
```
--------------------------------
### Render Markdown Node to React Elements
Source: https://github.com/ariabuckles/simple-markdown/blob/master/README.md
The `react` function converts a syntax tree node into React-renderable output. It takes the node, a `recurseOutput` function for handling nested nodes, and the current state. The output is typically a React element or an array of elements.
```javascript
function react(node, recurseOutput, state) {
return React.createElement(
'h1',
null,
recurseOutput(node.content, state)
);
}
```
--------------------------------
### Convert Markdown to React Elements with Simple-Markdown (JavaScript)
Source: https://context7.com/ariabuckles/simple-markdown/llms.txt
Transforms markdown text directly into React elements. Requires React and ReactDOMServer for rendering. Outputs a React element tree that can be rendered to static markup.
```javascript
var SimpleMarkdown = require("simple-markdown");
var React = require("react");
var ReactDOMServer = require("react-dom/server");
// Direct conversion to React elements
var markdownToReact = SimpleMarkdown.markdownToReact;
var reactElements = markdownToReact("## Subheading\n\nParagraph with [link](https://example.com)");
// Render to HTML using React
var html = ReactDOMServer.renderToStaticMarkup(
React.createElement('div', {}, reactElements)
);
console.log(html);
//
// Or use the ReactMarkdown component
var ReactMarkdown = SimpleMarkdown.ReactMarkdown;
var component = React.createElement(ReactMarkdown, {
source: "**Bold text** in markdown",
className: "markdown-content"
});
```
--------------------------------
### Convert Markdown to HTML with Simple-Markdown (JavaScript)
Source: https://context7.com/ariabuckles/simple-markdown/llms.txt
Generates HTML strings directly from markdown text. Can handle both full markdown documents and inline-only HTML output. No external dependencies beyond simple-markdown.
```javascript
var SimpleMarkdown = require("simple-markdown");
var markdownToHtml = SimpleMarkdown.markdownToHtml;
var html = markdownToHtml("# Title\n\n* Item 1\n* Item 2\n\nSome `code` here.");
console.log(html);
// Output:
// Title
//
// Some code here.
// For inline-only HTML output
var defaultHtmlOutput = SimpleMarkdown.defaultHtmlOutput;
var inlineParse = SimpleMarkdown.defaultInlineParse;
var tree = inlineParse("__underline__ and ~~strikethrough~~");
var inlineHtml = defaultHtmlOutput(tree);
// underline and strikethrough
```
--------------------------------
### Parse Markdown to AST with Simple-Markdown (JavaScript)
Source: https://context7.com/ariabuckles/simple-markdown/llms.txt
Parses markdown text into an Abstract Syntax Tree (AST). Handles both block-level and inline-only markdown. No external dependencies beyond the simple-markdown library.
```javascript
var SimpleMarkdown = require("simple-markdown");
// Parse block-level markdown (paragraphs, headings, lists, etc.)
var blockParse = SimpleMarkdown.defaultBlockParse;
var syntaxTree = blockParse("# Hello World\n\nThis is a **bold** paragraph.");
console.log(JSON.stringify(syntaxTree, null, 2));
// Output:
// [
// {
// "type": "heading",
// "level": 1,
// "content": [{ "type": "text", "content": "Hello World" }]
// },
// {
// "type": "paragraph",
// "content": [
// { "type": "text", "content": "This is a " },
// { "type": "strong", "content": [{ "type": "text", "content": "bold" }] },
// { "type": "text", "content": " paragraph." }
// ]
// }
// ]
// Parse inline-only markdown (no paragraphs or block elements)
var inlineParse = SimpleMarkdown.defaultInlineParse;
var inlineTree = inlineParse("Some *italic* and **bold** text");
// Returns inline elements without wrapping in paragraph
```
--------------------------------
### Extend Default Rules with Underline Rule (JavaScript)
Source: https://github.com/ariabuckles/simple-markdown/blob/master/README.md
Extends the default Simple Markdown rules by adding the previously defined `underlineRule`. This merges the new rule with existing ones, preparing them for parser construction.
```javascript
var rules = _.extend({}, SimpleMarkdown.defaultRules, {
underline: underlineRule,
});
```
--------------------------------
### Define Regex for Markdown Source Matching
Source: https://github.com/ariabuckles/simple-markdown/blob/master/README.md
The `match` function determines if a markdown source segment conforms to a specific rule. It takes the source string, a state object, and lookbehind information. If a match is found, it should return a capture object (similar to `RegExp.prototype.exec`); otherwise, it returns `null`. For regex-based matching, always prepend the regex with `^` to prevent infinite loops.
```javascript
function match(source, state, lookbehind) {
// Example using a regex to match a header
const headerRegex = /^#+ .*/;
const capture = headerRegex.exec(source);
return capture;
}
```
--------------------------------
### Access Default Markdown Rules
Source: https://github.com/ariabuckles/simple-markdown/blob/master/README.md
The `SimpleMarkdown.defaultRules` object provides access to the library's built-in parsing and outputting rules. Each rule is an object containing fields like `order`, `match`, `parse`, `react`, and `html`.
```javascript
const defaultRules = SimpleMarkdown.defaultRules;
console.log(defaultRules.heading);
```
--------------------------------
### Build Custom Inline Rules for Mentions in Simple Markdown
Source: https://context7.com/ariabuckles/simple-markdown/llms.txt
This code defines a custom inline rule for parsing '@mentions' in Simple Markdown. It uses a regular expression to match usernames, and provides functions for parsing, rendering in React, and generating HTML. Dependencies include the 'simple-markdown' library.
```javascript
var SimpleMarkdown = require("simple-markdown");
// Custom @mention rule
var mentionRule = {
order: SimpleMarkdown.defaultRules.text.order - 1,
match: SimpleMarkdown.inlineRegex(/^@([a-zA-Z0-9_]+)/),
parse: function(capture, parse, state) {
return {
username: capture[1]
};
},
react: function(node, output, state) {
return SimpleMarkdown.reactElement('a', state.key, {
href: '/users/' + node.username,
className: 'mention',
children: '@' + node.username
});
},
html: function(node, output, state) {
var attrs = {
href: '/users/' + node.username,
class: 'mention'
};
return SimpleMarkdown.htmlTag('a', '@' + node.username, attrs);
}
};
var rules = Object.assign({}, SimpleMarkdown.defaultRules, {
mention: mentionRule
});
var parser = SimpleMarkdown.parserFor(rules);
var reactOutput = SimpleMarkdown.outputFor(rules, 'react');
var parseInline = function(source) {
return parser(source, { inline: true });
};
var tree = parseInline("Hello @john and @jane!");
console.log(reactOutput(tree));
// [React elements with mention links]
```
--------------------------------
### Define and Parse Underline Rule (JavaScript)
Source: https://github.com/ariabuckles/simple-markdown/blob/master/README.md
Defines a new rule for handling double underscores for underlines. It includes a regex for matching, a parse function to capture content, and functions for rendering as React or HTML elements. This rule is intended to be processed before emphasis rules.
```javascript
var underlineRule = {
// Specify the order in which this rule is to be run
order: SimpleMarkdown.defaultRules.em.order - 0.5,
// First we check whether a string matches
match: function (source) {
return /^__([\s\S]+?)__(?!_)/.exec(source);
},
// Then parse this string into a syntax node
parse: function (capture, parse, state) {
return {
content: parse(capture[1], state),
};
},
// Finally transform this syntax node into a
// React element
react: function (node, output) {
return React.DOM.u(null, output(node.content));
},
// Or an html element:
// (Note: you may only need to make one of `react:` or
// `html:`, as long as you never ask for an outputter
// for the other type.)
html: function (node, output) {
return "" + output(node.content) + "";
},
};
```
--------------------------------
### Parse Markdown Capture to Syntax Tree Node
Source: https://github.com/ariabuckles/simple-markdown/blob/master/README.md
The `parse` function transforms the captured output from `match` into a syntax tree node. It utilizes a `recurseParse` function for nested content and a mutable `state` object. The returned node must have a `type` field, which designates the node's type for outputting. Custom fields can also be added to the node.
```javascript
function parse(capture, recurseParse, state) {
var text = capture[1];
var nestedNodes = recurseParse(
text,
_.defaults({ inline: true }, state)
);
return {
type: 'paragraph',
content: nestedNodes
};
}
```
--------------------------------
### Create Custom Block-Level Rules for Spoilers in Simple Markdown
Source: https://context7.com/ariabuckles/simple-markdown/llms.txt
This snippet demonstrates how to define a custom block-level rule for 'spoiler' content, enclosed in '>>> <<<'. It includes parsing logic to extract content, and functions for rendering spoiler blocks in React and HTML. The rule is integrated into Simple Markdown's default rules.
```javascript
var SimpleMarkdown = require("simple-markdown");
// Custom spoiler block rule: >>>spoiler content<<<
var spoilerRule = {
order: SimpleMarkdown.defaultRules.blockQuote.order + 0.5,
match: SimpleMarkdown.blockRegex(/^>>>([^<]+)<<<\n*/),
parse: function(capture, parse, state) {
return {
content: parse(capture[1].trim(), state)
};
},
react: function(node, output, state) {
return SimpleMarkdown.reactElement('details', state.key, {
className: 'spoiler',
children: [
SimpleMarkdown.reactElement('summary', null, { children: 'Spoiler' }),
output(node.content, state)
]
});
},
html: function(node, output, state) {
var summary = SimpleMarkdown.htmlTag('summary', 'Spoiler');
return SimpleMarkdown.htmlTag('details', summary + output(node.content, state), {
class: 'spoiler'
});
}
};
var rules = Object.assign({}, SimpleMarkdown.defaultRules, {
spoiler: spoilerRule
});
var parser = SimpleMarkdown.parserFor(rules);
var htmlOutput = SimpleMarkdown.outputFor(rules, 'html');
var source = ">>>This is hidden content!<<<
";
var tree = parser(source, { inline: false });
console.log(htmlOutput(tree));
// Spoiler
This is hidden content!
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.