Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

overwrite Indented code blocks but keep Fenced code blocks #1696

Closed
jackusay opened this issue May 31, 2020 · 2 comments
Closed

overwrite Indented code blocks but keep Fenced code blocks #1696

jackusay opened this issue May 31, 2020 · 2 comments
Labels

Comments

@jackusay
Copy link

jackusay commented May 31, 2020

I would like to overwrite Indented code blocks render without overwrite Fenced code blocks.
Is that possible in current marked?

Indented code blocks: is some space before text
Fenced code blocks: is ``` before and after your text

I overwrite Indented code blocks via #1302 (comment)

const marked = require('marked');
const renderer = new marked.Renderer();

renderer.code = function (text) {
  return text;
};

console.log(marked(markdownString, { renderer: renderer }));

but it also overwrites Fenced code blocks.


my situation is
I write markdown with html, and I always format my html.
So it treats my some html into <pre><code>...</code></pre>.
And I only use Fenced code blocks... Indented code blocks kind of useless to me... (someone really use Indented code blocks?)

@UziTech
Copy link
Member

UziTech commented May 31, 2020

Your best bet would be to override the tokenizer. It has separate tokenizers for code (indented code) and fences (fenced code).

Or you could unformat you code before sending it to marked. Something like:

marked(markdown.replace(/^\s+/gm, ''));

@jackusay
Copy link
Author

jackusay commented Jun 1, 2020

It works! thank you!

const marked = require('marked');
const renderer = new marked.Renderer();


// Override function
const tokenizer = {
  code(src, tokens) {
    const cap = this.rules.block.code.exec(src);
    if (cap) {
      const lastToken = tokens[tokens.length - 1];
      // An indented code block cannot interrupt a paragraph.
      if (lastToken && lastToken.type === 'paragraph') {
        return {
          raw: cap[0],
          text: cap[0].trimRight()
        };
      }

      //const text = cap[0].replace(/^ {4}/gm, '');
      return {
        type: 'html',
        raw: cap[0],
        text: cap[0]
      };
    }
  }
};

marked.use({ tokenizer });

var fs = require('fs');
var markdownString = fs.readFileSync('txt.md', 'utf8');

//markdownString = '    ##dsfsf';

console.log(marked(markdownString));

ref:
https://github.com/markedjs/marked/blob/master/src/Tokenizer.js#L82

const block = {

@jackusay jackusay closed this as completed Jun 1, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants