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

Parser.parse extension to be able to change tokens as a whole #2639

Closed
kapouer opened this issue Nov 3, 2022 · 3 comments
Closed

Parser.parse extension to be able to change tokens as a whole #2639

kapouer opened this issue Nov 3, 2022 · 3 comments
Labels

Comments

@kapouer
Copy link
Contributor

kapouer commented Nov 3, 2022

Describe the feature
Ability to get the "root" tokens list before rendering - either through a Parser.parse extension, or another mecanism.

Why is this feature necessary?
I need my extension to be able to prepend a default (depth 1) heading token when one is missing.

Describe alternatives you've considered

const defaultParse = Parser.parse;
Parser.parse = (tokens, options) => {
	const [{ type, depth }] = tokens;
	if (type != "heading" || depth != 1) {
		tokens.unshift({
			type: 'heading',
			depth: 1,
			tokens: []
		});
	}
	return defaultParse.call(Parser, tokens, options);
};

but i hate monkey-patching.

@calculuschild
Copy link
Contributor

The walkTokens function might be what you are looking for. It lets you modify the token tree before being sent to the final HTML renderer.

@kapouer
Copy link
Contributor Author

kapouer commented Nov 3, 2022

Yes, but (unless I'm mistaken) it's not possible to know if the token is the first token of the document.
I tried setting a flag, but that fails when using marked as a library.

@UziTech
Copy link
Member

UziTech commented Nov 3, 2022

If all you need are the root tokens you can get the array from marked.lexer

const tokens = marked.lexer(markdown, options);
const [{ type, depth }] = tokens;
if (type != "heading" || depth != 1) {
  tokens.unshift({
    type: 'heading',
    depth: 1,
    tokens: []
  });
}
marked.parser(tokens, options);

There isn't currently an easy way to make this into an extension. For that we may need to implement hooks.

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

3 participants