Hedgehog-Computing/hedgehog-lab

Consider using tag functions to process TeX strings

idiotWu opened this issue · 1 comments

Current Behavior

Currently, users have to escape backslashes when using tex() and formulaTex(), which makes the code a bit ugly and unclear:

tex('\\text{I } \\textbf{hate } \\\\ \\backslash')

Solution

We can use the tag functions to make the above example as clear as:

tex`\text{I } \textbf{hate} \\ \backslash`

Implementation

The function to process raw strings can be implemented as:

function processRawInputs(strs, ...vars): string {
  return strs?.raw ? String.raw(strs, ...vars) : strs;
}

// usage
const str0 = processRawInputs('str0\\n'); //=> 'str0\\n'
const str1 = processRawInputs`str1\n`;    //=> 'str1\\n'
const str2 = processRawInputs`result: ${str0} ${str1}`; //=> 'result: str0\\n str1\\n'

Test

You can test the following example in the playground.

function processRawInputs(strs, ...vars) {
  return strs?.raw ? String.raw(strs, ...vars) : strs;
}

function wrap(fn) {
  return (...inputs) => {
    const str = processRawInputs(...inputs);
    fn(str);
  }
}

const _tex = wrap(tex);
const _formulaTex = wrap(formulaTex);

_tex`\textbf{This} \text{ looks better.}`;
_formulaTex`
    \int_0^\pi \sin (t) dt
`;

// string interpolation
_formulaTex`
  \Theta
    \text{${'\u002e'.repeat(2)}}
  \Theta
`;

I can create a pull request if this looks good to you :).

Solved in #69.