# Technical Documentation: markedjs/marked

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/markedjs/marked)

### Overview (`README.md`)

<a href="https://marked.js.org">
  <img width="60px" height="60px" src="https://marked.js.org/img/logo-black.svg" align="right" />
</a>

# Marked

[](https://www.npmjs.com/package/marked)
[](https://packagephobia.now.sh/result?p=marked)
[](https://www.npmjs.com/package/marked)
[](https://github.com/markedjs/marked/actions)
[](https://snyk.io/test/npm/marked)
[](https://inspect.software/software/markedjs/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](https://marked.js.org/using_advanced#extensions)
- 🌐 works in a browser, on a server, or from a command line interface (CLI)

## Demo

Check out the [demo page](https://marked.js.org/demo/) to see Marked in action ⛹️

## Docs

Our [documentation pages](https://marked.js.org) are also rendered using marked 💯

Also read about:

* [Options](https://marked.js.org/using_advanced)
* [Extensibility](https://marked.js.org/using_pro)

## Compatibility

**Node.js:** Only [current and LTS](https://nodejs.org/en/about/releases/) 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](https://developer.mozilla.org/en-US/docs/Glossary/Baseline/Compatibility)

## Installation

**CLI:**

```sh
npm install marked
```

**In-browser:**

```sh
npm install marked
```

## Usage

### Warning: 🚨 Marked does not [sanitize](https://marked.js.org/using_advanced#options) the output HTML. Please use a sanitize library, like [DOMPurify](https://github.com/cure53/DOMPurify) (recommended), [sanitize-html](https://github.com/apostrophecms/sanitize-html) or [insane](https://github.com/bevacqua/insane) on the *output* HTML! 🚨

```
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.<sup>*</sup>
2. a low-level markdown compiler for parsing markdown without caching or blocking for long periods of time.<sup>**</sup>
3. light-weight while implementing all markdown features from the supported flavors & specifications.<sup>***</sup>
4. easily adaptable with [custom extensions](/using_advanced#extensions).
5. available as a command line interface (CLI) and running in client- or server-side JavaScript projects.

<p><small><sup>*</sup> Still working on metrics for comparative analysis and definition.</small><br>
<small><sup>**</sup> Zero dependencies.</small><br>
<small><sup>***</sup> Strict compliance could result in slower processing when running comparative benchmarking.</small></p>


<h2 id="demo">Demo</h2>

Checkout the [demo page](./demo/) to see marked in action ⛹️

These documentation pages are also rendered using marked 💯


<h2 id="installation">Installation</h2>

**CLI:** `npm install marked`

**In-browser:**
```
npm install marked
```
<h2 id="usage">Usage</h2>

### Warning: 🚨 Marked does not [sanitize](/using_advanced#options) the output HTML. If you are processing potentially unsafe strings, it's important to filter for possible XSS attacks. Some filtering options include [DOMPurify](https://github.com/cure53/DOMPurify) (recommended), [js-xss](https://github.com/leizongmin/js-xss), [sanitize-html](https://github.com/apostrophecms/sanitize-html) and [insane](https://github.com/bevacqua/insane) on the *output* HTML! 🚨

```
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](https://github.com/markedjs/marked/issues/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](/using_advanced) and [extensibility](/using_pro) as well.

<h2 id="specifications">Supported Markdown specifications</h2>

We actively support the features of the following [Markdown flavors](https://github.com/commonmark/CommonMark/wiki/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.

<h2 id="tools">List of Tools Using Marked</h2>

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](https://zerodevx.github.io/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](https://github.com/susam/texme)                             | TeXMe is a lightweight JavaScript utility to create self-rendering Markdown + LaTeX documents.             |
| [StrapDown.js](https://naereen.github.io/StrapDown.js/)             | StrapDown.js is an awesome on-the-fly Markdown to HTML text processor.                |
| [raito](https://raito.arnaud.at/)             | Mini Markdown Wiki/CMS in 8kb of JavaScript.                |
| [Homebrewery](https://homebrewery.naturalcrit.com/)             | 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](https://github.com/CNOCTAVE/marked_reader)          | marked_reader is an open source Markdown reader packed by Electron. |
| [AtlasDocs](https://atlasdocs.io/en/markdown-to-html)             | Free document tools that run entirely in the browser; uses Marked to turn Markdown into HTML, PDF and DOCX without uploading files. |

<h2 id="security">Security</h2>

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](/authors) as well as the [listed owners within NPM](https://docs.npmjs.com/cli/owner). 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",

    "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](https://medium.com/the-node-js-collection/healthy-open-source-967fa8be7951), where each group encompasses the following groups.

<table>
  <tbody>
  	<tr>
      <td align="center" valign="top" style="width:32%">
        <a href="https://github.com/chjj">
          <img width="100" height="100" src="https://github.com/chjj.png?s=150">
        </a>
        <br>
        <a href="https://github.com/chjj">Christopher Jeffrey</a>
        <div>Original Author</div>
        <small>Started the fire</small>
      </td>
      <td align="center" valign="top" style="width:32%">
        <a href="https://github.com/joshbruce">
          <img width="100" height="100" src="https://github.com/joshbruce.png?s=150">
        </a>
        <br>
        <a href="https://joshbruce.com">Josh Bruce</a>
        <div>Publisher</div>
        <small>Release Wrangler; Humaning Helper; Heckler of Hypertext</small>
      </td>
      <td align="center" valign="top" style="width:32%">
        <a href="https://github.com/styfle">
          <img width="100" height="100" src="https://github.com/styfle.png?s=150">
        </a>
        <br>
        <a href="https://www.ceriously.com">Steven</a>
        <div>Publisher</div>
        <small>Release Wrangler; Dr. Docs; Open source, of course; GitHub Guru; Humaning Helper</small>
      </td>
    </tr>
  	<tr>
      <td align="center" valign="top">
        <a href="https://github.com/davisjam">
          <img width="100" height="100" src="https://github.com/davisjam.png?s=150">
        </a>
        <br>
        <a href="https://github.com/davisjam">Jamie Davis</a>
        <div>Committer</div>
        <small>Seeker of Security</small>
      </td>
      <td align="center" valign="top">
        <a href="https://github.com/UziTech">
          <img width="100" height="100" src="https://github.com/UziTech.png?s=150">
        </a>
        <br>
        <a href="https://tony.brix.ninja">Tony Brix</a>
        <div>Publisher</div>
        <small>Release Wrangler; Titan of the test harness; Dr. DevOps</small>
      </td>
      <td align="center" valign="top">
        <a href="https://github.com/calculuschild">
          <img width="100" height="100" src="https://github.com/calculuschild.png?s=150">
        </a>
        <br>
        <a href="https://github.com/calculuschild">Trevor Buckner</a>
        <div>Committer</div>
        <small>Master of Marked</small>
      </td>
    </tr>
  </tbody>
</table>

## Contributors

<table>
  <tbody>
    <tr>
      <td align="center" valign="top">
        <a href="https://github.com/intcreator">
          <img width="100" height="100" src="https://github.com/intcreator.png?s=150">
        </a>
        <br>
        <a href="https://github.com/intcreator">Brandon der Blätter</a>
        <div>Contributor</div>
        <small>Curious Contributor</small>
      </td>
      <td align="center" valign="top">
        <a href="https://github.com/carlosvalle">
          <img width="100" height="100" src="https://github.com/carlosvalle.png?s=150">
        </a>
        <br>
        <a href="https://github.com/carlosvalle">Carlos Valle</a>
        <div>Contributor</div>
        <small>Maker of the Marked mark from 2018 to present</small>
      </td>
      <td align="center" width="20%" valign="top">
        <a href="https://github.com/Feder1co5oave">
          <img width="100" height="100" src="https://github.com/Feder1co5oave.png?s=150">
        </a>
        <br>
        <a href="https://github.com/Feder1co5oave">Federico Soave</a>
        <div>Contributor</div>
        <small>Regent of the Regex; Master of Marked</small>
      </td>
      <td align="center" valign="top">
        <a href="https://github.com/karenyavine">
          <img width="100" height="100" src="https://github.com/karenyavine.png?s=150">
        </a>
        <br>
        <a href="https://github.com/karenyavine">Karen Yavine</a>
        <div>Contributor</div>
        <small>Snyk's Security Saint</small>
      </td>
     </tr>
     <tr>
      <td align="center" valign="top">
        <a href="https://github.com/KostyaTretyak">
          <img width="100" height="100" src="https://github.com/KostyaTretyak.png?s=150">
        </a>
        <br>
        <a href="https://github.com/KostyaTretyak">Костя Третяк</a>
        <div>Contributor</div>
        <small></small>
      </td>
      <td align="center" width="20%" valign="top">
        <a href="https://github.com/tomtheisen">
          <img width="100" height="100" src="https://github.com/tomtheisen.png?s=150">
        </a>
        <br>
        <a href="https://github.com/tomtheisen">Tom Theisen</a>
        <div>Contributor</div>
        <small>Defibrillator</small>
      </td>
      <td align="center" width="20%" valign="top">
        <a href="https://github.com/mccraveiro">
          <img width="100" height="100" src="https://github.com/mccraveiro.png?s=150">
        </a>
        <br>
        <a href="https://github.com/mccraveiro">Mateus Craveiro</a>
        <div>Contributor</div>
        <small>Defibrillator</small>
      </td>
      <td align="center" width="20%" valign="top">
      </td>
     </tr>
  </tbody>
</table>

## 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](#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](https://help.github.com/articles/removing-yourself-from-a-collaborator-s-repository/).

[Details on badges](#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](https://reinventingorganizationswiki.com/en/theory/decision-making/). 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](https://help.github.com/articles/removing-yourself-from-a-collaborator-s-repository/).

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](#badges)

## Contributors

Contributors are users who submit a [PR](https://github.com/markedjs/marked/pulls), [Issue](https://github.com/markedjs/marked/issues), 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](#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.

<h2 id="badges">Badges</h2>

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&hellip;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&hellip;dramatic pause&hellip;why not two dramatic pauses for emphasis?&hellip; 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:

<dl>
	<dt>Curious Contributor</dt>
	<dd>A contributor with less than one year on this page who is actively engaged in submitting PRs, Issues, making recommendations, sharing thoughts&hellip;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).</dd>
	<dt>Dr. DevOps</dt>
	<dd>
		<p>Someone who understands and contributes to improving the developer experience and flow of Marked into the world.</p>
		<blockquote>
			"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." ~ <a href="https://www.wikipedia.org/wiki/DevOps">Wikipedia</a>
		</blockquote>
	</dd>
  <dt>Dr. Docs</dt>
  <dd>Someone who has contributed a great deal to the creation and maintenance of the non-code areas of marked.</dd>
	<dt>Eye for the CLI</dt>
	<dd>At this point? Pretty much anyone who can update that `man` file to the current Marked version without regression in the CLI tool itself.</dd>
	<dt>GitHub Guru</dt>
	<dd>Someone who always seems to be able to tell you easier ways to do things with GitHub.</dd>
	<dt>Humaning Helper</dt>
	<dd>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.</dd>
	<dt>Heckler of Hypertext</dt>
	<dd>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."</dd>
	<dt>Markdown Maestro</dt>
	<dd>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.</dd>
	<dt>Master of Marked</dt>
	<dd>Someone who demonstrates they know the ins and outs of the codebase for Marked.</dd>
	<dt>Open source, of course</dt>
	<dd>Someone who advocates for and has a proven understanding of how to operate within open source communities.</dd>
	<dt>Regent of the Regex</dt>
	<dd><p>Can you demonstrate you understand the following without Google and Stackoverflow?</p>
		<p><code>/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/</code></p>
		<p>Because this author can't yet. That's who gets these.</p>
	</dd>
	<dt>Seeker of Security</dt>
	<dd>Someone who has demonstrated a high degree of expertise or authority when it comes to software security.</dd>
	<dt>Titan of the Test Harness</dt>
	<dd>Someone who demonstrates high-levels of understanding regarding Marked's test harness.</dd>
	<dt>Totally Tron</dt>
	<dd>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).</dd>
</dl>

### Special badges that come with the job:

<dl>
	<dt>Defibrillator</dt>
	<dd>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.</dd>
	<dt>Maker of the Marked mark</dt>
	<dd>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.</dd>
	<dt>Release Wrangler</dt>
	<dd>This is a badge given to all Publishers.</dd>
	<dt>Snyk's Security Saint</dt>
	<dd>This is a badge given to whomever primarily reaches out from Snyk to let us know about security issues.</dd>
</dl>

---

### 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](/authors) page (or emailing josh@8fold.com). 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][homepage],
version [1.4][version].

[homepage]: https://www.contributor-covenant.org/
[version]: https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

---

### 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.

<h2 id="design-principles">Design principles</h2>

Marked tends to favor following the SOLID set of software design and development principles; mainly the [single responsibility](https://en.wikipedia.org/wiki/Single_responsibility_principle) and [open/closed principles](https://en.wikipedia.org/wiki/Open/closed_principle):

- **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.

<h2 id="priorities">Priorities</h2>

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](/#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](/#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.                                                                                           |

<h2 id="test-early-often-and-everything">Test early, often, and everything</h2>

We try to write test cases to validate output (writing tests based on the [supported specifications](/#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](https://spec.commonmark.org/current/) compliance                                        |
|/test/specs/gfm       |Tests for [GFM](https://github.github.com/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](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS) vulnerabilities|

If your test uses features or options, assuming `gfm` is set to `false`, for example, you can add [front-matter](https://www.npmjs.com/package/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 path`s 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](https://github.com/semantic-release/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](https://www.conventionalcommits.org/).

## 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](https://semver.org) 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](https://spec.commonmark.org/current/) or [GFM](https://github.github.com/gfm/) spec. Only [current and LTS](https://nodejs.org/en/about/releases/) 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`)

<h2 id="instance">Marked instance</h2>

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`](/using_pro#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.                       |
|<a href="#options">options</a>|`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));
```

<h2 id="options">Options</h2>

|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 `<br>` 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](https://github.github.com/gfm/).|
|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](/using_pro) 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](/using_pro) for more details.|
|walkTokens   |`function`  |`null`|v1.1.0|A function which is called for every token. See [extensibility](/using_pro) 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`](https://www.npmjs.com/package/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`](https://www.npmjs.com/package/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`](https://www.npmjs.com/package/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`](https://www.npmjs.com/package/marked-highlight) to add highlighting to code blocks. |
|langPrefix  (**removed**)|`string`  |`'language-'`|v0.3.0|Removed in v8.0.0 use [`marked-highlight`](https://www.npmjs.com/package/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`](https://www.npmjs.com/package/marked-mangle) to mangle email addresses.|
|sanitize (**removed**)|`boolean` |`false`  |v0.2.1   |Removed in v8.0.0 use a sanitize library, like [DOMPurify](https://github.com/cure53/DOMPurify) (recommended), [sanitize-html](https://github.com/apostrophecms/sanitize-html) or [insane](https://github.com/bevacqua/insane) on the output HTML! |
|sanitizer  (**removed**)|`function`|`null`   |v0.3.4   |Removed in v8.0.0 use a sanitize library, like [DOMPurify](https://github.com/cure53/DOMPurify) (recommended), [sanitize-html](https://github.com/apostrophecms/sanitize-html) or [insane](https://github.com/bevacqua/insane) on the output HTML!|
|smartypants (**removed**)|`boolean` |`false`  |v0.2.9   |Removed in v8.0.0 use [`marked-smartypants`](https://www.npmjs.com/package/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`](https://www.npmjs.com/package/marked-xhtml) to emit self-closing HTML tags for void elements (&lt;br/&gt;, &lt;img/&gt;, etc.) with a "/" as required by XHTML.|

<h2 id="extensions">Known Extensions</h2>

Marked can be extended using [custom extensions](/using_pro#extensions). This is a list of extensions that can be used with `marked.use(extension)`.



<div id="extension-search-container" class="relative my-6 max-w-lg">
  <span class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none text-subtle-light dark:text-subtle-dark">
    <span class="material-icons text-xl">search</span>
  </span>
  <input
    type="text"
    id="extension-search"
    placeholder="Search extensions by name, package, or description..."
    class="w-full pl-10 pr-10 py-2.5 bg-gray-50 dark:bg-gray-800/50 border border-border-light dark:border-border-dark rounded-xl text-text-light dark:text-text-dark placeholder-subtle-light dark:placeholder-subtle-dark focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all duration-200 shadow-sm"
  />
  <button
    id="extension-search-clear"
    type="button"
    class="absolute inset-y-0 right-0 flex items-center pr-3 text-subtle-light dark:text-subtle-dark hover:text-text-light dark:hover:text-text-dark hidden"
    aria-label="Clear search"
  >
    <span class="material-icons text-lg">close</span>
  </button>
</div>

<div id="no-extensions-msg" class="hidden p-8 text-center bg-gray-50 dark:bg-gray-800/30 border border-dashed border-border-light dark:border-border-dark rounded-xl my-6">
  <span class="material-icons text-4xl text-subtle-light dark:text-subtle-dark mb-2">search_off</span>
  <p class="text-text-light dark:text-text-dark font-medium">No extensions found</p>
  <p class="text-sm text-subtle-light dark:text-subtle-dark mt-1">Try adjusting your keywords or search term.</p>
</div>



|Name|Package Name|Description|
|:---|:-----------|:----------|
|[ABCjs](https://www.npmjs.com/package/marked-abc)|[`marked-abc`](https://www.npmjs.com/package/marked-abc)|[ABCjs](https://www.abcjs.net/) sheet music rendering|
|[Admonition](https://www.npmjs.com/package/marked-admonition-extension)|[`marked-admonition-extension`](https://www.npmjs.com/package/marked-admonition-extension)| Admonition extension |
|[Alert](https://github.com/bent10/marked-extensions/tree/main/packages/alert)|[`marked-alert`](https://www.npmjs.com/package/marked-alert)|Enables [GFM alerts](https://github.com/orgs/community/discussions/16925)|
|[Base URL](https://github.com/markedjs/marked-base-url)|[`marked-base-url`](https://www.npmjs.com/package/marked-base-url)|Prefix relative urls with a base URL|
|[Bidi](https://github.com/markedjs/marked-bidi)|[`marked-bidi`](https://www.npmjs.com/package/marked-bidi)|Add Bidirectional text support to the HTML|
|[CJK Breaks](https://github.com/chirsz-ever/marked-cjk-breaks)|[`marked-cjk-breaks`](https://www.npmjs.com/package/marked-cjk-breaks)|Suppress soft linebreaks between east asian characters|
|[Code Format](https://github.com/bent10/marked-extensions/tree/main/packages/code-format)|[`marked-code-format`](https://www.npmjs.com/package/marked-code-format)|Formatting code blocks using Prettier|
|[Code JSX Renderer](https://github.com/bent10/marked-extensions/tree/main/packages/code-jsx-renderer)|[`marked-code-jsx-renderer`](https://www.npmjs.com/package/marked-code-jsx-renderer)|Render JSX code blocks using a custom renderer and components|
|[Code Preview](https://github.com/bent10/marked-extensions/tree/main/packages/code-preview)|[`marked-code-preview`](https://www.npmjs.com/package/marked-code-preview)|Transform code blocks into code previews|
|[Custom Heading ID](https://github.com/markedjs/marked-custom-heading-id)|[`marked-custom-heading-id`](https://www.npmjs.com/package/marked-custom-heading-id)|Specify a custom heading id in headings with the [Markdown Extended Syntax](https://www.markdownguide.org/extended-syntax/#heading-ids) `# heading {#custom-id}`|
|[Directive](https://github.com/bent10/marked-extensions/tree/main/packages/directive)|[`marked-directive`](https://www.npmjs.com/package/marked-directive)|Supports [directives syntax](https://talk.commonmark.org/t/generic-directives-plugins-syntax/444)|
|[Emoji](https://github.com/UziTech/marked-emoji)|[`marked-emoji`](https://www.npmjs.com/package/marked-emoji)|Add emoji support like on GitHub|
|[Extended Tables](https://github.com/calculuschild/marked-extended-tables)|[`marked-extended-tables`](https://www.npmjs.com/package/marked-extended-tables)|Extends the standard Github-Flavored tables to support advanced features: Column Spanning, Row Spanning, Multi-row headers|
|[Footnote](https://github.com/bent10/marked-extensions/tree/main/packages/footnote)|[`marked-footnote`](https://www.npmjs.com/package/marked-footnote)|Enables [GFM footnotes](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#footnotes)|
|[GFM Heading ID](https://github.com/markedjs/marked-gfm-heading-id)|[`marked-gfm-heading-id`](https://www.npmjs.com/package/marked-gfm-heading-id)|Use [`github-slugger`](https://github.com/Flet/github-slugger) to create the heading IDs and allow a custom prefix|
|[GitLab](https://github.com/UziTech/marked-gitlab)|[`marked-gitlab`](https://www.npmjs.com/package/marked-gitlab)|Extension for [GitLab Flavored Markdown (GLFM)](https://docs.gitlab.com/user/markdown/)|
|[Highlight](https://github.com/markedjs/marked-highlight)|[`marked-highlight`](https://www.npmjs.com/package/marked-highlight)|Highlight code blocks|
|[HTML Renderer](https://github.com/UziTech/marked-html-renderer)|[`marked-html-renderer`](https://www.npmjs.com/package/marked-html-renderer)|Output HTML Elements instead of a string|
|[Jira Renderer](https://github.com/mrmarble/marked-jira)|[`marked-jira`](https://www.npmjs.com/package/marked-jira)|Output Jira compatible format|
|[Katex Code](https://github.com/UziTech/marked-katex-extension)|[`marked-katex-extension`](https://www.npmjs.com/package/marked-katex-extension)|Render [katex](https://katex.org/) code|
|[LinkifyIt](https://github.com/UziTech/marked-linkify-it)|[`marked-linkify-it`](https://www.npmjs.com/package/marked-linkify-it)|Use [linkify-it](https://github.com/markdown-it/linkify-it) for urls|
|[Mangle](https://github.com/markedjs/marked-mangle)|[`marked-mangle`](https://www.npmjs.com/package/marked-mangle)|Mangle mailto links with HTML character references|
|[Math](https://github.com/webc-site/math/tree/main/plugin/marked)|[`@webc.site/math-marked`](https://www.npmjs.com/package/@webc.site/math-marked)|Ultra-lightweight native MathML math rendering extension|
|[Misskey-flavored Markdown](https://akkoma.dev/sfr/marked-mfm)|[`marked-mfm`](https://www.npmjs.com/package/marked-mfm)|Custom extension for [Misskey-flavored Markdown](https://github.com/misskey-dev/mfm.js/blob/develop/docs/syntax.md)|
|[More Lists](https://github.com/jasny/marked-more-lists)|[`marked-more-lists`](https://www.npmjs.com/package/marked-more-lists)|Support for alphabetical and roman numeral ordered lists|
|[Plaintify](https://github.com/bent10/marked-extensions/tree/main/packages/plaintify)|[`marked-plaintify`](https://www.npmjs.com/package/marked-plaintify)|Converts Markdown to Plaintext|
|[Responsive Images](https://github.com/ELowry/MarkedResponsiveImages)|[`marked-responsive-images`](https://www.npmjs.com/package/marked-responsive-images)|Generate responsive (`srcset`) images based on structured filenames|
|[Shiki](https://github.com/bent10/marked-extensions/tree/main/packages/shiki)|[`marked-shiki`](https://www.npmjs.com/package/marked-shiki)|Integrating [Shiki](https://shiki.style/) syntax highlighting|
|[Sequential Hooks](https://github.com/bent10/marked-extensions/tree/main/packages/sequential-hooks)|[`marked-sequential-hooks`](https://www.npmjs.com/package/marked-sequential-hooks)|Enables the sequential preprocessing and post-processing within [sequential hooks](https://github.com/bent10/marked-extensions#sequential-hooks)|
|[Smartypants](https://github.com/markedjs/marked-smartypants)|[`marked-smartypants`](https://www.npmjs.com/package/marked-smartypants)|Use [smartypants](https://www.npmjs.com/package/smartypants) to use "smart" typographic punctuation for things like quotes and dashes|
|[Smartypants lite](https://github.com/calculuschild/marked-smartypants-lite)|[`marked-smartypants-lite`](https://www.npmjs.com/package/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](https://github.com/UziTech/marked-token-position)|[`marked-token-position`](https://www.npmjs.com/package/marked-token-position)|Adds a `position` field to each token with `start` and `end` properties containing `line`, `column`, and `offset`|
|[Typograf](https://github.com/laidrivm/marked-typograf)|[`marked-typograf`](https://www.npmjs.com/package/marked-typograf)|Use [typograf](https://www.npmjs.com/package/typograf) as a more powerful and extendable alternative to Smartypants for creating “smart” typographic punctuation, such as quotes and dashes|
|[XHTML](https://github.com/markedjs/marked-xhtml)|[`marked-xhtml`](https://www.npmjs.com/package/marked-xhtml)|Emit self-closing HTML tags for void elements (&lt;br/&gt;, &lt;img/&gt;, etc.) with a "/" as required by XHTML|

<h2 id="user-examples">User Examples</h2>

<details>

<summary>Marked can render on-page content as markdown in the browser.</summary>

```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>
```
</details>

<h2 id="inline">Inline Markdown</h2>

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>'
```

<h2 id="highlight">Highlighting</h2>

Use [`marked-highlight`](https://www.npmjs.com/package/marked-highlight) to highlight code blocks.

<h2 id="workers">Workers</h2>

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](https://nodejs.org/api/worker_threads.html) on a node server, or a [web worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) 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);
```

<h2 id="cli-extensions">CLI Extensions</h2>

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.

<h2 id="terminology">Terminology Note</h2>

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 }
  ]
});
```

<h2 id="use">marked.use()</h2>

`marked.use(extension)` is the recommended way to extend Marked. The `extension` object can contain any [option](/using_advanced#options) 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](/using_advanced#instance) so that your extensions are stored independently from the global instance Marked provides.

***

<h2>The Marked Pipeline</h2>

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.
4) The `parser` traverses the token tree and feeds each token into the appropriate `renderer`, and concatenates their outputs into the final HTML result.
5) 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](#custom-extensions-example) for insight on how to execute this.

***

<h2 id="renderer">The Renderer : <code>renderer</code></h2>

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

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

### Inline-level renderer methods

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

The Tokens.* properties can be found [here](https://github.com/markedjs/marked/blob/master/src/Tokens.ts).

***

<h2 id="tokenizer">The Tokenizer : <code>tokenizer</code></h2>

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](https://github.com/markedjs/marked/issues/1948).

### Block level tokenizer methods

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

### Inline level tokenizer methods

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

The Tokens.* properties can be found [here](https://github.com/markedjs/marked/blob/master/src/Tokens.ts).

***

<h2 id="walk-tokens">Walk Tokens : <code>walkTokens</code></h2>

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`](#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>
```

***

<h2 id="hooks">Hooks : <code>hooks</code></h2>

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](https://www.npmjs.com/package/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](https://www.npmjs.com/package/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>
```

***

<h2 id="extensions">Custom Extensions : <code>extensions</code></h2>

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

<dl>
<dt><code><strong>name</strong></code></dt>
<dd>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.</dd>

<dt><code><strong>level</strong></code></dt>
<dd>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.).</dd>

<dt><code><strong>start</strong>(<i>string</i> src)</code></dt>
<dd>A function that returns the index of the next potential start of the custom token.

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

<dt><code><strong>tokenizer</strong>(<i>string</i> src, <i>array</i> tokens)</code></dt>
<dd>A function that reads string of Markdown text and returns a generated token. The token pattern should be found at the beginning of the <code>src</code> string. Accordingly, if using a Regular Expression to detect a token, it should be anchored to the string start (`^`). The <code>tokens</code> 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:

<dl>
<dt><code><strong>type</strong></code></dt>
<dd>A string that matches the <code>name</code> parameter of the extension.</dd>

<dt><code><strong>raw</strong></code></dt>
<dd>A string containing all of the text that this token consumes from the source.</dd>

<dt><code><strong>tokens</strong> [optional]</code></dt>
<dd>An array of child tokens that will be traversed by the <code>walkTokens</code> function by default.</dd>
</dl>

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:

<dl>
<dt><code><strong>this.lexer.blockTokens</strong>(<i>string</i> text, <i>array</i> tokens)</code></dt>
<dd>This runs the block tokenizer functions (including any block-level extensions) on the provided text, and appends any resulting tokens onto the <code>tokens</code> array. The <code>tokens</code> 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.</dd>

<dt><code><strong>this.lexer.inline</strong>(<i>string</i> text, <i>array</i> tokens)</code></dt>
<dd>Parsing of inline-level tokens only occurs after all block-level tokens have been generated. This function adds <code>text</code> and <code>tokens</code> 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 <code>text</code>, and any resulting tokens will be appended to the <code>tokens</code> array. Note that this function does **NOT** return anything since the inline processing cannot happen until the block-level processing is complete.</dd>

<dt><code><strong>this.lexer.inlineTokens</strong>(<i>string</i> text, <i>array</i> tokens)</code></dt>
<dd>Sometimes an inline-level token contains further nested inline tokens (such as a <pre><code>**strong**</code></pre> token inside of a <pre><code>### Heading</code></pre>). This runs the inline tokenizer functions (including any inline-level extensions) on the provided text, and appends any resulting tokens onto the <code>tokens</code> array. The <code>tokens</code> array is also returned by the function.</dd>
</dl>
</dd>

<dt><code><strong>renderer</strong>(<i>object</i> token)</code></dt>
<dd>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:

<dl>
<dt><code><strong>this.parser.parse</strong>(<i>array</i> tokens)</code></dt>
<dd>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.</dd>

<dt><code><strong>this.parser.parseInline</strong>(<i>array</i> tokens)</code></dt>
<dd>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.</dd>
</dl>
</dd>

<dt><code><strong>childTokens</strong> [optional]</code></dt>
<dd>An array of strings that match the names of any token parameters that should be traversed by the <code>walkTokens</code> functions. For instance, if you want to use a second custom parameter to contain child tokens in addition to <code>tokens</code>, it could be listed here. If <code>childTokens</code> is provided, the <code>tokens</code> array will not be walked by default unless it is also included in the <code>childTokens</code> array.</dd>
</dl>

> Note: If you would like to release an extension as an npm package you may use the [Marked Extension Template](https://github.com/markedjs/marked-extension-template) which includes all of the things you need to get started. Feel free to create an issue in that [repo](https://github.com/markedjs/marked-extension-template) if you need help.

**Example:** <a name="custom-extensions-example"></a>Add a custom syntax to generate `<dl>` description lists.

```
/* 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>
```

***

<h2 id="async">Async Marked : <code>async</code></h2>

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

<h2 id="lexer">The Lexer</h2>

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


<h2 id="parser">The Parser</h2>

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

<h2 id="extend">Access to Lexer and Parser</h2>

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

```
$ markdown.pl

  * item1

    * item2

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

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

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


```
$ 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?

- - -

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

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

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

Again, which looks correct to you?

- - -

EXAMPLE:

```
$ 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.

```
$ 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:

```
$ 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.


```
$ 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?

- - -

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

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

More misnested tags.


```
$ 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](/demo/?text=) with a simple click.

[Marked]: https://github.com/markedjs/marked/
[Markdown]: http://daringfireball.net/projects/markdown/

---

### 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*.

[Markdown]: http://daringfireball.net/projects/markdown/


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:

    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 <u>HTML</u> you add will
    not show up formatted. This way you can show markdown examples in a
    markdown document.

>     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


Links
=====

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](https://www.google.com). 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.

[1]: https://www.wikipedia.org
[Yahoo]: https://www.yahoo.com

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

[2]: https://w3c.org (The W3C puts out specs for web-based things)
[Friend]: https://facebook.com "Facebook!"

Email addresses in plain text are not linked: test@example.com.
Email addresses wrapped in angle brackets are linked: <test@example.com>.
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
3738762. However, the actual number doesn't matter when converted to HTML.
1. 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 `<p>` 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

      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].

[Happy]: https://wpclipart.com/smiley/happy/simple_colors/smiley_face_simple_green_small.png ("Smiley face")


Inline HTML
-----------

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

<div style='font-family: "Comic Sans MS", "Comic Sans", cursive;'>
It is a pity, but markdown does **not** work in here for most markdown parsers.
[Marked] handles it pretty well.
</div>

---

--- METRICS ---
- Files Extracted: 12
- Estimated Token Budget: ~23841 tokens
- Canonical Reference: https://codewiki.google/github.com/markedjs/marked
