WeBWorK Main Forum

addToTeXPreamble

Re: addToTeXPreamble

by Davide Cervone -
Number of replies: 0
Here is an approach that I think should work. Start the problem with
$macros = join("",
  "\newcommand{\myMacro}{\mbox{This is myMacro!}}",
);

if ($displayMode eq "HTML_dpng") {
  $rh_envir->{imagegen}->addToTeXPreamble($macros);
} else {
  TEXT(MODES(
    TeX => "{".$macros,
    HTML => qq{
\($macros\)
}, )); } and use \myMacro in the problem as needed. At the end of the problem, add
TEXT("}") if $displayMode eq "TeX";
This should create the macros in the way needed by the various output modes (at least for hardcopy, MathJax, and Image modes), and localizes the macros to the given problem (except for MathJax mode in the library browser since macros in MathJax are global to the page).

One could, of course, create commands like

BeginTeXMacros(
   "\newcommand{\myMacro}{\mbox{This is myMacro}}",
);
...
EndTeXMacros();
that hide the mechanics of it, and load them from a local macro file if you want to do this in many problems.

Of course, the image-mode output does suffer from the same caching issue that we see below, so I would recommend doing development using MathJax mode instead.