// Simple typographyc replacements // // '' → ‘’ // "" → “”. Set '«»' for Russian, '„“' for German, empty to disable // (c) (C) → © // (tm) (TM) → ™ // (r) (R) → ® // +- → ± // (p) (P) -> § // ... → … (also ?.... → ?.., !.... → !..) // ???????? → ???, !!!!! → !!!, `,,` → `,` // -- → –, --- → — // 'use strict'; // TODO: // - fractionals 1/2, 1/4, 3/4 -> ½, ¼, ¾ // - miltiplication 2 x 4 -> 2 × 4 var RARE_RE = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/; var SCOPED_ABBR_RE = /\((c|tm|r|p)\)/ig; var SCOPED_ABBR = { 'c': '©', 'r': '®', 'p': '§', 'tm': '™' }; function replaceScopedAbbr(str) { if (str.indexOf('(') < 0) { return str; } return str.replace(SCOPED_ABBR_RE, function(match, name) { return SCOPED_ABBR[name.toLowerCase()]; }); } module.exports = function replace(state) { var i, token, text, inlineTokens, blkIdx; if (!state.options.typographer) { return; } for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) { if (state.tokens[blkIdx].type !== 'inline') { continue; } inlineTokens = state.tokens[blkIdx].children; for (i = inlineTokens.length - 1; i >= 0; i--) { token = inlineTokens[i]; if (token.type === 'text') { text = token.content; text = replaceScopedAbbr(text); if (RARE_RE.test(text)) { text = text.replace(/\+-/g, '±') // .., ..., ....... -> … // but ?..... & !..... -> ?.. & !.. .replace(/\.{2,}/g, '…').replace(/([?!])…/g, '$1..') .replace(/([?!]){4,}/g, '$1$1$1').replace(/,{2,}/g, ',') // em-dash .replace(/(^|[^-])---([^-]|$)/mg, '$1\u2014$2') // en-dash .replace(/(^|\s)--(\s|$)/mg, '$1\u2013$2') .replace(/(^|[^-\s])--([^-\s]|$)/mg, '$1\u2013$2'); } token.content = text; } } } };