Browse Source

Refactor typographer replacements functions

pull/762/head
Kyle E. Mitchell 4 years ago
parent
commit
386ee103be
  1. 54
      lib/rules_core/replacements.js

54
lib/rules_core/replacements.js

@ -55,20 +55,15 @@ function replace_scoped(inlineTokens) {
}
}
function replace_rare(inlineTokens) {
function replace_helper(inlineTokens, re, replacer) {
var i, token, inside_autolink = 0;
for (i = inlineTokens.length - 1; i >= 0; i--) {
token = inlineTokens[i];
if (token.type === 'text' && !inside_autolink) {
if (RARE_RE.test(token.content)) {
token.content = token.content
.replace(/\+-/g, '±')
// .., ..., ....... -> …
// but ?..... & !..... -> ?.. & !..
.replace(/\.{2,}/g, '…').replace(/([?!])…/g, '$1..')
.replace(/([?!]){4,}/g, '$1$1$1').replace(/,{2,}/g, ',');
if (re.test(token.content)) {
token.content = replacer(token.content);
}
}
@ -82,31 +77,26 @@ function replace_rare(inlineTokens) {
}
}
function replace_dashes(inlineTokens) {
var i, token, inside_autolink = 0;
for (i = inlineTokens.length - 1; i >= 0; i--) {
token = inlineTokens[i];
if (token.type === 'text' && !inside_autolink) {
if (DASHES_RE.test(token.content)) {
token.content = token.content
// em-dash
.replace(/(^|[^-])---(?=[^-]|$)/mg, '$1\u2014')
// en-dash
.replace(/(^|\s)--(?=\s|$)/mg, '$1\u2013')
.replace(/(^|[^-\s])--(?=[^-\s]|$)/mg, '$1\u2013');
}
}
if (token.type === 'link_open' && token.info === 'auto') {
inside_autolink--;
}
function replace_rare(inlineTokens) {
replace_helper(inlineTokens, RARE_RE, function (content) {
return content
.replace(/\+-/g, '±')
// .., ..., ....... -> …
// but ?..... & !..... -> ?.. & !..
.replace(/\.{2,}/g, '…').replace(/([?!])…/g, '$1..')
.replace(/([?!]){4,}/g, '$1$1$1').replace(/,{2,}/g, ',');
});
}
if (token.type === 'link_close' && token.info === 'auto') {
inside_autolink++;
}
}
function replace_dashes(inlineTokens) {
replace_helper(inlineTokens, DASHES_RE, function (content) {
return content
// em-dash
.replace(/(^|[^-])---(?=[^-]|$)/mg, '$1\u2014')
// en-dash
.replace(/(^|\s)--(?=\s|$)/mg, '$1\u2013')
.replace(/(^|[^-\s])--(?=[^-\s]|$)/mg, '$1\u2013');
});
}
module.exports = function replace(state) {

Loading…
Cancel
Save