Browse Source

Refactor typographer replacements functions

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

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

Loading…
Cancel
Save