index.js (2730B)
1 "use strict"; 2 3 // Map the characters to escape to their escaped values. The list is derived 4 // from http://www.cespedes.org/blog/85/how-to-escape-latex-special-characters 5 6 var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 7 8 var defaultEscapes = { 9 "{": "\\{", 10 "}": "\\}", 11 "\\": "\\textbackslash{}", 12 "#": "\\#", 13 $: "\\$", 14 "%": "\\%", 15 "&": "\\&", 16 "^": "\\textasciicircum{}", 17 _: "\\_", 18 "~": "\\textasciitilde{}" 19 }; 20 var formatEscapes = { 21 "\u2013": "\\--", 22 "\u2014": "\\---", 23 " ": "~", 24 "\t": "\\qquad{}", 25 "\r\n": "\\newline{}", 26 "\n": "\\newline{}" 27 }; 28 29 var defaultEscapeMapFn = function defaultEscapeMapFn(defaultEscapes, formatEscapes) { 30 return _extends({}, defaultEscapes, formatEscapes); 31 }; 32 33 /** 34 * Escape a string to be used in LaTeX documents. 35 * @param {string} str the string to be escaped. 36 * @param {boolean} params.preserveFormatting whether formatting escapes should 37 * be performed (default: false). 38 * @param {function} params.escapeMapFn the function to modify the escape maps. 39 * @return {string} the escaped string, ready to be used in LaTeX. 40 */ 41 module.exports = function (str) { 42 var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, 43 _ref$preserveFormatti = _ref.preserveFormatting, 44 preserveFormatting = _ref$preserveFormatti === undefined ? false : _ref$preserveFormatti, 45 _ref$escapeMapFn = _ref.escapeMapFn, 46 escapeMapFn = _ref$escapeMapFn === undefined ? defaultEscapeMapFn : _ref$escapeMapFn; 47 48 var runningStr = String(str); 49 var result = ""; 50 51 var escapes = escapeMapFn(_extends({}, defaultEscapes), preserveFormatting ? _extends({}, formatEscapes) : {}); 52 var escapeKeys = Object.keys(escapes); // as it is reused later on 53 54 // Algorithm: Go through the string character by character, if it matches 55 // with one of the special characters then we'll replace it with the escaped 56 // version. 57 58 var _loop = function _loop() { 59 var specialCharFound = false; 60 escapeKeys.forEach(function (key, index) { 61 if (specialCharFound) { 62 return; 63 } 64 if (runningStr.length >= key.length && runningStr.slice(0, key.length) === key) { 65 result += escapes[escapeKeys[index]]; 66 runningStr = runningStr.slice(key.length, runningStr.length); 67 specialCharFound = true; 68 } 69 }); 70 if (!specialCharFound) { 71 result += runningStr.slice(0, 1); 72 runningStr = runningStr.slice(1, runningStr.length); 73 } 74 }; 75 76 while (runningStr) { 77 _loop(); 78 } 79 return result; 80 };