@mathzetta/inlinemath 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +37 -33
  2. package/dist/cas.external.js +2 -2
  3. package/dist/cas.js +2 -2
  4. package/dist/chunks/calculate-BGMEvf3f.js +2 -0
  5. package/dist/chunks/draw-q86mDDWm.js +2 -0
  6. package/dist/chunks/edit-CTMRUElt.js +2 -0
  7. package/dist/chunks/edit-D2RO7fg0.js +2 -0
  8. package/dist/chunks/html-1wCO6EpZ.js +2 -0
  9. package/dist/chunks/html-D5QiXGXD.js +2 -0
  10. package/dist/chunks/lite-Bo8THzyq.js +2 -0
  11. package/dist/fonts/README-inlinemath-greek.txt +15 -0
  12. package/dist/fonts/fonts.css +19 -1
  13. package/dist/fonts/inlinemath-greek-italic.woff2 +0 -0
  14. package/dist/fonts/inlinemath-greek-regular.woff2 +0 -0
  15. package/dist/inlinemath-cas.external.global.min.js +2 -2
  16. package/dist/inlinemath-cas.global.min.js +2 -2
  17. package/dist/inlinemath-lite-calc.global.min.js +2 -2
  18. package/dist/inlinemath-lite.external.global.min.js +2 -2
  19. package/dist/inlinemath-lite.global.min.js +2 -2
  20. package/dist/inlinemath.css +17 -7
  21. package/dist/inlinemath.external.global.min.js +2 -2
  22. package/dist/inlinemath.external.js +2 -2
  23. package/dist/inlinemath.global.min.js +2 -2
  24. package/dist/inlinemath.js +2 -2
  25. package/dist/lite-calc.js +2 -2
  26. package/dist/lite.external.js +2 -2
  27. package/dist/lite.js +2 -2
  28. package/dist/markdown.external.js +2 -2
  29. package/dist/markdown.js +2 -2
  30. package/fonts/README-inlinemath-greek.txt +15 -0
  31. package/fonts/fonts.css +19 -1
  32. package/fonts/inlinemath-greek-italic.woff2 +0 -0
  33. package/fonts/inlinemath-greek-regular.woff2 +0 -0
  34. package/inlinemath.css +17 -7
  35. package/package.json +6 -6
  36. package/src/cas.d.ts +1 -1
  37. package/src/cas.js +15 -4
  38. package/src/draw.js +13 -9
  39. package/src/edit.js +11 -4
  40. package/src/html.js +1 -1
  41. package/src/index.js +1 -1
  42. package/src/layout.js +89 -32
  43. package/src/lite.js +1 -1
  44. package/src/markdown.d.ts +1 -1
  45. package/src/markdown.js +139 -57
  46. package/src/mathzetta.js +2 -2
  47. package/src/select.js +7 -0
  48. package/src/types.d.ts +12 -10
  49. package/src/variables.js +44 -10
  50. package/src/view.js +69 -18
  51. package/dist/chunks/calculate-Cz87Lt0N.js +0 -2
  52. package/dist/chunks/draw-Bev17BJJ.js +0 -2
  53. package/dist/chunks/edit-C65xXzo8.js +0 -2
  54. package/dist/chunks/edit-M68aRA5o.js +0 -2
  55. package/dist/chunks/html-BimAqn7x.js +0 -2
  56. package/dist/chunks/html-CupluJSh.js +0 -2
  57. package/dist/chunks/lite-3Fb-OHbt.js +0 -2
package/src/markdown.js CHANGED
@@ -1,31 +1,31 @@
1
1
  /**
2
- * '@mathzetta/inlinemath/markdown' — Markdown with maths in it.
2
+ * '@mathzetta/inlinemath/markdown' — Markdown with math in it.
3
3
  *
4
4
  * import { markdownToHTML } from '@mathzetta/inlinemath/markdown';
5
5
  * el.innerHTML = markdownToHTML('The area is $\\pi r^2$, so for $r = 3$ it is ${{pi r^2}}$.');
6
6
  *
7
- * Maths: $…$ inline, $$…$$ (or a ```math fence) on its own, \(…\) and \[…\] too.
7
+ * Math: $…$ inline, $$…$$ (or a ```math fence) on its own, \(…\) and \[…\] too.
8
8
  * Each is read by MathZetta (LaTeX, plain text or code all work) and drawn by
9
9
  * Inline Math; {{…}} inside is worked out first (MathZetta's calculator, or the CAS:
10
10
  * { blocks: casBlocks() } from '@mathzetta/inlinemath/cas'). A definition such as $r = 3$ is
11
11
  * remembered, as a number, for the {{…}} after it ({ define: false } turns that off).
12
12
  *
13
13
  * Saved variables: $A := 2+2$ saves A (and draws A ≔ 2 + 2); $_A := 2+2$ saves it without drawing.
14
- * After it, A in any maths is drawn as its expression and {{A}} is its value: $A = {{A}}$ draws
14
+ * After it, A in any math is drawn as its expression and {{A}} is its value: $A = {{A}}$ draws
15
15
  * 2 + 2 = 4. $A := [[2+2]]$ is a textbox that sets A, [[2+2 | x^2]] a dropdown, [[1..10]] a slider
16
16
  * ([[0..1 step 0.1 = 0.5]]). renderMarkdownInto keeps every part of a page in one store
17
17
  * (`variables`), so a variable saved in one part is used in the others, and changing an input
18
18
  * redraws everything that uses it.
19
19
  *
20
- * A $ is maths only when it looks like it (Pandoc's rule): the opening $ is not
20
+ * A $ is math only when it looks like it (Pandoc's rule): the opening $ is not
21
21
  * followed by a space, the closing $ is not after a space or before a digit, so
22
22
  * "$5 and $10" stays text. \$ is a dollar sign. Code spans and fences are left alone.
23
- * Maths that doesn't read is shown as written, marked, with the reason as its title.
23
+ * Math that doesn't read is shown as written, marked, with the reason as its title.
24
24
  *
25
25
  * The Markdown is a small built-in renderer (headings, emphasis, links, images,
26
26
  * lists, quotes, code, tables, rules). Raw HTML is shown as text unless { html: true }.
27
27
  * { render: (markdown) => html } uses another renderer (marked, markdown-it …):
28
- * the maths is taken out first and put back into its output.
28
+ * the math is taken out first and put back into its output.
29
29
  */
30
30
 
31
31
  import { toHTML, treeOf } from './html.js';
@@ -37,7 +37,7 @@ import { openEditor, replaceAt } from './edit.js';
37
37
 
38
38
  export { createVariables, variables, Variables } from './variables.js';
39
39
 
40
- // ---- finding the maths --------------------------------------------------------------------
40
+ // ---- finding the math --------------------------------------------------------------------
41
41
 
42
42
  const OPEN = '';
43
43
  const CLOSE = '';
@@ -45,7 +45,7 @@ const placeholder = (n) => `${OPEN}${n}${CLOSE}`;
45
45
  const PLACEHOLDER = new RegExp(`${OPEN}(\\d+)${CLOSE}`, 'g');
46
46
 
47
47
  /**
48
- * The maths in a Markdown text, and the text with each piece replaced by a
48
+ * The math in a Markdown text, and the text with each piece replaced by a
49
49
  * placeholder (private-use characters, which no Markdown renderer touches).
50
50
  * @returns {{ text: string, math: Array<{ source, display, raw, start, end }> }} (start, end: where the raw text is)
51
51
  */
@@ -53,14 +53,23 @@ export function extractMath(markdown, { delimiters = ['$$', '$', '\\[', '\\('] }
53
53
  const math = [];
54
54
  let out = '';
55
55
  let i = 0;
56
- const s = String(markdown);
56
+ // the private-use characters placeholders are made of: typed ones become U+FFFD (same length, so start and end still fit)
57
+ const s = String(markdown).replace(/[\uE000-\uE003]/g, '\uFFFD');
57
58
  const atLineStart = (k) => k === 0 || s[k - 1] === '\n';
59
+ const code = indentedCode(s); // start → end of each indented code block: math there is code too
60
+ let noCloser = -1; // no $ closes inline math before this index (it doesn't depend on where the math opened)
61
+ const never = new Set(); // \) or \] found nowhere ahead: looked for once, not at every \( that follows
58
62
  const keep = (source, display, raw) => {
59
63
  math.push({ source, display, raw, start: i, end: i + raw.length });
60
64
  return placeholder(math.length - 1);
61
65
  };
62
66
  while (i < s.length) {
63
- // a fenced code block: copied as is, except ```math, which is display maths
67
+ if (code.has(i)) {
68
+ out += s.slice(i, code.get(i));
69
+ i = code.get(i);
70
+ continue;
71
+ }
72
+ // a fenced code block: copied as is, except ```math, which is display math
64
73
  if (atLineStart(i)) {
65
74
  const fence = /^( {0,3})(`{3,}|~{3,})([^\n]*)\n?/.exec(s.slice(i));
66
75
  if (fence) {
@@ -95,7 +104,8 @@ export function extractMath(markdown, { delimiters = ['$$', '$', '\\[', '\\('] }
95
104
  const two = s.slice(i, i + 2);
96
105
  const closer = two === '\\[' ? '\\]' : two === '\\(' ? '\\)' : null;
97
106
  if (closer && delimiters.includes(two)) {
98
- const end = s.indexOf(closer, i + 2);
107
+ const end = never.has(closer) ? -1 : s.indexOf(closer, i + 2);
108
+ if (end < 0) never.add(closer);
99
109
  if (end > -1) {
100
110
  out += keep(s.slice(i + 2, end), two === '\\[', s.slice(i, end + 2));
101
111
  i = end + 2;
@@ -114,13 +124,14 @@ export function extractMath(markdown, { delimiters = ['$$', '$', '\\[', '\\('] }
114
124
  i = end + 2;
115
125
  continue;
116
126
  }
117
- } else if (delimiters.includes('$') && s[i + 1] && !/\s/.test(s[i + 1])) {
118
- const end = closingDollar(s, i + 1);
127
+ } else if (delimiters.includes('$') && s[i + 1] && !/\s/.test(s[i + 1]) && i + 1 >= noCloser) {
128
+ const { end, stop } = closingDollar(s, i + 1);
119
129
  if (end > -1) {
120
130
  out += keep(s.slice(i + 1, end), false, s.slice(i, end + 1));
121
131
  i = end + 1;
122
132
  continue;
123
133
  }
134
+ noCloser = stop; // every $ before `stop` opens nothing either: one scan per paragraph, not per $
124
135
  }
125
136
  }
126
137
  out += c;
@@ -129,19 +140,48 @@ export function extractMath(markdown, { delimiters = ['$$', '$', '\\[', '\\('] }
129
140
  return { text: out, math };
130
141
  }
131
142
 
132
- /** The $ that closes inline maths opened before `from`: not after a space, not before a digit, within the paragraph. */
143
+ /**
144
+ * The $ that closes inline math opened before `from`: not after a space, not before a digit, within the paragraph.
145
+ * @returns {{ end: number, stop: number }} end -1 if none; stop: where the search ended (code, a blank line, the end)
146
+ */
133
147
  function closingDollar(s, from) {
134
148
  for (let j = from; j < s.length; j++) {
135
149
  const c = s[j];
136
150
  if (c === '\\') { j++; continue; }
137
- if (c === '`') return -1; // maths doesn't run into code
138
- if (c === '\n' && /^\n[ \t]*\n/.test(s.slice(j))) return -1;
139
- if (c === '$' && !/\s/.test(s[j - 1]) && !/\d/.test(s[j + 1] ?? '') && s[j + 1] !== '$') return j;
151
+ if (c === '`') return { end: -1, stop: j }; // math doesn't run into code
152
+ if (c === '\n' && /^\n[ \t]*\n/.test(s.slice(j, j + 64))) return { end: -1, stop: j };
153
+ if (c === '$' && !/\s/.test(s[j - 1]) && !/\d/.test(s[j + 1] ?? '') && s[j + 1] !== '$') return { end: j, stop: j };
154
+ }
155
+ return { end: -1, stop: s.length };
156
+ }
157
+
158
+ /**
159
+ * Indented code blocks, as the renderer finds them: a line indented four spaces (or a tab) after a blank
160
+ * line or at the start, outside a list, and the indented or blank lines after it. Start → end offsets.
161
+ */
162
+ function indentedCode(s) {
163
+ const blocks = new Map();
164
+ const indented = (line) => /^( {4}|\t)/.test(line);
165
+ let at = 0;
166
+ let prevBlank = true;
167
+ let inList = false;
168
+ let start = -1;
169
+ for (const line of s.split('\n')) {
170
+ const blank = !line.trim();
171
+ if (start > -1 && !(blank || indented(line))) {
172
+ blocks.set(start, at - 1); // up to the newline before this line
173
+ start = -1;
174
+ }
175
+ if (start < 0 && !blank && indented(line) && prevBlank && !inList) start = at;
176
+ if (!blank && !indented(line)) inList = LIST_ITEM.test(line) || (inList && /^\s/.test(line));
177
+ prevBlank = blank;
178
+ at += line.length + 1;
140
179
  }
141
- return -1;
180
+ if (start > -1) blocks.set(start, s.length);
181
+ return blocks;
142
182
  }
143
183
 
144
- // ---- drawing the maths --------------------------------------------------------------------
184
+ // ---- drawing the math --------------------------------------------------------------------
145
185
 
146
186
  const escape = (t) => String(t).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
147
187
 
@@ -149,7 +189,7 @@ const escape = (t) => String(t).replace(/&/g, '&amp;').replace(/</g, '&lt;').rep
149
189
  const DEFINITION = /^\s*([A-Za-z\u0370-\u03ff](?:_\{?\w+\}?)?)\s*=\s*([^=<>≤≥]+)$/;
150
190
 
151
191
  /**
152
- * Maths that saves a variable: `A := 2+2` (drawn), `_A := 2+2` or `_A = 2+2` (not drawn),
192
+ * Math that saves a variable: `A := 2+2` (drawn), `_A := 2+2` or `_A = 2+2` (not drawn),
153
193
  * `A := [[…]]` (an input). Else null; `{ error }` for a `$_…$` that saves nothing.
154
194
  */
155
195
  function savingOf(source) {
@@ -177,9 +217,9 @@ function savingOf(source) {
177
217
  }
178
218
 
179
219
  /** `A = …` drawn as `A ≔ …`: the first relation is the definition's. */
180
- function asDefinition(html) {
220
+ function asDefinition(html, prefix = 'mv') {
181
221
  return html
182
- .replace('<span class="mv-rel">=</span>', '<span class="mv-rel mv-rel-def">≔</span>')
222
+ .replace(`<span class="${prefix}-rel">=</span>`, `<span class="${prefix}-rel ${prefix}-rel-def">≔</span>`)
183
223
  .replace(/(aria-label="[^"]*?) equals /, '$1 is defined as ')
184
224
  .replace('<mo>=</mo>', '<mo>≔</mo>');
185
225
  }
@@ -200,7 +240,7 @@ function controlHTML(def, text) {
200
240
  }
201
241
 
202
242
  /**
203
- * Every piece of maths drawn, in reading order: a variable is known to the maths after it, and
243
+ * Every piece of math drawn, in reading order: a variable is known to the math after it, and
204
244
  * the variables already in `store` (the other parts of the page) to all of it.
205
245
  */
206
246
  function drawAll(markdown, options, store, owner) {
@@ -267,10 +307,15 @@ function drawAll(markdown, options, store, owner) {
267
307
  };
268
308
  };
269
309
 
270
- refresh();
310
+ // worked out only when a {{…}} block will read them: a page of 200 definitions and no blocks is not 200 recalculations
311
+ let stale = true;
271
312
 
272
313
  const drawItem = (item, i) => {
273
314
  const { source, display } = item;
315
+ if (stale && source.includes('{{')) {
316
+ refresh();
317
+ stale = false;
318
+ }
274
319
  const cls = display ? 'mv-md-display' : 'mv-md-math';
275
320
  const wrap = (html, extra = '') => `<span class="${cls}${extra}" data-mv-md="${i}">${html}</span>`;
276
321
  try {
@@ -292,13 +337,13 @@ function drawAll(markdown, options, store, owner) {
292
337
  if (!hidden) {
293
338
  const tree = numberTree({ type: 'op', op: '=', args: [bare(treeOf(save.lhs)), rhs.id === undefined ? rhs : bare(rhs)] });
294
339
  trees[i] = tree;
295
- html = asDefinition(toHTML(tree, drawOpts));
340
+ html = asDefinition(toHTML(tree, drawOpts), drawOpts.prefix);
296
341
  }
297
342
  }
298
343
  defs.delete(name);
299
344
  defs.set(name, def);
300
345
  mine.set(name, def);
301
- refresh();
346
+ stale = true;
302
347
  if (hidden && !input) return '';
303
348
  return wrap(html, input ? ' mv-md-input-def' : '');
304
349
  }
@@ -306,7 +351,7 @@ function drawAll(markdown, options, store, owner) {
306
351
  if (changed) numberTree(tree);
307
352
  trees[i] = tree;
308
353
  const html = toHTML(tree, drawOpts);
309
- if (!changed && options.define !== false && define(source, numbers, defs)) refresh();
354
+ if (!changed && options.define !== false && define(source, numbers, defs)) stale = true;
310
355
  return wrap(html);
311
356
  } catch (error) {
312
357
  return `<span class="mv-md-error" data-mv-md="${i}" title="${escape(error.message)}"><code>${escape(item.raw)}</code></span>`;
@@ -340,15 +385,22 @@ function define(source, numbers, saved) {
340
385
  const SAFE_URL = /^(https?:|mailto:|#|\/|\.{0,2}\/|[^:]*$)/i;
341
386
  const safeUrl = (u) => (SAFE_URL.test(u.trim()) ? escape(u.trim()) : '#');
342
387
 
343
- /** Inline Markdown: code, links, images, emphasis, breaks. Placeholders pass through. */
344
- function inline(text, options, sourceOf) {
345
- const parts = [];
388
+ const HELD = /\uE002(\d+)\uE003/g;
389
+ const unescape = (t) => t.replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
390
+
391
+ /**
392
+ * Inline Markdown: code, links, images, emphasis, breaks. Placeholders pass through. `parts` is shared with
393
+ * a link's label (read by the same function), so what was held outside it still resolves inside it.
394
+ */
395
+ function inline(text, options, sourceOf, parts = []) {
346
396
  const hold = (html) => {
347
397
  parts.push(html);
348
- return `${parts.length - 1}`;
398
+ return `\uE002${parts.length - 1}\uE003`;
349
399
  };
400
+ // an attribute or address: what was held there as its text (a\_b is a_b), math as typed — then escaped once
401
+ const plain = (s) => unescape(sourceOf(s).replace(HELD, (_, n) => (parts[Number(n)] ?? '').replace(/<[^>]*>/g, '')));
350
402
  let t = text;
351
- // code spans (maths placeholders inside are written back as their source)
403
+ // code spans (math placeholders inside are written back as their source)
352
404
  t = t.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g, (_, run, code) => hold(`<code>${escape(sourceOf(code.trim()))}</code>`));
353
405
  // backslash escapes
354
406
  t = t.replace(/\\([\\`*_{}[\]()#+\-.!|~$<>"'])/g, (_, ch) => hold(escape(ch)));
@@ -356,30 +408,59 @@ function inline(text, options, sourceOf) {
356
408
  t = t.replace(/<((?:https?:\/\/|mailto:)[^\s>]+)>/g, (_, url) => hold(`<a href="${safeUrl(url)}">${escape(url)}</a>`));
357
409
  // raw HTML (only with { html: true })
358
410
  if (options.html) t = t.replace(/<\/?[A-Za-z][^>]*>/g, (tag) => hold(tag));
359
- // images and links
411
+ // images and links (a label holds no bracket of its own: a run of [[[[… was read again from every one of them)
360
412
  // an address may hold balanced brackets: wiki/Function_(mathematics)
361
- t = t.replace(/!\[([^\]]*)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g, (_, alt, url, title) =>
362
- hold(`<img src="${safeUrl(url)}" alt="${escape(alt)}"${title ? ` title="${escape(title)}"` : ''}>`));
363
- t = t.replace(/\[([^\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g, (_, label, url, title) =>
364
- hold(`<a href="${safeUrl(url)}"${title ? ` title="${escape(title)}"` : ''}>${inline(label, options, sourceOf)}</a>`));
365
- t = escape(t);
413
+ t = t.replace(/!\[([^\[\]]*)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g, (_, alt, url, title) =>
414
+ hold(`<img src="${safeUrl(plain(url))}" alt="${escape(plain(alt))}"${title ? ` title="${escape(plain(title))}"` : ''}>`));
415
+ t = t.replace(/\[([^\[\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g, (_, label, url, title) =>
416
+ hold(`<a href="${safeUrl(plain(url))}"${title ? ` title="${escape(plain(title))}"` : ''}>${inline(label, options, sourceOf, parts)}</a>`));
417
+ // escaped as text, except an entity reference written as one: &copy; &mdash; &#8212;
418
+ t = t.replace(/&(?!#\d{1,7};|#x[0-9a-f]{1,6};|[a-z][a-z0-9]{1,31};)/gi, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
419
+ t = t.replace(/(\*\*\*|___)(?=\S)([\s\S]*?\S)\1/g, '<strong><em>$2</em></strong>'); // ***both***, nested the right way round
420
+ // ***a** b* and ***a* b**: the inner run closes first
421
+ t = t.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*\*|__)(?![*_])([\s\S]*?\S)(\*|_)(?![*_])/g, '<em><strong>$2</strong>$4</em>');
422
+ t = t.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*|_)(?![*_])([\s\S]*?\S)(\*\*|__)(?![*_])/g, '<strong><em>$2</em>$4</strong>');
366
423
  t = t.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g, '<strong>$2</strong>');
367
424
  t = t.replace(/(^|[^*\w])\*(?=\S)([\s\S]*?\S)\*(?!\*)/g, '$1<em>$2</em>');
368
425
  t = t.replace(/(^|[^_\w])_(?=\S)([\s\S]*?\S)_(?![_\w])/g, '$1<em>$2</em>');
369
426
  t = t.replace(/~~(?=\S)([\s\S]*?\S)~~/g, '<del>$1</del>');
370
427
  t = t.replace(/( {2,}|\\)\n/g, '<br>\n');
371
- return t.replace(/(\d+)/g, (_, n) => parts[Number(n)]);
428
+ // a held piece can hold another (a link's label): resolve until none is left
429
+ for (let k = 0; k < 8 && /\uE002\d+\uE003/.test(t); k++) t = t.replace(HELD, (_, n) => parts[Number(n)] ?? '');
430
+ return t;
372
431
  }
373
432
 
374
433
  const BLOCK_START = /^( {0,3})(#{1,6}\s|>|```|~~~|([-*+]|\d{1,9}[.)])\s|(\*[ \t]*){3,}$|(-[ \t]*){3,}$|(_[ \t]*){3,}$)/;
375
434
  const LIST_ITEM = /^( {0,3})([-*+]|\d{1,9}[.)])(\s+|$)/;
376
435
  const TABLE_RULE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
377
436
 
437
+ /** Does this line end a paragraph? A block starts, but an underline is a heading's and only a list from 1 interrupts:
438
+ * "The year was\n1986. What a year." stays one paragraph. */
439
+ const interrupts = (line) => BLOCK_START.test(line) && !/^ {0,3}[-=]+\s*$/.test(line)
440
+ && !/^ {0,3}(?!1[.)])\d{1,9}[.)]\s/.test(line);
441
+
442
+ const MAX_NESTING = 100;
443
+
444
+ /**
445
+ * A heading's text: without the spaces around it and a closing run of #s set off by a space (`# Title ##`).
446
+ * By hand: one pattern for all of it (\s+ … \s*#*\s*$) tried every split of a long run of spaces, cubic in its length.
447
+ */
448
+ function headingText(rest) {
449
+ const text = rest.trim();
450
+ let end = text.length;
451
+ while (end > 0 && text[end - 1] === '#') end--;
452
+ if (end === text.length) return text;
453
+ if (end === 0) return ''; // only #s
454
+ return /[ \t]/.test(text[end - 1]) ? text.slice(0, end).trimEnd() : text; // a# and \# keep theirs
455
+ }
456
+
378
457
  /** Block Markdown → HTML. */
379
- function blocks(lines, options, sourceOf) {
458
+ function blocks(lines, options, sourceOf, depth = 0) {
380
459
  const out = [];
381
460
  let i = 0;
382
461
  const para = (text) => inline(text, options, sourceOf);
462
+ // quotes in quotes, lists in lists: past any depth a person writes, the rest is a paragraph (a line of 2,500 >s overflowed the stack)
463
+ if (depth > MAX_NESTING) return `<p>${para(lines.join('\n'))}</p>`;
383
464
  while (i < lines.length) {
384
465
  const line = lines[i];
385
466
  if (!line.trim()) { i++; continue; }
@@ -395,9 +476,9 @@ function blocks(lines, options, sourceOf) {
395
476
  continue;
396
477
  }
397
478
  // ATX heading
398
- const h = /^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/.exec(line);
479
+ const h = /^ {0,3}(#{1,6})[ \t]+/.exec(line);
399
480
  if (h) {
400
- out.push(`<h${h[1].length}>${para(h[2])}</h${h[1].length}>`);
481
+ out.push(`<h${h[1].length}>${para(headingText(line.slice(h[0].length)))}</h${h[1].length}>`);
401
482
  i++;
402
483
  continue;
403
484
  }
@@ -414,7 +495,7 @@ function blocks(lines, options, sourceOf) {
414
495
  body.push(lines[i].replace(/^ {0,3}> ?/, ''));
415
496
  i++;
416
497
  }
417
- out.push(`<blockquote>\n${blocks(body, options, sourceOf)}\n</blockquote>`);
498
+ out.push(`<blockquote>\n${blocks(body, options, sourceOf, depth + 1)}\n</blockquote>`);
418
499
  continue;
419
500
  }
420
501
  // list
@@ -454,7 +535,7 @@ function blocks(lines, options, sourceOf) {
454
535
  }
455
536
  const tag = ordered ? 'ol' : 'ul';
456
537
  const html = items.map((body) => {
457
- let inner = blocks(body, options, sourceOf);
538
+ let inner = blocks(body, options, sourceOf, depth + 1);
458
539
  if (!loose) inner = inner.replace(/^<p>([\s\S]*?)<\/p>/, '$1').replace(/\n<p>([\s\S]*?)<\/p>/g, '\n$1');
459
540
  return `<li>${inner}</li>`;
460
541
  });
@@ -483,7 +564,7 @@ function blocks(lines, options, sourceOf) {
483
564
  }
484
565
  // paragraph (or a setext heading)
485
566
  const text = [];
486
- while (i < lines.length && lines[i].trim() && !(text.length && BLOCK_START.test(lines[i]) && !/^ {0,3}[-=]+\s*$/.test(lines[i]))) {
567
+ while (i < lines.length && lines[i].trim() && !(text.length && interrupts(lines[i]))) {
487
568
  if (text.length && /^ {0,3}(=+|-+)\s*$/.test(lines[i])) {
488
569
  const level = lines[i].trim()[0] === '=' ? 1 : 2;
489
570
  out.push(`<h${level}>${para(text.join('\n'))}</h${level}>`);
@@ -501,35 +582,36 @@ function blocks(lines, options, sourceOf) {
501
582
 
502
583
  /** The built-in renderer: Markdown → HTML, raw HTML escaped unless options.html. */
503
584
  export function renderMarkdown(markdown, options = {}, sourceOf = (t) => t) {
504
- return blocks(String(markdown).replace(/\r\n?/g, '\n').split('\n'), options, sourceOf);
585
+ // typed U+E002/U+E003 would be read as held pieces: they become U+FFFD
586
+ return blocks(String(markdown).replace(/\r\n?/g, '\n').replace(/[\uE002\uE003]/g, '\uFFFD').split('\n'), options, sourceOf);
505
587
  }
506
588
 
507
589
  // ---- together ---------------------------------------------------------------------------
508
590
 
509
- /** The Markdown around the drawn maths. */
591
+ /** The Markdown around the drawn math. */
510
592
  function assemble({ text, math, drawn }, options) {
511
- const sourceOf = (t) => t.replace(PLACEHOLDER, (_, n) => math[Number(n)].raw);
593
+ const sourceOf = (t) => t.replace(PLACEHOLDER, (_, n) => math[Number(n)]?.raw ?? '');
512
594
  const html = options.render ? options.render(text) : renderMarkdown(text, options, sourceOf);
513
595
  return html
514
- // display maths alone in a paragraph is a block of its own
596
+ // display math alone in a paragraph is a block of its own
515
597
  .replace(new RegExp(`<p>\\s*${OPEN}(\\d+)${CLOSE}\\s*</p>`, 'g'), (whole, n) => (math[Number(n)].display && drawn[Number(n)] ? `<div class="mv-md-block">${drawn[Number(n)]}</div>` : whole))
516
- .replace(PLACEHOLDER, (_, n) => drawn[Number(n)])
598
+ .replace(PLACEHOLDER, (_, n) => drawn[Number(n)] ?? '')
517
599
  // a paragraph that only saved variables ($_A := 2+2$) leaves nothing behind
518
600
  .replace(/<p>\s*<\/p>\n?/g, '');
519
601
  }
520
602
 
521
603
  /**
522
- * Markdown with maths → HTML.
604
+ * Markdown with math → HTML.
523
605
  * @param {string} markdown
524
606
  * @param {object} [options]
525
607
  * @param {object} [options.math] options for each drawing (toHTML's: fnParens, colors …)
526
608
  * @param {Function} [options.blocks] the {{…}} handler (default the calculator; casBlocks() for the CAS)
527
609
  * @param {object} [options.scope] values for {{…}}: { r: 3 }
528
610
  * @param {boolean} [options.define] remember $r = 3$ for later {{…}} (default true)
529
- * @param {object} [options.variables] a store (createVariables()) whose variables the maths may use
611
+ * @param {object} [options.variables] a store (createVariables()) whose variables the math may use
530
612
  * @param {boolean} [options.html] let raw HTML through (default false: it is shown as text)
531
613
  * @param {(markdown: string) => string} [options.render] another Markdown renderer
532
- * @param {string[]} [options.delimiters] which of '$$', '$', '\\[', '\\(' mark maths (default all)
614
+ * @param {string[]} [options.delimiters] which of '$$', '$', '\\[', '\\(' mark math (default all)
533
615
  */
534
616
  export function markdownToHTML(markdown, options = {}) {
535
617
  return assemble(drawAll(markdown, options, options.variables || null), options);
@@ -544,11 +626,11 @@ function sweep() {
544
626
  }
545
627
 
546
628
  /**
547
- * Draw Markdown with maths into an element, live: its variables join the page's store
548
- * (options.variables, default `variables`; false for none), its inputs set them, and its maths is
629
+ * Draw Markdown with math into an element, live: its variables join the page's store
630
+ * (options.variables, default `variables`; false for none), its inputs set them, and its math is
549
631
  * drawn again whenever a variable it can see changes. Drawing into the element again replaces it all.
550
632
  * Double-clicking a part drawn from a textbox variable edits it ({ editable: { toText } }, toText
551
- * from 'mathzetta/text'); any other part fires 'inlinemath:select' with where its maths is in the
633
+ * from 'mathzetta/text'); any other part fires 'inlinemath:select' with where its math is in the
552
634
  * Markdown ({ index, start, end, raw }).
553
635
  */
554
636
  export function renderMarkdownInto(element, markdown, options = {}) {
@@ -599,7 +681,7 @@ export function renderMarkdownInto(element, markdown, options = {}) {
599
681
  };
600
682
  // double-click a part: a part that came from a textbox variable is edited there (in place,
601
683
  // with options.editable = { toText }; else the textbox is focused); anything else tells the
602
- // page where that maths is in the Markdown, as an 'inlinemath:select' event
684
+ // page where that math is in the Markdown, as an 'inlinemath:select' event
603
685
  const onDoubleClick = (event) => {
604
686
  const part = event.target.closest?.('[data-node]');
605
687
  const piece = part && part.closest('[data-mv-md]');
package/src/mathzetta.js CHANGED
@@ -9,10 +9,10 @@
9
9
  */
10
10
 
11
11
  export {
12
- parse, parseTree, fromPostfix, toPostfix, asTree, walk, firstVariable,
12
+ parse, parseTree, fromPostfix, toPostfix, walk, firstVariable,
13
13
  operator, precedenceOf, isCustomFunction, VARIADIC,
14
14
  GREEK, needsBrackets, unaryNeedsBrackets, isMinusOneTimes, isImplicitProduct, isVariable,
15
15
  firstLeaf, customName, derivativeOrder, bracketedSides, bracketOp,
16
16
  MATRICES, matrixRows,
17
17
  } from 'mathzetta';
18
- export { toSpeech, toSpeechSegments, toAudioSpeech } from 'mathzetta/speech';
18
+ export { toSpeechSegments, toAudioSpeech } from 'mathzetta/speech';
package/src/select.js CHANGED
@@ -17,6 +17,13 @@
17
17
 
18
18
  import { parseTree, toPostfix, walk, operator, VARIADIC } from './mathzetta.js';
19
19
 
20
+ /** A tree with its ids (and where-it-came-from marks) dropped, so it can be numbered again inside another. */
21
+ export function bare(node) {
22
+ const { id, from, ...rest } = node;
23
+ if (rest.args) rest.args = rest.args.map(bare);
24
+ return rest;
25
+ }
26
+
20
27
  /** A subtree's postfix as one string: two parts look the same exactly when these match. */
21
28
  export const signature = (node) => toPostfix(node).join(' ');
22
29
 
package/src/types.d.ts CHANGED
@@ -9,7 +9,7 @@ export type { Input, Node, BlockHandler };
9
9
  * input ('x^2': every part that is x²), a path ({ path: [0, 1] }, as @mathzetta/cas reports it), a test,
10
10
  * or a list of any of these.
11
11
  */
12
- export type Target = number | string | { path: number[] } | ((node: Node) => boolean) | Target[];
12
+ export type Target = number | string | Node | { path: number[] } | ((node: Node, parent?: Node | null) => boolean) | Target[];
13
13
 
14
14
  export interface LayoutOptions {
15
15
  /** CSS class prefix (default 'mv'). */
@@ -40,7 +40,7 @@ export interface LayoutOptions {
40
40
  }
41
41
 
42
42
  export interface DrawOptions extends LayoutOptions {
43
- /** Colours by target: { 'x^2': 'red', 3: '#06c' } or [[target, colour], …]. */
43
+ /** Colors by target: { 'x^2': 'red', 3: '#06c' } or [[target, color], …]. */
44
44
  colors?: Record<string | number, string> | Array<[Target, string]>;
45
45
  /** Parts to mark with the `<prefix>-hl` class. */
46
46
  highlight?: Target;
@@ -79,7 +79,7 @@ export const PATHS: Record<string, { fill?: string; stroke?: string }>;
79
79
 
80
80
  export interface ClickInfo { node: Node; id: number; path: number[] | null; element: Element; event: Event }
81
81
 
82
- /** A live drawing: highlight, colour, listen, step with animation. */
82
+ /** A live drawing: highlight, color, listen, step with animation. */
83
83
  export class View {
84
84
  constructor(element: Element, input: Input, options?: ViewOptions);
85
85
  readonly element: Element;
@@ -96,9 +96,8 @@ export class View {
96
96
  elementOf(node: Node): Element | null;
97
97
  highlight(target: Target, className?: string): this;
98
98
  unhighlight(target?: Target | null, className?: string): this;
99
- color(target: Target, colour: string): this;
100
- /** Listen for an event on a part; returns a function that stops listening. */
101
- /** Listen for an event on the parts. A 'click' listener also makes the drawing work from the keyboard:
99
+ color(target: Target, color: string): this;
100
+ /** Listen for an event on the parts; returns a function that stops listening. A 'click' listener also makes the drawing work from the keyboard:
102
101
  * one tab stop, arrow keys walk the parts (each spoken), Enter or Space calls the listener for the
103
102
  * current part — `event` is then the KeyboardEvent. */
104
103
  on(type: string, fn: (info: ClickInfo) => void): () => void;
@@ -117,10 +116,13 @@ export class View {
117
116
  /** The expression read aloud in pieces, each tagged with the node it describes. */
118
117
  segments(options?: SpeechOptions): { text: string; id?: number }[];
119
118
  showSegment(segment: { id?: number } | null, className?: string): this;
119
+ /** Stop listening (on() handlers, keys, double-click editing), close an open editor and remove the live
120
+ * regions this view added; the drawing stays. */
121
+ destroy(): this;
120
122
  }
121
123
  /** Draw into an element and return the live view. */
122
124
  export function render(element: Element, input: Input, options?: ViewOptions): View;
123
- /** Should a step animate: true honours prefers-reduced-motion, 'always' does not, false never. */
125
+ /** Should a step animate: true honors prefers-reduced-motion, 'always' does not, false never. */
124
126
  export function shouldAnimate(animate?: boolean | 'always'): boolean;
125
127
 
126
128
  // ---- inlinemath/markdown --------------------------------------------------------------------
@@ -136,12 +138,12 @@ export interface MarkdownOptions {
136
138
  define?: boolean;
137
139
  /** Let raw HTML through (default false: it is shown as text). */
138
140
  html?: boolean;
139
- /** Another Markdown renderer; the maths is taken out first and put back into its output. */
141
+ /** Another Markdown renderer; the math is taken out first and put back into its output. */
140
142
  render?: (markdown: string) => string;
141
- /** Which of '$$', '$', '\\[', '\\(' mark maths (default all). */
143
+ /** Which of '$$', '$', '\\[', '\\(' mark math (default all). */
142
144
  delimiters?: string[];
143
145
  /**
144
- * The saved variables ($A := 2+2$) the maths may use. markdownToHTML: none by default;
146
+ * The saved variables ($A := 2+2$) the math may use. markdownToHTML: none by default;
145
147
  * renderMarkdownInto: the page's `variables` by default, false for none.
146
148
  */
147
149
  variables?: Variables | false | null;
package/src/variables.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Saved variables for '@mathzetta/inlinemath/markdown': `$A := 2+2$` saves A, and A in any maths
2
+ * Saved variables for '@mathzetta/inlinemath/markdown': `$A := 2+2$` saves A, and A in any math
3
3
  * after it is drawn as 2 + 2 (and `{{A}}` is 4). A store holds them for a whole page, so every
4
4
  * part drawn with renderMarkdownInto sees the others' variables, and an input bound to a variable
5
5
  * (`$A := [[2+2]]$`, a textbox) redraws everything that uses it.
@@ -30,12 +30,11 @@ export function nameOf(node) {
30
30
  return null;
31
31
  }
32
32
 
33
- /** A tree with its ids (and where-it-came-from marks) dropped, so it can be numbered again inside another. */
34
- export function bare(node) {
35
- const { id, from, ...rest } = node;
36
- if (rest.args) rest.args = rest.args.map(bare);
37
- return rest;
38
- }
33
+ // bare(): ids and where-it-came-from marks dropped; it lives in select.js so edit.js (and with it the
34
+ // main entry, for View.editable) doesn't pull in this store
35
+ import { bare } from './select.js';
36
+ import { firstVariable } from './mathzetta.js';
37
+ export { bare };
39
38
 
40
39
  /** Ids dropped (to be numbered again), `from` marks kept. */
41
40
  function renumber(node) {
@@ -58,6 +57,31 @@ export function unexpand(node, named) {
58
57
  return visit(node, true);
59
58
  }
60
59
 
60
+ const NONE = new Set();
61
+
62
+ /**
63
+ * The variable an operation binds, and which of its arguments it is bound in: d/dx (der(f, x)) and
64
+ * ∫ … dx (int(f, x, a, b)) in f and x but not the limits; lim(f, x → a) in f and x; ∑ and ∏
65
+ * (\\sumidx(f, k = 1, n), \\sumidx(f, k ∈ S)) in f and k. Null for anything else.
66
+ */
67
+ function boundBy(node) {
68
+ const [f, second] = node.args;
69
+ const symbol = (n) => (n && n.type === 'symbol' ? n.value : null);
70
+ switch (node.op) {
71
+ case 'der':
72
+ if (second?.op === '=') return symbol(second.args[0]) && { name: symbol(second.args[0]), where: (i) => i === 0, index: 1 }; // der(f, x = a): a takes values
73
+ return symbol(second) && { name: symbol(second), where: (i) => i <= 1 };
74
+ case 'int': {
75
+ const name = symbol(second) ?? (node.args.length === 3 || node.args.length === 1 ? firstVariable(f) || 'x' : null);
76
+ return name && { name, where: (i) => i === 0 || (i === 1 && symbol(second) === name) };
77
+ }
78
+ case 'lim': return second?.op === '→' && symbol(second.args[0]) && { name: symbol(second.args[0]), where: (i) => i === 0, index: 1 };
79
+ case '\\sumidx': case '\\prodidx':
80
+ return (second?.op === '=' || second?.op === '∈') && symbol(second.args[0]) && { name: symbol(second.args[0]), where: (i) => i === 0, index: 1 };
81
+ default: return null;
82
+ }
83
+ }
84
+
61
85
  /**
62
86
  * Every saved name in a tree replaced by its own tree (which may use other saved names).
63
87
  * `lookup(name)` gives a saved name's tree, or null. A name inside its own definition is left as it is.
@@ -66,10 +90,10 @@ export function unexpand(node, named) {
66
90
  export function substitute(tree, lookup) {
67
91
  let changed = false;
68
92
  const seen = new Set();
69
- const visit = (node) => {
93
+ const visit = (node, bound = NONE) => {
70
94
  const name = nameOf(node);
71
95
  if (name !== null) {
72
- if (!seen.has(name)) {
96
+ if (!seen.has(name) && !bound.has(name)) {
73
97
  const value = lookup(name);
74
98
  if (value) {
75
99
  changed = true;
@@ -81,7 +105,17 @@ export function substitute(tree, lookup) {
81
105
  }
82
106
  return node; // A_1 is one name: its A is not substituted
83
107
  }
84
- if (node.args) return { ...node, args: node.args.map(visit) };
108
+ if (node.args) {
109
+ // d/dx, ∫ … dx, lim and ∑ bind their variable: a saved x isn't put into x³ in d/dx x³
110
+ const binds = boundBy(node);
111
+ if (!binds) return { ...node, args: node.args.map((a) => visit(a, bound)) };
112
+ const inside = new Set([...bound, binds.name]);
113
+ return { ...node, args: node.args.map((a, i) => {
114
+ // the index (x → a, k = 1, k ∈ S): its variable is bound, its value isn't
115
+ if (i === binds.index) return { ...a, args: a.args.map((c, j) => visit(c, j === 0 ? inside : bound)) };
116
+ return visit(a, binds.where(i) ? inside : bound);
117
+ }) };
118
+ }
85
119
  return node;
86
120
  };
87
121
  const out = visit(tree);