Allow macro definitions in settings (#493)

* Introduce MacroExpander

The job of the MacroExpander is turning a stream of possibly expandable
tokens, as obtained from the Lexer, into a stream of non-expandable tokens
(in KaTeX, even though they may well be expandable in TeX) which can be
processed by the Parser.  The challenge here is that we don't have
mode-specific lexer implementations any more, so we need to do everything on
the token level, including reassembly of sizes and colors.

* Make macros available in development server

Now one can specify macro definitions like \foo=bar as part of the query
string and use these macros in the formula being typeset.

* Add tests for macro expansions

* Handle end of input in special groups

This avoids an infinite loop if input ends prematurely.

* Simplify parseSpecialGroup

The parseSpecialGroup methos now returns a single token spanning the whole
special group, and leaves matching that string against a suitable regular
expression to whoever is calling the method.  Suggested by @cbreeden.

* Incorporate review suggestions

Add improvements suggested by Kevin Barabash during review.

* Input range sanity checks

Ensure that both tokens of a token range come from the same lexer,
and that the range has a non-negative length.

* Improved wording of two comments
This commit is contained in:
Martin von Gagern
2016-07-08 21:24:31 +02:00
committed by Kevin Barabash
parent b49eee4de7
commit 8c55aed39a
11 changed files with 509 additions and 296 deletions

View File

@@ -10,13 +10,9 @@ function init() {
}
if ("addEventListener" in permalink) {
permalink.addEventListener("click", function() {
window.location.search = "?text=" + encodeURIComponent(input.value);
});
permalink.addEventListener("click", setSearch);
} else {
permalink.attachEvent("click", function() {
window.location.search = "?text=" + encodeURIComponent(input.value);
});
permalink.attachEvent("click", setSearch);
}
var match = (/(?:^\?|&)text=([^&]*)/).exec(window.location.search);
@@ -24,11 +20,26 @@ function init() {
input.value = decodeURIComponent(match[1]);
}
var macros = {};
var options = {};
var macroRegex = /(?:^\?|&)(?:\\|%5[Cc])([A-Za-z]+)=([^&]*)/g;
var macroString = "";
while ((match = macroRegex.exec(window.location.search)) !== null) {
options.macros = macros;
macros["\\" + match[1]] = decodeURIComponent(match[2]);
macroString += "&" + match[0].substr(1);
}
reprocess();
function setSearch() {
window.location.search =
"?text=" + encodeURIComponent(input.value) + macroString;
}
function reprocess() {
try {
katex.render(input.value, math);
katex.render(input.value, math, options);
} catch (e) {
if (e.__proto__ == katex.ParseError.prototype) {
console.error(e);