From 0ccc687367e900e93a2a0183814af9d65a54fef3 Mon Sep 17 00:00:00 2001 From: Christopher Breeden Date: Sat, 18 Jun 2016 15:40:18 -0500 Subject: [PATCH] Add shallow cloning capabilities to Tokens to preserve the AST after rendering --- lib/renderer.js | 5 ++++- lib/token.js | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/lib/renderer.js b/lib/renderer.js index 0da9ad8..bbee085 100644 --- a/lib/renderer.js +++ b/lib/renderer.js @@ -29,7 +29,10 @@ default_rules.code_block = function (tokens, idx /*, options, env */) { default_rules.fence = function (tokens, idx, options, env, slf) { - var token = tokens[idx], + // We will make modifications of the attributes object of this + // token while processing, so we obtain a shallow clone as to + // prevent modifying the token in the token list. + var token = tokens[idx].clone(), info = token.info ? unescapeAll(token.info).trim() : '', langName = '', highlighted; diff --git a/lib/token.js b/lib/token.js index 54e1a5c..77f4d12 100644 --- a/lib/token.js +++ b/lib/token.js @@ -194,4 +194,28 @@ Token.prototype.attrJoin = function attrJoin(name, value) { }; +/** + * Token.clone() + * + * Obtain a shallow clone of the token. You can use this while rendering to + * prevent modifying the token list while rendering. + */ + +Token.prototype.clone = function clone() { + var token = new Token(this.type, this.tag, this.nesting); + + token.attrs = this.attrs; + token.level = this.level; + token.children = this.children; + token.content = this.content; + token.map = this.map; + token.markup = this.markup; + token.info = this.info; + token.meta = this.meta; + token.block = this.block; + token.hidden = this.hidden; + + return token; +}; + module.exports = Token;