### Install Marked.js CLI Source: https://github.com/markedjs/marked/blob/master/README.md Install the Marked.js command-line interface globally using npm. ```sh npm install -g marked ``` -------------------------------- ### Install Marked.js for Browser Source: https://github.com/markedjs/marked/blob/master/README.md Install the Marked.js library for use in a browser environment using npm. ```sh npm install marked ``` -------------------------------- ### Shell Execution Example Source: https://github.com/markedjs/marked/blob/master/test/specs/original/markdown_documentation_syntax.md An example of executing a shell command that pipes input through a markdown script. This snippet is illustrative and may require specific environment setup. ```shell return shell_exec("echo $input | $markdown_script"); ``` -------------------------------- ### Using Marked with Node.js Source: https://github.com/markedjs/marked/blob/master/test/specs/redos/backticks_in_link_no_close.md Import and use Marked.js in a Node.js environment. This example demonstrates basic parsing. ```javascript const { marked } = require('marked'); const markdown = '## Node.js Example'; marked.parse(markdown, (err, html) => { if (err) { console.error(err); return; } console.log(html); // Output:

Node.js Example

}); ``` -------------------------------- ### Example List Item (Tab Indentation) Source: https://github.com/markedjs/marked/blob/master/test/specs/original/tabs.html An example list item indented with tabs. ```text + this is an example list item indented with tabs ``` -------------------------------- ### Mixed Indentation Example Source: https://github.com/markedjs/marked/blob/master/test/specs/original/tabs.md Provides an example combining list items and code blocks with mixed indentation. ```markdown + this is an example list item indented with tabs + this is an example list item indented with spaces ``` -------------------------------- ### Example List Item (Space Indentation) Source: https://github.com/markedjs/marked/blob/master/test/specs/original/tabs.html An example list item indented with spaces. ```text + this is an example list item indented with spaces ``` -------------------------------- ### Marked.js CLI: File Input Source: https://github.com/markedjs/marked/blob/master/docs/INDEX.md Example of using the Marked.js CLI to convert a markdown file to an HTML file. ```bash # Example with file input echo "**bold text example**" > readme.md $ marked -i readme.md -o readme.html $ cat readme.html

bold text example

``` -------------------------------- ### Handling Images Source: https://github.com/markedjs/marked/blob/master/test/specs/redos/backticks_in_link_no_close.md Customize how images are rendered. This example adds a class to image tags. ```javascript import { marked } from 'marked'; const renderer = { image(href, title, text) { return `\"${text}\${token.text}`; } }; marked.use({ extensions: [myExtension] }); ``` -------------------------------- ### Lexer Usage Example Source: https://github.com/markedjs/marked/blob/master/docs/USING_PRO.md Illustrates the usage of `marked.lexer()` to tokenize a Markdown string into an array of tokens. This example shows how the lexer processes blockquotes and returns a structured token array. ```bash $ node > require('marked').lexer('> I am using marked.') [ { type: "blockquote", raw: "> I am using marked.", tokens: [ { type: "paragraph", raw: "I am using marked.", text: "I am using marked.", tokens: [ { type: "text", raw: "I am using marked.", text: "I am using marked." } ] } ] }, links: {} ] ``` -------------------------------- ### Marked.js CLI: String Input Source: https://github.com/markedjs/marked/blob/master/docs/INDEX.md Example of using the Marked.js CLI to convert a markdown string directly to HTML. ```bash # Example with string input $ marked -s "*hello world*"

hello world

``` -------------------------------- ### GFM Link Reference Example Source: https://github.com/markedjs/marked/blob/master/test/specs/new/toplevel_paragraphs.md Demonstrates a link using reference style. This requires a corresponding definition elsewhere in the Markdown. ```markdown hello [world][how] [how]: /are/you ``` -------------------------------- ### Marked CLI Input to HTML Output Source: https://github.com/markedjs/marked/blob/master/README.md Example of using the Marked CLI to convert standard input (stdin) markdown to an HTML file. Press Ctrl+D (or equivalent) to signal end of input. ```bash # Example with stdin input $ marked -o hello.html hello world ^D $ cat hello.html

hello world

``` -------------------------------- ### Handling Links Source: https://github.com/markedjs/marked/blob/master/test/specs/redos/backticks_in_link_no_close.md Customize how links are rendered. This example overrides the default link renderer to add a target attribute. ```javascript import { marked } from 'marked'; const renderer = { link(href, title, text) { return `${text}`; } }; marked.use({ renderer }); const markdown = '[Google](https://google.com)'; const html = marked.parse(markdown); // html == '

Google

' ``` -------------------------------- ### Basic Code Block Source: https://github.com/markedjs/marked/blob/master/test/specs/original/code_blocks.html A simple code block example. ```markdown code block on the first line ``` -------------------------------- ### Inline Code Example Source: https://github.com/markedjs/marked/blob/master/test/specs/new/backtick_precedence.html Demonstrates how to render inline code using backticks. Note that double asterisks within backticks are treated as literal characters. ```markdown `**` ``` -------------------------------- ### Basic Markdown Parsing Source: https://github.com/markedjs/marked/blob/master/test/specs/redos/backticks_in_link_no_close.html Use this to parse basic Markdown strings into HTML. No additional setup is required. ```javascript marked.parse("# hello world\n\nThis is *bold* text."); // Returns: '

hello world

\n

This bold text.

' ``` -------------------------------- ### Parsing with Options Source: https://github.com/markedjs/marked/blob/master/test/specs/redos/backticks_in_link_no_close.md Configure parsing behavior using options. For example, to enable GFM tables, set 'gfm' to true. ```javascript import { marked } from 'marked'; const markdown = '| Name | Age | |---|---| | Bob | 23 |'; const html = marked.parse(markdown, { gfm: true }); // html == '
NameAge
Bob23
' ``` -------------------------------- ### Markdown Rendering in Node.js Source: https://github.com/markedjs/marked/blob/master/docs/INDEX.md Provides an example of how to use Marked.js to render Markdown to HTML within a Node.js environment, supporting both ES module and CommonJS imports. ```javascript import { marked } from 'marked'; // or const { marked } = require('marked'); const html = marked.parse('# Marked in Node.js\n\nRendered by **marked**.'); ``` -------------------------------- ### Example of Backticks in HTML Tag Source: https://github.com/markedjs/marked/blob/master/test/specs/original/code_spans.md Demonstrates how Marked.js renders HTML tags with backticks in attributes. ```html like this ``` -------------------------------- ### GFM Code Block Example Source: https://github.com/markedjs/marked/blob/master/test/specs/new/toplevel_paragraphs.md Demonstrates a fenced code block in GFM. Ensure GFM is enabled in Marked.js for this to render correctly. ```markdown ``` text inside block code ``` ``` -------------------------------- ### GFM Unordered List Example Source: https://github.com/markedjs/marked/blob/master/test/specs/new/toplevel_paragraphs.md Demonstrates an unordered list item using an asterisk. Marked.js supports standard Markdown list syntax. ```markdown * text inside list ``` -------------------------------- ### GFM Blockquote Example Source: https://github.com/markedjs/marked/blob/master/test/specs/new/toplevel_paragraphs.md Illustrates a blockquote using the greater-than symbol. This is a common Markdown element. ```markdown > text for blockquote ``` -------------------------------- ### CLI Extension with Custom Heading IDs Source: https://github.com/markedjs/marked/blob/master/docs/USING_ADVANCED.md This example shows how to create a custom CLI script that extends Marked.js with the `marked-custom-heading-id` extension. This allows for custom IDs on headings. ```javascript // file: myMarked #!/usr/bin/node import { marked } from 'marked'; import customHeadingId from 'marked-custom-heading-id'; marked.use(customHeadingId()); import 'marked/bin/marked'; ``` ```shell $ ./myMarked -s "# heading {#custom-id}" ``` ```html

heading

``` -------------------------------- ### Extending Marked with Plugins Source: https://github.com/markedjs/marked/blob/master/test/specs/redos/backticks_in_link_no_close.md Add custom functionality using extensions. This example shows a simple extension to add a custom emoji. ```javascript import { marked } from 'marked'; const emojiExtension = { name: 'emoji', level: 'inline', tokenizer(src) { const emojiRegex = /^:([a-zA-Z0-9]+):/; const match = src.match(emojiRegex); if (match) { return { type: 'emoji', raw: match[0], token: match[1] }; } }, renderer(token) { const emojiMap = { smile: '😊', laugh: '😂' }; return emojiMap[token.token] || token.raw; } }; marked.use({ extensions: [emojiExtension] }); const markdown = 'Hello :smile:'; const html = marked.parse(markdown); // html == 'Hello 😊' ``` -------------------------------- ### Render Full Page Markdown in Browser Source: https://github.com/markedjs/marked/blob/master/docs/USING_ADVANCED.md This example demonstrates how to use Marked.js to parse and render markdown content directly within an HTML page in the browser. It includes setting up the necessary HTML structure, including a textarea for the markdown source and a div for the rendered output, along with the required Marked.js library. ```html Marked for the full page
``` -------------------------------- ### Custom Renderer Source: https://github.com/markedjs/marked/blob/master/test/specs/redos/backticks_in_link_no_close.md Create a custom renderer to override default HTML generation for specific tokens. This example customizes heading rendering. ```javascript import { marked } from 'marked'; const renderer = { heading(text, level) { return `${text} `; } }; marked.use({ renderer }); const markdown = '# Hello world'; const html = marked.parse(markdown); // html == '

Hello world

' ``` -------------------------------- ### Extend Marked.js with New Heading Renderer Extension Source: https://github.com/markedjs/marked/blob/master/docs/USING_PRO.md This example shows an alternative method to extend Marked.js by defining a new renderer within the `extensions` array. This approach avoids directly overriding existing renderers and instead adds a new named extension, which can be useful for modularity. ```javascript marked.use({ extensions: [{ name: 'heading', renderer(token) { return /* ... */ } }] }) ``` -------------------------------- ### Using Marked.js Block Level Tokenizer Methods Source: https://github.com/markedjs/marked/blob/master/docs/USING_PRO.md This example demonstrates how to invoke specific block-level tokenizer methods within a custom Marked.js lexer. These methods take a string input and return the corresponding token object. ```javascript const lexer = new marked.Lexer(); const src = '# Heading\n\nThis is a paragraph.'; // Tokenizing a heading const headingToken = lexer.block.heading(src); // Tokenizing a paragraph const paragraphToken = lexer.block.paragraph('This is a paragraph.'); ``` -------------------------------- ### Marked.js: Custom Description List Extension Source: https://github.com/markedjs/marked/blob/master/docs/USING_PRO.md This JavaScript code defines two custom extensions for Marked.js: `descriptionList` for block-level parsing and `description` for inline parsing. It demonstrates how to create custom tokenizers and renderers to generate HTML `
`, `
`, and `
` tags from a custom syntax. The `descriptionList` extension handles the overall structure, while the `description` extension parses individual term-description pairs. It also shows how to integrate these extensions using `marked.use()` and includes an example of parsing text with the new syntax. ```javascript const descriptionList = { name: 'descriptionList', level: 'block', start(src) { return src.match(/:[^: ]/)?.index; }, tokenizer(src, tokens) { const rule = /^(?::[^: ]+:[^: ]*(?:\n|$))+/; const match = rule.exec(src); if (match) { const token = { type: 'descriptionList', raw: match[0], text: match[0].trim(), tokens: [] }; this.lexer.inline(token.text, token.tokens); return token; } }, renderer(token) { return `
${this.parser.parseInline(token.tokens)}\n
`; } }; const description = { name: 'description', level: 'inline', start(src) { return src.match(/:/)?.index; }, tokenizer(src, tokens) { const rule = /^:([^:\n]+):([^:\n]*)(?:\n|$)/; const match = rule.exec(src); if (match) { return { type: 'description', raw: match[0], dt: this.lexer.inlineTokens(match[1].trim()), dd: this.lexer.inlineTokens(match[2].trim()) }; } }, renderer(token) { return `\n
${this.parser.parseInline(token.dt)}
${this.parser.parseInline(token.dd)}
`; }, childTokens: ['dt', 'dd'], }; function walkTokens(token) { if (token.type === 'strong') { token.text += ' walked'; token.tokens = this.Lexer.lexInline(token.text) } } marked.use({ extensions: [descriptionList, description], walkTokens }); console.log(marked.parse('A Description List:\n' + ': Topic 1 : Description 1\n' + ': **Topic 2** : *Description 2*')); ``` -------------------------------- ### Markdown Ordered Lists Source: https://github.com/markedjs/marked/blob/master/test/specs/original/markdown_documentation_syntax.md Illustrates the creation of ordered lists using numbers followed by periods. The actual numbers used in the Markdown source do not affect the HTML output, but starting with '1' is recommended. ```markdown 1. Bird 2. McHale 3. Parish ``` ```markdown 1. Bird 1. McHale 1. Parish ``` ```markdown 3. Bird 1. McHale 8. Parish ``` -------------------------------- ### Markdown Blockquote Syntax Source: https://github.com/markedjs/marked/blob/master/test/specs/original/markdown_documentation_syntax.html Demonstrates the basic syntax for creating Markdown blockquotes using the '>' character. This includes examples of quoting multi-line paragraphs and lazy quoting where '>' is only applied to the first line of a paragraph. ```markdown > This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet, > consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus. > Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus. > > Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse > id sem consectetuer libero luctus adipiscing. ``` ```markdown > This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus. > Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse id sem consectetuer libero luctus adipiscing. ``` -------------------------------- ### Render Markdown in Browser with UMD Script Source: https://github.com/markedjs/marked/blob/master/README.md Example of rendering markdown to HTML in a browser using the UMD (Universal Module Definition) build of Marked.js, included via a CDN script tag. ```html Marked in the browser
``` -------------------------------- ### Basic Markdown Rendering with Custom Configuration (CLI) Source: https://github.com/markedjs/marked/blob/master/docs/INDEX.md Demonstrates how to use Marked.js via the command-line interface with a custom configuration file to enable line breaks. ```bash echo '{ "breaks": true }' > config.json marked -s 'line1\nline2' -c config.json ``` -------------------------------- ### Display Marked CLI Help Source: https://github.com/markedjs/marked/blob/master/README.md Command to display all available options and help information for the Marked CLI. ```bash # Print all options $ marked --help ``` -------------------------------- ### Marked Instance Creation Source: https://github.com/markedjs/marked/blob/master/docs/USING_ADVANCED.md Demonstrates how to create a new instance of Marked to manage options and extensions locally, avoiding global scope mutation. This is useful for isolating configurations in different parts of an application. ```APIDOC ## Marked Instance Creation By default, Marked stores options and extensions in the global scope. To avoid mutating the global scope and ensure options and extensions are locally scoped, create a new instance of Marked. ### Usage ```js import { Marked } from 'marked'; const marked = new Marked([options, extension, ...]); ``` ### Arguments #### Options - **options** (`object`) - The same arguments that can be passed to [`marked.use`](/using_pro#use). **Note:** `marked.use(...)` should only be used directly after `new Marked` is created or `marked` is imported, and not within loops or functions. ``` -------------------------------- ### Create Headers, Paragraphs, and Blockquotes Source: https://github.com/markedjs/marked/blob/master/test/specs/original/markdown_documentation_basics.html Demonstrates how to create Setext and atx-style headers, standard paragraphs, and blockquotes using Markdown syntax. ```markdown A First Level Header ==================== A Second Level Header --------------------- Now is the time for all good men to come to the aid of their country. This is just a regular paragraph. The quick brown fox jumped over the lazy dog's back. ### Header 3 > This is a blockquote. > > This is the second paragraph in the blockquote. > > ## This is an H2 in a blockquote ``` ```html

A First Level Header

A Second Level Header

Now is the time for all good men to come to the aid of their country. This is just a regular paragraph.

The quick brown fox jumped over the lazy dog's back.

Header 3

This is a blockquote.

This is the second paragraph in the blockquote.

This is an H2 in a blockquote

``` -------------------------------- ### Create Inline and Reference Links in Markdown Source: https://github.com/markedjs/marked/blob/master/test/specs/original/markdown_documentation_basics.html Demonstrates how to create links using inline syntax with optional titles and reference-style syntax for cleaner document management. ```markdown This is an [example link](http://example.com/ "With a Title"). I get 10 times more traffic from [Google][1] than from [Yahoo][2]. [1]: http://google.com/ "Google" [2]: http://search.yahoo.com/ "Yahoo Search" ``` -------------------------------- ### Parse Markdown with Custom Options and Reference Instance Source: https://github.com/markedjs/marked/blob/master/docs/USING_ADVANCED.md Demonstrates setting specific options like `async`, `pedantic`, and `gfm` on a Marked instance before parsing Markdown. The `marked.use` method configures the instance, and `marked.parse` is then called to compile the markdownString. ```javascript // Create reference instance import { marked } from 'marked'; // Set options marked.use({ async: true, pedantic: false, gfm: true, }); // Compile console.log(marked.parse(markdownString)); ``` -------------------------------- ### Basic Marked.js Configuration with marked.use() Source: https://github.com/markedjs/marked/blob/master/docs/USING_PRO.md Shows the fundamental usage of `marked.use()` to configure Marked.js with basic options like `pedantic`, `gfm`, and `breaks`. This method is the primary way to apply extensions and settings. ```javascript import { marked } from 'marked'; marked.use({ pedantic: false, gfm: true, breaks: false }); ``` -------------------------------- ### Create Unordered and Ordered Lists Source: https://github.com/markedjs/marked/blob/master/test/specs/original/markdown_documentation_basics.html Demonstrates the creation of bulleted lists using various markers and numbered lists, including multi-paragraph list items. ```markdown * Candy. * Gum. * Booze. 1. Red 2. Green 3. Blue * A list item. With multiple paragraphs. * Another item in the list. ``` ```html
  1. Red
  2. Green
  3. Blue
``` -------------------------------- ### Parse Markdown Programmatically Source: https://github.com/markedjs/marked/blob/master/man/marked.1.md Shows how to initialize the Marked class with custom configurations and parse a Markdown string into HTML within a JavaScript environment. ```js import { Marked } from 'marked'; const marked = new Marked({ gfm: true }); marked.parse('*foo*'); ``` -------------------------------- ### Applying Marked Extensions and Custom Syntax Source: https://github.com/markedjs/marked/blob/master/docs/USING_PRO.md Demonstrates how to use `marked.use()` to apply a Marked Extension, which can include renderer and tokenizer overrides, as well as custom syntax extensions. Custom extensions define specific patterns for tokenization and rendering. ```javascript marked.use({ gfm: true, breaks: false, renderer: { /* renderer overrides */ }, tokenizer: { /* tokenizer overrides */ }, // Custom Extensions (TokenizerAndRendererExtension[]) extensions: [ { name: 'myCustomSyntax', level: 'block', tokenizer: fn, renderer: fn } ] }); ``` -------------------------------- ### Configuring Marked with Options Object Source: https://github.com/markedjs/marked/blob/master/test/specs/redos/backticks_in_link_no_close.md Pass an options object to marked.use() to configure global settings like the renderer, extensions, and more. ```javascript import { marked } from 'marked'; const options = { async: true, // Enable async rendering pedantic: false, // Don't be overly strict gfm: true, // Enable GitHub Flavored Markdown breaks: false, // Don't add
for single newlines // Add custom renderer or extensions here }; marked.use(options); const markdown = 'A list:\n* Item 1\n* Item 2'; marked.parse(markdown).then(html => { console.log(html); // Output:

A list:

}); ``` -------------------------------- ### Creating Inline Markdown Links Source: https://github.com/markedjs/marked/blob/master/test/specs/original/markdown_documentation_syntax.html Demonstrates how to create links by placing the URL and optional title in parentheses immediately following the link text in square brackets. ```markdown This is [an example](http://example.com/ "Title") inline link. [This link](http://example.net/) has no title attribute. See my [About](/about/) page for details. ``` -------------------------------- ### Embed Images via Inline and Reference Syntax Source: https://github.com/markedjs/marked/blob/master/test/specs/original/markdown_documentation_syntax.html Illustrates how to insert images using inline syntax with alt text and optional titles, as well as reference-style syntax for cleaner document structure. ```markdown ![Alt text](/path/to/img.jpg) ![Alt text](/path/to/img.jpg "Optional title") ![Alt text][id] [id]: url/to/image "Optional title attribute" ``` -------------------------------- ### Nested HTML Structure Source: https://github.com/markedjs/marked/blob/master/test/specs/original/inline_html_simple.md Example of nested HTML elements. Marked.js supports rendering complex, nested HTML structures. ```html
foo
``` -------------------------------- ### Build Marked Project Versions Source: https://github.com/markedjs/marked/blob/master/docs/CONTRIBUTING.md Builds the es5, esm, and minified versions of the Marked library. This script is essential for generating distributable code. ```bash npm run build ``` -------------------------------- ### GFM Horizontal Rule Example Source: https://github.com/markedjs/marked/blob/master/test/specs/new/toplevel_paragraphs.md Shows a horizontal rule using asterisks. This is a standard Markdown feature often supported by GFM. ```markdown * * * ``` -------------------------------- ### Convert Markdown via CLI Source: https://github.com/markedjs/marked/blob/master/man/marked.1.md Demonstrates how to use the marked CLI to parse Markdown files or strings into HTML. These commands support piping input, specifying output files, and enabling GFM features. ```sh cat in.md | marked > out.html ``` ```sh echo "hello *world*" | marked ``` ```sh marked -o out.html -i in.md --gfm ``` ```sh marked --output="hello world.html" -i in.md --no-breaks ``` -------------------------------- ### Modify Tokens with walkTokens Source: https://github.com/markedjs/marked/blob/master/docs/USING_PRO.md Demonstrates how to use the walkTokens hook to traverse and modify the token tree. In this example, heading depths are incremented to shift h1 to h2. ```javascript import { marked } from 'marked'; const walkTokens = (token) => { if (token.type === 'heading') { token.depth += 1; } }; marked.use({ walkTokens }); console.log(marked.parse('# heading 2\n\n## heading 3')); ``` -------------------------------- ### Run Marked Project Tests Source: https://github.com/markedjs/marked/blob/master/docs/CONTRIBUTING.md Executes the test suite for the Marked project using the NPM test script. This is a standard command for verifying the project's functionality. ```bash npm test ``` -------------------------------- ### Parse Markdown in Node.js Source: https://github.com/markedjs/marked/blob/master/README.md Example of parsing markdown text to HTML using the Marked.js library within a Node.js environment. Requires importing the 'marked' object. ```javascript import { marked } from 'marked'; const html = marked.parse('# Marked in Node.js'); console.log(html); ``` -------------------------------- ### Custom Lexing and Token Processing Source: https://github.com/markedjs/marked/blob/master/docs/USING_PRO.md Demonstrates using processAllTokens and provideLexer to persist reference links across multiple parsing calls. ```javascript import { marked, Lexer } from 'marked'; let refLinks = {}; function processAllTokens(tokens) { refLinks = tokens.links; return tokens; } function provideLexer(src, options) { return (src, options) => { const lexer = new Lexer(options); lexer.tokens.links = refLinks; return this.block ? lexer.lex(src) : lexer.inlineTokens(src); }; } marked.use({ hooks: { processAllTokens, provideLexer } }); marked.parse('[test]: http://example.com'); console.log(marked.parse('[test link][test]')); ``` -------------------------------- ### Applying Multiple Marked Extensions Source: https://github.com/markedjs/marked/blob/master/docs/USING_PRO.md Illustrates how to apply multiple extension objects to Marked.js simultaneously using `marked.use()`. This is equivalent to calling `marked.use()` for each extension individually. ```javascript marked.use(myExtension, extension2, extension3); // EQUIVALENT TO: marked.use(myExtension); marked.use(extension2); marked.use(extension3); ``` -------------------------------- ### Assign constant integer value in JavaScript Source: https://github.com/markedjs/marked/blob/master/test/specs/new/code_consistent_newline.md This snippet demonstrates the assignment of a numeric literal to a constant variable. It is a basic example of JavaScript syntax used within the project. ```javascript const value = 42; ``` -------------------------------- ### Apply Emphasis Styles Source: https://github.com/markedjs/marked/blob/master/test/specs/original/markdown_documentation_syntax.html Demonstrates how to use asterisks and underscores to generate HTML emphasis (em) and strong tags. It also shows how to escape literal characters using backslashes. ```markdown *single asterisks* _single underscores_ **double asterisks** __double underscores__ \*this text is surrounded by literal asterisks\* ``` -------------------------------- ### String Overlaying: OVERLAY Source: https://github.com/markedjs/marked/blob/master/test/specs/redos/link_code.html The OVERLAY function overlays a new string onto an old string starting at a specified position for a given length. Padding is applied if necessary. ```JavaScript OVERLAY(new, old[, start][, length][, pad]) OVERLAY("4", "123", 5, 5) == "123-4----" ``` -------------------------------- ### Markdown Escaping Ordered List Trigger Source: https://github.com/markedjs/marked/blob/master/test/specs/original/markdown_documentation_syntax.html Shows how to prevent accidental triggering of an ordered list when a line starts with a number followed by a period and space, by escaping the period with a backslash. ```markdown 1986\. What a great season. ``` -------------------------------- ### Markdown Headers, Paragraphs, and Blockquotes Source: https://github.com/markedjs/marked/blob/master/test/specs/original/markdown_documentation_basics.md Demonstrates the syntax for Setext and atx-style headers, standard paragraphs, and nested blockquotes with their resulting HTML structure. ```markdown A First Level Header ==================== A Second Level Header --------------------- Now is the time for all good men to come to the aid of their country. This is just a regular paragraph. ### Header 3 > This is a blockquote. > ## This is an H2 in a blockquote ``` ```html

A First Level Header

A Second Level Header

Now is the time for all good men to come to the aid of their country. This is just a regular paragraph.

Header 3

This is a blockquote.

This is an H2 in a blockquote

``` -------------------------------- ### Markdown Unordered Lists Source: https://github.com/markedjs/marked/blob/master/test/specs/original/markdown_documentation_syntax.md Demonstrates the creation of unordered lists using asterisks, pluses, and hyphens as list markers. These markers are interchangeable and produce the same HTML output. ```markdown * Red * Green * Blue ``` ```markdown + Red + Green + Blue ``` ```markdown - Red - Green - Blue ``` -------------------------------- ### Render HTML Code Blocks in Marked.js Source: https://github.com/markedjs/marked/blob/master/test/specs/original/inline_html_simple.html Marked.js interprets indented blocks as code blocks, rendering them as preformatted text. This example shows how HTML content within such blocks is handled. ```html
foo
``` ```html
foo
``` -------------------------------- ### Invalid Backtick Fence Usage Source: https://github.com/markedjs/marked/blob/master/test/specs/new/fences_breaking_paragraphs.html This example shows an invalid use of backtick fences with tildes. Marked.js may not interpret this as a standard code block, depending on its parsing rules for malformed fences. ```plaintext ~D` Invalid use of backtick fences This will be read as part of a codeblock that ends with the file ``` -------------------------------- ### Apply Phrase Emphasis Source: https://github.com/markedjs/marked/blob/master/test/specs/original/markdown_documentation_basics.html Shows how to apply emphasis and strong emphasis using asterisks or underscores. ```markdown Some of these words *are emphasized*. Some of these words _are emphasized also_. Use two asterisks for **strong emphasis**. Or, if you prefer, __use two underscores instead__. ``` ```html

Some of these words are emphasized. Some of these words are emphasized also.

Use two asterisks for strong emphasis. Or, if you prefer, use two underscores instead.

``` -------------------------------- ### Render Markdown Heading Source: https://github.com/markedjs/marked/blob/master/test/specs/new/tasklist_blocks.md Demonstrates the rendering of a Markdown heading. ```markdown # heading ``` -------------------------------- ### Render Horizontal Rules in Marked.js Source: https://github.com/markedjs/marked/blob/master/test/specs/original/inline_html_simple.html Marked.js supports the rendering of horizontal rules using asterisks or hyphens. This example shows the common markdown syntax for creating horizontal rules, which are rendered as `
` tags. ```markdown * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ``` -------------------------------- ### Markdown Link Syntax Source: https://github.com/markedjs/marked/blob/master/test/specs/original/markdown_documentation_syntax.md Demonstrates different ways to create links in Markdown, including reference-style and inline styles. Reference-style links improve document readability by separating link metadata from the text. ```Markdown I get 10 times more traffic from [Google][1] than from [Yahoo][2] or [MSN][3]. [1]: http://google.com/ "Google" [2]: http://search.yahoo.com/ "Yahoo Search" [3]: http://search.msn.com/ "MSN Search" ``` ```Markdown I get 10 times more traffic from [Google][] than from [Yahoo][] or [MSN][]. [google]: http://google.com/ "Google" [yahoo]: http://search.yahoo.com/ "Yahoo Search" [msn]: http://msn.com/ "MSN Search" ``` ```Markdown I get 10 times more traffic from [Google](http://google.com/ "Google") than from [Yahoo](http://search.yahoo.com/ "Yahoo Search") or [MSN](http://search.msn.com/ "MSN Search"). ``` -------------------------------- ### Preprocess Markdown with Hooks Source: https://github.com/markedjs/marked/blob/master/docs/USING_PRO.md Shows how to use the preprocess hook to extract front-matter attributes and apply them to the marked options before parsing. ```javascript import { marked } from 'marked'; import fm from 'front-matter'; function preprocess(markdown) { const { attributes, body } = fm(markdown); for (const prop in attributes) { if (prop in this.options) { this.options[prop] = attributes[prop]; } } return body; } marked.use({ hooks: { preprocess } }); console.log(marked.parse('---\nbreaks: true\n---\n\nline1\nline2'.trim())); ``` -------------------------------- ### String Overlay Function (OVERLAY) Source: https://github.com/markedjs/marked/blob/master/test/specs/redos/link_code.md The OVERLAY function replaces a portion of an old string with a new string, starting at a specified position and for a given length. It supports padding if the new string is shorter than the specified length. ```JavaScript OVERLAY("4", "123", 5, 5) == "123-4----" ``` -------------------------------- ### Remove Zero-Width Characters Before Parsing Source: https://github.com/markedjs/marked/blob/master/docs/INDEX.md Removes common zero-width Unicode characters from the beginning of a string before parsing it with Marked.js. This addresses potential parsing issues caused by hidden characters, often found at the start of files. ```javascript // remove the most common zerowidth characters from the start of the file marked.parse( contents.replace(/^[​‌‍‎‏]/,"") ) ``` -------------------------------- ### Render Markdown in Browser with ESM Module Source: https://github.com/markedjs/marked/blob/master/README.md Example of rendering markdown to HTML in a browser using the ESM (ECMAScript Module) build of Marked.js, imported directly via a script tag with type="module". ```html ``` -------------------------------- ### Render Markdown List Source: https://github.com/markedjs/marked/blob/master/test/specs/new/tasklist_blocks.md Demonstrates the rendering of a Markdown list. ```markdown - list ``` -------------------------------- ### String Searching: INDEX and POS Source: https://github.com/markedjs/marked/blob/master/test/specs/redos/link_code.html The INDEX and POS functions search for the first occurrence of a pattern within a string. They can optionally start the search from a specified position. The LASTPOS function searches backwards for the last occurrence of a pattern. ```JavaScript INDEX("123123", "23", 3) == 5 POS("123123", "23", 3) == 5 LASTPOS("123123", "23", 4) == 2 ``` -------------------------------- ### Async Marked Processing with WalkTokens Source: https://github.com/markedjs/marked/blob/master/docs/USING_PRO.md Demonstrates how to use the `async: true` option in Marked.js to enable asynchronous processing, particularly useful for `walkTokens` functions that perform I/O operations like fetching URLs. This allows for awaiting asynchronous tasks before the final HTML is generated. ```javascript const walkTokens = async (token) => { if (token.type === 'link') { try { await fetch(token.href); } catch (ex) { token.title = 'invalid'; } } }; marked.use({ walkTokens, async: true }); const markdown = ` [valid link](https://example.com) [invalid link](https://invalidurl.com) `; const html = await marked.parse(markdown); ``` ```javascript const importUrl = { extensions: [{ name: 'importUrl', level: 'block', start(src) { return src.indexOf('\n:'); }, tokenizer(src) { const rule = /^:(https?:\/\/.+?):/; const match = rule.exec(src); if (match) { return { type: 'importUrl', raw: match[0], url: match[1], html: '' // will be replaced in walkTokens }; } }, renderer(token) { return token.html; } }], async: true, // needed to tell marked to return a promise async walkTokens(token) { if (token.type === 'importUrl') { const res = await fetch(token.url); token.html = await res.text(); } } }; marked.use(importUrl); const markdown = ` # example.com :https://example.com: `; const html = await marked.parse(markdown); ``` -------------------------------- ### Basic HTML Block Source: https://github.com/markedjs/marked/blob/master/test/specs/original/inline_html_simple.md Demonstrates a simple HTML block. Marked.js preserves basic HTML structures. ```html
foo
``` -------------------------------- ### String Searching Functions (INDEX, LASTPOS, POS) Source: https://github.com/markedjs/marked/blob/master/test/specs/redos/link_code.md These functions search for occurrences of a pattern within a string. INDEX and POS find the first occurrence, while LASTPOS searches backward from a specified position. They support an optional starting position for the search. ```JavaScript INDEX("123123", "23", 3) == 5 LASTPOS("123123", "23", 4) == 2 POS("123123", "23", 0) == 1 ``` -------------------------------- ### String Insertion: INSERT Source: https://github.com/markedjs/marked/blob/master/test/specs/redos/link_code.html The INSERT function inserts a new string into an old string at a specified position. The new string can be truncated or padded to a specified length. If the start position is beyond the end of the old string, the old string will be padded. ```JavaScript INSERT(new, old[, start][, length][, pad]) ``` -------------------------------- ### Create a New Marked Instance Source: https://github.com/markedjs/marked/blob/master/docs/USING_ADVANCED.md Create a new instance of Marked to ensure options and extensions are locally scoped, preventing mutation of the global scope. This is useful when you need isolated configurations. ```javascript import { Marked } from 'marked'; const marked = new Marked([options, extension, ...]); ``` -------------------------------- ### Node Worker Thread for Marked Parsing Source: https://github.com/markedjs/marked/blob/master/docs/USING_ADVANCED.md This example shows how to run Marked.js parsing in a Node.js worker thread to prevent ReDoS attacks. The worker thread receives markdown strings and posts back the HTML output. The main thread manages the worker, including setting a timeout to terminate it if parsing takes too long. ```js // markedWorker.js import { marked } from 'marked'; import { parentPort } from 'worker_threads'; parentPort.on('message', (markdownString) => { parentPort.postMessage(marked.parse(markdownString)); }); ``` ```js // index.js import { Worker } from 'worker_threads'; const markedWorker = new Worker('./markedWorker.js'); const markedTimeout = setTimeout(() => { markedWorker.terminate(); throw new Error('Marked took too long!'); }, timeoutLimit); markedWorker.on('message', (html) => { clearTimeout(markedTimeout); console.log(html); markedWorker.terminate(); }); markedWorker.postMessage(markdownString); ``` -------------------------------- ### Theme Preference Logic Source: https://github.com/markedjs/marked/blob/master/docs/_document.html Handles theme preference (dark, light, system) by checking localStorage and system settings. Adds 'dark' class to documentElement if dark theme is preferred. ```javascript function () { try { var STORAGE_KEY = "theme-preference"; var LEGACY_KEY = "theme"; var stored = localStorage.getItem(STORAGE_KEY) || localStorage.getItem(LEGACY_KEY); var preference = stored === "dark" || stored === "light" || stored === "system" ? stored : "system"; var prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches; var shouldUseDark = prefersDark; if (preference === "dark") { shouldUseDark = true; } else if (preference === "light") { shouldUseDark = false; } if (shouldUseDark) { document.documentElement.classList.add("dark"); } else { document.documentElement.classList.remove("dark"); } document.documentElement.setAttribute("data-theme-preference", preference); document.documentElement.setAttribute( "data-theme", shouldUseDark ? "dark" : "light", ); localStorage.setItem(STORAGE_KEY, preference); if (preference === "system") { localStorage.removeItem(LEGACY_KEY); } else { localStorage.setItem(LEGACY_KEY, preference); } } catch (e) {} }() ``` -------------------------------- ### Benchmark Marked vs. Other Markdown Libraries Source: https://github.com/markedjs/marked/blob/master/docs/CONTRIBUTING.md Initiates a benchmarking process to compare the performance of Marked against other popular Markdown libraries. This script helps in understanding Marked's efficiency. ```bash npm run bench ``` -------------------------------- ### Direct Lexer and Parser Access Source: https://github.com/markedjs/marked/blob/master/docs/USING_PRO.md Shows how to directly access and utilize the lexer and parser components of Marked.js. This allows for tokenizing Markdown strings into an abstract syntax tree (AST) and then parsing these tokens into HTML, offering granular control over the conversion process. ```javascript const tokens = marked.lexer(markdown, options); console.log(marked.parser(tokens, options)); ``` ```javascript const lexer = new marked.Lexer(options); const tokens = lexer.lex(markdown); console.log(tokens); console.log(lexer.tokenizer.rules.block); // block level rules used console.log(lexer.tokenizer.rules.inline); // inline level rules used console.log(marked.Lexer.rules.block); // all block level rules console.log(marked.Lexer.rules.inline); // all inline level rules ``` ```javascript import { marked } from 'marked'; const md = ` # heading [link][1] [1]: #heading "heading" `; const tokens = marked.lexer(md); console.log(tokens); const html = marked.parser(tokens); console.log(html); ``` -------------------------------- ### Define Markdown Headings Source: https://github.com/markedjs/marked/blob/master/test/specs/new/paragraph-after-list-item.html Demonstrates the use of Setext-style headings in Markdown. These are created by underlining text with equals signs. ```markdown heading ======= ``` -------------------------------- ### Markdown Unordered Lists Source: https://github.com/markedjs/marked/blob/master/test/specs/original/markdown_documentation_syntax.html Demonstrates the creation of unordered lists using asterisks, pluses, and hyphens as markers. Markdown allows interchangeable use of these symbols for bulleted lists. ```markdown * Red * Green * Blue ``` ```markdown + Red + Green + Blue ``` ```markdown - Red - Green - Blue ``` -------------------------------- ### Markdown Ordered Lists Source: https://github.com/markedjs/marked/blob/master/test/specs/original/markdown_documentation_syntax.html Illustrates how to create ordered lists using numbers followed by periods. The actual numbers used in the Markdown source do not affect the HTML output, which will be sequentially numbered. ```markdown 1. Bird 2. McHale 3. Parish ``` ```markdown 1. Bird 1. McHale 1. Parish ``` ```markdown 3. Bird 1. McHale 8. Parish ``` -------------------------------- ### Using Implicit Link Name Shortcuts Source: https://github.com/markedjs/marked/blob/master/test/specs/original/markdown_documentation_syntax.html Explains the implicit link shortcut which allows the link text itself to serve as the reference label by using empty square brackets. ```markdown Visit [Daring Fireball][] for more information. [Daring Fireball]: http://daringfireball.net/ ``` -------------------------------- ### Render Markdown Table Source: https://github.com/markedjs/marked/blob/master/test/specs/new/tasklist_blocks.md Demonstrates the rendering of a Markdown table. ```markdown | a | b | |---|---| | 1 | 1 | ``` -------------------------------- ### The `parse` function Source: https://github.com/markedjs/marked/blob/master/docs/USING_ADVANCED.md Explains how to use the `parse` function to convert markdown strings into HTML. It details the function's arguments, including the markdown string and an optional options object. ```APIDOC ## The `parse` function Compiles a markdown string into HTML. ### Usage ```js import { marked } from 'marked'; marked.parse(markdownString [,options]); ``` ### Arguments #### markdownString - **markdownString** (`string`) - String of markdown source to be compiled. #### options - **options** (`object`) - Hash of options. Can also use `marked.use` to set global options. ### Alternative using reference ```js // Create reference instance import { marked } from 'marked'; // Set options marked.use({ async: true, pedantic: false, gfm: true, }); // Compile console.log(marked.parse(markdownString)); ``` ``` -------------------------------- ### Basic Markdown Parsing Source: https://github.com/markedjs/marked/blob/master/test/specs/new/toplevel_paragraphs.html This snippet demonstrates basic Markdown parsing. Ensure Marked.js is included in your project. ```javascript const marked = require('marked'); const html = marked.parse('## Hello World\n\nThis is *markdown*.'); console.log(html); ``` -------------------------------- ### HTML Tag Handling Comparison (markdown.js vs. marked) Source: https://github.com/markedjs/marked/blob/master/docs/broken.md Shows the difference in how markdown.js and marked render raw HTML tags. Marked attempts to render them directly, while markdown.js escapes them. ```bash $ markdown.js
hello
hello ^D

<div>hello</div>

<span>hello</span>

``` ```bash $ marked
hello
hello ^D
hello

hello

```