| 26 | * @private |
| 27 | **/ |
| 28 | function expandTemplate (template, node, options) { |
| 29 | let latex = '' |
| 30 | |
| 31 | // Match everything of the form ${identifier} or ${identifier[2]} or $$ |
| 32 | // while submatching identifier and 2 (in the second case) |
| 33 | const regex = /\$(?:\{([a-z_][a-z_0-9]*)(?:\[([0-9]+)\])?\}|\$)/gi |
| 34 | |
| 35 | let inputPos = 0 // position in the input string |
| 36 | let match |
| 37 | while ((match = regex.exec(template)) !== null) { // go through all matches |
| 38 | // add everything in front of the match to the LaTeX string |
| 39 | latex += template.substring(inputPos, match.index) |
| 40 | inputPos = match.index |
| 41 | |
| 42 | if (match[0] === '$$') { // escaped dollar sign |
| 43 | latex += '$' |
| 44 | inputPos++ |
| 45 | } else { // template parameter |
| 46 | inputPos += match[0].length |
| 47 | const property = node[match[1]] |
| 48 | if (!property) { |
| 49 | throw new ReferenceError('Template: Property ' + match[1] + ' does not exist.') |
| 50 | } |
| 51 | if (match[2] === undefined) { // no square brackets |
| 52 | switch (typeof property) { |
| 53 | case 'string': |
| 54 | latex += property |
| 55 | break |
| 56 | case 'object': |
| 57 | if (isNode(property)) { |
| 58 | latex += property.toTex(options) |
| 59 | } else if (Array.isArray(property)) { |
| 60 | // make array of Nodes into comma separated list |
| 61 | latex += property.map(function (arg, index) { |
| 62 | if (isNode(arg)) { |
| 63 | return arg.toTex(options) |
| 64 | } |
| 65 | throw new TypeError('Template: ' + match[1] + '[' + index + '] is not a Node.') |
| 66 | }).join(',') |
| 67 | } else { |
| 68 | throw new TypeError('Template: ' + match[1] + ' has to be a Node, String or array of Nodes') |
| 69 | } |
| 70 | break |
| 71 | default: |
| 72 | throw new TypeError('Template: ' + match[1] + ' has to be a Node, String or array of Nodes') |
| 73 | } |
| 74 | } else { // with square brackets |
| 75 | if (isNode(property[match[2]] && property[match[2]])) { |
| 76 | latex += property[match[2]].toTex(options) |
| 77 | } else { |
| 78 | throw new TypeError('Template: ' + match[1] + '[' + match[2] + '] is not a Node.') |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | latex += template.slice(inputPos) // append rest of the template |
| 84 | |
| 85 | return latex |