Browse Source

Use template literals for string interpolation

pull/1197/head
Vitaly Puzrin 3 months ago
parent
commit
fed6e34e42
  1. 6
      README.md
  2. 2
      bin/markdown-it.mjs
  3. 4
      docs/architecture.md
  4. 13
      src/common/html_re.ts
  5. 2
      src/common/utils.ts
  6. 10
      src/markdownit.ts
  7. 14
      src/renderer.ts
  8. 10
      src/ruler.ts
  9. 4
      src/rules_block/heading.ts
  10. 4
      src/rules_block/html_block.ts
  11. 4
      src/rules_block/lheading.ts
  12. 4
      src/rules_block/table.ts
  13. 4
      src/rules_core/linkify.ts
  14. 2
      src/rules_inline/autolink.ts
  15. 2
      src/token.ts
  16. 24
      support/demo_template/index.mjs
  17. 7
      support/specsplit.mjs
  18. 2
      test/cmspec/commonmark.test.mjs
  19. 4
      test/markdown-it/misc.test.mjs

6
README.md

@ -185,13 +185,11 @@ const md = markdownit({
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return '<pre><code class="hljs">' +
hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
'</code></pre>';
return `<pre><code class="hljs">${hljs.highlight(str, { language: lang, ignoreIllegals: true }).value}</code></pre>`;
} catch (__) {}
}
return '<pre><code class="hljs">' + md.utils.escapeHtml(str) + '</code></pre>';
return `<pre><code class="hljs">${md.utils.escapeHtml(str)}</code></pre>`;
}
});
```

2
bin/markdown-it.mjs

@ -68,7 +68,7 @@ readFile(options.file, 'utf8', function (err, input) {
if (err) {
if (err.code === 'ENOENT') {
console.error('File not found: ' + options.file)
console.error(`File not found: ${options.file}`)
process.exit(2)
}

4
docs/architecture.md

@ -121,9 +121,7 @@ md.renderer.rules.image = function (tokens, idx, options, env, self) {
if (vimeoRE.test(src)) {
var id = src.match(vimeoRE)[2];
return '<div class="embed-responsive embed-responsive-16by9">\n' +
' <iframe class="embed-responsive-item" src="//player.vimeo.com/video/' + id + '"></iframe>\n' +
'</div>\n';
return `<div class="embed-responsive embed-responsive-16by9">\n <iframe class="embed-responsive-item" src="//player.vimeo.com/video/${id}"></iframe>\n</div>\n`;
}
// Pass the token to the default renderer.

13
src/common/html_re.ts

@ -6,11 +6,11 @@ const unquoted = '[^"\'=<>`\\x00-\\x20]+'
const single_quoted = "'[^']*'"
const double_quoted = '"[^"]*"'
const attr_value = '(?:' + unquoted + '|' + single_quoted + '|' + double_quoted + ')'
const attr_value = `(?:${unquoted}|${single_quoted}|${double_quoted})`
const attribute = '(?:\\s+' + attr_name + '(?:\\s*=\\s*' + attr_value + ')?)'
const attribute = `(?:\\s+${attr_name}(?:\\s*=\\s*${attr_value})?)`
const open_tag = '<[A-Za-z][A-Za-z0-9\\-]*' + attribute + '*\\s*\\/?>'
const open_tag = `<[A-Za-z][A-Za-z0-9\\-]*${attribute}*\\s*\\/?>`
const close_tag = '<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>'
const comment = '<!---?>|<!--(?:[^-]|-[^-]|--[^>])*-->'
@ -18,8 +18,9 @@ const processing = '<[?][\\s\\S]*?[?]>'
const declaration = '<![A-Za-z][^>]*>'
const cdata = '<!\\[CDATA\\[[\\s\\S]*?\\]\\]>'
const HTML_TAG_RE = new RegExp('^(?:' + open_tag + '|' + close_tag + '|' + comment +
'|' + processing + '|' + declaration + '|' + cdata + ')')
const HTML_OPEN_CLOSE_TAG_RE = new RegExp('^(?:' + open_tag + '|' + close_tag + ')')
const HTML_TAG_RE = new RegExp(
`^(?:${open_tag}|${close_tag}|${comment}|${processing}|${declaration}|${cdata})`
)
const HTML_OPEN_CLOSE_TAG_RE = new RegExp(`^(?:${open_tag}|${close_tag})`)
export { HTML_TAG_RE, HTML_OPEN_CLOSE_TAG_RE }

2
src/common/utils.ts

@ -63,7 +63,7 @@ function fromCodePoint (c: number) {
const UNESCAPE_MD_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g
const ENTITY_RE = /&([a-z#][a-z0-9]{1,31});/gi
const UNESCAPE_ALL_RE = new RegExp(UNESCAPE_MD_RE.source + '|' + ENTITY_RE.source, 'gi')
const UNESCAPE_ALL_RE = new RegExp(`${UNESCAPE_MD_RE.source}|${ENTITY_RE.source}`, 'gi')
const DIGITAL_ENTITY_TEST_RE = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i

10
src/markdownit.ts

@ -228,13 +228,11 @@ function normalizeLinkText (url: string): string {
* highlight: function (str, lang) {
* if (lang && hljs.getLanguage(lang)) {
* try {
* return '<pre><code class="hljs">' +
* hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
* '</code></pre>';
* return `<pre><code class="hljs">${hljs.highlight(str, { language: lang, ignoreIllegals: true }).value}</code></pre>`;
* } catch (__) {}
* }
*
* return '<pre><code class="hljs">' + md.utils.escapeHtml(str) + '</code></pre>';
* return `<pre><code class="hljs">${md.utils.escapeHtml(str)}</code></pre>`;
* }
* });
* ```
@ -468,7 +466,7 @@ class MarkdownIt {
const missed = list.filter((name) => result.indexOf(name) < 0)
if (missed.length && !ignoreInvalid) {
throw new Error('MarkdownIt. Failed to enable unknown rule(s): ' + missed)
throw new Error(`MarkdownIt. Failed to enable unknown rule(s): ${missed}`)
}
return this
@ -496,7 +494,7 @@ class MarkdownIt {
const missed = list.filter((name) => result.indexOf(name) < 0)
if (missed.length && !ignoreInvalid) {
throw new Error('MarkdownIt. Failed to disable unknown rule(s): ' + missed)
throw new Error(`MarkdownIt. Failed to disable unknown rule(s): ${missed}`)
}
return this
}

14
src/renderer.ts

@ -29,9 +29,7 @@ default_rules.code_inline = function (
): string {
const token = tokens[idx]
return '<code' + slf.renderAttrs(token) + '>' +
escapeHtml(token.content) +
'</code>'
return `<code${slf.renderAttrs(token)}>${escapeHtml(token.content)}</code>`
}
default_rules.code_block = function (
@ -43,9 +41,7 @@ default_rules.code_block = function (
): string {
const token = tokens[idx]
return '<pre' + slf.renderAttrs(token) + '><code>' +
escapeHtml(tokens[idx].content) +
'</code></pre>\n'
return `<pre${slf.renderAttrs(token)}><code>${escapeHtml(tokens[idx].content)}</code></pre>\n`
}
default_rules.fence = function (
@ -85,10 +81,10 @@ default_rules.fence = function (
const tmpAttrs = token.attrs ? token.attrs.slice() : []
if (i < 0) {
tmpAttrs.push(['class', options.langPrefix + langName])
tmpAttrs.push(['class', `${options.langPrefix}${langName}`])
} else {
tmpAttrs[i] = [tmpAttrs[i][0], tmpAttrs[i][1]] // shallow clone
tmpAttrs[i][1] += ' ' + options.langPrefix + langName
tmpAttrs[i][1] += ` ${options.langPrefix}${langName}`
}
// Fake token just to render attributes
@ -197,7 +193,7 @@ class Renderer {
result = ''
for (i = 0, l = token.attrs.length; i < l; i++) {
result += ' ' + escapeHtml(token.attrs[i][0]) + '="' + escapeHtml(String(token.attrs[i][1])) + '"'
result += ` ${escapeHtml(token.attrs[i][0])}="${escapeHtml(String(token.attrs[i][1]))}"`
}
return result

10
src/ruler.ts

@ -119,7 +119,7 @@ class Ruler<Args extends unknown[], Result> {
at (name: string, fn: (...args: Args) => Result, options: RuleOptions = {}): void {
const index = this.__find__(name)
if (index === -1) { throw new Error('Parser rule not found: ' + name) }
if (index === -1) { throw new Error(`Parser rule not found: ${name}`) }
this.__rules__[index].fn = fn
this.__rules__[index].alt = options.alt || []
@ -153,7 +153,7 @@ class Ruler<Args extends unknown[], Result> {
before (beforeName: string, ruleName: string, fn: (...args: Args) => Result, options: RuleOptions = {}): void {
const index = this.__find__(beforeName)
if (index === -1) { throw new Error('Parser rule not found: ' + beforeName) }
if (index === -1) { throw new Error(`Parser rule not found: ${beforeName}`) }
this.__rules__.splice(index, 0, {
name: ruleName,
@ -192,7 +192,7 @@ class Ruler<Args extends unknown[], Result> {
after (afterName: string, ruleName: string, fn: (...args: Args) => Result, options: RuleOptions = {}): void {
const index = this.__find__(afterName)
if (index === -1) { throw new Error('Parser rule not found: ' + afterName) }
if (index === -1) { throw new Error(`Parser rule not found: ${afterName}`) }
this.__rules__.splice(index + 1, 0, {
name: ruleName,
@ -261,7 +261,7 @@ class Ruler<Args extends unknown[], Result> {
if (idx < 0) {
if (ignoreInvalid) { return }
throw new Error('Rules manager: invalid rule name ' + name)
throw new Error(`Rules manager: invalid rule name ${name}`)
}
this.__rules__[idx].enabled = true
result.push(name)
@ -312,7 +312,7 @@ class Ruler<Args extends unknown[], Result> {
if (idx < 0) {
if (ignoreInvalid) { return }
throw new Error('Rules manager: invalid rule name ' + name)
throw new Error(`Rules manager: invalid rule name ${name}`)
}
this.__rules__[idx].enabled = false
result.push(name)

4
src/rules_block/heading.ts

@ -36,7 +36,7 @@ export default function heading (state: StateBlock, startLine: number, endLine:
state.line = startLine + 1
const token_o = state.push('heading_open', 'h' + String(level), 1)
const token_o = state.push('heading_open', `h${level}`, 1)
token_o.markup = '########'.slice(0, level)
token_o.map = [startLine, state.line]
@ -45,7 +45,7 @@ export default function heading (state: StateBlock, startLine: number, endLine:
token_i.map = [startLine, state.line]
token_i.children = []
const token_c = state.push('heading_close', 'h' + String(level), -1)
const token_c = state.push('heading_close', `h${level}`, -1)
token_c.markup = '########'.slice(0, level)
return true

4
src/rules_block/html_block.ts

@ -17,8 +17,8 @@ const HTML_SEQUENCES: Array<[
[/^<\?/, /\?>/, true],
[/^<![A-Za-z]/, />/, true],
[/^<!\[CDATA\[/, /\]\]>/, true],
[new RegExp('^</?(' + block_names.join('|') + ')(?=(\\s|/?>|$))', 'i'), /^$/, true],
[new RegExp(HTML_OPEN_CLOSE_TAG_RE.source + '\\s*$'), /^$/, false]
[new RegExp(`^</?(${block_names.join('|')})(?=(\\s|/?>|$))`, 'i'), /^$/, true],
[new RegExp(`${HTML_OPEN_CLOSE_TAG_RE.source}\\s*$`), /^$/, false]
]
export default function html_block (state: StateBlock, startLine: number, endLine: number, silent: boolean): boolean {

4
src/rules_block/lheading.ts

@ -68,7 +68,7 @@ export default function lheading (state: StateBlock, startLine: number, endLine:
state.line = nextLine + 1
const token_o = state.push('heading_open', 'h' + String(level), 1)
const token_o = state.push('heading_open', `h${level}`, 1)
token_o.markup = String.fromCharCode(marker!)
token_o.map = [startLine, state.line]
@ -77,7 +77,7 @@ export default function lheading (state: StateBlock, startLine: number, endLine:
token_i.map = [startLine, state.line - 1]
token_i.children = []
const token_c = state.push('heading_close', 'h' + String(level), -1)
const token_c = state.push('heading_close', `h${level}`, -1)
token_c.markup = String.fromCharCode(marker!)
state.parentType = oldParentType

4
src/rules_block/table.ts

@ -152,7 +152,7 @@ export default function table (state: StateBlock, startLine: number, endLine: nu
for (let i = 0; i < columns.length; i++) {
const token_ho = state.push('th_open', 'th', 1)
if (aligns[i]) {
token_ho.attrs = [['style', 'text-align:' + aligns[i]]]
token_ho.attrs = [['style', `text-align:${aligns[i]}`]]
}
const token_il = state.push('inline', '', 0)
@ -203,7 +203,7 @@ export default function table (state: StateBlock, startLine: number, endLine: nu
for (let i = 0; i < columnCount; i++) {
const token_tdo = state.push('td_open', 'td', 1)
if (aligns[i]) {
token_tdo.attrs = [['style', 'text-align:' + aligns[i]]]
token_tdo.attrs = [['style', `text-align:${aligns[i]}`]]
}
const token_il = state.push('inline', '', 0)

4
src/rules_core/linkify.ts

@ -84,9 +84,9 @@ export default function linkify (state: StateCore): void {
// and remove it afterwards.
//
if (!links[ln].schema) {
urlText = state.md.normalizeLinkText('http://' + urlText).replace(/^http:\/\//, '')
urlText = state.md.normalizeLinkText(`http://${urlText}`).replace(/^http:\/\//, '')
} else if (links[ln].schema === 'mailto:' && !/^mailto:/i.test(urlText)) {
urlText = state.md.normalizeLinkText('mailto:' + urlText).replace(/^mailto:/, '')
urlText = state.md.normalizeLinkText(`mailto:${urlText}`).replace(/^mailto:/, '')
} else {
urlText = state.md.normalizeLinkText(urlText)
}

2
src/rules_inline/autolink.ts

@ -49,7 +49,7 @@ export default function autolink (state: StateInline, silent: boolean): boolean
}
if (EMAIL_RE.test(url)) {
const fullUrl = state.md.normalizeLink('mailto:' + url)
const fullUrl = state.md.normalizeLink(`mailto:${url}`)
if (!state.md.validateLink(fullUrl)) { return false }
if (!silent) {

2
src/token.ts

@ -197,7 +197,7 @@ class Token {
if (idx < 0) {
this.attrPush([name, value])
} else {
this.attrs![idx][1] = this.attrs![idx][1] + ' ' + value
this.attrs![idx][1] = `${this.attrs![idx][1]} ${value}`
}
}
}

24
support/demo_template/index.mjs

@ -126,28 +126,24 @@ defaults.highlight = function (str, lang) {
}
if (lang && lang !== 'auto' && hljs.getLanguage(lang)) {
return '<pre class="hljs language-' + esc(lang.toLowerCase()) + '"><code>' +
hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
'</code></pre>'
return `<pre class="hljs language-${esc(lang.toLowerCase())}"><code>${hljs.highlight(str, { language: lang, ignoreIllegals: true }).value}</code></pre>`
} else if (lang === 'auto') {
const result = hljs.highlightAuto(str)
console.log('highlight language: ' + result.language + ', relevance: ' + result.relevance)
console.log(`highlight language: ${result.language}, relevance: ${result.relevance}`)
return '<pre class="hljs language-' + esc(result.language) + '"><code>' +
result.value +
'</code></pre>'
return `<pre class="hljs language-${esc(result.language)}"><code>${result.value}</code></pre>`
}
} catch (__) { /**/ }
return '<pre><code class="hljs">' + esc(str) + '</code></pre>'
return `<pre><code class="hljs">${esc(str)}</code></pre>`
}
function setOptionClass (name, val) {
if (val) {
document.body.classList.add('opt_' + name)
document.body.classList.add(`opt_${name}`)
} else {
document.body.classList.remove('opt_' + name)
document.body.classList.remove(`opt_${name}`)
}
}
@ -155,7 +151,7 @@ function setResultView (val) {
document.body.classList.remove('result-as-html')
document.body.classList.remove('result-as-src')
document.body.classList.remove('result-as-debug')
document.body.classList.add('result-as-' + val)
document.body.classList.add(`result-as-${val}`)
defaults._view = val
}
@ -227,10 +223,10 @@ function updateResult () {
try {
if (source) {
// serialize state - source and options
permalink.href = '#md3=' + mdurl.encode(JSON.stringify({
permalink.href = `#md3=${mdurl.encode(JSON.stringify({
source,
defaults: permalinkDefaults()
}), '-_.!~', false)
}), '-_.!~', false)}`
} else {
permalink.href = ''
}
@ -252,7 +248,7 @@ function buildScrollMap () {
position: 'absolute',
visibility: 'hidden',
height: 'auto',
width: textarea.clientWidth + 'px',
width: `${textarea.clientWidth}px`,
fontSize: textareaStyle.fontSize,
fontFamily: textareaStyle.fontFamily,
lineHeight: textareaStyle.lineHeight,

7
support/specsplit.mjs

@ -59,7 +59,7 @@ readFile(options.spec, 'utf8', function (error, input) {
if (error) {
if (error.code === 'ENOENT') {
process.stderr.write('File not found: ' + options.spec)
process.stderr.write(`File not found: ${options.spec}`)
process.exit(2)
}
@ -102,10 +102,7 @@ readFile(options.spec, 'utf8', function (error, input) {
const data = options.type === 'good' ? good : bad
data.forEach(function (sample) {
out.push(
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' +
`src line: ${sample.line}\n\n.\n${sample.md}.\n${sample.html}.\n`
)
out.push(`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nsrc line: ${sample.line}\n\n.\n${sample.md}.\n${sample.html}.\n`)
if (sample.err) {
out.push(`error:\n\n${sample.err}\n`)
}

2
test/cmspec/commonmark.test.mjs

@ -31,7 +31,7 @@ function loadSpecExamples (path, md) {
function generate (path, md) {
describe('spec.txt', function () {
loadSpecExamples(path, md).forEach(function (fixture) {
it('line ' + fixture.line, function () {
it(`line ${fixture.line}`, function () {
assert.strictEqual(md.render(fixture.md), normalize(fixture.html))
})
})

4
test/markdown-it/misc.test.mjs

@ -42,7 +42,7 @@ describe('API', function () {
it('highlight', function () {
const md = markdownit({
highlight: function (str) {
return '<pre><code>==' + str + '==</code></pre>'
return `<pre><code>==${str}==</code></pre>`
}
})
@ -64,7 +64,7 @@ describe('API', function () {
highlight: function (str, lang, attrs) {
assert.strictEqual(lang, 'a')
assert.strictEqual(attrs, 'b c d')
return '<pre><code>==' + str + '==</code></pre>'
return `<pre><code>==${str}==</code></pre>`
}
})

Loading…
Cancel
Save