Skip to content

Commit

Permalink
Move TextNode escaping to a separate rule, escapes to options and sim…
Browse files Browse the repository at this point in the history
…plify node processing.
  • Loading branch information
Vojtěch Srdečný committed Nov 15, 2019
1 parent cae7098 commit 706dc1d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 23 deletions.
11 changes: 11 additions & 0 deletions src/commonmark-rules.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,17 @@ import { repeat } from './utilities'

var rules = {}

rules.text = {
filter: '#text',

replacement: function (content, node, options) {
if (node.isCode) return node.nodeValue
return options.escapes.reduce(function (accumulator, escape) {
return accumulator.replace(escape[0], escape[1])
}, node.nodeValue).trim()
}
}

rules.paragraph = {
filter: 'p',

Expand Down
26 changes: 3 additions & 23 deletions src/turndown.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import Node from './node'
var reduce = Array.prototype.reduce
var leadingNewLinesRegExp = /^\n*/
var trailingNewLinesRegExp = /\n*$/
var escapes = [
var DEFAULT_ESCAPES = [
[/\\/g, '\\\\'],
[/\*/g, '\\*'],
[/^-/g, '\\-'],
Expand All @@ -27,6 +27,7 @@ export default function TurndownService (options) {

var defaults = {
rules: COMMONMARK_RULES,
escapes: DEFAULT_ESCAPES,
headingStyle: 'setext',
hr: '* * *',
bulletListMarker: '*',
Expand Down Expand Up @@ -130,20 +131,6 @@ TurndownService.prototype = {
remove: function (filter) {
this.rules.remove(filter)
return this
},

/**
* Escapes Markdown syntax
* @public
* @param {String} string The string to escape
* @returns A string with Markdown syntax escaped
* @type String
*/

escape: function (string) {
return escapes.reduce(function (accumulator, escape) {
return accumulator.replace(escape[0], escape[1])
}, string)
}
}

Expand All @@ -159,14 +146,7 @@ function process (parentNode) {
var self = this
return reduce.call(parentNode.childNodes, function (output, node) {
node = new Node(node)

var replacement = ''
if (node.nodeType === 3) {
replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue)
} else if (node.nodeType === 1) {
replacement = replacementForNode.call(self, node)
}

var replacement = replacementForNode.call(self, node)
return join(output, replacement)
}, '')
}
Expand Down

0 comments on commit 706dc1d

Please sign in to comment.