Files
KaTeX/contrib/copy-tex/katex2tex.js
Erik Demaine e71c7d4b81 copy-tex contrib module (#813)
* copy-tex contrib module

* Factor out replacement code

* Fix lint

* Support for more browsers, in particular Firefox

* Use for loop instead of Array.forEach
* Use replaceChild if replaceWith is unavailable
* Browserify to remove let etc.

* Fix HTML handling, in particular for Edge

* Convert DocumentFragment to HTML directly (via children' outerHTML)
* Set HTML content *before* text content; Edge takes the last only

* Handle .katex-html and .katex-mathml separately

* Implement option 2: CSS user-select: all

Also fix auto-render.js build location

* Revise documentation according to @kevinbarabash's comments

* Split copy-tex.js into it + katex2tex.js

This supports re-use of code in a custom copy handler.

* Document custom copy handler

* Add missing file
2017-09-04 21:17:46 -04:00

53 lines
2.1 KiB
JavaScript

// Set these to how you want inline and display math to be delimited.
export const defaultCopyDelimiters = {
inline: ['$', '$'], // alternative: ['\(', '\)']
display: ['$$', '$$'], // alternative: ['\[', '\]']
};
// Replace .katex elements with their TeX source (<annotation> element).
// Modifies fragment in-place. Useful for writing your own 'copy' handler,
// as in copy-tex.js.
export const katexReplaceWithTex = function(fragment,
copyDelimiters = defaultCopyDelimiters) {
// Remove .katex-html blocks that are preceded by .katex-mathml blocks
// (which will get replaced below).
const katexHtml = fragment.querySelectorAll('.katex-mathml + .katex-html');
for (let i = 0; i < katexHtml.length; i++) {
const element = katexHtml[i];
if (element.remove) {
element.remove(null);
} else {
element.parentNode.removeChild(element);
}
}
// Replace .katex-mathml elements with their annotation (TeX source)
// descendant, with inline delimiters.
const katexMathml = fragment.querySelectorAll('.katex-mathml');
for (let i = 0; i < katexMathml.length; i++) {
const element = katexMathml[i];
const texSource = element.querySelector('annotation');
if (texSource) {
if (element.replaceWith) {
element.replaceWith(texSource);
} else {
element.parentNode.replaceChild(texSource, element);
}
texSource.innerHTML = copyDelimiters.inline[0] +
texSource.innerHTML + copyDelimiters.inline[1];
}
}
// Switch display math to display delimiters.
const displays = fragment.querySelectorAll('.katex-display annotation');
for (let i = 0; i < displays.length; i++) {
const element = displays[i];
element.innerHTML = copyDelimiters.display[0] +
element.innerHTML.substr(copyDelimiters.inline[0].length,
element.innerHTML.length - copyDelimiters.inline[0].length
- copyDelimiters.inline[1].length)
+ copyDelimiters.display[1];
}
return fragment;
};
module.exports = katexReplaceWithTex;