marked Documentation

A markdown parser and compiler. Built for speed.

37,242 stars JavaScript JavaScript 12 files ยท ~23,919 tokens #commonmark#compiler#gfm#hacktoberfest#markdown#parser
RAW Doc

Technical Documentation: markedjs/marked

โ„น๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference

Overview (`README.md`)

Marked






  • โšก built for speed
  • โฌ‡๏ธ low-level compiler for parsing markdown without caching or blocking for long periods of time
  • โš–๏ธ light-weight while implementing all markdown features from the supported flavors & specifications
  • ๐Ÿ› ๏ธ easily adaptable with custom extensions
  • ๐ŸŒ works in a browser, on a server, or from a command line interface (CLI)

Demo

Check out the demo page to see Marked in action โ›น๏ธ

Docs

Our documentation pages are also rendered using marked ๐Ÿ’ฏ

Also read about:

Compatibility

Node.js: Only current and LTS Node.js versions are supported. End of life Node.js versions may become incompatible with Marked at any point in time.

Browser: Baseline Widely Available

Installation

CLI:

sh
npm install marked

In-browser:

sh
npm install marked

Usage

text
DOMPurify.sanitize(marked.parse(`<img src="x" onerror="alert('not happening')">`));

CLI

bash
# Example with stdin input
$ marked -o hello.html
hello world
^D
$ cat hello.html
<p>hello world</p>
bash
# Print all options
$ marked --help

Node.js

js
import { marked } from 'marked';
const html = marked.parse('# Marked in Node.js');
console.log(html);

Browser

html
<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <title>Marked in the browser</title>
</head>
<body>
  <div id="content"></div>
  <script src="https://cdn.jsdelivr.net/npm/marked/lib/marked.umd.js"></script>
  <script>
    document.getElementById('content').innerHTML =
      marked.parse('# Marked in the browser\n\nRendered by **marked**.');
  </script>
</body>
</html>

or import esm module

html
<script type="module">
  import { marked } from "https://cdn.jsdelivr.net/npm/marked/lib/marked.esm.js";
  document.getElementById('content').innerHTML =
    marked.parse('# Marked in the browser\n\nRendered by **marked**.');
</script>

License

Copyright (c) 2018+, MarkedJS. (MIT License)
Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License)


INDEX (`docs/INDEX.md`)

Marked is

  1. built for speed.*
  2. a low-level markdown compiler for parsing markdown without caching or blocking for long periods of time.**
  3. light-weight while implementing all markdown features from the supported flavors & specifications.***
  4. easily adaptable with custom extensions.
  5. available as a command line interface (CLI) and running in client- or server-side JavaScript projects.

Still working on metrics for comparative analysis and definition.
Zero dependencies.
Strict compliance could result in slower processing when running comparative benchmarking.

Demo

Checkout the demo page to see marked in action โ›น๏ธ

These documentation pages are also rendered using marked ๐Ÿ’ฏ

Installation

CLI: npm install marked

In-browser:

text
npm install marked

Usage

text
DOMPurify.sanitize(marked.parse(`<img src="x" onerror="alert('not happening')">`));

โš ๏ธ Input: special ZERO WIDTH unicode characters (for example \uFEFF) might interfere with parsing. Some text editors add them at the start of the file (see: #2139).

js
// remove the most common zerowidth characters from the start of the file
marked.parse(
  contents.replace(/^[\u200B\u200C\u200D\u200E\u200F\uFEFF]/,"")
)

CLI

bash
# Example with stdin input
$ marked -o hello.html
hello world
^D
$ cat hello.html
<p>hello world</p>
bash
# Example with string input
$ marked -s "*hello world*"
<p><em>hello world</em></p>
bash
# Example with file input

echo "**bold text example**" > readme.md

$ marked -i readme.md -o readme.html
$ cat readme.html
<p><strong>bold text example</strong></p>
bash
# Print all options
$ marked --help

CLI Config

A config file can be used to configure the marked cli.

If it is a .json file it should be a JSON object that will be passed to marked as options.

If .js is used it should have a default export of a marked options object or a function that takes marked as a parameter.
It can use the marked parameter to install extensions using marked.use.

By default the marked cli will look for a config file in your home directory in the following order.

  • ~/.marked.json
  • ~/.marked.js
  • ~/.marked/index.js
bash
# Example with custom config

echo '{ "breaks": true }' > config.json

$ marked -s 'line1\nline2' -c config.json
<p>line1<br>line2</p>

Browser

html
<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <title>Marked in the browser</title>
</head>
<body>
  <div id="content"></div>
  <script src="https://cdn.jsdelivr.net/npm/marked/lib/marked.umd.js"></script>
  <script>
    document.getElementById('content').innerHTML =
      marked.parse('# Marked in browser\n\nRendered by **marked**.');
  </script>
</body>
</html>

or import esm module

html
<script type="module">
  import { marked } from "https://cdn.jsdelivr.net/npm/marked/lib/marked.esm.js";
  document.getElementById('content').innerHTML =
    marked.parse('# Marked in the browser\n\nRendered by **marked**.');
</script>

Node.js

js
import { marked } from 'marked';
// or const { marked } = require('marked');

const html = marked.parse('# Marked in Node.js\n\nRendered by **marked**.');

Marked offers advanced configurations and extensibility as well.

Supported Markdown specifications

We actively support the features of the following Markdown flavors.

By supporting the above Markdown flavors, it's possible that Marked can help you use other flavors as well; however, these are not actively supported by the community.

List of Tools Using Marked

We actively support the usability of Marked in super-fast markdown transformation, some of Tools using Marked for single-page creations are

Tools Description
zero-md A native markdown-to-html web component to load and display an external MD file.It uses Marked for super-fast markdown transformation.
texme TeXMe is a lightweight JavaScript utility to create self-rendering Markdown + LaTeX documents.
StrapDown.js StrapDown.js is an awesome on-the-fly Markdown to HTML text processor.
raito Mini Markdown Wiki/CMS in 8kb of JavaScript.
Homebrewery The Homebrewery is a tool for making authentic looking D&D content using Markdown. It is distributed under the terms of the MIT.
marked_reader marked_reader is an open source Markdown reader packed by Electron.
AtlasDocs Free document tools that run entirely in the browser; uses Marked to turn Markdown into HTML, PDF and DOCX without uploading files.

Security

The only completely secure system is the one that doesn't exist in the first place. Having said that, we take the security of Marked very seriously.

Therefore, please disclose potential security issues by email to the project committers as well as the listed owners within NPM. We will provide an initial assessment of security reports within 48 hours and should apply patches within 2 weeks (also, feel free to contribute a fix for the issue).


.Eslintrc.Json (`docs/.eslintrc.json`)

{
"extends": "standard",
"parserOptions": {
"ecmaVersion": 2015,
"sourceType": "script"
},
"rules": {
"semi": ["error", "always"],
"indent": ["error", 2, {
"SwitchCase": 1,
"VariableDeclarator": { "var": 2 },
"outerIIFEBody": 0
}],
"operator-linebreak": ["error", "before", { "overrides": { "=": "after" } }],
"space-before-function-paren": ["error", "never"],
"no-cond-assign": "off",
"no-useless-escape": "off",
"one-var": "off",
"no-control-regex": "off",
"no-prototype-builtins": "off",

text
"prefer-const": "error",
"no-var": "error"

},
"env": {
"node": true,
"browser": true,
"amd": true
}
}


AUTHORS (`docs/AUTHORS.md`)

Authors

Marked takes an encompassing approach to its community. As such, you can think of these as concentric circles, where each group encompasses the following groups.

| Christopher Jeffrey
Original Author
Started the fire | Josh Bruce
Publisher
Release Wrangler; Humaning Helper; Heckler of Hypertext | Steven
Publisher
Release Wrangler; Dr. Docs; Open source, of course; GitHub Guru; Humaning Helper |

| --- | --- | --- |
| Jamie Davis
Committer
Seeker of Security | Tony Brix
Publisher
Release Wrangler; Titan of the test harness; Dr. DevOps | Trevor Buckner
Committer
Master of Marked |

Contributors

| Brandon der Blรคtter
Contributor
Curious Contributor | Carlos Valle
Contributor
Maker of the Marked mark from 2018 to present | Federico Soave
Contributor
Regent of the Regex; Master of Marked | Karen Yavine
Contributor
Snyk's Security Saint |

| --- | --- | --- | --- |
| ะšะพัั‚ั ะขั€ะตั‚ัะบ
Contributor | Tom Theisen
Contributor
Defibrillator | Mateus Craveiro
Contributor
Defibrillator | |

Publishers

Publishers are admins who also have the responsibility, privilege, and burden of publishing the new releases to NPM and performing outreach and external stakeholder communications. Further, when things go pear-shaped, they're the ones taking most of the heat. Finally, when things go well, they're the primary ones praising the contributors who made it possible.

(In other words, while Admins are focused primarily on the internal workings of the project, Publishers are focused on internal and external concerns.)

Should not exceed 2: Having more people with the authority to publish a release can quickly turn into a consensus seeking nightmare (design by committee). Having only one is preferred (Directly Responsible Individual); however, given the nature of the project and its history, having an immediate fallback, and a potential deep fallback (Original author) is probably a good idea.

Details on badges

Admins

Admins are committers who also have the responsibility, privilege, and burden of selecting committers and making sure the project itself runs smoothly, which includes community maintenance, governance, dispute resolution, and so on. (Letting the contributors easily enter into, and work within, the project to begin contributing, with as little friction as possible.)

Should not exceed 3: When there are too many people with the ability to resolve disputes, the dispute itself can quickly turn into a dispute amongst the admins themselves; therefore, we want this group to be small enough to commit to action and large enough to not put too much burden on one person. (Should ensure faster resolution and responsiveness.)

To be listed: Admins are usually selected from the pool of committers (or they volunteer, using the same process) who demonstrate good understanding of the marked culture, operations, and do their best to help new contributors get up to speed on how to contribute effectively to the project.

To be removed: You can remove yourself through the GitHub UI.

Details on badges

Committers

Committers are contributors who also have the responsibility, privilege, some might even say burden of being able to review and merge contributions (just usually not their own).

A note on "decision making authority". This is related to submitting PRs and the advice process. The person marked as having decision making authority over a certain area should be sought for advice in that area before committing to a course of action.

Should not exceed 5: For larger PRs affecting more of the codebase and, most likely, review by more people, we try to keep this pool small and responsive and let those with decision making authority have final say without negative repercussions from the other committers.

To be listed: Committers are usually selected (or they volunteer, using the same process) from contributors who enter the discussions regarding the future direction of Marked (maybe even doing informal reviews of contributions despite not being able to merge them yourself).

To be removed: You can remove yourself through the GitHub UI.

A note on volunteering:

  1. Please do not volunteer unless you believe you can demonstrate to your peers you can do the work required.
  2. Please do not overcommit yourself; we count on those committed to the project to be responsive. Really consider, with all you have going on, whether you able to really commit to it.
  3. Don't let the previous frighten you away, it can always be changed later by you or your peers.

Details on badges

Contributors

Contributors are users who submit a PR, Issue, or collaborate in making Marked a better product and experience for all the users.

To be listed: make a contribution and, if it has significant impact, the committers may be able to add you here.

To be removed: please let us know or submit a PR.

Details on badges

Users

Users are anyone using Marked in some fashion, without them, there's no reason for us to exist.

Individual or Organization Website Project Submitted by
MarkedJS https://marked.js.org https://github.com/markedjs/marked The marked committers

To be listed: All fields are optional. Contact any of the committers or, more timely, submit a pull request with the following (using the first row as an example):

  • Individual or Organization: The name you would like associated with the record.
  • Website: A URL to a standalone website for the project.
  • Project: A URL for the repository of the project using marked.
  • Submitted by: The name and optional honorifics for the person adding the listing.

To be removed: Same as above. Only instead of requesting addition request deletion or delete the row yourself.

Badges

Badges? You don't need no stinkin' badges.

Movie references aside. (It was either that or, "Let's play a game", but that would have been creepy…that's why it will most likely come later.)

Badges? If you want 'em, we got 'em, and here's how you get 'em (and…dramatic pause…why not two dramatic pauses for emphasis?… how they can be taken away).

  • Add the appropriate badge to the desired contributor in the desired column of this page, even if they're not listed here yet.
  • Submit a PR (we're big on PRs around here, if you haven't noticed, help us help you).
  • Follow the instructions for submitting a badge PR. (There are more details to find within. Come on. Everybody likes surprises, right? No? Actually, we just try to put documentation where it belongs, closer to the code and part of the sequence of events.)

Badges at play:

Curious Contributor
A contributor with less than one year on this page who is actively engaged in submitting PRs, Issues, making recommendations, sharing thoughts…without being too annoying about it (let's be clear, submitting 100 Issues recommending the Marked Committers send everyone candy is trying for the badge, not honestly earning it).
Dr. DevOps
Someone who understands and contributes to improving the developer experience and flow of Marked into the world.
text
"The main characteristic of the DevOps movement is to strongly advocate automation and monitoring at all steps of software construction, from integration, testing, releasing to deployment and infrastructure management. DevOps aims at shorter development cycles, increased deployment frequency, more dependable releases, in close alignment with business objectives." ~ [Wikipedia](https://www.wikipedia.org/wiki/DevOps)
	
</dd>
Dr. Docs
Someone who has contributed a great deal to the creation and maintenance of the non-code areas of marked.
Eye for the CLI
At this point? Pretty much anyone who can update that `man` file to the current Marked version without regression in the CLI tool itself.
GitHub Guru
Someone who always seems to be able to tell you easier ways to do things with GitHub.
Humaning Helper
Someone who goes out of their way to help contributors feel welcomed and valued. Further, someone who takes the extra steps(s) necessary to help new contributors get up to speed. Finally, they maintain composure even in times of disagreement and dispute resolution.
Heckler of Hypertext
Someone who demonstrates an esoteric level of knowledge when it comes to HTML. In other words, someone who says things like, "Did you know most Markdown flavors don't have a way to render a description list (`dl`)? All the more reason Markdown `!==` HTML."
Markdown Maestro
You know that person who knows about way too many different flavors of Markdown? The one who maybe seems a little too obsessed with the possibilities of Markdown beyond HTML? Come on. You know who they are. Or, at least you could, if you give them this badge.
Master of Marked
Someone who demonstrates they know the ins and outs of the codebase for Marked.
Open source, of course
Someone who advocates for and has a proven understanding of how to operate within open source communities.
Regent of the Regex
Can you demonstrate you understand the following without Google and Stackoverflow? `/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/` Because this author can't yet. That's who gets these.
Seeker of Security
Someone who has demonstrated a high degree of expertise or authority when it comes to software security.
Titan of the Test Harness
Someone who demonstrates high-levels of understanding regarding Marked's test harness.
Totally Tron
Someone who demonstrates they are willing and able to "fight for the users", both developers dependent on marked to do their jobs as well as end-users interacting with the output (particularly in the realm of those with the disabilities).

Special badges that come with the job:

Defibrillator
A contributor who stepped up to help bring Marked back to life by contributing solutions to help Marked pass when compared against the CommonMark and GitHub Flavored Markdown specifications.
Maker of the Marked mark
This badge is given to the person or organization credited with creating the logo (or logotype) used in Marked communications for a given period of time. **Maker of the Marked mark from 2017 to present**, for example.
Release Wrangler
This is a badge given to all Publishers.
Snyk's Security Saint
This is a badge given to whomever primarily reaches out from Snyk to let us know about security issues.

CODE OF CONDUCT (`docs/CODE_OF_CONDUCT.md`)

Contributor Covenant Code of Conduct

Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.

Our Standards

Examples of behavior that contributes to creating a positive environment
include:

  • Using welcoming and inclusive language
  • Being respectful of differing viewpoints and experiences
  • Gracefully accepting constructive criticism
  • Focusing on what is best for the community
  • Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

  • The use of sexualized language or imagery and unwelcome sexual attention or
    advances
  • Trolling, insulting/derogatory comments, and personal or political attacks
  • Public or private harassment
  • Publishing others' private information, such as a physical or electronic
    address, without explicit permission
  • Other conduct which could reasonably be considered inappropriate in a
    professional setting

Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to block temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team by submitting a PR with changes to the AUTHORS page (or emailing [email protected]). All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

Attribution

This Code of Conduct is adapted from the Contributor Covenant,
version 1.4.


CONTRIBUTING (`docs/CONTRIBUTING.md`)

Contributing to Marked

  • Fork markedjs/marked.
  • Clone the library locally using GitHub Desktop or the command line.
  • Make sure you are on the master branch.
  • Be sure to run npm install or npm update.
  • Create a branch.
  • Update code in src folder. (lib folder is for auto compiled code)
  • Run npm test, fix any broken things (for linting, you can run npm run lint to have the linter fix them for you).
  • Run npm run build:reset to remove changes to compiled files.
  • Submit a Pull Request.

Design principles

Marked tends to favor following the SOLID set of software design and development principles; mainly the single responsibility and open/closed principles:

  • Single responsibility: Marked, and the components of Marked, have the single responsibility of converting Markdown strings into HTML.
  • Open/closed: Marked favors giving developers the means to easily extend the library and its components over changing Marked's behavior through configuration options.

Priorities

We think we have our priorities sorted to build quality in.

The following table lists the ticket type labels we use when there is work to be done on the code either through an Issue or a PR; in priority order.

Ticket type label Description
L0 - security A security vulnerability within the Marked library is discovered.
L1 - broken Valid usage results in incorrect output compared to supported specifications OR causes marked to crash AND there is no known workaround for the issue.
L2 - annoying Similar to L1 - broken only there is a known workaround available for the issue.
RR - refactor and re-engineer Results in an improvement to developers using Marked (improved readability) or end-users (faster performance) or both.
NFS - new feature (spec related) A capability Marked does not currently provide but is in one of the supported specifications
NFU - new feature (user requested) A capability Marked does not currently provide but has been requested by users of Marked.
NFE - new feature (should be an extension) A capability Marked does not currently provide and is not part of a spec.

Test early, often, and everything

We try to write test cases to validate output (writing tests based on the supported specifications) and minimize regression (writing tests for issues fixed). Therefore, if you would like to contribute, some things you should know regarding the test harness.

Location Description
/test/specs/commonmark Tests for CommonMark compliance
/test/specs/gfm Tests for GFM compliance
/test/specs/new Tests not related to the original markdown.pl.
/test/specs/original Tests validating against the original markdown.pl.
/test/specs/redos Tests for ReDOS vulnerabilities

If your test uses features or options, assuming gfm is set to false, for example, you can add front-matter to the top of
your .md file

yml
---
gfm: false
---

Submitting PRs and Issues

Marked provides templates for submitting both pull requests and issues. When you begin creating a new PR or issue, you will see instructions on using the template.

The PR templates include checklists for both the submitter and the reviewer, which, in most cases, will not be the same person.

Scripts

When it comes to NPM commands, we try to use the native scripts provided by the NPM framework.

To run the tests:

bash
npm test

To test whether you are using the standard syntax rules for the project:

bash
npm run test:lint

To see time comparisons between Marked and other popular Markdown libraries:

bash
npm run bench

To see the compiled rules from src/rules.js:

bash
npm run rules

You can specify one or more rule paths to only show certain rules:

bash
npm run rules -- block.gfm.item inline.pedantic.br

{
  block: {
    gfm: {
      item: /^( *)((?:[*+-]|\\d{1,9}\\.)) ?[^\\n]*(?:\\n(?!\\1(?:[*+-]|\\d{1,9}\\.) ?)[^\\n]*)*/gm
    }
  },
  inline: {
    pedantic: {
      br: /^( {2,}|\\\\)\\n(?!\\s*$)/
    }
  }
}

To check for (and fix) standardized syntax (lint):

bash
npm run lint

To build your own es5, esm, and minified versions of Marked:

bash
npm run build

PUBLISHING (`docs/PUBLISHING.md`)

Releasing Marked

Marked uses semantic-release to release new versions. All PRs should use the "Squash and merge" strategy and the commit message should follow the conventional commit guidelines.

Overall strategy

Master is always shippable: We try to merge PRs in such a way that master is the only branch to really be concerned about and master can always be released. This allows smoother flow between new features, bug fixes, and so on.

Versioning

We follow semantic versioning where the following sequence is true [major].[minor].[patch]:

  1. Major: There is at least one change to the public API or a break from the CommonMark or GFM spec. Only current and LTS Node.js versions are supported at any point in time. A drop in support for a Node.js version may not result in a semver major bump to Marked.
  2. Minor: There is at least one new feature added to the public API.
  3. Patch: Changes that move Marked closer to spec compliance or change a public API that does not break backwards compatibility.

USING ADVANCED (`docs/USING_ADVANCED.md`)

Marked instance

By default, Marked stores options and extensions in the global scope. That means changing the options in one script will also change the options in another script since they share the same instance.

If you don't want to mutate global scope, you can create a new instance of Marked to ensure options and extensions are locally scoped.

js
import { Marked } from 'marked';
const marked = new Marked([options, extension, ...]);
Argument Type Notes
options object The same arguments that can be passed to marked.use

Be careful: marked.use(...) should not be used in a loop or function. It should only be used directly after new Marked is created or marked is imported.

The `parse` function

js
import { marked } from 'marked';
marked.parse(markdownString [,options])
Argument Type Notes
markdownString string String of markdown source to be compiled.
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));

Options

Member Type Default Since Notes
async boolean false 4.1.0 If true, walkTokens functions can be async and marked.parse will return a promise that resolves when all walk tokens functions resolve.
breaks boolean false v0.2.7 If true, add `` on a single line break (copies GitHub behavior on comments, but not on rendered markdown files). Requires gfm be true.
gfm boolean true v0.2.1 If true, use approved GitHub Flavored Markdown (GFM) specification.
pedantic boolean false v0.2.1 If true, conform to the original markdown.pl as much as possible. Don't fix original markdown bugs or behavior. Turns off and overrides gfm.
renderer object new Renderer() v0.3.0 An object containing functions to render tokens to HTML. See extensibility for more details.
silent boolean false v0.2.7 If true, the parser does not throw any exception or log any warning. Any error will be returned as a string.
tokenizer object new Tokenizer() v1.0.0 An object containing functions to create tokens from markdown. See extensibility for more details.
walkTokens function null v1.1.0 A function which is called for every token. See extensibility for more details.

Old Options

Member Type Default Since Notes
smartLists (removed) boolean false v0.2.8 Removed in v3.0.0.
baseUrl (removed) string null v0.3.9 Removed in v8.0.0 use marked-base-url to prefix url for any relative link.
headerIds (removed) boolean true v0.4.0 Removed in v8.0.0 use marked-gfm-heading-id to include an id attribute when emitting headings (h1, h2, h3, etc).
headerPrefix (removed) string '' v0.3.0 Removed in v8.0.0 use marked-gfm-heading-id to add a string to prefix the id attribute when emitting headings (h1, h2, h3, etc).
highlight (removed) function null v0.3.0 Removed in v8.0.0 use marked-highlight to add highlighting to code blocks.
langPrefix (removed) string 'language-' v0.3.0 Removed in v8.0.0 use marked-highlight to prefix the className in a <code> block. Useful for syntax highlighting.
mangle (removed) boolean true v0.3.4 Removed in v8.0.0 use marked-mangle to mangle email addresses.
sanitize (removed) boolean false v0.2.1 Removed in v8.0.0 use a sanitize library, like DOMPurify (recommended), sanitize-html or insane on the output HTML!
sanitizer (removed) function null v0.3.4 Removed in v8.0.0 use a sanitize library, like DOMPurify (recommended), sanitize-html or insane on the output HTML!
smartypants (removed) boolean false v0.2.9 Removed in v8.0.0 use marked-smartypants to use "smart" typographic punctuation for things like quotes and dashes.
xhtml (removed) boolean false v0.3.2 Removed in v8.0.0 use marked-xhtml to emit self-closing HTML tags for void elements (<br/>, <img/>, etc.) with a "/" as required by XHTML.

Known Extensions

Marked can be extended using custom extensions. This is a list of extensions that can be used with marked.use(extension).

text
search



close

search_off
No extensions found
Try adjusting your keywords or search term.

Name Package Name Description
ABCjs marked-abc ABCjs sheet music rendering
Admonition marked-admonition-extension Admonition extension
Alert marked-alert Enables GFM alerts
Base URL marked-base-url Prefix relative urls with a base URL
Bidi marked-bidi Add Bidirectional text support to the HTML
CJK Breaks marked-cjk-breaks Suppress soft linebreaks between east asian characters
Code Format marked-code-format Formatting code blocks using Prettier
Code JSX Renderer marked-code-jsx-renderer Render JSX code blocks using a custom renderer and components
Code Preview marked-code-preview Transform code blocks into code previews
Custom Heading ID marked-custom-heading-id Specify a custom heading id in headings with the Markdown Extended Syntax # heading {#custom-id}
Directive marked-directive Supports directives syntax
Emoji marked-emoji Add emoji support like on GitHub
Extended Tables marked-extended-tables Extends the standard Github-Flavored tables to support advanced features: Column Spanning, Row Spanning, Multi-row headers
Footnote marked-footnote Enables GFM footnotes
GFM Heading ID marked-gfm-heading-id Use github-slugger to create the heading IDs and allow a custom prefix
GitLab marked-gitlab Extension for GitLab Flavored Markdown (GLFM)
Highlight marked-highlight Highlight code blocks
HTML Renderer marked-html-renderer Output HTML Elements instead of a string
Jira Renderer marked-jira Output Jira compatible format
Katex Code marked-katex-extension Render katex code
LinkifyIt marked-linkify-it Use linkify-it for urls
Mangle marked-mangle Mangle mailto links with HTML character references
Math @webc.site/math-marked Ultra-lightweight native MathML math rendering extension
Misskey-flavored Markdown marked-mfm Custom extension for Misskey-flavored Markdown
More Lists marked-more-lists Support for alphabetical and roman numeral ordered lists
Plaintify marked-plaintify Converts Markdown to Plaintext
Responsive Images marked-responsive-images Generate responsive (srcset) images based on structured filenames
Shiki marked-shiki Integrating Shiki syntax highlighting
Sequential Hooks marked-sequential-hooks Enables the sequential preprocessing and post-processing within sequential hooks
Smartypants marked-smartypants Use smartypants to use "smart" typographic punctuation for things like quotes and dashes
Smartypants lite marked-smartypants-lite A faster lighter version of marked-smartypants that doesn't use any external dependencies to create "smart" typographic punctuation for things like quotes and dashes
Token Position marked-token-position Adds a position field to each token with start and end properties containing line, column, and offset
Typograf marked-typograf Use typograf as a more powerful and extendable alternative to Smartypants for creating โ€œsmartโ€ typographic punctuation, such as quotes and dashes
XHTML marked-xhtml Emit self-closing HTML tags for void elements (<br/>, <img/>, etc.) with a "/" as required by XHTML

User Examples

Marked can render on-page content as markdown in the browser.

html
<!DOCTYPE html>
<html>
 <head>
   
   <link rel="stylesheet" 
    href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.8.1/github-markdown.min.css"
    crossorigin="anonymous" referrerpolicy="no-referrer" />

   <title>Marked for the full page</title>
 </head>

 <body> 
  <textarea id="markdown-source" style="display: none;">
# Title

Lots of text using **markdown syntax.**
  </textarea>
  <div id="content" class="markdown-body"></div>
  
  <script src="https://cdn.jsdelivr.net/npm/marked/lib/marked.umd.js"></script>
  <script>
    const source = document.getElementById('markdown-source').value;
    
    // Parse the markdown and render it into the content div.
    document.getElementById('content').innerHTML = marked.parse(source);
  </script>
 </body>
</html>

Inline Markdown

You can parse inline markdown by running markdown through marked.parseInline.

js
const blockHtml = marked.parse('**strong** _em_');
console.log(blockHtml); // '<p><strong>strong</strong> <em>em</em></p>'

const inlineHtml = marked.parseInline('**strong** _em_');
console.log(inlineHtml); // '<strong>strong</strong> <em>em</em>'

Highlighting

Use marked-highlight to highlight code blocks.

Workers

To prevent ReDoS attacks you can run marked on a worker and terminate it when parsing takes longer than usual.

Marked can be run in a worker thread on a node server, or a web worker in a browser.

Node Worker Thread

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);

Web Worker

NOTE: Web Workers send the payload from postMessage in an object with the payload in a .data property

js
// markedWorker.js

importScripts('path/to/marked.umd.js');

onmessage = (e) => {
  const markdownString = e.data
  postMessage(marked.parse(markdownString));
};
js
// script.js

const markedWorker = new Worker('./markedWorker.js');

const markedTimeout = setTimeout(() => {
  markedWorker.terminate();
  throw new Error('Marked took too long!');
}, timeoutLimit);

markedWorker.onmessage = (e) => {
  clearTimeout(markedTimeout);
  const html = e.data;
  console.log(html);
  markedWorker.terminate();
};

markedWorker.postMessage(markdownString);

CLI Extensions

You can use extensions in the CLI by creating a new CLI that imports marked and the marked binary.

js
// file: myMarked
#!/usr/bin/node

import { marked } from 'marked';
import customHeadingId from 'marked-custom-heading-id';

marked.use(customHeadingId());

import 'marked/bin/marked';
sh
$ ./myMarked -s "# heading {#custom-id}"
<h1 id="custom-id">heading</h1>

USING PRO (`docs/USING_PRO.md`)

Extending Marked

To champion the single-responsibility and open/closed principles, we have tried to make it relatively painless to extend Marked. If you are looking to add custom functionality, this is the place to start.

Terminology Note

Before diving in, it's important to understand the terminology used in this documentation:

Term TypeScript Type Description
Marked Extension MarkedExtension The configuration object passed to marked.use(). Can contain options, hooks, renderer overrides, tokenizer overrides, and custom extensions.
Custom Extension TokenizerAndRendererExtension Objects within the extensions array that define custom tokenizers and renderers for new syntax.

In other words, a Marked Extension is the top-level plugin configuration, while Custom Extensions are the individual tokenizer/renderer definitions for custom syntax within that configuration.

js
// Marked Extension (MarkedExtension)
marked.use({
  gfm: true,
  breaks: false,
  renderer: { /* renderer overrides */ },
  tokenizer: { /* tokenizer overrides */ },
  // Custom Extensions (TokenizerAndRendererExtension[])
  extensions: [
    { name: 'myCustomSyntax', level: 'block', tokenizer: fn, renderer: fn }
  ]
});

marked.use()

marked.use(extension) is the recommended way to extend Marked. The extension object can contain any option available in Marked:

js
import { marked } from 'marked';

marked.use({
  pedantic: false,
  gfm: true,
  breaks: false
});

You can also supply multiple extension objects at once.

js
marked.use(myExtension, extension2, extension3);

\\ EQUIVALENT TO:

marked.use(myExtension);
marked.use(extension2);
marked.use(extension3);

All options will overwrite those previously set, except for the following options which will be merged with the existing framework and can be used to change or extend the functionality of Marked: renderer, tokenizer, hooks, walkTokens, and extensions.

  • The renderer, tokenizer, and hooks options are objects with functions that will be merged into the built-in renderer and tokenizer respectively.

  • The walkTokens option is a function that will be called to post-process every token before rendering.

  • The extensions option is an array of objects that can contain additional custom renderer and tokenizer steps that will execute before any of the default parsing logic occurs.

Importantly, ensure that the extensions are only added to marked once (ie in the global scope of a regular JavaScript or TypeScript module). If they are added in a function that is called repeatedly, or in the JS for an HTML component in a library such as Svelte, your extensions will be added repeatedly, eventually causing a recursion error. If you cannot prevent the code from being run repeatedly, you should create a Marked instance so that your extensions are stored independently from the global instance Marked provides.


The Marked Pipeline

Before building your custom extensions, it is important to understand the components that Marked uses to translate from Markdown to HTML:

  1. The user supplies Marked with an input string to be translated.
  2. The lexer feeds segments of the input text string into each tokenizer, and from their output, generates a series of tokens in a nested tree structure.
  3. Each tokenizer receives a segment of Markdown text and, if it matches a particular pattern, generates a token object containing any relevant information.
  4. The walkTokens function will traverse every token in the tree and perform any final adjustments to the token contents.
  5. The parser traverses the token tree and feeds each token into the appropriate renderer, and concatenates their outputs into the final HTML result.
  6. Each renderer receives a token and manipulates its contents to generate a segment of HTML.

Marked provides methods for directly overriding the renderer and tokenizer for any existing token type, as well as inserting additional custom renderer and tokenizer functions to handle entirely custom syntax. For example, using marked.use({renderer}) would modify a renderer, whereas marked.use({extensions: [{renderer}]}) would add a new renderer. See the custom extensions example for insight on how to execute this.


The Renderer : `renderer`

The renderer defines the HTML output of a given token. If you supply a renderer in the options object passed to marked.use(), any functions in the object will override the default handling of that token type.

Calling marked.use() to override the same function multiple times will give priority to the version that was assigned last. Overriding functions can return false to fall back to the previous override in the sequence, or resume default behavior if all overrides return false. Returning any other value (including nothing) will prevent fallback behavior.

Example: Overriding output of the default heading token by adding an embedded anchor tag like on GitHub.

js
// Create reference instance
import { marked } from 'marked';

// Override function
const renderer = {
  heading({ tokens, depth }) {
    const text = this.parser.parseInline(tokens);
    const escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');

    return `
            <h${depth}>
              <a name="${escapedText}" class="anchor" href="#${escapedText}">
                <span class="header-link"></span>
              </a>
              ${text}
            </h${depth}>`;
  }
};

marked.use({ renderer });

// Run marked
console.log(marked.parse('# heading+'));

Output:

html
<h1>
  <a name="heading-" class="anchor" href="#heading-">
    <span class="header-link"></span>
  </a>
  heading+
</h1>

Note: Calling marked.use() in the following way will avoid overriding the heading token output but create a new heading renderer in the process.

js
marked.use({
 extensions: [{
    name: 'heading',
    renderer(token) {
      return /* ... */
    }
  }]
})

Block-level renderer methods

  • **space**(token: *Tokens.Space*): *string*
  • **code**(token: *Tokens.Code*): *string*
  • **blockquote**(token: *Tokens.Blockquote*): *string*
  • **html**(token: *Tokens.HTML | Tokens.Tag*): *string*
  • **heading**(token: *Tokens.Heading*): *string*
  • **hr**(token: *Tokens.Hr*): *string*
  • **list**(token: *Tokens.List*): *string*
  • **listitem**(token: *Tokens.ListItem*): *string*
  • **checkbox**(token: *Tokens.Checkbox*): *string*
  • **paragraph**(token: *Tokens.Paragraph*): *string*
  • **table**(token: *Tokens.Table*): *string*
  • **tablerow**(token: *Tokens.TableRow*): *string*
  • **tablecell**(token: *Tokens.TableCell*): *string*

Inline-level renderer methods

  • **strong**(token: *Tokens.Strong*): *string*
  • **em**(token: *Tokens.Em*): *string*
  • **codespan**(token: *Tokens.Codespan*): *string*
  • **br**(token: *Tokens.Br*): *string*
  • **del**(token: *Tokens.Del*): *string*
  • **link**(token: *Tokens.Link*): *string*
  • **image**(token: *Tokens.Image*): *string*
  • **text**(token: *Tokens.Text | Tokens.Escape | Tokens.Tag*): *string*

The Tokens.* properties can be found here.


The Tokenizer : `tokenizer`

The tokenizer defines how to turn markdown text into tokens. If you supply a tokenizer object to the Marked options, it will be merged with the built-in tokenizer and any functions inside will override the default handling of that token type.

Calling marked.use() to override the same function multiple times will give priority to the version that was assigned last. Overriding functions can return false to fall back to the previous override in the sequence, or resume default behavior if all overrides return false. Returning any other value (including nothing) will prevent fallback behavior.

Example: Overriding default codespan tokenizer to include LaTeX.

js
// Create reference instance
import { marked } from 'marked';

// Override function
const tokenizer = {
  codespan(src) {
    const match = src.match(/^\$+([^\$\n]+?)\$+/);
    if (match) {
      return {
        type: 'codespan',
        raw: match[0],
        text: match[1].trim()
      };
    }

    // return false to use original codespan tokenizer
    return false;
  }
};

marked.use({ tokenizer });

// Run marked
console.log(marked.parse('$ latex code $\n\n` other code `'));

Output:

html
<p><code>latex code</code></p>
<p><code>other code</code></p>

NOTE: This does not fully support latex, see issue #1948.

Block level tokenizer methods

  • **space**(src: *string*): *Tokens.Space*
  • **code**(src: *string*): *Tokens.Code*
  • **fences**(src: *string*): *Tokens.Code*
  • **heading**(src: *string*): *Tokens.Heading*
  • **hr**(src: *string*): *Tokens.Hr*
  • **blockquote**(src: *string*): *Tokens.Blockquote*
  • **list**(src: *string*): *Tokens.List*
  • **html**(src: *string*): *Tokens.HTML*
  • **def**(src: *string*): *Tokens.Def*
  • **table**(src: *string*): *Tokens.Table*
  • **lheading**(src: *string*): *Tokens.Heading*
  • **paragraph**(src: *string*): *Tokens.Paragraph*
  • **text**(src: *string*): *Tokens.Text*

Inline level tokenizer methods

  • **escape**(src: *string*): *Tokens.Escape*
  • **tag**(src: *string*): *Tokens.Tag*
  • **link**(src: *string*): *Tokens.Link | Tokens.Image*
  • **reflink**(src: *string*, links: *object*): *Tokens.Link | Tokens.Image | Tokens.Text*
  • **emStrong**(src: *string*, maskedSrc: *string*, prevChar: *string*): *Tokens.Em | Tokens.Strong*
  • **codespan**(src: *string*): *Tokens.Codespan*
  • **br**(src: *string*): *Tokens.Br*
  • **del**(src: *string*): *Tokens.Del*
  • **autolink**(src: *string*): *Tokens.Link*
  • **url**(src: *string*): *Tokens.Link*
  • **inlineText**(src: *string*): *Tokens.Text*

The Tokens.* properties can be found here.


Walk Tokens : `walkTokens`

The walkTokens function gets called with every token. Child tokens are called before moving on to sibling tokens. Each token is passed by reference so updates are persisted when passed to the parser. When async mode is enabled, the return value is awaited. Otherwise the return value is ignored.

marked.use() can be called multiple times with different walkTokens functions. Each function will be called in order, starting with the function that was assigned last.

Example: Overriding heading tokens to start at h2.

js
import { marked } from 'marked';

// Override function
const walkTokens = (token) => {
  if (token.type === 'heading') {
    token.depth += 1;
  }
};

marked.use({ walkTokens });

// Run marked
console.log(marked.parse('# heading 2\n\n## heading 3'));

Output:

html
<h2 id="heading-2">heading 2</h2>
<h3 id="heading-3">heading 3</h3>

Hooks : `hooks`

Hooks are methods that hook into some part of marked. The following hooks are available:

signature description
preprocess(markdown: string): string Process markdown before sending it to marked.
postprocess(html: string): string Process html after marked has finished parsing.
processAllTokens(tokens: Token[]): Token[] Process all tokens before walk tokens.
emStrongMask(src: string): string Mask part of the content that should not be interpreted as Markdown em/strong delimiters.
provideLexer(): (src: string, options?: MarkedOptions) => Token[] Provide function to tokenize markdown.
provideParser(): (tokens: Token[], options?: MarkedOptions) => string Provide function to parse tokens.

marked.use() can be called multiple times with different hooks functions. Each function will be called in order, starting with the function that was assigned last.

Example: Set options based on front-matter

js
import { marked } from 'marked';
import fm from 'front-matter';

// Override function
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 } });

// Run marked
console.log(marked.parse(`
---
breaks: true
---

line1
line2
`.trim()));

Output:

html
<p>line1<br>line2</p>

Example: Sanitize HTML with isomorphic-dompurify

js
import { marked } from 'marked';
import DOMPurify from 'isomorphic-dompurify';

// Override function
function postprocess(html) {
  return DOMPurify.sanitize(html);
}

marked.use({ hooks: { postprocess } });

// Run marked
console.log(marked.parse(`
<img src=x onerror=alert(1)//>
`));

Output:

html
<img src="x">

Example: Save reflinks for chunked rendering

js
import { marked, Lexer } from 'marked';

let refLinks = {};

// Override function
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 } });

// Parse reflinks separately from markdown that uses them
marked.parse(`
[test]: http://example.com
`);

console.log(marked.parse(`
[test link][test]
`));

Output:

html
<p><a href="http://example.com">test link</a></p>

Example: Mask underline characters inside Mathjax content delimited by $

js
import { marked } from 'marked';

// Override function
function emStrongMask(src) {
  return src.replace(/\$([^$]+)\$/g, (match) => `[${'a'.repeat(match.length - 2)}]`);
}

marked.use({ hooks: { emStrongMask } });

console.log(marked.parse(`_The formula is $a_ b=c_ d$._`));

Output:

html
<p><em>The formula is $a_ b=c_ d$.</em></p>

Custom Extensions : `extensions`

You may supply an extensions array to the options object. This array can contain any number of extension objects, using the following properties:

`**name**`
A string used to identify the token that will be handled by this extension.

If the name matches an existing extension name, or an existing method in the tokenizer/renderer methods listed above, they will override the previously assigned behavior, with priority on the extension that was assigned last. An extension can return false to fall back to the previous behavior.

`**level**`
A string to determine when to run the extension tokenizer. Must be equal to 'block' or 'inline'.

A block-level extension will be handled before any of the block-level tokenizer methods listed above, and generally consists of 'container-type' text (paragraphs, tables, blockquotes, etc.).

An inline-level extension will be handled inside each block-level token, before any of the inline-level tokenizer methods listed above. These generally consist of 'style-type' text (italics, bold, etc.).

`**start**(*string* src)`
A function that returns the index of the next potential start of the custom token.

The index can be the result of a src.match().index, or even a simple src.indexOf(). Marked will use this function to ensure that it does not skip over any text that should be part of the custom token.

`**tokenizer**(*string* src, *array* tokens)`
A function that reads string of Markdown text and returns a generated token. The token pattern should be found at the beginning of the `src` string. Accordingly, if using a Regular Expression to detect a token, it should be anchored to the string start (`^`). The `tokens` parameter contains the array of tokens that have been generated by the lexer up to that point, and can be used to access the previous token, for instance.

The return value should be an object with the following parameters:

`**type**`
A string that matches the `name` parameter of the extension.
`**raw**`
A string containing all of the text that this token consumes from the source.
`**tokens** [optional]`
An array of child tokens that will be traversed by the `walkTokens` function by default.

The returned token can also contain any other custom parameters of your choice that your custom renderer might need to access.

The tokenizer function has access to the lexer in the this object, which can be used if any internal section of the string needs to be parsed further, such as in handling any inline syntax on the text within a block token. The key functions that may be useful include:

`**this.lexer.blockTokens**(*string* text, *array* tokens)`
This runs the block tokenizer functions (including any block-level extensions) on the provided text, and appends any resulting tokens onto the `tokens` array. The `tokens` array is also returned by the function. You might use this, for example, if your extension creates a "container"-type token (such as a blockquote) that can potentially include other block-level tokens inside.
`**this.lexer.inline**(*string* text, *array* tokens)`
Parsing of inline-level tokens only occurs after all block-level tokens have been generated. This function adds `text` and `tokens` to a queue to be processed using inline-level tokenizers (including any inline-level extensions) at that later step. Tokens will be generated using the provided `text`, and any resulting tokens will be appended to the `tokens` array. Note that this function does **NOT** return anything since the inline processing cannot happen until the block-level processing is complete.
`**this.lexer.inlineTokens**(*string* text, *array* tokens)`
Sometimes an inline-level token contains further nested inline tokens (such as a `**strong**` token inside of a `### Heading`). This runs the inline tokenizer functions (including any inline-level extensions) on the provided text, and appends any resulting tokens onto the `tokens` array. The `tokens` array is also returned by the function.
`**renderer**(*object* token)`
A function that reads a token and returns the generated HTML output string.

The renderer function has access to the parser in the this object, which can be used if any part of the token needs needs to be parsed further, such as any child tokens. The key functions that may be useful include:

`**this.parser.parse**(*array* tokens)`
Runs the block renderer functions (including any extensions) on the provided array of tokens, and returns the resulting HTML string output. This is used to generate the HTML from any child block-level tokens, for example if your extension is a "container"-type token (such as a blockquote) that can potentially include other block-level tokens inside.
`**this.parser.parseInline**(*array* tokens)`
Runs the inline renderer functions (including any extensions) on the provided array of tokens, and returns the resulting HTML string output. This is used to generate the HTML from any child inline-level tokens.
`**childTokens** [optional]`
An array of strings that match the names of any token parameters that should be traversed by the `walkTokens` functions. For instance, if you want to use a second custom parameter to contain child tokens in addition to `tokens`, it could be listed here. If `childTokens` is provided, the `tokens` array will not be walked by default unless it is also included in the `childTokens` array.

Note: If you would like to release an extension as an npm package you may use the Marked Extension Template which includes all of the things you need to get started. Feel free to create an issue in that repo if you need help.

Example: Add a custom syntax to generate <dl> description lists.

text
/* Detailed source-code truncated for AI context efficiency. */

Output

bash
<p>A Description List:</p>
<dl>
<dt>Topic 1</dt><dd>Description 1</dd>
<dt><strong>Topic 2 walked</strong></dt><dd><em>Description 2</em></dd>
</dl>

Async Marked : `async`

Marked will return a promise if the async option is true. The async option will tell marked to await any walkTokens functions before parsing the tokens and returning an HTML string.

Simple Example:

js
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);

Custom Extension Example:

js
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);

The Lexer

The lexer takes a markdown string and calls the tokenizer functions.

The Parser

The parser takes tokens as input and calls the renderer functions.

Access to Lexer and Parser

You also have direct access to the lexer and parser if you so desire. The lexer and parser options are the same as passed to marked.setOptions() except they have to be full options objects, they don't get merged with the current or default options.

js
const tokens = marked.lexer(markdown, options);
console.log(marked.parser(tokens, options));
js
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

Note that the lexer can be used in two different ways:

  • marked.lexer(): this method tokenizes a string and returns its tokens. Subsequent calls to lexer() ignore any previous calls.
  • new marked.Lexer().lex(): this instance tokenizes a string and returns its tokens along with any previous tokens. Subsequent calls to lex() accumulate tokens.
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: {}
]

The Lexer builds an array of tokens, which will be passed to the Parser.
The Parser processes each token in the token array:

js
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);
bash
[
  {
    type: "heading",
    raw: "  # heading\n\n",
    depth: 1,
    text: "heading",
    tokens: [
      {
        type: "text",
        raw: "heading",
        text: "heading"
      }
    ]
  },
  {
    type: "paragraph",
    raw: "  [link][1]",
    text: "  [link][1]",
    tokens: [
      {
        type: "text",
        raw: "  ",
        text: "  "
      },
      {
        type: "link",
        raw: "[link][1]",
        text: "link",
        href: "#heading",
        title: "heading",
        tokens: [
          {
            type: "text",
            raw: "link",
            text: "link"
          }
        ]
      }
    ]
  },
  {
    type: "space",
    raw: "\n\n"
  },
  links: {
    "1": {
      href: "#heading",
      title: "heading"
    }
  }
]
<h1 id="heading">heading</h1>
<p>  <a href="#heading" title="heading">link</a></p>

Broken (`docs/broken.md`)

Markdown is broken

I have a lot of scraps of markdown engine oddities that I've collected over the
years. What you see below is slightly messy, but it's what I've managed to
cobble together to illustrate the differences between markdown engines, and
why, if there ever is a markdown specification, it has to be absolutely
thorough. There are a lot more of these little differences I have documented
elsewhere. I know I will find them lingering on my disk one day, but until
then, I'll continue to add whatever strange nonsensical things I find.

Some of these examples may only mention a particular engine compared to marked.
However, the examples with markdown.pl could easily be swapped out for
discount, upskirt, or markdown.js, and you would very easily see even more
inconsistencies.

A lot of this was written when I was very unsatisfied with the inconsistencies
between markdown engines. Please excuse the frustration noticeable in my
writing.

Examples of markdown's "stupid" list parsing

text
$ markdown.pl

  * item1

    * item2

  text
^D
<ul>
<li><p>item1</p>

<ul>
<li>item2</li>
</ul>

<p><p>text</p></li>
</ul></p>
text
$ marked
  * item1

    * item2

  text
^D
<ul>
<li><p>item1</p>
<ul>
<li>item2</li>
</ul>
<p>text</p>
</li>
</ul>

Which looks correct to you?


text
$ markdown.pl
* hello
  > world
^D
<p><ul>
<li>hello</p>

<blockquote>
  <p>world</li>
</ul></p>
</blockquote>
text
$ marked
* hello
  > world
^D
<ul>
<li>hello<blockquote>
<p>world</p>
</blockquote>
</li>
</ul>

Again, which looks correct to you?


EXAMPLE:

text
$ markdown.pl
* hello
  * world
    * hi
          code
^D
<ul>
<li>hello
<ul>
<li>world</li>
<li>hi
  code</li>
</ul></li>
</ul>

The code isn't a code block even though it's after the bullet margin. I know,
lets give it two more spaces, effectively making it 8 spaces past the bullet.

text
$ markdown.pl
* hello
  * world
    * hi
            code
^D
<ul>
<li>hello
<ul>
<li>world</li>
<li>hi
    code</li>
</ul></li>
</ul>

And, it's still not a code block. Did you also notice that the 3rd item isn't
even its own list? Markdown screws that up too because of its indentation
unaware parsing.


Let's look at some more examples of markdown's list parsing:

text
$ markdown.pl

  * item1

    * item2

  text
^D
<ul>
<li><p>item1</p>

<ul>
<li>item2</li>
</ul>

<p><p>text</p></li>
</ul></p>

Misnested tags.

text
$ marked
  * item1

    * item2

  text
^D
<ul>
<li><p>item1</p>
<ul>
<li>item2</li>
</ul>
<p>text</p>
</li>
</ul>

Which looks correct to you?


text
$ markdown.pl
* hello
  > world
^D
<p><ul>
<li>hello</p>

<blockquote>
  <p>world</li>
</ul></p>
</blockquote>

More misnested tags.

text
$ marked
* hello
  > world
^D
<ul>
<li>hello<blockquote>
<p>world</p>
</blockquote>
</li>
</ul>

Again, which looks correct to you?


Why quality matters - Part 2

bash
$ markdown.pl
* hello
  > world
^D
<p><ul>
<li>hello</p>

<blockquote>
  <p>world</li>
</ul></p>
</blockquote>
bash
$ sundown # upskirt
* hello
  > world
^D
<ul>
<li>hello
&gt; world</li>
</ul>
bash
$ marked
* hello
  > world
^D
<ul><li>hello <blockquote><p>world</p></blockquote></li></ul>

Which looks correct to you?


See: https://github.com/evilstreak/markdown-js/issues/23

bash
$ markdown.pl # upskirt/markdown.js/discount
* hello
      var a = 1;
* world
^D
<ul>
<li>hello
var a = 1;</li>
<li>world</li>
</ul>
bash
$ marked
* hello
      var a = 1;
* world
^D
<ul><li>hello
<pre>code>var a = 1;</code></pre></li>
<li>world</li></ul>

Which looks more reasonable? Why shouldn't code blocks be able to appear in
list items in a sane way?


bash
$ markdown.js
<div>hello</div>

<span>hello</span>
^D
<p>&lt;div&gt;hello&lt;/div&gt;</p>

<p>&lt;span&gt;hello&lt;/span&gt;</p>
bash
$ marked
<div>hello</div>

<span>hello</span>
^D
<div>hello</div>


<p><span>hello</span>
</p>

See: https://github.com/evilstreak/markdown-js/issues/27

bash
$ markdown.js
[](/link)
^D
<p><a href="/image)](/link">![an image</a></p>
bash
$ marked
[](/link)
^D
<p><a href="/link"><img src="/image" alt="an image"></a>
</p>

See: https://github.com/evilstreak/markdown-js/issues/24

bash
$ markdown.js
> a

> b

> c
^D
<blockquote><p>a</p><p>bundefined&gt; c</p></blockquote>
bash
$ marked
> a

> b

> c
^D
<blockquote><p>a

</p></blockquote>
<blockquote><p>b

</p></blockquote>
<blockquote><p>c
</p></blockquote>

bash
$ markdown.pl
* hello
  * world
    how

    are
    you

  * today
* hi
^D
<ul>
<li><p>hello</p>

<ul>
<li>world
how</li>
</ul>

<p>are
you</p>

<ul>
<li>today</li>
</ul></li>
<li>hi</li>
</ul>
bash
$ marked
* hello
  * world
    how

    are
    you

  * today
* hi
^D
<ul>
<li><p>hello</p>
<ul>
<li><p>world
how</p>
<p>are
you</p>
</li>
<li><p>today</p>
</li>
</ul>
</li>
<li>hi</li>
</ul>

Demo Initial (`docs/demo/initial.md`)

Marked - Markdown Parser

Marked lets you convert Markdown into HTML. Markdown is a simple text format whose goal is to be very easy to read and write, even when not converted to HTML. This demo page will let you type anything you like and see how it gets converted. Live. No more waiting around.

How To Use The Demo

  1. Type in stuff on the left.
  2. See the live updates on the right.

That's it. Pretty simple. There's also a drop-down option above to switch between various views:

  • Preview: A live display of the generated HTML as it would render in a browser.
  • HTML Source: The generated HTML before your browser makes it pretty.
  • Lexer Data: What marked uses internally, in case you like gory stuff like this.
  • Quick Reference: A brief run-down of how to format things using markdown.

Why Markdown?

It's easy. It's not overly bloated, unlike HTML. Also, as the creator of markdown says,

The overriding design goal for Markdown's
formatting syntax is to make it as readable
as possible. The idea is that a
Markdown-formatted document should be
publishable as-is, as plain text, without
looking like it's been marked up with tags
or formatting instructions.

Ready to start writing? Either start changing stuff on the left or
clear everything with a simple click.


Demo Quickref (`docs/demo/quickref.md`)

Markdown Quick Reference

This guide is a very brief overview, with examples, of the syntax that Markdown supports. It is itself written in Markdown and you can copy the samples over to the left-hand pane for experimentation. It's shown as text and not rendered HTML.

Simple Text Formatting

First thing is first. You can use stars or underscores for italics. Double stars and double underscores for bold. Three together for both.

Paragraphs are pretty easy too. Just have a blank line between chunks of text.

This chunk of text is in a block quote. Its multiple lines will all be
indented a bit from the rest of the text.

Multiple levels of block quotes also work.

Sometimes you want to include code, such as when you are explaining how <h1> HTML tags work, or maybe you are a programmer and you are discussing someMethod().

If you want to include code and have new
lines preserved, indent the line with a tab
or at least four spaces:

text
Extra spaces work here too.
This is also called preformatted text and it is useful for showing examples.
The text will stay as text, so any *markdown* or HTML you add will
not show up formatted. This way you can show markdown examples in a
markdown document.
text
You can also use preformatted text with your blockquotes
as long as you add at least five spaces.

Headings

There are a couple of ways to make headings. Using three or more equals signs on a line under a heading makes it into an "h1" style. Three or more hyphens under a line makes it "h2" (slightly smaller). You can also use multiple pound symbols (#) before and after a heading. Pounds after the title are ignored. Here are some examples:

This is H1

This is H2

This is H1

This is H2

This is H3 with some extra pounds

You get the idea

I don't need extra pounds at the end

H6 is the max

Let's link to a few sites. First, let's use the bare URL, like https://www.github.com. Great for text, but ugly for HTML.
Next is an inline link to Google. A little nicer.
This is a reference-style link to [Wikipedia] 1.
Lastly, here's a pretty link to Yahoo. The reference-style and pretty links both automatically use the links defined below, but they could be defined anywhere in the markdown and are removed from the HTML. The names are also case insensitive, so you can use YaHoO and have it link properly.

Title attributes may be added to links by adding text after a link.
This is the inline link with a "Bing" title.
You can also go to [W3C] 2 and maybe visit a friend.

Email addresses in plain text are not linked: [email protected].
Email addresses wrapped in angle brackets are linked: [email protected].
They are also obfuscated so that email harvesting spam robots hopefully won't get them.

Lists

  • This is a bulleted list
  • Great for shopping lists
  • You can also use hyphens
  • Or plus symbols

The above is an "unordered" list. Now, on for a bit of order.

  1. Numbered lists are also easy
  2. Just start with a number
  3. However, the actual number doesn't matter when converted to HTML.
  4. This will still show up as 4.

You might want a few advanced lists:

  • This top-level list is wrapped in paragraph tags

  • This generates an extra space between each top-level item.

  • You do it by adding a blank line

  • This nested list also has blank lines between the list items.

  • How to create nested lists

    1. Start your regular list
    2. Indent nested lists with two spaces
    3. Further nesting means you should indent with two more spaces
    • This line is indented with four spaces.
  • List items can be quite lengthy. You can keep typing and either continue
    them on the next line with no indentation.

  • Alternately, if that looks ugly, you can also
    indent the next line a bit for a prettier look.

  • You can put large blocks of text in your list by just indenting with two spaces.

    This is formatted the same as code, but you can inspect the HTML
    and find that it's just wrapped in a `` tag and won't be shown
    as preformatted text.

    You can keep adding more and more paragraphs to a single
    list item by adding the traditional blank line and then keep
    on indenting the paragraphs with two spaces.

    You really only need to indent the first line,
    but that looks ugly.

  • Lists support blockquotes

    Just like this example here. By the way, you can
    nest lists inside blockquotes!

    • Fantastic!
  • Lists support preformatted text

    text
    You just need to indent an additional four spaces.

Even More

Horizontal Rule

If you need a horizontal rule you just need to put at least three hyphens, asterisks, or underscores on a line by themselves. You can also even put spaces between the characters.




Those three all produced horizontal lines. Keep in mind that three hyphens under any text turns that text into a heading, so add a blank like if you use hyphens.

Images

Images work exactly like links, but they have exclamation points in front. They work with references and titles too.

and Happy.

Inline HTML

If markdown is too limiting, you can just insert your own crazy HTML. Span-level HTML can still use markdown. Block level elements must be separated from text by a blank line and must not have any spaces before the opening and closing HTML.

It is a pity, but markdown does not work in here for most markdown parsers.
Marked handles it pretty well.


--- METRICS ---