WeBWorK Problems

percent as a unit

Re: percent as a unit

by Davide Cervone -
Number of replies: 0
Sorry for the long delay in getting back to you. I don't really have time to answer WeBWorK questions when I'm teaching.

The issue is in the TeXunits method of the NumberWithUnits object (lines 84 through 92). This doesn't escape all possible TeX special characters (since all the units were alphabetical at the time it was written).

One solution for your case would be to use

sub TeXunits {
  my $units = shift;
  $units =~ s/\^\(?([-+]?\d+)\)?/^{$1}/g;
  $units =~ s/\*/\\,/g;
  $units =~ s/%/\\%/g;   # escape percent signs
  return '{\rm '.$units.'}' unless $units =~ m!^(.*)/(.*)$!;
  my $displayMode = WeBWorK::PG::Translator::PG_restricted_eval(q!$main::displayMode!);
  return '{\textstyle\frac{'.$1.'}{'.$2.'}}' if ($displayMode eq 'HTML_tth');
  return '{\textstyle\frac{\rm\mathstrut '.$1.'}{\rm\mathstrut '.$2.'}}';
}
but this just fixes it for percents. If you want to handle all possible special characters, then something like this might work:

my %escape = (
  '"'  => '{\ttfamily\char34}',
  "\#" => '{\ttfamily\char35}',
  '$'  => '\$',
  '%'  => '\%',
  '&'  => '\&',
  '<'  => '{\ttfamily\char60}',
  '>'  => '{\ttfamily\char62}',
  '\\' => '{\ttfamily\char92}',
  '^'  => '{\ttfamily\char94}',
  '_'  => '\_',
  '{'  => '{\ttfamily\char123}',
  '|'  => '{\ttfamily\char124}',
  '}'  => '{\ttfamily\char125}',
  '~'  => '{\ttfamily\char126}',
);

sub TeXunits {
  my $units = shift;
  $units =~ s/(["\#\$%&<>\\^_\{|\}~])/$escape{$1}/eg;
  $units =~ s/\^\(?([-+]?\d+)\)?/^{$1}/g;
  $units =~ s/\*/\\,/g;
  return '{\rm '.$units.'}' unless $units =~ m!^(.*)/(.*)$!;
  my $displayMode = WeBWorK::PG::Translator::PG_restricted_eval(q!$main::displayMode!);
  return '{\textstyle\frac{'.$1.'}{'.$2.'}}' if ($displayMode eq 'HTML_tth');
  return '{\textstyle\frac{\rm\mathstrut '.$1.'}{\rm\mathstrut '.$2.'}}';
}
(This was cribbed from the PGML.pl file, so it should work, but I haven't tested it.) I suppose such an escaping function should be more readily available rather than having to redo it every time it is needed.

Hope that helps.

Davide