GithubHelp home page GithubHelp logo

ts-stack / markdown Goto Github PK

View Code? Open in Web Editor NEW
128.0 7.0 27.0 1013 KB

A full-featured markdown parser and compiler, written in TypeScript.

JavaScript 1.21% TypeScript 37.16% HTML 61.63%
markdown markdown-parser markdown-flavors gfm typescript javascript

markdown's Introduction

@ts-stack/markdown

A full-featured markdown parser and compiler, written in TypeScript.

This is fork of popular library marked from this commit (Merge pull request #961 from chjj/release-0.3.7, Dec 1, 2017).

lang

Table of contents

Install

npm install @ts-stack/markdown --save

Usage

Minimal usage:

import { Marked } from '@ts-stack/markdown';

console.log(Marked.parse('I am using __markdown__.'));
// Outputs: I am using <strong>markdown</strong>.

Example setting options with default values:

import { Marked, Renderer } from '@ts-stack/markdown';

Marked.setOptions ({
  renderer: new Renderer,
  gfm: true,
  tables: true,
  breaks: false,
  pedantic: false,
  sanitize: false,
  smartLists: true,
  smartypants: false
});

console.log(Marked.parse('I am using __markdown__.'));

Example usage with highlight.js

npm install highlight.js --save

A function to highlight code blocks:

import { Marked } from '@ts-stack/markdown';
import hljs from 'highlight.js';

Marked.setOptions({ highlight: (code, lang) => hljs.highlight(lang, code).value });
let md = '```js\n console.log("hello"); \n```';
console.log(Marked.parse(md));

Overriding renderer methods

The renderer option allows you to render tokens in a custom manner. Here is an example of overriding the default heading token rendering by adding custom head id:

import { Marked, Renderer } from '@ts-stack/markdown';

class MyRenderer extends Renderer {
  // Overriding parent method.
  override heading(text: string, level: number, raw: string) {
    const regexp = /\s*{([^}]+)}$/;
    const execArr = regexp.exec(text);
    let id: string;
    
    if(execArr) {
      text = text.replace(regexp, '');
      id = execArr[1];
    } else {
      id = text.toLocaleLowerCase().replace(/[^\wа-яіїє]+/gi, '-');
    }

    return `<h${level} id="${id}">${text}</h${level}>`;
  }
}

Marked.setOptions({ renderer: new MyRenderer });

console.log(Marked.parse('# heading {my-custom-hash}'));

This code will output the following HTML:

<h1 id="my-custom-hash">heading</h1>

Example of setting a simple block rule

If you do not need recursiveness or checks some conditions before execute a regular expression, you can use the Marked.setBlockRule( regexp[, callback] ) method, which takes a regular expression as the first argument, and returns result regexp.exec(string) to callback(execArr), which can be passed as a second argument.

In regular expression very important adding symbol ^ from start. You should do this anyway.

import { Marked, escape } from '@ts-stack/markdown';

/**
 * KaTeX is a fast, easy-to-use JavaScript library for TeX math rendering on the web.
 */
import * as katex from 'katex';


Marked.setBlockRule(/^@@@ *(\w+)\n([\s\S]+?)\n@@@/, function (execArr) {

  // Don't use arrow function for this callback
  // if you need Renderer's context, for example to `this.options`.

  const channel = execArr[1];
  const content = execArr[2];

  switch(channel) {
    case 'youtube': {
      const id = escape(content);
      return `\n<iframe width="420" height="315" src="https://www.youtube.com/embed/${id}"></iframe>\n`;
    }
    case 'katex': {
      return katex.renderToString(escape(content));
    }
    default: {
      const msg = `[Error: a channel "${channel}" for an embedded code is not recognized]`;
      return '<div style="color: red">' + msg + '</div>';
    }
  }
});

const blockStr = `
# Example usage with embed block code

@@@ katex
c = \\pm\\sqrt{a^2 + b^2}
@@@

@@@ youtube
JgwnkM5WwWE
@@@
`;

const html = Marked.parse(blockStr);

console.log(html);

Benchmarks

node v8.9.x

git clone https://github.com/ts-stack/markdown.git
cd markdown
npm install
npm run bench

By default, these benchmarks run the entire markdown test suite once. The test suite includes every markdown feature, it doesn't cater to specific aspects.

Lib Lib load, ms Lib init, ms Bench work, ms Total, ms
@ts-stack/markdown v1.5.0 9 5 67 81
marked v7.0.4 30 22 128 180
markdown v0.5.0 10 8 180 198
remarkable v2.0.1 22 9 126 157
commonmark v0.30.0 51 2 120 173
markdown-it v13.0.1 56 3 171 230
showdown v2.1.0 18 38 545 601

Options for benchmarks

-l, --length       Approximate string length in kilobytes. Default ~ 300 KB.
-t, --times        Number of runs this bench. Default - 1 times.

Test files are accumulated in one file. If you specify, for example, --length 100 the first file will be taken, checked whether it is longer than 100 kilobytes, and if no - it will be attached to the next one and checked its length, and so on.

Example of usage bench options

In order for npm passing the parameters, they need to be separated via --:

npm run bench -- -l 500 -t 1

Contribution and License Agreement

If you contribute code to this project, you are implicitly allowing your code to be distributed under the MIT license. You are also implicitly verifying that all code is your original work. </legalese>

Other libs from the author

If you enjoy working with TypeScript, we also recommend other libraries by the same author:

  • Ditsmod - a web framework for Node.js to build modular applications;
  • @ts-stack/openapi-spec - TypeScript models for writing OpenAPI documentation.

markdown's People

Contributors

dependabot[bot] avatar habc0807 avatar kostyatretyak avatar mvanassche avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

markdown's Issues

A way skip initial <P> tag?

First; Thank you for a wonderful Markdown parser!

When using it inside React I think i have to insert generated markup like this

return <div dangerouslySetInnerHTML={{ __html: Marked.parse(markup) }} />

Please advice me if I'm wrong. But then I get this error from React:

Warning: validateDOMNesting(...): <p> cannot appear as a descendant of <div>.

Is there a way to skip the surrounding p-tag generated by the parser ?

Escaping `{` into `{{ '{' }}`?

Nice work with marked-ts!


Wrote a little script to allow Angular to support Markdown, using marked-ts.

Given b.component.md:

## Hello
<div *ngIf="true">
```bash
echo ${5}
```
</div>

It generates:

<h2 id="hello">Hello</h2>
<div *ngIf="true">
<code>bash
echo ${5}</code>
</div>

How would I escape things Angular doesn't support?

Namely, I want to generate:

<h2 id="hello">Hello</h2>
<div *ngIf="true">
<code>bash
echo ${{'{'}}5{{'}'}}</code>
</div>

EDIT_0: I can't escape with NgNonBindable due to angular/angular#11859
EDIT_1: Wrote a very basic custom post processing for this:
https://github.com/SamuelMarks/ng-md-components/blob/ceec9783881a2864fe5e2fff82bec115895733de/index.ts#L73-L91

this.options.escape is not a function

Received an error while trying some more complicated markdown rendering.

Message: this.options.escape is not a function Please report this to https://github.com/KostyaTretyak/marked-ts
Exception type: TypeError
Failed method: Renderer.code

Stack:

TypeError:
   at Renderer.code (at Renderer.code (/home/site/wwwroot/dist/server.js:78487:69)at Renderer.code (/home/site/wwwroot/dist/server.js:78487:69): /home/site/wwwroot/dist/server.jsat Renderer.code (/home/site/wwwroot/dist/server.js:78487:69): 78487)
   at Parser.tok (at Parser.tok (/home/site/wwwroot/dist/server.js:78392:42)at Parser.tok (/home/site/wwwroot/dist/server.js:78392:42): /home/site/wwwroot/dist/server.jsat Parser.tok (/home/site/wwwroot/dist/server.js:78392:42): 78392)
   at Parser.parse (at Parser.parse (/home/site/wwwroot/dist/server.js:78314:25)at Parser.parse (/home/site/wwwroot/dist/server.js:78314:25): /home/site/wwwroot/dist/server.jsat Parser.parse (/home/site/wwwroot/dist/server.js:78314:25): 78314)
   at Function.Parser.parse (at Function.Parser.parse (/home/site/wwwroot/dist/server.js:78307:23)at Function.Parser.parse (/home/site/wwwroot/dist/server.js:78307:23): /home/site/wwwroot/dist/server.jsat Function.Parser.parse (/home/site/wwwroot/dist/server.js:78307:23): 78307)
   at Function.Marked.callParser (at Function.Marked.callParser (/home/site/wwwroot/dist/server.js:78256:36)at Function.Marked.callParser (/home/site/wwwroot/dist/server.js:78256:36): /home/site/wwwroot/dist/server.jsat Function.Marked.callParser (/home/site/wwwroot/dist/server.js:78256:36): 78256)
   at Function.Marked.parse (at Function.Marked.parse (/home/site/wwwroot/dist/server.js:78202:25)at Function.Marked.parse (/home/site/wwwroot/dist/server.js:78202:25): /home/site/wwwroot/dist/server.jsat Function.Marked.parse (/home/site/wwwroot/dist/server.js:78202:25): 78202)
   at renderMarkdown (at renderMarkdown (/home/site/wwwroot/dist/server.js:77732:61)at renderMarkdown (/home/site/wwwroot/dist/server.js:77732:61): /home/site/wwwroot/dist/server.jsat renderMarkdown (/home/site/wwwroot/dist/server.js:77732:61): 77732)
   at contentSection.item.data.contentSection.item.data.contentSection.map.section (at contentSection.item.data.contentSection.item.data.contentSection.map.section (/home/site/wwwroot/dist/server.js:79220:116)at contentSection.item.data.contentSection.item.data.contentSection.map.section (/home/site/wwwroot/dist/server.js:79220:116): /home/site/wwwroot/dist/server.jsat contentSection.item.data.contentSection.item.data.contentSection.map.section (/home/site/wwwroot/dist/server.js:79220:116): 79220)
   at mapCommunicationArticle (at mapCommunicationArticle (/home/site/wwwroot/dist/server.js:79217:77)at mapCommunicationArticle (/home/site/wwwroot/dist/server.js:79217:77): /home/site/wwwroot/dist/server.jsat mapCommunicationArticle (/home/site/wwwroot/dist/server.js:79217:77): 79217)

The offending markdown (but with three backticks):

`` 
{
  "firstName": "John",
  "lastName": "Smith",
  "age": 25
}
`` 

How to get `hljs` class on code element?

When using with highlightjs the resulting <code> element should have the hljs class as well as lang-whatever in order to properly theme the code with background color etc.

Is there an easy way to configure marked-ts to do this automatically?

Issue using {sanitize:true} inline

Using following way to sanitize causes runtime error.

     {@html Marked.parse(event.description ?? '', {sanitize: true})}

TypeError: this.options.escape is not a function
Please report this to https://github.com/ts-stack/markdown
at InlineLexer.output (/Users/xxxx/node_modules/@ts-stack/markdown/bundles/ts-stack-markdown.umd.js:797:60)
at Parser.tok (/Users/xxxx/node_modules/@ts-stack/markdown/bundles/ts-stack-markdown.umd.js:930:69)
at Parser.parse (/Users/xxxx/node_modules/@ts-stack/markdown/bundles/ts-stack-markdown.umd.js:894:29)
at Parser.parse (/Users/xxxx/node_modules/@ts-stack/markdown/bundles/ts-stack-markdown.umd.js:887:27)
at Marked.callParser (/Users/xxxx/node_modules/@ts-stack/markdown/bundles/ts-stack-markdown.umd.js:1137:31)
at Marked.parse (/Users/xxxx/node_modules/@ts-stack/markdown/bundles/ts-stack-markdown.umd.js:1078:29)
at eval (/Users/xxxx/src/lib/components/EventCard.svelte:29:1006)
at Object.$$render (/Users/xxxx/node_modules/svelte/src/runtime/internal/ssr.js:174:16)
at Object.default (/Users/xxxx/src/routes/(prerender)/(home)/+page.svelte:93:102)
at eval (/Users/xxxx/src/lib/components/Section.svelte:17:39)

identity parsing for markdown transformation

Problem

This library takes md as input and parse more-or-less creates HTML, but I expected a parsed IR of the markdown, versus a transformed format. parse seems to actually be convert, vs parse.

I need to take md => md, but adding content along the way.

Can this library support that use case?

There is an error when trying to pass options as `parse` argument

let options: MarkedOptions = {isNoP: true};

Marked.setOptions(options);//is working but

Marked.parse("some intput", options)//provides to error:

TypeError: this.options.escape is not a function
Please report this to https://github.com/KostyaTretyak/marked-ts
    at InlineLexer.output (http://localhost:8100/build/vendor.js:74738:56)
    at Parser.parseText (http://localhost:8100/build/vendor.js:74372:33)
    at Parser.tok (http://localhost:8100/build/vendor.js:74387:37)
    at Parser.parse (http://localhost:8100/build/vendor.js:74345:25)
    at Function.Parser.parse (http://localhost:8100/build/vendor.js:74338:23)
    at Function.Marked.callParser (http://localhost:8100/build/vendor.js:50612:36)
    at Function.Marked.parse (http://localhost:8100/build/vendor.js:50558:25)
    at MarkedProvider.webpackJsonp.214.MarkedProvider.simpleMarked (http://localhost:8100/build/main.js:162:66)
....

Detect code block vs code snippet

How can I detect if it was a tripple backtick codeblock or a single backtick code snippet in renderer?

class MarkdownRenderer extends Renderer {
    code(code: string, lang: string, escaped: boolean) {
        if (escaped) return code
        return `<pre><code class="codeblock lang-${lang}">${code}</code></pre>`
    }
}

IE 11 issue on 1.0.0-beta.5

Hello,

The latest versjon of markdown-ts has issue with polyfills.

Issue is in this line

Object.assign(this.options, options);

Describe the bug

The latest version or 1.0.0-beta.5 does not work in IE 11

To Reproduce

Import it in any file and open this one in IE 11

Expected behavior

It works :) .

Add option for line break ('<br>') character

I would like to use a backslash \ instead of double spaces to render a line break, maybe this could be an option in the settings - or is it possible somehow to change the regex for a line break?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.