How can I add custom tags to commonmark.js? Is commonmark.js the correct way to go about adding custom tags? I’ve had limited success using the walker class in the example below.
For example, I want to provide the user with the ability to type:
[one-third]some text here[/one-third]
and translate it to:
<div class="col-lg-4">some text here</div>
My walker function:
function oneThird(walker){
while ((event = walker.next())) {
node = event.node;
console.log(node);
console.log(node.literal); // [, heading1, ]
//console.log(node.next);
//console.log(node.next.next);
if (event.entering && node.type === 'text' && node.literal == "[" && node.next.literal == "one-third" && node.next.next.literal == "]") {
node.literal = "<div class='col-lg-4'>";
node.next.next.unlink();
node.next.unlink();
}
if (event.entering && node.type === 'text' && node.literal == "[" && node.next.literal == "/one-third" && node.next.next.literal == "]") {
node.literal = "</div>";
node.next.next.unlink();
node.next.unlink();
}
}
}
And then this is used like so:
var reader = new commonmark.Parser();
var writer = new commonmark.HtmlRenderer();
var parsed = reader.parse("Hello *world* [one-third]test[/one-third]"); // parsed is a 'Node' tree
var walker = parsed.walker();
var event, node;
var exitEntering;
oneThird(walker);
/*
Add all of my custom tag functions here
*/
// transform parsed if you like...
var result = writer.render(parsed); // result is a String
console.log(result); // <p>Hello <em>world</em> <div class='col-lg-4'>test[/one-third]</p>
This method doesn’t seem to account for situations in which the user doesn’t add the closing bracket either. Overall I just feel like I’m missing something and there is a better way to do this.
Edit:
Just to add, prior to my last post I came across some issue threads on commonmark.js github page which lead me to believe the renderer object might be a better option than the walker object. But I’m having a difficult time finding information on how to manipulate/extend it. Also, some of those threads are over a year old, so I’m not sure if there have been changes to the implementation since then.