[system] / trunk / pg / macros / PGbasicmacros.pl Repository:
ViewVC logotype

View of /trunk/pg/macros/PGbasicmacros.pl

Parent Directory Parent Directory | Revision Log Revision Log


Revision 5901 - (download) (as text) (annotate)
Fri Sep 12 14:28:59 2008 UTC (11 years, 4 months ago) by gage
File size: 78814 byte(s)
have  hint always print hints for instructorsCVS: ----------------------------------------------------------------------

    1 
    2 
    3 ####################################################################
    4 # Copyright @ 1995-1998 University of Rochester
    5 # All Rights Reserved
    6 ####################################################################
    7 
    8 =head1 NAME
    9 
   10     PGbasicmacros.pl --- located in the courseScripts directory
   11 
   12 =head1 SYNPOSIS
   13 
   14 
   15 
   16 =head1 DESCRIPTION
   17 
   18 
   19 
   20 =cut
   21 
   22 # this is equivalent to use strict, but can be used within the Safe compartment.
   23 BEGIN{
   24   be_strict;
   25 }
   26 
   27 
   28 my $displayMode;
   29 
   30 my ($PAR,
   31   $BR,
   32   $LQ,
   33   $RQ,
   34   $BM,
   35   $EM,
   36   $BDM,
   37   $EDM,
   38   $LTS,
   39   $GTS,
   40   $LTE,
   41   $GTE,
   42   $BEGIN_ONE_COLUMN,
   43   $END_ONE_COLUMN,
   44   $SOL,
   45   $SOLUTION,
   46   $HINT,
   47   $COMMENT,
   48   $US,
   49   $SPACE,
   50   $BBOLD,
   51   $EBOLD,
   52   $BITALIC,
   53   $EITALIC,
   54   $BCENTER,
   55   $ECENTER,
   56   $HR,
   57   $LBRACE,
   58   $RBRACE,
   59   $LB,
   60   $RB,
   61   $DOLLAR,
   62   $PERCENT,
   63   $CARET,
   64   $PI,
   65   $E,
   66   @ALPHABET,
   67   $envir,
   68   $PG_random_generator,
   69   $inputs_ref,
   70   $rh_sticky_answers,
   71   $r_ans_rule_count,
   72   );
   73 
   74 sub _PGbasicmacros_init {
   75     # The big problem is that at compile time in the cached Safe compartment
   76     # main:: has one definition, probably Safe::Root1::
   77     # At runtime main has another definition Safe::Rootx:: where x is > 1
   78 
   79     # It is important to
   80     # initialize the my variable version of $displayMode from the "runtime" version
   81     # of main::displayMode
   82 
   83     $displayMode         =    main::PG_restricted_eval(q!$main::displayMode!);
   84 
   85 # This is initializes the remaining variables in the runtime main:: compartment.
   86 
   87 main::PG_restricted_eval( <<'EndOfFile');
   88     $displayMode            = $displayMode;
   89 
   90   $main::PAR        = PAR();
   91   $main::BR       = BR();
   92   $main::LQ       = LQ();
   93   $main::RQ       = RQ();
   94   $main::BM       = BM();
   95   $main::EM       = EM();
   96   $main::BDM        = BDM();
   97   $main::EDM        = EDM();
   98   $main::LTS        = LTS();
   99   $main::GTS        = GTS();
  100   $main::LTE        = LTE();
  101   $main::GTE        = GTE();
  102   $main::BEGIN_ONE_COLUMN = BEGIN_ONE_COLUMN();
  103   $main::END_ONE_COLUMN = END_ONE_COLUMN();
  104   $main::SOL        = SOLUTION_HEADING();
  105   $main::SOLUTION     = SOLUTION_HEADING();
  106   $main::HINT       = HINT_HEADING();
  107   $main::US       = US();
  108   $main::SPACE      = SPACE();
  109   $main::BBOLD      = BBOLD();
  110   $main::EBOLD      = EBOLD();
  111   $main::BITALIC      = BITALIC();
  112   $main::EITALIC          = EITALIC();
  113   $main::BCENTER          = BCENTER();
  114   $main::ECENTER          = ECENTER();
  115   $main::HR       = HR();
  116   $main::LBRACE     = LBRACE();
  117   $main::RBRACE     = RBRACE();
  118   $main::LB       = LB();
  119   $main::RB       = RB();
  120   $main::DOLLAR     = DOLLAR();
  121   $main::PERCENT      = PERCENT();
  122   $main::CARET      = CARET();
  123   $main::PI       = PI();
  124   $main::E        = E();
  125   @main::ALPHABET     = ('A'..'ZZ');
  126   %main::STICKY_ANSWERS   = ();
  127 
  128 
  129 EndOfFile
  130 
  131 # Next we transfer the correct definitions in the main:: compartment to the local my variables
  132 # This can't be done inside the eval above because my variables seem to be invisible inside the eval
  133 
  134 
  135     $PAR         = PAR();
  136   $BR            = BR();
  137   $LQ            = LQ();
  138   $RQ            = RQ();
  139   $BM            = BM();
  140   $EM            = EM();
  141   $BDM         = BDM();
  142   $EDM         = EDM();
  143   $LTS         = LTS();
  144   $GTS         = GTS();
  145   $LTE         = LTE();
  146   $GTE         = GTE();
  147   $BEGIN_ONE_COLUMN  = BEGIN_ONE_COLUMN();
  148   $END_ONE_COLUMN      = END_ONE_COLUMN();
  149   $SOL         = SOLUTION_HEADING();
  150   $SOLUTION      = SOLUTION_HEADING();
  151   $HINT        = HINT_HEADING();
  152   $US            = US();
  153   $SPACE           = SPACE();
  154   $BBOLD           = BBOLD();
  155   $EBOLD           = EBOLD();
  156   $BITALIC       = BITALIC();
  157   $EITALIC             = EITALIC();
  158   $BCENTER             = BCENTER();
  159   $ECENTER             = ECENTER();
  160   $HR            = HR();
  161   $LBRACE          = LBRACE();
  162   $RBRACE          = RBRACE();
  163   $LB            = LB();
  164   $RB            = RB();
  165   $DOLLAR          = DOLLAR();
  166   $PERCENT       = PERCENT();
  167   $CARET           = CARET();
  168   $PI            = PI();
  169   $E             = E();
  170   @ALPHABET      = ('A'..'ZZ');
  171 
  172    $envir               = PG_restricted_eval(q!\%main::envir!);
  173    $PG_random_generator = PG_restricted_eval(q!$main::PG_random_generator!);
  174    $inputs_ref          = $envir{inputs_ref};
  175    $rh_sticky_answers   = PG_restricted_eval(q!\%main::STICKY_ANSWERS!);
  176    $r_ans_rule_count     = PG_restricted_eval(q!\$ans_rule_count!);
  177 }
  178 
  179 =head2  Answer blank macros:
  180 
  181 These produce answer blanks of various sizes or pop up lists or radio answer buttons.
  182 The names for the answer blanks are
  183 generated implicitly.
  184 
  185   ans_rule( width )
  186   tex_ans_rule( width )
  187   ans_radio_buttons(value1=>label1, value2,label2 => value3,label3=>...)
  188   pop_up_list(@list)   # list consists of (value => label,  PR => "Product rule",...)
  189   pop_up_list([@list]) # list consists of values
  190 
  191 In the last case, one can use C<pop_up_list(['?', 'yes', 'no'])> to produce a
  192 pop-up list containing the three strings listed, and then use str_cmp to check
  193 the answer.
  194 
  195 To indicate the checked position of radio buttons put a '%' in front of the value: C<ans_radio_buttons(1, 'Yes','%2','No')>
  196 will have 'No' checked.  C<tex_ans_rule> works inside math equations in C<HTML_tth> mode.  It does not work in C<Latex2HTML> mode
  197 since this mode produces gif pictures.
  198 
  199 
  200 The following method is defined in F<PG.pl> for entering the answer evaluators corresponding
  201 to answer rules with automatically generated names.  The answer evaluators are matched with the
  202 answer rules in the order in which they appear on the page.
  203 
  204   ANS(ans_evaluator1, ans_evaluator2,...);
  205 
  206 These are more primitive macros which produce answer blanks for specialized cases when complete
  207 control over the matching of answers blanks and answer evaluators is desired.
  208 The names of the answer blanks must be generated manually, and it is best if they do NOT begin
  209 with the default answer prefix (currently AnSwEr).
  210 
  211   labeled_ans_rule(name, width)  # an alias for NAMED_ANS_RULE where width defaults to 20 if omitted.
  212 
  213   NAMED_ANS_RULE(name, width)
  214   NAMED_ANS_BOX(name, rows, cols)
  215   NAMED_ANS_RADIO(name, value,label,)
  216   NAMED_ANS_RADIO_EXTENSION(name, value,label)
  217   NAMED_ANS_RADIO_BUTTONS(name,value1,label1,value2,label2,...)
  218   check_box('-name' =>answer5,'-value' =>'statement3','-label' =>'I loved this course!'   )
  219   NAMED_POP_UP_LIST($name, @list) # list consists of (value => tag,  PR => "Product rule",...)
  220   NAMED_POP_UP_LIST($name, [@list]) # list consists of a list of values (and each tag will be set to the corresponding value)
  221 
  222 (Name is the name of the variable, value is the value given to the variable when this option is selected,
  223 and label is the text printed next to the button or check box.    Check box variables can have multiple values.)
  224 
  225 NAMED_ANS_RADIO_BUTTONS creates a sequence of NAMED_ANS_RADIO and NAMED_ANS_RADIO_EXTENSION  items which
  226 are  output either as an array or, in scalar context, as the array glued together with spaces.  It is
  227 usually easier to use this than to manually construct the radio buttons by hand.  However, sometimes
  228  extra flexibility is desiredin which case:
  229 
  230 When entering radio buttons using the "NAMED" format, you should use NAMED_ANS_RADIO button for the first button
  231 and then use NAMED_ANS_RADIO_EXTENSION for the remaining buttons.  NAMED_ANS_RADIO requires a matching answer evalutor,
  232 while NAMED_ANS_RADIO_EXTENSION does not. The name used for NAMED_ANS_RADIO_EXTENSION should match the name
  233 used for NAMED_ANS_RADIO (and the associated answer evaluator).
  234 
  235 
  236 The following method is defined in  F<PG.pl> for entering the answer evaluators corresponding
  237 to answer rules with automatically generated names.  The answer evaluators are matched with the
  238 answer rules in the order in which they appear on the page.
  239 
  240       NAMED_ANS(name1 => ans_evaluator1, name2 => ans_evaluator2,...);
  241 
  242 These auxiliary macros are defined in PG.pl
  243 
  244 
  245   NEW_ANS_NAME( number );   # produces a new answer blank name from a number by adding a prefix (AnSwEr)
  246                             # and registers this name as an implicitly labeled answer
  247                             # Its use is paired with each answer evaluator being entered using ANS()
  248 
  249     ANS_NUM_TO_NAME(number);  # adds the prefix (AnSwEr) to the number, but does nothing else.
  250 
  251   RECORD_ANS_NAME( name );  # records the order in which the answer blank  is rendered
  252                             # This is called by all of the constructs above, but must
  253                             # be called explicitly if an input blank is constructed explictly
  254                             # using HTML code.
  255 
  256 These are legacy macros:
  257 
  258   ANS_RULE( number, width );                  # equivalent to NAMED_ANS_RULE( NEW_ANS_NAME(number), width)
  259   ANS_BOX( question_number,height, width );       # equivalent to NAMED_ANS_BOX( NEW_ANS_NAME(number), height, width)
  260   ANS_RADIO( question_number, value,tag );        # equivalent to NAMED_ANS_RADIO( NEW_ANS_NAME(number), value,tag)
  261   ANS_RADIO_OPTION( question_number, value,tag );   # equivalent to NAMED_ANS_RADIO_EXTENSION( ANS_NUM_TO_NAME(number), value,tag)
  262 
  263 
  264 =cut
  265 
  266 
  267 
  268 sub labeled_ans_rule {   # syntactic sugar for NAMED_ANS_RULE
  269   my($name,$col) = @_;
  270   $col = 20 unless defined($col);
  271   NAMED_ANS_RULE($name,$col);
  272 }
  273 
  274 sub NAMED_ANS_RULE {
  275   my($name,$col) = @_;
  276   my $answer_value = '';
  277   $answer_value = ${$inputs_ref}{$name} if    defined(${$inputs_ref}{$name});
  278     if ($answer_value =~ /\0/ ) {
  279       my @answers = split("\0", $answer_value);
  280       $answer_value = shift(@answers);  # use up the first answer
  281       $rh_sticky_answers->{$name}=\@answers;
  282       # store the rest -- beacuse this stores to a main:; variable
  283       # it must be evaluated at run time
  284       $answer_value= '' unless defined($answer_value);
  285   } elsif (ref($answer_value) eq 'ARRAY') {
  286     my @answers = @{ $answer_value};
  287       $answer_value = shift(@answers);  # use up the first answer
  288       $rh_sticky_answers->{$name}=\@answers;
  289       # store the rest -- beacuse this stores to a main:; variable
  290       # it must be evaluated at run time
  291       $answer_value= '' unless defined($answer_value);
  292   }
  293 
  294   $answer_value =~ tr/\\$@`//d;   #`## make sure student answers can not be interpolated by e.g. EV3
  295   $answer_value =~ s/\s+/ /g;     ## remove excessive whitespace from student answer
  296   $name = RECORD_ANS_NAME($name);
  297 
  298   my $tcol = $col/2 > 3 ? $col/2 : 3;  ## get max
  299   $tcol = $tcol < 40 ? $tcol : 40;     ## get min
  300 
  301   MODES(
  302     TeX => "\\mbox{\\parbox[t]{${tcol}ex}{\\hrulefill}}",
  303     Latex2HTML => qq!\\begin{rawhtml}<INPUT TYPE=TEXT SIZE=$col NAME=\"$name\" VALUE = \"\">\\end{rawhtml}!,
  304     HTML => qq!<INPUT TYPE=TEXT SIZE=$col NAME="$name" VALUE="$answer_value">!.
  305                         qq!<INPUT TYPE=HIDDEN  NAME="previous_$name" VALUE="$answer_value">!
  306   );
  307 }
  308 
  309 sub NAMED_HIDDEN_ANS_RULE { # this is used to hold information being passed into and out of applets
  310                             # -- preserves state -- identical to NAMED_ANS_RULE except input type "hidden"
  311   my($name,$col) = @_;
  312   my $answer_value = '';
  313   $answer_value = ${$inputs_ref}{$name} if    defined(${$inputs_ref}{$name});
  314     if ($answer_value =~ /\0/ ) {
  315       my @answers = split("\0", $answer_value);
  316       $answer_value = shift(@answers);  # use up the first answer
  317       $rh_sticky_answers->{$name}=\@answers;
  318       # store the rest -- beacuse this stores to a main:; variable
  319       # it must be evaluated at run time
  320       $answer_value= '' unless defined($answer_value);
  321   } elsif (ref($answer_value) eq 'ARRAY') {
  322     my @answers = @{ $answer_value};
  323       $answer_value = shift(@answers);  # use up the first answer
  324       $rh_sticky_answers->{$name}=\@answers;
  325       # store the rest -- beacuse this stores to a main:; variable
  326       # it must be evaluated at run time
  327       $answer_value= '' unless defined($answer_value);
  328   }
  329 
  330   $answer_value =~ tr/\\$@`//d;   #`## make sure student answers can not be interpolated by e.g. EV3
  331   $answer_value =~ s/\s+/ /g;     ## remove excessive whitespace from student answer
  332   $name = RECORD_ANS_NAME($name);
  333 
  334   my $tcol = $col/2 > 3 ? $col/2 : 3;  ## get max
  335   $tcol = $tcol < 40 ? $tcol : 40;     ## get min
  336 
  337   MODES(
  338     TeX => "\\mbox{\\parbox[t]{${tcol}ex}{\\hrulefill}}",
  339     Latex2HTML => qq!\\begin{rawhtml}<INPUT TYPE=TEXT SIZE=$col NAME=\"$name\" VALUE = \"\">\\end{rawhtml}!,
  340     HTML => qq!<INPUT TYPE=HIDDEN SIZE=$col NAME="$name" VALUE="$answer_value">!.
  341                         qq!<INPUT TYPE=HIDDEN  NAME="previous_$name" VALUE="$answer_value">!
  342   );
  343 }
  344 sub NAMED_ANS_RULE_OPTION {   # deprecated
  345   &NAMED_ANS_RULE_EXTENSION;
  346 }
  347 
  348 sub NAMED_ANS_RULE_EXTENSION {
  349   my($name,$col) = @_;
  350   my $answer_value = '';
  351   $answer_value = ${$inputs_ref}{$name} if defined(${$inputs_ref}{$name});
  352   if ( defined( $rh_sticky_answers->{$name} ) ) {
  353     $answer_value = shift( @{ $rh_sticky_answers->{$name} });
  354     $answer_value = '' unless defined($answer_value);
  355   }
  356   $answer_value =~ tr/\\$@`//d;   #`## make sure student answers can not be interpolated by e.g. EV3
  357   $answer_value =~ s/\s+/ /g;     ## remove excessive whitespace from student answer
  358   my $tcol = $col/2 > 3 ? $col/2 : 3;  ## get max
  359   $tcol = $tcol < 40 ? $tcol : 40;     ## get min
  360   MODES(
  361     TeX => "\\mbox{\\parbox[t]{${tcol}ex}{\\hrulefill}}",
  362     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=TEXT SIZE=$col NAME=\"$name\" VALUE = \"\">\n\\end{rawhtml}\n!,
  363     HTML => qq!<INPUT TYPE=TEXT SIZE=$col NAME = "$name" VALUE = "$answer_value">!.
  364                         qq!<INPUT TYPE=HIDDEN  NAME="previous_$name" VALUE = "$answer_value">!
  365   );
  366 }
  367 
  368 sub ANS_RULE {  #deprecated
  369   my($number,$col) = @_;
  370   my $name = NEW_ANS_NAME($number);
  371     NAMED_ANS_RULE($name,$col);
  372 }
  373 
  374 
  375 sub  NAMED_ANS_BOX {
  376   my($name,$row,$col) = @_;
  377   $row = 10 unless defined($row);
  378   $col = 80 unless defined($col);
  379   $name = RECORD_ANS_NAME($name);
  380   my $height = .07*$row;
  381   my $answer_value = '';
  382   $answer_value = $inputs_ref->{$name} if defined( $inputs_ref->{$name} );
  383 # $answer_value =~ tr/\\$@`//d;   #`## make sure student answers can not be interpolated by e.g. EV3
  384   my $out = M3(
  385        qq!\\vskip $height in \\hrulefill\\quad !,
  386        qq!\\begin{rawhtml}<TEXTAREA NAME="$name" ROWS="$row" COLS="$col"
  387                WRAP="VIRTUAL">$answer_value</TEXTAREA>\\end{rawhtml}!,
  388          qq!<TEXTAREA NAME="$name" ROWS="$row" COLS="$col"
  389                WRAP="VIRTUAL">$answer_value</TEXTAREA>
  390              <INPUT TYPE=HIDDEN  NAME="previous_$name" VALUE = "$answer_value">
  391            !
  392          );
  393   $out;
  394 }
  395 
  396 sub  ANS_BOX { #deprecated
  397   my($number,$row,$col) = @_;
  398   my $name = NEW_ANS_NAME($number);
  399     NAMED_ANS_BOX($name,$row,$col);
  400 }
  401 
  402 sub NAMED_ANS_RADIO {
  403   my $name = shift;
  404   my $value = shift;
  405     my $tag =shift;
  406     $name = RECORD_ANS_NAME($name);
  407     my $checked = '';
  408     if ($value =~/^\%/) {
  409       $value =~ s/^\%//;
  410       $checked = 'CHECKED'
  411     }
  412   if (defined($inputs_ref->{$name}) ) {
  413     if ($inputs_ref->{$name} eq $value) {
  414       $checked = 'CHECKED'
  415     } else {
  416       $checked = '';
  417     }
  418 
  419     }
  420 
  421   MODES(
  422     TeX => qq!\\item{$tag}\n!,
  423     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=RADIO NAME="$name" VALUE="$value" $checked>\\end{rawhtml}$tag!,
  424     HTML => qq!<INPUT TYPE=RADIO NAME="$name" VALUE="$value" $checked>$tag!
  425   );
  426 
  427 }
  428 
  429 sub NAMED_ANS_RADIO_OPTION { #deprecated
  430   &NAMED_ANS_RADIO_EXTENSION;
  431 }
  432 
  433 sub NAMED_ANS_RADIO_EXTENSION {
  434   my $name = shift;
  435   my $value = shift;
  436   my $tag =shift;
  437 
  438 
  439     my $checked = '';
  440     if ($value =~/^\%/) {
  441       $value =~ s/^\%//;
  442       $checked = 'CHECKED'
  443     }
  444   if (defined($inputs_ref->{$name}) ) {
  445     if ($inputs_ref->{$name} eq $value) {
  446       $checked = 'CHECKED'
  447     } else {
  448       $checked = '';
  449     }
  450 
  451     }
  452 
  453   MODES(
  454     TeX => qq!\\item{$tag}\n!,
  455     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=RADIO NAME="$name" VALUE="$value" $checked>\\end{rawhtml}$tag!,
  456     HTML => qq!<INPUT TYPE=RADIO NAME="$name" VALUE="$value" $checked>$tag!
  457   );
  458 
  459 }
  460 
  461 sub NAMED_ANS_RADIO_BUTTONS {
  462     my $name  =shift;
  463     my $value = shift;
  464     my $tag = shift;
  465 
  466 
  467   my @out = ();
  468   push(@out, NAMED_ANS_RADIO($name, $value,$tag));
  469   my @buttons = @_;
  470   while (@buttons) {
  471     $value = shift @buttons;  $tag = shift @buttons;
  472     push(@out, NAMED_ANS_RADIO_OPTION($name, $value,$tag));
  473   }
  474   (wantarray) ? @out : join(" ",@out);
  475 }
  476 sub ANS_RADIO {
  477   my $number = shift;
  478   my $value = shift;
  479   my $tag =shift;
  480     my $name = NEW_ANS_NAME($number);
  481   NAMED_ANS_RADIO($name,$value,$tag);
  482 }
  483 
  484 sub ANS_RADIO_OPTION {
  485   my $number = shift;
  486   my $value = shift;
  487   my $tag =shift;
  488 
  489 
  490     my $name = ANS_NUM_TO_NAME($number);
  491   NAMED_ANS_RADIO_OPTION($name,$value,$tag);
  492 }
  493 sub ANS_RADIO_BUTTONS {
  494     my $number  =shift;
  495     my $value = shift;
  496     my $tag = shift;
  497 
  498 
  499   my @out = ();
  500   push(@out, ANS_RADIO($number, $value,$tag));
  501   my @buttons = @_;
  502   while (@buttons) {
  503       $value = shift @buttons; $tag = shift @buttons;
  504     push(@out, ANS_RADIO_OPTION($number, $value,$tag));
  505   }
  506   (wantarray) ? @out : join(" ",@out);
  507 }
  508 ##############################################
  509 #   contained_in( $elem, $array_reference or null separated string);
  510 #   determine whether element is equal
  511 #   ( in the sense of eq,  not ==, ) to an element in the array.
  512 ##############################################
  513 sub contained_in {
  514   my $element = shift;
  515   my @input_list    = @_;
  516   my @output_list = ();
  517   # Expand the list -- convert references to  arrays to arrays
  518   # Convert null separated strings to arrays
  519   foreach my $item   (@input_list ) {
  520     if ($item =~ /\0/) {
  521       push @output_list,   split('\0', $item);
  522      } elsif (ref($item) =~/ARRAY/) {
  523       push @output_list, @{$item};
  524      } else {
  525       push @output_list, $item;
  526      }
  527   }
  528 
  529   my @match_list = grep {$element eq $_ } @output_list;
  530   if ( @match_list ) {
  531     return 1;
  532   } else {
  533     return 0;
  534   }
  535 }
  536 
  537 ##########################
  538 # If multiple boxes are checked then the $inputs_ref->{name }will be a null separated string
  539 # or a reference to an array.
  540 ##########################
  541 
  542 sub NAMED_ANS_CHECKBOX {
  543   my $name = shift;
  544   my $value = shift;
  545     my $tag =shift;
  546     $name = RECORD_ANS_NAME($name);
  547 
  548     my $checked = '';
  549     if ($value =~/^\%/) {
  550       $value =~ s/^\%//;
  551       $checked = 'CHECKED'
  552     }
  553 
  554   if (defined($inputs_ref->{$name}) ) {
  555     if ( contained_in($value, $inputs_ref->{$name} ) ) {
  556       $checked = 'CHECKED'
  557     }
  558     else {
  559       $checked = '';
  560     }
  561 
  562     }
  563 
  564   MODES(
  565     TeX => qq!\\item{$tag}\n!,
  566     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=CHECKBOX NAME="$name" VALUE="$value" $checked>\\end{rawhtml}$tag!,
  567     HTML => qq!<INPUT TYPE=CHECKBOX NAME="$name" VALUE="$value" $checked>$tag!
  568   );
  569 
  570 }
  571 
  572 sub NAMED_ANS_CHECKBOX_OPTION {
  573   my $name = shift;
  574   my $value = shift;
  575   my $tag =shift;
  576 
  577     my $checked = '';
  578     if ($value =~/^\%/) {
  579       $value =~ s/^\%//;
  580       $checked = 'CHECKED'
  581     }
  582 
  583   if (defined($inputs_ref->{$name}) ) {
  584     if ( contained_in($value, $inputs_ref->{$name}) ) {
  585       $checked = 'CHECKED'
  586     }
  587     else {
  588       $checked = '';
  589     }
  590 
  591     }
  592 
  593   MODES(
  594     TeX => qq!\\item{$tag}\n!,
  595     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=CHECKBOX NAME="$name" VALUE="$value" $checked>\\end{rawhtml}$tag!,
  596     HTML => qq!<INPUT TYPE=CHECKBOX NAME="$name" VALUE="$value" $checked>$tag!
  597   );
  598 
  599 }
  600 
  601 sub NAMED_ANS_CHECKBOX_BUTTONS {
  602     my $name  =shift;
  603     my $value = shift;
  604     my $tag = shift;
  605 
  606   my @out = ();
  607   push(@out, NAMED_ANS_CHECKBOX($name, $value,$tag));
  608 
  609   my @buttons = @_;
  610   while (@buttons) {
  611     $value = shift @buttons;  $tag = shift @buttons;
  612     push(@out, NAMED_ANS_CHECKBOX_OPTION($name, $value,$tag));
  613   }
  614 
  615   (wantarray) ? @out : join(" ",@out);
  616 }
  617 
  618 sub ANS_CHECKBOX {
  619   my $number = shift;
  620   my $value = shift;
  621   my $tag =shift;
  622     my $name = NEW_ANS_NAME($number);
  623 
  624   NAMED_ANS_CHECKBOX($name,$value,$tag);
  625 }
  626 
  627 sub ANS_CHECKBOX_OPTION {
  628   my $number = shift;
  629   my $value = shift;
  630   my $tag =shift;
  631     my $name = ANS_NUM_TO_NAME($number);
  632 
  633   NAMED_ANS_CHECKBOX_OPTION($name,$value,$tag);
  634 }
  635 
  636 
  637 
  638 sub ANS_CHECKBOX_BUTTONS {
  639     my $number  =shift;
  640     my $value = shift;
  641     my $tag = shift;
  642 
  643   my @out = ();
  644   push(@out, ANS_CHECKBOX($number, $value, $tag));
  645 
  646   my @buttons = @_;
  647   while (@buttons) {
  648     $value = shift @buttons;  $tag = shift @buttons;
  649     push(@out, ANS_CHECKBOX_OPTION($number, $value,$tag));
  650   }
  651 
  652   (wantarray) ? @out : join(" ",@out);
  653 }
  654 
  655 sub ans_rule {
  656   my $len = shift;     # gives the optional length of the answer blank
  657   $len    = 20 unless $len ;
  658   my $name = NEW_ANS_NAME(inc_ans_rule_count());
  659   NAMED_ANS_RULE($name ,$len);
  660 }
  661 sub ans_rule_extension {
  662   my $len = shift;
  663     $len    = 20 unless $len ;
  664   my $name = NEW_ANS_NAME($$r_ans_rule_count);  # don't update the answer name
  665   NAMED_ANS_RULE($name ,$len);
  666 }
  667 sub ans_radio_buttons {
  668   my $name  = NEW_ANS_NAME(inc_ans_rule_count());
  669   my @radio_buttons = NAMED_ANS_RADIO_BUTTONS($name, @_);
  670 
  671   if ($displayMode eq 'TeX') {
  672     $radio_buttons[0] = "\n\\begin{itemize}\n" . $radio_buttons[0];
  673     $radio_buttons[$#radio_buttons] .= "\n\\end{itemize}\n";
  674   }
  675 
  676   (wantarray) ? @radio_buttons: join(" ", @radio_buttons);
  677 }
  678 
  679 #added 6/14/2000 by David Etlinger
  680 sub ans_checkbox {
  681   my $name = NEW_ANS_NAME( inc_ans_rule_count() );
  682   my @checkboxes = NAMED_ANS_CHECKBOX_BUTTONS( $name, @_ );
  683 
  684   if ($displayMode eq 'TeX') {
  685     $checkboxes[0] = "\n\\begin{itemize}\n" . $checkboxes[0];
  686     $checkboxes[$#checkboxes] .= "\n\\end{itemize}\n";
  687   }
  688 
  689   (wantarray) ? @checkboxes: join(" ", @checkboxes);
  690 }
  691 
  692 
  693 ## define a version of ans_rule which will work inside TeX math mode or display math mode -- at least for tth mode.
  694 ## This is great for displayed fractions.
  695 ## This will not work with latex2HTML mode since it creates gif equations.
  696 
  697 sub tex_ans_rule {
  698   my $len = shift;
  699   $len    = 20 unless $len ;
  700     my $name = NEW_ANS_NAME(inc_ans_rule_count());
  701     my $answer_rule = NAMED_ANS_RULE($name ,$len);  # we don't want to create three answer rules in different modes.
  702     my $out = MODES(
  703                      'TeX' => $answer_rule,
  704                      'Latex2HTML' => '\\fbox{Answer boxes cannot be placed inside typeset equations}',
  705                      'HTML_tth' => '\\begin{rawhtml} '. $answer_rule.'\\end{rawhtml}',
  706                      'HTML_dpng' => '\\fbox{Answer boxes cannot be placed inside typeset equations}',
  707                      'HTML'     => $answer_rule
  708                    );
  709 
  710     $out;
  711 }
  712 sub tex_ans_rule_extension {
  713   my $len = shift;
  714   $len    = 20 unless $len ;
  715     my $name = NEW_ANS_NAME($$r_ans_rule_count);
  716     my $answer_rule = NAMED_ANS_RULE($name ,$len);  # we don't want to create three answer rules in different modes.
  717     my $out = MODES(
  718                      'TeX' => $answer_rule,
  719                      'Latex2HTML' => '\fbox{Answer boxes cannot be placed inside typeset equations}',
  720                      'HTML_tth' => '\\begin{rawhtml} '. $answer_rule.'\\end{rawhtml}',
  721                      'HTML_dpng' => '\fbox{Answer boxes cannot be placed inside typeset equations}',
  722                      'HTML'     => $answer_rule
  723                    );
  724 
  725     $out;
  726 }
  727 # still needs some cleanup.
  728 sub NAMED_TEX_ANS_RULE {
  729     my $name = shift;
  730   my $len = shift;
  731   $len    = 20 unless $len ;
  732     my $answer_rule = NAMED_ANS_RULE($name ,$len);  # we don't want to create three answer rules in different modes.
  733     my $out = MODES(
  734                      'TeX' => $answer_rule,
  735                      'Latex2HTML' => '\\fbox{Answer boxes cannot be placed inside typeset equations}',
  736                      'HTML_tth' => '\\begin{rawhtml} '. $answer_rule.'\\end{rawhtml}',
  737                      'HTML_dpng' => '\\fbox{Answer boxes cannot be placed inside typeset equations}',
  738                      'HTML'     => $answer_rule
  739                    );
  740 
  741     $out;
  742 }
  743 sub NAMED_TEX_ANS_RULE_EXTENSION {
  744   my $name = shift;
  745   my $len = shift;
  746   $len    = 20 unless $len ;
  747     my $answer_rule = NAMED_ANS_RULE_EXTENSION($name ,$len);  # we don't want to create three answer rules in different modes.
  748     my $out = MODES(
  749                      'TeX' => $answer_rule,
  750                      'Latex2HTML' => '\fbox{Answer boxes cannot be placed inside typeset equations}',
  751                      'HTML_tth' => '\\begin{rawhtml} '. $answer_rule.'\\end{rawhtml}',
  752                      'HTML_dpng' => '\fbox{Answer boxes cannot be placed inside typeset equations}',
  753                      'HTML'     => $answer_rule
  754                    );
  755 
  756     $out;
  757 }
  758 sub ans_box {
  759   my $row = shift;
  760   my $col =shift;
  761   $row = 5 unless $row;
  762   $col = 80 unless $col;
  763   my $name = NEW_ANS_NAME(inc_ans_rule_count());
  764   NAMED_ANS_BOX($name ,$row,$col);
  765 }
  766 
  767 #this is legacy code; use ans_checkbox instead
  768 sub checkbox {
  769   my %options = @_;
  770   qq!<INPUT TYPE="checkbox" NAME="$options{'-name'}" VALUE="$options{'-value'}">$options{'-label'}!
  771 }
  772 
  773 
  774 sub NAMED_POP_UP_LIST {
  775     my $name = shift;
  776   my @list = @_;
  777   if(ref($list[0]) eq 'ARRAY') {
  778     my @list1 = @{$list[0]};
  779     @list = map { $_ => $_ } @list1;
  780   }
  781   $name = RECORD_ANS_NAME($name);   # record answer name
  782     my $answer_value = '';
  783   $answer_value = ${$inputs_ref}{$name} if defined(${$inputs_ref}{$name});
  784   my $out = "";
  785   if ($displayMode eq 'HTML' or $displayMode eq 'HTML_tth' or
  786             $displayMode eq 'HTML_dpng' or $displayMode eq 'HTML_img' or $displayMode eq 'HTML_jsMath' or
  787       $displayMode eq 'HTML_asciimath' or $displayMode eq 'HTML_LaTeXMathML') {
  788     $out = qq!<SELECT NAME = "$name" SIZE=1> \n!;
  789     my $i;
  790     foreach ($i=0; $i< @list; $i=$i+2) {
  791       my $select_flag = ($list[$i] eq $answer_value) ? "SELECTED" : "";
  792       $out .= qq!<OPTION $select_flag VALUE ="$list[$i]" > $list[$i+1]  </OPTION>\n!;
  793     };
  794     $out .= " </SELECT>\n";
  795   } elsif ( $displayMode eq "Latex2HTML") {
  796     $out = qq! \\begin{rawhtml}<SELECT NAME = "$name" SIZE=1> \\end{rawhtml} \n !;
  797     my $i;
  798     foreach ($i=0; $i< @list; $i=$i+2) {
  799       my $select_flag = ($list[$i] eq $answer_value) ? "SELECTED" : "";
  800       $out .= qq!\\begin{rawhtml}<OPTION $select_flag VALUE ="$list[$i]" > $list[$i+1]  </OPTION>\\end{rawhtml}\n!;
  801     };
  802     $out .= " \\begin{rawhtml}</SELECT>\\end{rawhtml}\n";
  803   } elsif ( $displayMode eq "TeX") {
  804       $out .= "\\fbox{?}";
  805   }
  806 
  807 }
  808 
  809 sub pop_up_list {
  810   my @list = @_;
  811   my $name = NEW_ANS_NAME(inc_ans_rule_count());  # get new answer name
  812   NAMED_POP_UP_LIST($name, @list);
  813 }
  814 
  815 
  816 
  817 =head5  answer_matrix
  818 
  819     Usage   \[ \{   answer_matrix(rows,columns,width_of_ans_rule, @options) \} \]
  820 
  821     Creates an array of answer blanks and passes it to display_matrix which returns
  822     text which represents the matrix in TeX format used in math display mode. Answers
  823     are then passed back to whatever answer evaluators you write at the end of the problem.
  824     (note, if you have an m x n matrix, you will need mn answer evaluators, and they will be
  825     returned to the evaluaters starting in the top left hand corner and proceed to the left
  826     and then at the end moving down one row, just as you would read them.)
  827 
  828     The options are passed on to display_matrix.
  829 
  830 
  831 =cut
  832 
  833 
  834 sub answer_matrix{
  835   my $m = shift;
  836   my $n = shift;
  837   my $width = shift;
  838   my @options = @_;
  839   my @array=();
  840   for( my $i = 0; $i < $m; $i+=1)
  841   {
  842     my @row_array = ();
  843 
  844     for( my $i = 0; $i < $n; $i+=1)
  845     {
  846       push @row_array,  ans_rule($width);
  847     }
  848     my $r_row_array = \@row_array;
  849     push @array,  $r_row_array;
  850   }
  851   # display_matrix hasn't been loaded into the cache safe compartment
  852   # so we need to refer to the subroutine in this way to make
  853   # sure that main is defined correctly.
  854   my $ra_local_display_matrix=PG_restricted_eval(q!\&main::display_matrix!);
  855   &$ra_local_display_matrix( \@array, @options );
  856 
  857 }
  858 
  859 sub NAMED_ANS_ARRAY_EXTENSION{
  860 
  861   my $name = shift;
  862   my $col = shift;
  863   $col = 20 unless $col;
  864   my $answer_value = '';
  865 
  866   $answer_value = ${$inputs_ref}{$name} if    defined(${$inputs_ref}{$name});
  867   if ($answer_value =~ /\0/ ) {
  868     my @answers = split("\0", $answer_value);
  869     $answer_value = shift(@answers);
  870     $answer_value= '' unless defined($answer_value);
  871   } elsif (ref($answer_value) eq 'ARRAY') {
  872     my @answers = @{ $answer_value};
  873       $answer_value = shift(@answers);
  874         $answer_value= '' unless defined($answer_value);
  875   }
  876 
  877   $answer_value =~ tr/\\$@`//d;   #`## make sure student answers can not be interpolated by e.g. EV3
  878   MODES(
  879     TeX => "\\mbox{\\parbox[t]{10pt}{\\hrulefill}}\\hrulefill\\quad ",
  880     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=TEXT SIZE=$col NAME=\"$name\" VALUE = \"\">\n\\end{rawhtml}\n!,
  881     HTML => "<INPUT TYPE=TEXT SIZE=$col NAME=\"$name\" VALUE = \"$answer_value\">\n"
  882   );
  883 }
  884 
  885 sub ans_array{
  886   my $m = shift;
  887   my $n = shift;
  888   my $col = shift;
  889   $col = 20 unless $col;
  890   my $num = inc_ans_rule_count() ;
  891   my $name = NEW_ANS_ARRAY_NAME($num,0,0);
  892   my @options = @_;
  893   my @array=();
  894   my $string;
  895   my $answer_value = "";
  896 
  897   $array[0][0] =   NAMED_ANS_RULE($name,$col);
  898 
  899   for( my $i = 1; $i < $n; $i+=1)
  900   {
  901     $name = NEW_ANS_ARRAY_NAME_EXTENSION($num,0,$i);
  902     $array[0][$i] =   NAMED_ANS_ARRAY_EXTENSION($name,$col);
  903 
  904   }
  905 
  906   for( my $j = 1; $j < $m; $j+=1 ){
  907 
  908     for( my $i = 0; $i < $n; $i+=1)
  909     {
  910       $name = NEW_ANS_ARRAY_NAME_EXTENSION($num,$j,$i);
  911       $array[$j][$i] =  NAMED_ANS_ARRAY_EXTENSION($name,$col);
  912 
  913     }
  914 
  915   }
  916   my $ra_local_display_matrix=PG_restricted_eval(q!\&main::display_matrix!);
  917   &$ra_local_display_matrix( \@array, @options );
  918 
  919 }
  920 
  921 sub ans_array_extension{
  922   my $m = shift;
  923   my $n = shift;
  924   my $col = shift;
  925   $col = 20 unless $col;
  926   my $num = PG_restricted_eval(q!$main::ans_rule_count!);
  927   my @options = @_;
  928   my $name;
  929   my @array=();
  930   my $string;
  931   my $answer_value = "";
  932 
  933   for( my $j = 0; $j < $m; $j+=1 ){
  934 
  935     for( my $i = 0; $i < $n; $i+=1)
  936     {
  937       $name = NEW_ANS_ARRAY_NAME_EXTENSION($num,$j,$i);
  938       $array[$j][$i] =  NAMED_ANS_ARRAY_EXTENSION($name,$col);
  939 
  940     }
  941 
  942   }
  943   my $ra_local_display_matrix=PG_restricted_eval(q!\&main::display_matrix!);
  944   &$ra_local_display_matrix( \@array, @options );
  945 
  946 }
  947 
  948 
  949 # end answer blank macros
  950 
  951 =head2 Hints and solutions macros
  952 
  953   solution('text','text2',...);
  954   SOLUTION('text','text2',...);   # equivalent to TEXT(solution(...));
  955 
  956   hint('text', 'text2', ...);
  957   HINT('text', 'text2',...);      # equivalent to TEXT("$BR$HINT" . hint(@_) . "$BR") if hint(@_);
  958 
  959 Solution prints its concatenated input when the check box named 'ShowSol' is set and
  960 the time is after the answer date.  The check box 'ShowSol' is visible only after the
  961 answer date or when the problem is viewed by a professor.
  962 
  963 $main::envir{'displaySolutionsQ'} is set to 1 when a solution is to be displayed.
  964 
  965 Hints are shown only after the number of attempts is greater than $:showHint
  966 ($main::showHint defaults to 1) and the check box named 'ShowHint' is set. The check box
  967 'ShowHint' is visible only after the number of attempts is greater than $main::showHint.
  968 
  969 $main::envir{'displayHintsQ'} is set to 1 when a hint is to be displayed.
  970 
  971 
  972 =cut
  973 
  974 
  975 
  976 #   solution prints its input when $displaySolutionsQ is set.
  977 #   use as TEXT(solution("blah, blah");
  978 #   \$solutionExists
  979 #   is passed to processProblem which displays a "show Solution" button
  980 #   when a solution is available for viewing
  981 
  982 
  983 sub solution {
  984   my @in = @_;
  985   my $out = '';
  986   PG_restricted_eval(q!$main::solutionExists =1!);
  987   if (PG_restricted_eval(q!$main::envir{'displaySolutionsQ'}!)) {$out = join(' ',@in);}
  988     $out;
  989 }
  990 
  991 
  992 sub SOLUTION {
  993   TEXT( solution(@_)) ;
  994 }
  995 
  996 
  997 sub hint {
  998     my @in = @_;
  999   my $out = '';
 1000   my $permissionLevel = PG_restricted_eval(q!$main::envir{permissionLevel}!);
 1001   my $PRINT_FILE_NAMES_PERMISSION_LEVEL = PG_restricted_eval(q!$envir->{'PRINT_FILE_NAMES_PERMISSION_LEVEL'}!);
 1002     my $printHintForInstructor = $permissionLevel >= $PRINT_FILE_NAMES_PERMISSION_LEVEL;
 1003     my $showHint = PG_restricted_eval(q!$main::showHint!);
 1004     my $displayHint = PG_restricted_eval(q!$envir->{'displayHintsQ'}!);
 1005   PG_restricted_eval(q!$main::hintExists =1!);
 1006     my $attempts = PG_restricted_eval(q!$main::numOfAttempts = 0 unless defined($main::numOfAttempts);!);
 1007 
 1008   if ($displayMode eq 'TeX')   {
 1009       if ($printHintForInstructor) {
 1010         $out = join(' ',@in, "$BR(Show hint after $showHint attempts. ) $BR");
 1011     } else  {
 1012       $out = '';  # do nothing since hints are not available for download for students
 1013     }
 1014   } elsif ($printHintForInstructor) {  # always print hints for instructor types
 1015     $out = join(' ',@in, "$BR(Show hint after $showHint attempts. )$BR ");
 1016   } elsif ( $displayHint  and ( $attempts > $showHint ))  {
 1017 
 1018    ## the second test above prevents a hint being shown if a doctored form is submitted
 1019 
 1020     $out = join(' ',@in);
 1021   }    # show hint
 1022 
 1023   $out ;
 1024 }
 1025 
 1026 
 1027 sub HINT {
 1028     TEXT("$BR" . hint(@_) . "$BR") if hint(@_);
 1029 }
 1030 
 1031 
 1032 
 1033 # End hints and solutions macros
 1034 #################################
 1035 
 1036 =head2 Comments to instructors
 1037 
 1038   COMMENT('text','text2',...);
 1039 
 1040 Takes the text to be lines of a comment to be shown only
 1041 in the Library Browser below the rendered problem.
 1042 
 1043 The function COMMENT stores the needed html in the variable
 1044 pgComment, which gets transfered to the flag 'comment' in PG_FLAGS.
 1045 
 1046 =cut
 1047 
 1048 # Add a comment which will display in the Library browser
 1049 #  Currently, the only output is html
 1050 
 1051 sub COMMENT {
 1052     my @in = @_;
 1053   my $out = join("$BR", @in);
 1054   my $out = '<div class=\"AuthorComment\">'.$out.'</div>';
 1055 
 1056   PG_restricted_eval(q!$main::pgComment = "!.$out.q!"!);
 1057   return('');
 1058 }
 1059 
 1060 #################################
 1061 # Produces a random number between $begin and $end with increment 1.
 1062 # You do not have to worry about integer or floating point types.
 1063 
 1064 =head2 Pseudo-random number generator
 1065 
 1066   Usage:
 1067   random(0,5,.1)      # produces a random number between 0 and 5 in increments of .1
 1068   non_zero_random(0,5,.1) # gives a non-zero random number
 1069 
 1070   list_random(2,3,5,6,7,8,10) # produces random value from the list
 1071   list_random(2,3, (5..8),10) # does the same thing
 1072 
 1073   SRAND(seed)     # resets the main random generator -- use very cautiously
 1074 
 1075 
 1076 SRAND(time) will create a different problem everytime it is called.  This makes it difficult
 1077 to check the answers :-).
 1078 
 1079 SRAND($envir->{'inputs_ref'}->{'key'} ) will create a different problem for each login session.
 1080 This is probably what is desired.
 1081 
 1082 =cut
 1083 
 1084 
 1085 sub random  {
 1086   my ($begin, $end, $incr) = @_;
 1087   $PG_random_generator->random($begin,$end,$incr);
 1088 }
 1089 
 1090 
 1091 sub non_zero_random { ##gives a non-zero random number
 1092   my (@arguments)=@_;
 1093   my $a=0;
 1094   my $i=100; #safety counter
 1095   while ($a==0 && ( 0 < $i-- ) ) {
 1096     $a=random(@arguments);
 1097   }
 1098   $a;
 1099 }
 1100 
 1101 sub list_random {
 1102         my(@li) = @_;
 1103         return $li[random(1,scalar(@li))-1];
 1104 }
 1105 
 1106 sub SRAND { # resets the main random generator -- use cautiously
 1107     my $seed = shift;
 1108   $PG_random_generator -> srand($seed);
 1109 }
 1110 
 1111 # display macros
 1112 
 1113 =head2 Display Macros
 1114 
 1115 These macros produce different output depending on the display mode being used to show
 1116 the problem on the screen, or whether the problem is being converted to TeX to produce
 1117 a hard copy output.
 1118 
 1119   MODES   ( TeX =>        "Output this in TeX mode",
 1120             HTML =>       "output this in HTML mode",
 1121             HTML_tth =>   "output this in HTML_tth mode",
 1122             HTML_dpng =>   "output this in HTML_dpng mode",
 1123             Latex2HTML => "output this in Latex2HTML mode",
 1124            )
 1125 
 1126   TEX     (tex_version, html_version) #obsolete
 1127 
 1128   M3      (tex_version, latex2html_version, html_version) #obsolete
 1129 
 1130 
 1131 
 1132 =cut
 1133 
 1134 
 1135 sub TEX {
 1136   my ($tex, $html ) = @_;
 1137   MODES(TeX => $tex, HTML => $html, HTML_tth => $html, HTML_dpng => $html);
 1138 }
 1139 
 1140 
 1141 sub M3 {
 1142   my($tex,$l2h,$html) = @_;
 1143   MODES(TeX => $tex, Latex2HTML => $l2h, HTML => $html, HTML_tth => $html, HTML_dpng => $html);
 1144 }
 1145 
 1146 # MODES() is now table driven
 1147 our %DISPLAY_MODE_FAILOVER = (
 1148   TeX              => [],
 1149   HTML             => [],
 1150   HTML_tth         => [ "HTML", ],
 1151   HTML_dpng        => [ "HTML_tth", "HTML", ],
 1152   HTML_jsMath      => [ "HTML_dpng", "HTML_tth", "HTML", ],
 1153   HTML_asciimath   => [ "HTML_dpng", "HTML_tth", "HTML", ],
 1154   HTML_LaTeXMathML => [ "HTML_dpng", "HTML_tth", "HTML", ],
 1155   # legacy modes -- these are not supported, but some problems might try to
 1156   # set the display mode to one of these values manually and some macros may
 1157   # provide rendered versions for these modes but not the one we want.
 1158   Latex2HTML  => [ "TeX", "HTML", ],
 1159   HTML_img    => [ "HTML_dpng", "HTML_tth", "HTML", ],
 1160 );
 1161 
 1162 # This replaces M3.  You can add new modes at will to this one.
 1163 sub MODES {
 1164   my %options = @_;
 1165 
 1166   # is a string supplied for the current display mode? if so, return it
 1167   return $options{$displayMode} if defined $options{$displayMode};
 1168 
 1169   # otherwise, fail over to backup modes
 1170   my @backup_modes;
 1171   if (exists $DISPLAY_MODE_FAILOVER{$displayMode}) {
 1172     @backup_modes = @{$DISPLAY_MODE_FAILOVER{$displayMode}};
 1173     foreach my $mode (@backup_modes) {
 1174       return $options{$mode} if defined $options{$mode};
 1175     }
 1176   }
 1177   die "ERROR in defining MODES: neither display mode $displayMode nor",
 1178     " any fallback modes (", join(", ", @backup_modes), ") supplied.\n";
 1179 }
 1180 
 1181 # end display macros
 1182 
 1183 
 1184 =head2  Display constants
 1185 
 1186   @ALPHABET       ALPHABET()      capital letter alphabet -- ALPHABET[0] = 'A'
 1187   $PAR        PAR()       paragraph character (\par or <p>)
 1188   $BR             BR()        line break character
 1189   $LQ         LQ()        left double quote
 1190   $RQ         RQ()        right double quote
 1191   $BM         BM()        begin math
 1192   $EM         EM()        end math
 1193   $BDM        BDM()       begin display math
 1194   $EDM        EDM()       end display math
 1195   $LTS        LTS()       strictly less than
 1196   $GTS        GTS()       strictly greater than
 1197   $LTE        LTE()       less than or equal
 1198   $GTE        GTE()       greater than or equal
 1199   $BEGIN_ONE_COLUMN BEGIN_ONE_COLUMN()  begin one-column mode
 1200   $END_ONE_COLUMN   END_ONE_COLUMN()  end one-column mode
 1201   $SOL        SOLUTION_HEADING()  solution headline
 1202   $SOLUTION     SOLUTION_HEADING()  solution headline
 1203   $HINT       HINT_HEADING()    hint headline
 1204   $US         US()        underscore character
 1205   $SPACE        SPACE()       space character (tex and latex only)
 1206   $BBOLD        BBOLD()       begin bold typeface
 1207   $EBOLD        EBOLD()       end bold typeface
 1208   $BITALIC        BITALIC()       begin italic typeface
 1209   $EITALIC        EITALIC()       end italic typeface
 1210   $BCENTER        BCENTER()       begin centered environment
 1211   $ECENTER        ECENTER()       end centered environment
 1212   $HR         HR()        horizontal rule
 1213   $LBRACE       LBRACE()      left brace
 1214   $LB         LB ()       left brace
 1215   $RBRACE       RBRACE()      right brace
 1216   $RB         RB ()       right brace
 1217   $DOLLAR       DOLLAR()      a dollar sign
 1218   $PERCENT      PERCENT()     a percent sign
 1219   $CARET        CARET()       a caret sign
 1220   $PI         PI()        the number pi
 1221   $E          E()         the number e
 1222 
 1223 =cut
 1224 
 1225 
 1226 
 1227 
 1228 
 1229 # A utility variable.  Notice that "B"=$ALPHABET[1] and
 1230 # "ABCD"=@ALPHABET[0..3].
 1231 
 1232 sub ALPHABET  {
 1233   ('A'..'ZZ')[@_];
 1234 }
 1235 
 1236 ###############################################################
 1237 # Some constants which are different in tex and in HTML
 1238 # The order of arguments is TeX, Latex2HTML, HTML
 1239 # Adopted Davide Cervone's improvements to PAR, LTS, GTS, LTE, GTE, LBRACE, RBRACE, LB, RB. 7-14-03 AKP
 1240 sub PAR { MODES( TeX => '\\par ', Latex2HTML => '\\begin{rawhtml}<P>\\end{rawhtml}', HTML => '<P>'); };
 1241 #sub BR { MODES( TeX => '\\par\\noindent ', Latex2HTML => '\\begin{rawhtml}<BR>\\end{rawhtml}', HTML => '<BR>'); };
 1242 # Alternate definition of BR which is slightly more flexible and gives more white space in printed output
 1243 # which looks better but kills more trees.
 1244 sub BR { MODES( TeX => '\\leavevmode\\\\\\relax ', Latex2HTML => '\\begin{rawhtml}<BR>\\end{rawhtml}', HTML => '<BR>'); };
 1245 sub LQ { MODES( TeX => "\\lq\\lq{}", Latex2HTML =>   '"',  HTML =>  '&quot;' ); };
 1246 sub RQ { MODES( TeX => "\\rq\\rq{}", Latex2HTML =>   '"',   HTML =>  '&quot;' ); };
 1247 sub BM { MODES(TeX => '\\(', Latex2HTML => '\\(', HTML =>  ''); };  # begin math mode
 1248 sub EM { MODES(TeX => '\\)', Latex2HTML => '\\)', HTML => ''); };  # end math mode
 1249 sub BDM { MODES(TeX => '\\[', Latex2HTML =>   '\\[', HTML =>   '<P ALIGN=CENTER>'); };  #begin displayMath mode
 1250 sub EDM { MODES(TeX => '\\]',  Latex2HTML =>  '\\]', HTML => '</P>'); };              #end displayMath mode
 1251 sub LTS { MODES(TeX => '<', Latex2HTML => '\\lt ', HTML => '&lt;', HTML_tth => '<' ); };
 1252 sub GTS { MODES(TeX => '>', Latex2HTML => '\\gt ', HTML => '&gt;', HTML_tth => '>' ); };
 1253 sub LTE { MODES(TeX => '\\le ', Latex2HTML => '\\le ', HTML => '<U>&lt;</U>', HTML_tth => '\\le ' ); };
 1254 sub GTE { MODES(TeX => '\\ge ', Latex2HTML => '\\ge ', HTML => '<U>&gt;</U>', HTML_tth => '\\ge ' ); };
 1255 sub BEGIN_ONE_COLUMN { MODES(TeX => " \\end{multicols}\n",  Latex2HTML => " ", HTML =>   " "); };
 1256 sub END_ONE_COLUMN { MODES(TeX =>
 1257               " \\begin{multicols}{2}\n\\columnwidth=\\linewidth\n",
 1258                             Latex2HTML => ' ', HTML => ' ');
 1259 
 1260 };
 1261 sub SOLUTION_HEADING { MODES( TeX => '\\par {\\bf Solution:}',
 1262                  Latex2HTML => '\\par {\\bf Solution:}',
 1263                HTML =>  '<P><B>Solution:</B>');
 1264               };
 1265 sub HINT_HEADING { MODES( TeX => "\\par {\\bf Hint:}", Latex2HTML => "\\par {\\bf Hint:}", HTML => "<P><B>Hint:</B>"); };
 1266 sub US { MODES(TeX => '\\_', Latex2HTML => '\\_', HTML => '_');};  # underscore, e.g. file${US}name
 1267 sub SPACE { MODES(TeX => '\\ ',  Latex2HTML => '\\ ', HTML => '&nbsp;');};  # force a space in latex, doesn't force extra space in html
 1268 sub BBOLD { MODES(TeX => '{\\bf ',  Latex2HTML => '{\\bf ', HTML => '<B>'); };
 1269 sub EBOLD { MODES( TeX => '}', Latex2HTML =>  '}',HTML =>  '</B>'); };
 1270 sub BITALIC { MODES(TeX => '{\\it ',  Latex2HTML => '{\\it ', HTML => '<I>'); };
 1271 sub EITALIC { MODES(TeX => '} ',  Latex2HTML => '} ', HTML => '</I>'); };
 1272 sub BCENTER { MODES(TeX => '\\begin{center} ',  Latex2HTML => ' \\begin{rawhtml} <div align="center"> \\end{rawhtml} ', HTML => '<div align="center">'); };
 1273 sub ECENTER { MODES(TeX => '\\end{center} ',  Latex2HTML => ' \\begin{rawhtml} </div> \\end{rawhtml} ', HTML => '</div>'); };
 1274 sub HR { MODES(TeX => '\\par\\hrulefill\\par ', Latex2HTML => '\\begin{rawhtml} <HR> \\end{rawhtml}', HTML =>  '<HR>'); };
 1275 sub LBRACE { MODES( TeX => '\{', Latex2HTML =>   '\\lbrace',  HTML =>  '{' , HTML_tth=> '\\lbrace' ); };
 1276 sub RBRACE { MODES( TeX => '\}', Latex2HTML =>   '\\rbrace',  HTML =>  '}' , HTML_tth=> '\\rbrace',); };
 1277 sub LB { MODES( TeX => '\{', Latex2HTML =>   '\\lbrace',  HTML =>  '{' , HTML_tth=> '\\lbrace' ); };
 1278 sub RB { MODES( TeX => '\}', Latex2HTML =>   '\\rbrace',  HTML =>  '}' , HTML_tth=> '\\rbrace',); };
 1279 sub DOLLAR { MODES( TeX => '\\$', Latex2HTML => '&#36;', HTML => '&#36;' ); };
 1280 sub PERCENT { MODES( TeX => '\\%', Latex2HTML => '\\%', HTML => '%' ); };
 1281 sub CARET { MODES( TeX => '\\verb+^+', Latex2HTML => '\\verb+^+', HTML => '^' ); };
 1282 sub PI {4*atan2(1,1);};
 1283 sub E {exp(1);};
 1284 
 1285 ###############################################################
 1286 ## Evaluation macros
 1287 
 1288 
 1289 =head2 TEXT macros
 1290 
 1291   Usage:
 1292     TEXT(@text);
 1293 
 1294 This is the simplest way to print text from a problem.  The strings in the array C<@text> are concatenated
 1295 with spaces between them and printed out in the text of the problem.  The text is not processed in any other way.
 1296 C<TEXT> is defined in PG.pl.
 1297 
 1298   Usage:
 1299     BEGIN_TEXT
 1300       text.....
 1301     END_TEXT
 1302 
 1303 This is the most common way to enter text into the problem.  All of the text between BEGIN_TEXT and END_TEXT
 1304 is processed by the C<EV3> macro described below and then printed using the C<TEXT> command.  The two key words
 1305 must appear on lines by themselves.  The preprocessing that makes this construction work is done in F<PGtranslator.pm>.
 1306 See C<EV3> below for details on the processing.
 1307 
 1308 
 1309 =cut
 1310 
 1311 =head2 Evaluation macros
 1312 
 1313 =head3 EV3
 1314 
 1315         TEXT(EV3("This is a formulat \( \int_0^5 x^2 \, dx \) ");
 1316         TEXT(EV3(@text));
 1317 
 1318     TEXT(EV3(<<'END_TEXT'));
 1319       text stuff...
 1320     END_TEXT
 1321 
 1322 
 1323 The BEGIN_TEXT/END_TEXT construction is translated into the construction above by PGtranslator.pm.  END_TEXT must appear
 1324 on a line by itself and be left justified.  (The << construction is known as a "here document" in UNIX and in PERL.)
 1325 
 1326 The single quotes around END_TEXT mean that no automatic interpolation of variables takes place in the text.
 1327 Using EV3 with strings which have been evaluated by double quotes may lead to unexpected results.
 1328 
 1329 
 1330 The evaluation macro E3 first evaluates perl code inside the braces:  C<\{  code \}>.
 1331 Any perl statment can be put inside the braces.  The
 1332 result of the evaluation (i.e. the last statement evaluated) replaces the C<\{ code \}> construction.
 1333 
 1334 Next interpolation of all variables (e.g. C<$var or @array> ) is performed.
 1335 
 1336 Then mathematical formulas in TeX are evaluated within the
 1337 C<\(  tex math mode \)> and
 1338 C<\[ tex display math mode \] >
 1339 constructions, in that order:
 1340 
 1341 =head3 FEQ
 1342 
 1343   FEQ($string);   # processes and outputs the string
 1344 
 1345 
 1346 The mathematical formulas are run through the macro C<FEQ> (Format EQuations) which performs
 1347 several substitutions (see below).
 1348 In C<HTML_tth> mode the resulting code is processed by tth to obtain an HTML version
 1349 of the formula. (In the future processing by WebEQ may be added here as another option.)
 1350 The Latex2HTML mode does nothing
 1351 at this stage; it creates the entire problem before running it through
 1352 TeX and creating the GIF images of the equations.
 1353 
 1354 The resulting string is output (and usually fed into TEXT to be printed in the problem).
 1355 
 1356   Usage:
 1357 
 1358     $string2 = FEQ($string1);
 1359 
 1360 This is a filter which is used to format equations by C<EV2> and C<EV3>, but can also be used on its own.  It is best
 1361 understood with an example.
 1362 
 1363     $string1 = "${a}x^2 + ${b}x + {$c:%.1f}"; $a = 3;, $b = -2; $c = -7.345;
 1364 
 1365 when interpolated becomes:
 1366 
 1367     $string1 = '3x^2 + -2x + {-7.345:%0.1f}
 1368 
 1369 FEQ first changes the number of decimal places displayed, so that the last term becomes -7.3 Then it removes the
 1370 extraneous plus and minus signs, so that the final result is what you want:
 1371 
 1372     $string2 = '3x^2 - 2x -7.3';
 1373 
 1374 (The %0.1f construction
 1375 is the same formatting convention used by Perl and nearly identical to the one used by the C printf statement. Some common
 1376 usage:  %0.3f 3 decimal places, fixed notation; %0.3e 3 significant figures exponential notation; %0.3g uses either fixed
 1377 or exponential notation depending on the size of the number.)
 1378 
 1379 Two additional legacy formatting constructions are also supported:
 1380 
 1381 C<!{$c:%0.3f} > will give a number with 3 decimal places and a negative
 1382 sign if the number is negative, no sign if the number is positive.  Since this is
 1383 identical to the behavior of C<{$c:%0.3f}> the use of this syntax is depricated.
 1384 
 1385 C<?{$c:%0.3f}> determines the sign and prints it
 1386 whether the number is positive or negative.  You can use this
 1387 to force an expression such as C<+5.456>.
 1388 
 1389 =head3 EV2
 1390 
 1391     TEXT(EV2(@text));
 1392 
 1393     TEXT(EV2(<<END_OF_TEXT));
 1394       text stuff...
 1395     END_OF_TEXT
 1396 
 1397 This is a precursor to EV3.  In this case the constants are interpolated first, before the evaluation of the \{ ...code...\}
 1398 construct. This can lead to unexpected results.  For example C<\{ join(" ", @text) \}> with C<@text = ("Hello","World");> becomes,
 1399 after interpolation, C<\{ join(" ",Hello World) \}> which then causes an error when evaluated because Hello is a bare word.
 1400 C<EV2> can still be useful if you allow for this, and in particular it works on double quoted strings, which lead to
 1401 unexpected results with C<EV3>. Using single quoted strings with C<EV2> may lead to unexpected results.
 1402 
 1403 The unexpected results have to do with the number of times backslashed constructions have to be escaped. It is quite messy.  For
 1404 more details get a good Perl book and then read the code. :-)
 1405 
 1406 
 1407 
 1408 
 1409 =cut
 1410 
 1411 
 1412 sub ev_substring {
 1413     my $string      = shift;
 1414   my $start_delim = shift;
 1415   my $end_delim   = shift;
 1416   my $actionRef   = shift;
 1417   my ($eval_out,$PG_eval_errors,$PG_full_error_report)=();
 1418     my $out = "";
 1419                 #
 1420                 #  DPVC -- 2001/12/07
 1421                 #     original "while ($string)" fails to process the string "0" correctly
 1422                 #
 1423     while ($string ne "") {
 1424                 #
 1425                 #  end DPVC
 1426                 #
 1427         if ($string =~ /\Q$start_delim\E/s) {
 1428        #print "$start_delim $end_delim evaluating_substring=$string<BR>";
 1429         $string =~ s/^(.*?)\Q$start_delim\E//s;  # get string up to next \{ ---treats string as a single line, ignoring returns
 1430         $out .= $1;
 1431        #print "$start_delim $end_delim substring_out=$out<BR>";
 1432         $string =~ s/^(.*?)\Q$end_delim\E//s;  # get perl code up to \} ---treats string as a single line,  ignoring returns
 1433            #print "$start_delim $end_delim evaluate_string=$1<BR>";
 1434         ($eval_out,$PG_eval_errors,$PG_full_error_report) = &$actionRef($1);
 1435         $eval_out = "$start_delim $eval_out $end_delim" if $PG_full_error_report;
 1436         $out = $out . $eval_out;
 1437        #print "$start_delim $end_delim new substring_out=$out<BR><p><BR>";
 1438         $out .="$PAR ERROR $0 in ev_substring, PGbasicmacros.pl:$PAR <PRE>  $@ </PRE>$PAR" if $@;
 1439         }
 1440       else {
 1441         $out .= $string;  # flush the last part of the string
 1442         last;
 1443         }
 1444 
 1445       }
 1446   $out;
 1447 }
 1448 sub  safe_ev {
 1449     my ($out,$PG_eval_errors,$PG_full_error_report) = &old_safe_ev;   # process input by old_safe_ev first
 1450     $out =~s/\\/\\\\/g;   # protect any new backslashes introduced.
 1451   ($out,$PG_eval_errors,$PG_full_error_report)
 1452 }
 1453 
 1454 sub  old_safe_ev {
 1455     my $in = shift;
 1456     my   ($out,$PG_eval_errors,$PG_full_error_report) = PG_restricted_eval("$in;");
 1457     # the addition of the ; seems to provide better error reporting
 1458     if ($PG_eval_errors) {
 1459       my @errorLines = split("\n",$PG_eval_errors);
 1460     #$out = "<PRE>$PAR % ERROR in $0:old_safe_ev, PGbasicmacros.pl: $PAR % There is an error occuring inside evaluation brackets \\{ ...code... \\} $BR % somewhere in an EV2 or EV3 or BEGIN_TEXT block. $BR % Code evaluated:$BR $in $BR % $BR % $errorLines[0]\n % $errorLines[1]$BR % $BR % $BR </PRE> ";
 1461     warn " ERROR in old_safe_ev, PGbasicmacros.pl: <PRE>
 1462      ## There is an error occuring inside evaluation brackets \\{ ...code... \\}
 1463      ## somewhere in an EV2 or EV3 or BEGIN_TEXT block.
 1464      ## Code evaluated:
 1465      ## $in
 1466      ##" .join("\n     ", @errorLines). "
 1467      ##</PRE>$BR
 1468      ";
 1469      $out ="$PAR $BBOLD  $in $EBOLD $PAR";
 1470 
 1471 
 1472   }
 1473 
 1474   ($out,$PG_eval_errors,$PG_full_error_report);
 1475 }
 1476 
 1477 sub FEQ   {    # Format EQuations
 1478   my $in = shift;
 1479    # formatting numbers -- the ?{} and !{} constructions
 1480   $in =~s/\?\s*\{([.\-\$\w\d]+):?([%.\da-z]*)\}/${ \( &sspf($1,$2) )}/g;
 1481   $in =~s/\!\s*\{([.\-\$\w\d]+):?([%.\da-z]*)\}/${ \( &spf($1,$2) )}/g;
 1482 
 1483   # more formatting numbers -- {number:format} constructions
 1484   $in =~ s/\{(\s*[\+\-\d\.]+[eE]*[\+\-]*\d*):(\%\d*.\d*\w)}/${ \( &spf($1,$2) )}/g;
 1485   $in =~ s/\+\s*\-/ - /g;
 1486   $in =~ s/\-\s*\+/ - /g;
 1487   $in =~ s/\+\s*\+/ + /g;
 1488   $in =~ s/\-\s*\-/ + /g;
 1489   $in;
 1490 }
 1491 
 1492 #sub math_ev3 {
 1493 # my $in = shift; #print "in=$in<BR>";
 1494 # my ($out,$PG_eval_errors,$PG_full_error_report);
 1495 # $in = FEQ($in);
 1496 # $in =~ s/%/\\%/g;   #  % causes trouble in TeX and HTML_tth it usually (always?) indicates an error, not comment
 1497 # return("$BM $in $EM") unless ($displayMode eq 'HTML_tth');
 1498 # $in = "\\(" . $in . "\\)";
 1499 # $out = tth($in);
 1500 # ($out,$PG_eval_errors,$PG_full_error_report);
 1501 #
 1502 #}
 1503 #
 1504 #sub display_math_ev3 {
 1505 # my $in = shift; #print "in=$in<BR>";
 1506 # my ($out,$PG_eval_errors,$PG_full_error_report);
 1507 # $in = FEQ($in);
 1508 # $in =~ s/%/\\%/g;
 1509 # return("$main::BDM $in $main::EDM") unless $displayMode eq 'HTML_tth' ;
 1510 # $in = "\\[" . $in . "\\]";
 1511 # $out =tth($in);
 1512 # ($out,$PG_eval_errors,$PG_full_error_report);
 1513 #}
 1514 
 1515 sub math_ev3 {
 1516   my $in = shift;
 1517   return general_math_ev3($in, "inline");
 1518 }
 1519 
 1520 sub display_math_ev3 {
 1521   my $in = shift;
 1522   return general_math_ev3($in, "display");
 1523 }
 1524 
 1525 sub general_math_ev3 {
 1526   my $in = shift;
 1527   my $mode = shift || "inline";
 1528 
 1529   $in = FEQ($in); # Format EQuations
 1530   $in =~ s/%/\\%/g; # avoid % becoming TeX comments
 1531 
 1532   ## remove leading and trailing spaces so that HTML mode will
 1533   ## not include unwanted spaces as per Davide Cervone.
 1534   $in =~ s/^\s+//;
 1535   $in =~ s/\s+$//;
 1536   ## If it ends with a backslash, there should be another space
 1537   ## at the end
 1538   if($in =~ /\\$/) { $in .= ' ';}
 1539 
 1540   # some modes want the delimiters, some don't
 1541   my $in_delim = $mode eq "inline"
 1542     ? "\\($in\\)"
 1543     : "\\[$in\\]";
 1544 
 1545   my $out;
 1546   if($displayMode eq "HTML_tth") {
 1547     $out = tth($in_delim);
 1548     ## remove leading and trailing spaces as per Davide Cervone.
 1549     $out =~ s/^\s+//;
 1550     $out =~ s/\s+$//;
 1551   } elsif ($displayMode eq "HTML_dpng") {
 1552     # for jj's version of ImageGenerator
 1553     $out = $envir->{'imagegen'}->add($in_delim);
 1554     # for my version of ImageGenerator
 1555     #$out = $envir->{'imagegen'}->add($in, $mode);
 1556   } elsif ($displayMode eq "HTML_img") {
 1557     $out = math2img($in, $mode);
 1558   } elsif ($displayMode eq "HTML_jsMath") {
 1559     $in =~ s/</&lt;/g; $in =~ s/>/&gt;/g;
 1560     $out = '<SPAN CLASS="math">'.$in.'</SPAN>' if $mode eq "inline";
 1561     $out = '<DIV CLASS="math">'.$in.'</DIV>' if $mode eq "display";
 1562   } elsif ($displayMode eq "HTML_asciimath") {
 1563     $out = "`$in`" if $mode eq "inline";
 1564     $out = '<DIV ALIGN="CENTER">`'.$in.'`</DIV>' if $mode eq "display";
 1565   } elsif ($displayMode eq "HTML_LaTeXMathML") {
 1566     $in = '{'.$in.'}';
 1567     $in =~ s/</\\lt/g; $in =~ s/>/\\gt/g;
 1568     $in =~ s/\{\s*(\\(display|text|script|scriptscript)style)/$1\{/g;
 1569     $out = '$$'.$in.'$$' if $mode eq "inline";
 1570     $out = '<DIV ALIGN="CENTER">$$\displaystyle{'.$in.'}$$</DIV>' if $mode eq "display";
 1571   } else {
 1572     $out = "\\($in\\)" if $mode eq "inline";
 1573     $out = "\\[$in\\]" if $mode eq "display";
 1574   }
 1575   return $out;
 1576 }
 1577 
 1578 sub EV2 {
 1579   my $string = join(" ",@_);
 1580   # evaluate code inside of \{  \}  (no nesting allowed)
 1581     $string = ev_substring($string,"\\{","\\}",\&old_safe_ev);
 1582     $string = ev_substring($string,"\\<","\\>",\&old_safe_ev);
 1583   $string = ev_substring($string,"\\(","\\)",\&math_ev3);
 1584   $string = ev_substring($string,"\\[","\\]",\&display_math_ev3);
 1585   # macros for displaying math
 1586   $string =~ s/\\\(/$BM/g;
 1587   $string =~ s/\\\)/$EM/g;
 1588   $string =~ s/\\\[/$BDM/g;
 1589   $string =~ s/\\\]/$EDM/g;
 1590   $string;
 1591 }
 1592 
 1593 sub EV3{
 1594   my $string = join(" ",@_);
 1595   # evaluate code inside of \{  \}  (no nesting allowed)
 1596     $string = ev_substring($string,"\\\\{","\\\\}",\&safe_ev);  # handles \{ \} in single quoted strings of PG files
 1597   # interpolate variables
 1598   my ($evaluated_string,$PG_eval_errors,$PG_full_errors) = PG_restricted_eval("<<END_OF_EVALUATION_STRING\n$string\nEND_OF_EVALUATION_STRING\n");
 1599   if ($PG_eval_errors) {
 1600       my @errorLines = split("\n",$PG_eval_errors);
 1601       $string =~ s/</&lt;/g; $string =~ s/>/&gt;/g;
 1602     $evaluated_string = "<PRE>$PAR % ERROR in $0:EV3, PGbasicmacros.pl: $PAR % There is an error occuring in the following code:$BR $string $BR % $BR % $errorLines[0]\n % $errorLines[1]$BR % $BR % $BR </PRE> ";
 1603     $@="";
 1604   }
 1605   $string = $evaluated_string;
 1606   $string = ev_substring($string,"\\(","\\)",\&math_ev3);
 1607     $string = ev_substring($string,"\\[","\\]",\&display_math_ev3);
 1608   $string;
 1609 }
 1610 
 1611 sub EV4{
 1612     if ($displayMode eq "HTML_dpng") {
 1613         my $string = join(" ",@_);
 1614         my ($evaluated_string,$PG_eval_errors,$PG_full_errors) = PG_restricted_eval("<<END_OF_EVALUATION_STRING\n$string\nEND_OF_EVALUATION_STRING\n");
 1615         if ($PG_eval_errors) {
 1616             my @errorLines = split("\n",$PG_eval_errors);
 1617             $string =~ s/</&lt;/g; $string =~ s/>/&gt;/g;
 1618             $evaluated_string = "<PRE>$PAR % ERROR in $0:EV3, PGbasicmacros.pl:".
 1619       "$PAR % There is an error occuring in the following code:$BR ".
 1620       "$string $BR % $BR % $errorLines[0]\n % $errorLines[1]$BR ".
 1621       "% $BR % $BR </PRE> ";
 1622         }
 1623         $string = $evaluated_string;
 1624         $string = $envir{'imagegen'}->add($string);
 1625         $string;
 1626     } else {
 1627       EV3(@_);
 1628     }
 1629 }
 1630 
 1631 =head3 EV3P
 1632 
 1633   ######################################################################
 1634   #
 1635   #  New version of EV3 that allows `...` and ``...`` to insert TeX produced
 1636   #  by the new Parser (in math and display modes).
 1637   #
 1638   #  Format:  EV3P(string,...);
 1639   #           EV3P({options},string,...);
 1640   #
 1641   #           `x^2/5` will become \(\frac{x^2}{5}\) and then rendered for hardcopy or screen output
 1642   #
 1643   #  where options can include:
 1644   #
 1645   #    processCommands => 0 or 1     Indicates if the student's answer will
 1646   #                                  be allowed to process \{...\}.
 1647   #                                    Default: 1
 1648   #
 1649   #    processVariables => 0 1       Indicates whether variable substitution
 1650   #                                  should be performed on the student's
 1651   #                                  answer.
 1652   #                                    Default: 1
 1653   #
 1654   #    processMath => 0 or 1         Indicates whether \(...\), \[...\],
 1655   #                                  `...` and ``...`` will be processed
 1656   #                                  in the student's answer.
 1657   #                                    Default: 1
 1658   #
 1659   #    processParser => 0 or 1       Indicates if `...` and ``...`` should
 1660   #                                  be processed when math is being
 1661   #                                  processed.
 1662   #                                    Default: 1
 1663   #
 1664   #    fixDollars => 0 or 1          Specifies whether dollar signs not followed
 1665   #                                  by a letter should be replaced by ${DOLLAR}
 1666   #                                  prior to variable substitution (to prevent
 1667   #                                  accidental substitution of strange Perl
 1668   #                                  values).
 1669   #                                    Default: 1
 1670   #
 1671 
 1672 =cut
 1673 
 1674 sub EV3P {
 1675   my $option_ref = {}; $option_ref = shift if ref($_[0]) eq 'HASH';
 1676   my %options = (
 1677     processCommands => 1,
 1678     processVariables => 1,
 1679     processParser => 1,
 1680     processMath => 1,
 1681     fixDollars => 1,
 1682     %{$option_ref},
 1683   );
 1684   my $string = join(" ",@_);
 1685   $string = ev_substring($string,"\\\\{","\\\\}",\&safe_ev) if $options{processCommands};
 1686   if ($options{processVariables}) {
 1687     my $eval_string = $string;
 1688     $eval_string =~ s/\$(?![a-z\{])/\${DOLLAR}/gi if $options{fixDollars};
 1689     my ($evaluated_string,$PG_eval_errors,$PG_full_errors) =
 1690       PG_restricted_eval("<<END_OF_EVALUATION_STRING\n$eval_string\nEND_OF_EVALUATION_STRING\n");
 1691     if ($PG_eval_errors) {
 1692       my $error = (split("\n",$PG_eval_errors))[0]; $error =~ s/at \(eval.*//gs;
 1693       $string =~ s/&/&amp;/g; $string =~ s/</&lt;/g; $string =~ s/>/&gt;/g;
 1694       $evaluated_string = $BBOLD."(Error: $error in '$string')".$EBOLD;
 1695     }
 1696     $string = $evaluated_string;
 1697   }
 1698   if ($options{processMath}) {
 1699     $string = EV3P_parser($string) if $options{processParser};
 1700     $string = ev_substring($string,"\\(","\\)",\&math_ev3);
 1701     $string = ev_substring($string,"\\[","\\]",\&display_math_ev3);
 1702   }
 1703   return $string;
 1704 }
 1705 
 1706 #
 1707 #  Look through a string for ``...`` or `...` and use
 1708 #  the parser to produce TeX code for the specified mathematics.
 1709 #  ``...`` does display math, `...` does in-line math.  They
 1710 #  can also be used within math mode already, in which case they
 1711 #  use whatever mode is already in effect.
 1712 #
 1713 sub EV3P_parser {
 1714   my $string = shift;
 1715   return $string unless $string =~ m/`/;
 1716   my $start = ''; my %end = ('\('=>'\)','\['=>'\]');
 1717   my @parts = split(/(``.*?``\*?|`.+?`\*?|(?:\\[()\[\]]))/s,$string);
 1718   foreach my $part (@parts) {
 1719     if ($part =~ m/^(``?)(.*)\1(\*?)$/s) {
 1720       my ($delim,$math,$star) = ($1,$2,$3);
 1721       my $f = Parser::Formula($math);
 1722       if (defined($f)) {
 1723         $f = $f->reduce if $star;
 1724   $part = $f->TeX;
 1725   $part = ($delim eq '`' ? '\('.$part.'\)': '\['.$part.'\]') if (!$start);
 1726       } else {
 1727   ## FIXME:  use context->{error}{ref} to highlight error in $math.
 1728   $part = $BBOLD."(Error: $$Value::context->{error}{message} '$math')".$EBOLD;
 1729   $part = $end{$start}." ".$part." ".$start if $start;
 1730       }
 1731     }
 1732     elsif ($start) {$start = '' if $part eq $end{$start}}
 1733     elsif ($end{$part}) {$start = $part}
 1734   }
 1735   return join('',@parts);
 1736 }
 1737 
 1738 
 1739 =head2 Formatting macros
 1740 
 1741   beginproblem()  # generates text listing number and the point value of
 1742                   # the problem. It will also print the file name containing
 1743                   # the problem for users listed in the PRINT_FILE_NAMES_FOR PG_environment
 1744                   # variable.
 1745   OL(@array)      # formats the array as an Ordered List ( <OL> </OL> ) enumerated by letters.
 1746 
 1747   htmlLink($url, $text)
 1748                   # Places a reference to the URL with the specified text in the problem.
 1749                   # A common usage is \{ htmlLink(alias('prob1_help.html') \}, 'for help')
 1750                   # where alias finds the full address of the prob1_help.html file in the same directory
 1751                   # as the problem file
 1752   appletLink( { name => "xFunctions",
 1753                 codebase => '',    # use this to specify the complete url
 1754                                    # otherwise libraries specified in global.conf are searched
 1755                 archive  => 'xFunctions.zip', # name the archive containing code (.jar files go here also)
 1756                 code     => 'xFunctionsLauncher.class',
 1757                 width    => 100,
 1758                 height   => 14,
 1759                 params   => { param1 =>value1, param2 => value2},
 1760               }
 1761             );
 1762   helpLink()     allows site specific help specified in global.conf or course.conf
 1763                  the parameter localHelpURL  must be defined in the environment
 1764                  currently works only for 'interval notation' and 'units'
 1765                  NEEDS REFINEMENT
 1766 
 1767   ########################
 1768                 deprecated coding method
 1769           appletLink  ($url, $parameters)
 1770                   # For example
 1771                   # appletLink(q!  archive="http: //webwork.math.rochester.edu/gage/xFunctions/xFunctions.zip"
 1772                                   code="xFunctionsLauncher.class"  width=100 height=14!,
 1773                   " parameter text goes here")
 1774                   # will link to xFunctions.
 1775 
 1776   low level:
 1777 
 1778   spf($number, $format)   # prints the number with the given format
 1779   sspf($number, $format)  # prints the number with the given format, always including a sign.
 1780   nicestring($coefficients, $terms) # print a linear combinations of terms using coefficients
 1781   nicestring($coefficients) # uses the coefficients to make a polynomial
 1782       # For example
 1783       # nicestring([1,-2, 0]) produces 'x^2-2x'
 1784       # nicestring([2,0,-1],['', 't', 't^2']) produces '2-t^2'
 1785   protect_underbar($string) # protects the underbar (class_name) in strings which may have to pass through TeX.
 1786 
 1787 =cut
 1788 
 1789 sub beginproblem {
 1790   my $out = "";
 1791   my $problemValue = $envir->{problemValue};
 1792   my $fileName     = $envir->{fileName};
 1793   my $probNum      = $envir->{probNum};
 1794     my $TeXFileName = protect_underbar($envir->{fileName});
 1795     my $l2hFileName = protect_underbar($envir->{fileName});
 1796   my %inlist;
 1797   my $points ='pts';
 1798 
 1799   $points = 'pt' if $problemValue == 1;
 1800   ##    Prepare header for the problem
 1801   grep($inlist{$_}++,@{ $envir->{'PRINT_FILE_NAMES_FOR'} });
 1802   my $permissionLevel = $envir->{permissionLevel};
 1803   my $PRINT_FILE_NAMES_PERMISSION_LEVEL = $envir->{'PRINT_FILE_NAMES_PERMISSION_LEVEL'};
 1804   my $studentLogin = $envir->{studentLogin};
 1805   my $print_path_name_flag =
 1806       (defined($permissionLevel) && defined($PRINT_FILE_NAMES_PERMISSION_LEVEL) && $permissionLevel >= $PRINT_FILE_NAMES_PERMISSION_LEVEL)
 1807        || ( defined($inlist{ $studentLogin }) and ( $inlist{ $studentLogin }>0 )  ) ;
 1808 
 1809   if ( $print_path_name_flag ) {
 1810     $out = &M3("{\\bf ${probNum}. {\\footnotesize ($problemValue $points) $TeXFileName}}\\newline ",
 1811     " \\begin{rawhtml} ($problemValue $points) <B>$l2hFileName</B><BR>\\end{rawhtml}",
 1812      "($problemValue $points) <B>$fileName</B><BR>"
 1813        ) if ($problemValue ne "");
 1814   } else {
 1815     $out = &M3("{\\bf ${probNum}.} ($problemValue $points) ",
 1816     "($problemValue $points) ",
 1817      "($problemValue $points) "
 1818        ) if ($problemValue ne "");
 1819   }
 1820   $out .= MODES(%{main::PG_restricted_eval(q!$main::problemPreamble!)});
 1821   $out;
 1822 
 1823 }
 1824 
 1825 sub nicestring {
 1826     my($thingy) = shift;
 1827     my(@coefs) = @{$thingy};
 1828     my $n = scalar(@coefs);
 1829     $thingy = shift;
 1830     my(@others);
 1831     if(defined($thingy)) {
 1832   @others = @{$thingy};
 1833     } else {
 1834   my($j);
 1835   for $j (1..($n-2)) {
 1836       $others[$j-1] = "x^".($n-$j);
 1837   }
 1838   if($n>=2) { $others[$n-2] = "x";}
 1839   $others[$n-1] = "";
 1840     }
 1841     my($j, $k)=(0,0);
 1842     while(($k<$n) && ($coefs[$k]==0)) {$k++;}
 1843     if($k==$n) {return("0");}
 1844     my $ans;
 1845     if($coefs[$k]==1) {$ans = ($others[$k]) ? "$others[$k]" : "1";}
 1846     elsif($coefs[$k]== -1) {$ans =  ($others[$k]) ? "- $others[$k]" : "-1"}
 1847     else { $ans = "$coefs[$k] $others[$k]";}
 1848     $k++;
 1849     for $j ($k..($n-1)) {
 1850   if($coefs[$j] != 0) {
 1851       if($coefs[$j] == 1) {
 1852     $ans .= ($others[$j]) ? "+ $others[$j]" : "+ 1";
 1853       } elsif($coefs[$j] == -1) {
 1854     $ans .= ($others[$j]) ? "- $others[$j]" : "-1";
 1855       } else {
 1856     $ans .= "+ $coefs[$j] $others[$j]";
 1857       }
 1858   }
 1859     }
 1860     return($ans);
 1861 }
 1862 
 1863 # kludge to clean up path names
 1864             ## allow underscore character in set and section names and also allows line breaks at /
 1865 sub protect_underbar {
 1866     my $in = shift;
 1867     if ($displayMode eq 'TeX')  {
 1868 
 1869         $in =~ s|_|\\\_|g;
 1870         $in =~ s|/|\\\-/|g;  # allows an optional hyphenation of the path (in tex)
 1871     }
 1872     $in;
 1873 }
 1874 
 1875 
 1876 # An example of a macro which prints out a list (with letters)
 1877 sub OL {
 1878   my(@array) = @_;
 1879   my $i = 0;
 1880   my @alpha = ('A'..'Z', 'AA'..'ZZ');
 1881   my $letter;
 1882   my  $out=   &M3(
 1883           "\\begin{enumerate}\n",
 1884           " \\begin{rawhtml} <OL TYPE=\"A\" VALUE=\"1\"> \\end{rawhtml} ",
 1885           # kludge to fix IE/CSS problem
 1886           #"<OL TYPE=\"A\" VALUE=\"1\">\n"
 1887           "<BLOCKQUOTE>\n"
 1888           ) ;
 1889   my $elem;
 1890   foreach $elem (@array) {
 1891     $letter = shift @alpha;
 1892                 $out .= MODES(
 1893                         TeX=>   "\\item[$ALPHABET[$i].] $elem\n",
 1894                         Latex2HTML=>    " \\begin{rawhtml} <LI> \\end{rawhtml} $elem  ",
 1895                         #HTML=>  "<LI> $elem\n",
 1896                         HTML=>  "<br /> <b>$letter.</b> $elem\n",
 1897                         #HTML_dpng=>     "<LI> $elem <br /> <br /> \n"
 1898                         HTML_dpng=>     "<br /> <b>$letter.</b> $elem \n"
 1899                                         );
 1900     $i++;
 1901   }
 1902   $out .= &M3(
 1903         "\\end{enumerate}\n",
 1904         " \\begin{rawhtml} </OL>\n \\end{rawhtml} ",
 1905         #"</OL>\n"
 1906         "</BLOCKQUOTE>\n"
 1907         ) ;
 1908 }
 1909 
 1910 sub htmlLink {
 1911   my $url = shift;
 1912   my $text = shift;
 1913   my $options = shift;
 1914   $options = "" unless defined($options);
 1915   return "$BBOLD\[ broken link:  $text \] $EBOLD" unless defined($url);
 1916   M3( "{\\bf \\underline{$text}}",
 1917       "\\begin{rawhtml}<A HREF=\"$url\" $options>$text</A>\\end{rawhtml}",
 1918       "<A HREF=\"$url\" $options>$text</A>"
 1919       );
 1920 }
 1921 
 1922 
 1923 sub helpLink {
 1924   my $type1 = shift;
 1925   return "" if(not defined($envir{'localHelpURL'}));
 1926   my $type = lc($type1);
 1927   my %typeHash = (
 1928     'interval notation' => 'IntervalNotation.html',
 1929     'units' => 'Units.html',
 1930     );
 1931 
 1932   my $infoRef = $typeHash{$type};
 1933   return htmlLink( $envir{'localHelpURL'}.$infoRef, $type1,
 1934 'target="ww_help" onclick="window.open(this.href,this.target,\'width=550,height=350,scrollbars=yes,resizable=on\'); return false;"');
 1935 }
 1936 
 1937 sub appletLink {
 1938   my $url  = $_[0];
 1939   return oldAppletLink(@_) unless ref($url) ; # handle legacy where applet link completely defined
 1940   # search for applet
 1941   # get fileName of applet
 1942   my $applet       = shift;
 1943   my $options      = shift;
 1944   my $archive      = $applet ->{archive};
 1945   my $codebase     = $applet ->{codebase};
 1946   my $code         = $applet ->{code};
 1947   my $appletHeader = '';
 1948   # find location of applet
 1949     if (defined($codebase) and $codebase =~/\S/) {
 1950       # do nothing
 1951     } elsif(defined($archive) and $archive =~/\S/) {
 1952       $codebase = findAppletCodebase($archive )
 1953     } elsif (defined($code) and $code =~/\S/) {
 1954       $codebase =  findAppletCodebase($code )
 1955     } else {
 1956       warn "Must define the achive (.jar file) or code (.class file) where the applet code is to be found";
 1957       return;
 1958     }
 1959 
 1960   if ( $codebase =~/^Error/) {
 1961     warn $codebase;
 1962     return;
 1963   } else {
 1964      # we are set to include the applet
 1965   }
 1966   my $appletHeader  =  qq! archive = "$archive " codebase = "$codebase" !;
 1967   foreach my $key ('name', 'code','width','height', ) {
 1968     if ( defined($applet->{$key})   ) {
 1969       $appletHeader .= qq! $key = "!.$applet->{$key}.q!" ! ;
 1970     } else {
 1971       warn " $key is not defined for applet ".$applet->{name};
 1972       # technically name is not required, but all of the other parameters are
 1973     }
 1974   }
 1975   # add parameters to options
 1976   if (defined($applet->{params}) ) {
 1977     foreach my $key (keys %{ $applet->{params} }) {
 1978       my $value = $applet->{params}->{$key};
 1979       $options .=  qq{<PARAM NAME = "$key" VALUE = "$value" >\n};
 1980     }
 1981 
 1982 
 1983   }
 1984   MODES( TeX        => "{\\bf \\underline{APPLET}  }".$applet->{name},
 1985          Latex2HTML => "\\begin{rawhtml} <APPLET $appletHeader> $options </APPLET>\\end{rawhtml}",
 1986          HTML       => "<APPLET\n $appletHeader> \n $options \n </APPLET>",
 1987          #HTML       => qq!<OBJECT $appletHeader codetype="application/java"> $options </OBJECT>!
 1988   );
 1989 }
 1990 
 1991 sub oldAppletLink {
 1992   my $url = shift;
 1993   my $options = shift;
 1994   $options = "" unless defined($options);
 1995   MODES( TeX        => "{\\bf \\underline{APPLET}  }",
 1996          Latex2HTML => "\\begin{rawhtml} <APPLET $url> $options </APPLET>\\end{rawhtml}",
 1997          HTML       => "<APPLET $url> $options </APPLET>"
 1998       );
 1999 }
 2000 sub spf {
 2001   my($number,$format) = @_;  # attention, the order of format and number are reversed
 2002   $format = "%4.3g" unless $format;   # default value for format
 2003   sprintf($format, $number);
 2004   }
 2005 sub sspf {
 2006   my($number,$format) = @_;  # attention, the order of format and number are reversed
 2007   $format = "%4.3g" unless $format;   # default value for format
 2008   my $sign = $number>=0 ? " + " : " - ";
 2009   $number = $number>=0 ? $number : -$number;
 2010   $sign .sprintf($format, $number);
 2011   }
 2012 
 2013 =head2  Sorting and other list macros
 2014 
 2015 
 2016 
 2017   Usage:
 2018   lex_sort(@list);   # outputs list in lexigraphic (alphabetical) order
 2019   num_sort(@list);   # outputs list in numerical order
 2020   uniq( @list);      # outputs a list with no duplicates.  Order is unspecified.
 2021 
 2022   PGsort( \&sort_subroutine, @list);
 2023   # &sort_subroutine defines order. It's output must be 1 or 0 (true or false)
 2024 
 2025 =cut
 2026 
 2027 #  uniq gives unique elements of a list:
 2028  sub uniq {
 2029    my (@in) =@_;
 2030    my %temp = ();
 2031    while (@in) {
 2032           $temp{shift(@in)}++;
 2033       }
 2034    my @out =  keys %temp;  # sort is causing trouble with Safe.??
 2035    @out;
 2036 }
 2037 
 2038 sub lex_sort {
 2039   PGsort sub {$_[0] lt $_[1]}, @_;
 2040 }
 2041 sub num_sort {
 2042   PGsort sub {$_[0] < $_[1]}, @_;
 2043 }
 2044 
 2045 
 2046 =head2 Macros for handling tables
 2047 
 2048   Usage:
 2049   begintable( number_of_columns_in_table)
 2050   row(@dataelements)
 2051   endtable()
 2052 
 2053 Example of useage:
 2054 
 2055   BEGIN_TEXT
 2056     This problem tests calculating new functions from old ones:$BR
 2057     From the table below calculate the quantities asked for:$BR
 2058     \{begintable(scalar(@firstrow)+1)\}
 2059     \{row(" \(x\) ",@firstrow)\}
 2060     \{row(" \(f(x)\) ", @secondrow)\}
 2061     \{row(" \(g(x)\) ", @thirdrow)\}
 2062     \{row(" \(f'(x)\) ", @fourthrow)\}
 2063     \{row(" \(g'(x)\) ", @fifthrow)\}
 2064     \{endtable()\}
 2065 
 2066    (The arrays contain numbers which are placed in the table.)
 2067 
 2068   END_TEXT
 2069 
 2070 =cut
 2071 
 2072 sub begintable {
 2073   my ($number)=shift;   #number of columns in table
 2074   my %options = @_;
 2075   warn "begintable(cols) requires a number indicating the number of columns" unless defined($number);
 2076   my $out = "";
 2077   if ($displayMode eq 'TeX') {
 2078     $out .= "\n\\par\\smallskip\\begin{center}\\begin{tabular}{"  .  "|c" x $number .  "|} \\hline\n";
 2079     }
 2080   elsif ($displayMode eq 'Latex2HTML') {
 2081     $out .= "\n\\begin{rawhtml} <TABLE , BORDER=1>\n\\end{rawhtml}";
 2082     }
 2083   elsif ($displayMode eq 'HTML' || $displayMode eq 'HTML_tth' || $displayMode eq 'HTML_dpng' ||
 2084                $displayMode eq 'HTML_img' || $displayMode eq 'HTML_jsMath' ||
 2085          $displayMode eq 'HTML_asciimath' || $displayMode eq 'HTML_LaTeXMathML') {
 2086     $out .= "<TABLE BORDER=1>\n"
 2087   }
 2088   else {
 2089     $out = "Error: PGbasicmacros: begintable: Unknown displayMode: $displayMode.\n";
 2090     }
 2091   $out;
 2092   }
 2093 
 2094 sub endtable {
 2095   my $out = "";
 2096   if ($displayMode eq 'TeX') {
 2097     $out .= "\n\\end {tabular}\\end{center}\\par\\smallskip\n";
 2098     }
 2099   elsif ($displayMode eq 'Latex2HTML') {
 2100     $out .= "\n\\begin{rawhtml} </TABLE >\n\\end{rawhtml}";
 2101     }
 2102   elsif ($displayMode eq 'HTML' || $displayMode eq 'HTML_tth' || $displayMode eq 'HTML_dpng' ||
 2103                $displayMode eq 'HTML_img' || $displayMode eq 'HTML_jsMath' ||
 2104          $displayMode eq 'HTML_asciimath' || $displayMode eq 'HTML_LaTeXMathML') {
 2105     $out .= "</TABLE>\n";
 2106     }
 2107   else {
 2108     $out = "Error: PGbasicmacros: endtable: Unknown displayMode: $displayMode.\n";
 2109     }
 2110   $out;
 2111   }
 2112 
 2113 
 2114 sub row {
 2115   my @elements = @_;
 2116   my $out = "";
 2117   if ($displayMode eq 'TeX') {
 2118     while (@elements) {
 2119       $out .= shift(@elements) . " &";
 2120       }
 2121      chop($out); # remove last &
 2122      $out .= "\\\\ \\hline \n";
 2123      # carriage returns must be added manually for tex
 2124     }
 2125   elsif ($displayMode eq 'Latex2HTML') {
 2126     $out .= "\n\\begin{rawhtml}\n<TR>\n\\end{rawhtml}\n";
 2127     while (@elements) {
 2128       $out .= " \n\\begin{rawhtml}\n<TD> \n\\end{rawhtml}\n" . shift(@elements) . " \n\\begin{rawhtml}\n</TD> \n\\end{rawhtml}\n";
 2129       }
 2130     $out .= " \n\\begin{rawhtml}\n</TR> \n\\end{rawhtml}\n";
 2131   }
 2132   elsif ($displayMode eq 'HTML' || $displayMode eq 'HTML_tth' || $displayMode eq 'HTML_dpng'||
 2133          $displayMode eq 'HTML_img' || $displayMode eq 'HTML_jsMath' ||
 2134          $displayMode eq 'HTML_asciimath' || $displayMode eq 'HTML_LaTeXMathML') {
 2135     $out .= "<TR>\n";
 2136     while (@elements) {
 2137       $out .= "<TD>" . shift(@elements) . "</TD>";
 2138       }
 2139     $out .= "\n</TR>\n";
 2140   }
 2141   else {
 2142     $out = "Error: PGbasicmacros: row: Unknown displayMode: $displayMode.\n";
 2143     }
 2144   $out;
 2145 }
 2146 
 2147 =head2 Macros for displaying static images
 2148 
 2149   Usage:
 2150   $string = image($image, width => 100, height => 100, tex_size => 800)
 2151   $string = image($image, width => 100, height => 100, extra_html_tags => 'align="middle"', tex_size => 800)
 2152   $string = image([$image1, $image2], width => 100, height => 100, tex_size => 800)
 2153   $string = caption($string);
 2154   $string = imageRow([$image1, $image2 ], [$caption1, $caption2]);
 2155            # produces a complete table with rows of pictures.
 2156 
 2157 
 2158 =cut
 2159 
 2160 #   More advanced macros
 2161 sub image {
 2162   my $image_ref  = shift;
 2163   my @opt = @_;
 2164   unless (scalar(@opt) % 2 == 0 ) {
 2165     warn "ERROR in image macro.  A list of macros must be inclosed in square brackets.";
 2166   }
 2167   my %in_options = @opt;
 2168   my %known_options = (
 2169     width    => 100,
 2170     height   => 100,
 2171     tex_size => 800,
 2172     extra_html_tags => '',
 2173   );
 2174   # handle options
 2175   my %out_options = %known_options;
 2176   foreach my $opt_name (keys %in_options) {
 2177     if ( exists( $known_options{$opt_name} ) ) {
 2178       $out_options{$opt_name} = $in_options{$opt_name} if exists( $in_options{$opt_name} ) ;
 2179     } else {
 2180       die "Option $opt_name not defined for image. " .
 2181           "Default options are:<BR> ", display_options2(%known_options);
 2182     }
 2183   }
 2184   my $width       = $out_options{width};
 2185   my $height      = $out_options{height};
 2186   my $tex_size    = $out_options{tex_size};
 2187   my $width_ratio = $tex_size*(.001);
 2188   my @image_list  = ();
 2189 
 2190   if (ref($image_ref) =~ /ARRAY/ ) {
 2191     @image_list = @{$image_ref};
 2192   } else {
 2193     push(@image_list,$image_ref);
 2194   }
 2195 
 2196   my @output_list = ();
 2197     while(@image_list) {
 2198     my $imageURL = alias(shift @image_list);
 2199     my $out="";
 2200 
 2201     if ($displayMode eq 'TeX') {
 2202       my $imagePath = $imageURL; # in TeX mode, alias gives us a path, not a URL
 2203       if (defined $envir->{texDisposition} and $envir->{texDisposition} eq "pdf") {
 2204         # We're going to create PDF files with our TeX (using pdflatex), so
 2205         # alias should have given us the path to a PNG image. What we need
 2206         # to do is find out the dimmensions of this image, since pdflatex
 2207         # is too dumb to live.
 2208 
 2209         #my ($height, $width) = getImageDimmensions($imagePath);
 2210         ##warn "&image: $imagePath $height $width\n";
 2211         #unless ($height and $width) {
 2212         # warn "Couldn't get the dimmensions of image $imagePath.\n"
 2213         #}
 2214         #$out = "\\includegraphics[bb=0 0 $height $width,width=$width_ratio\\linewidth]{$imagePath}\n";
 2215         $out = "\\includegraphics[width=$width_ratio\\linewidth]{$imagePath}\n";
 2216       } else {
 2217         # Since we're not creating PDF files, alias should have given us the
 2218         # path to an EPS file. latex can get its dimmensions no problem!
 2219 
 2220         $out = "\\includegraphics[width=$width_ratio\\linewidth]{$imagePath}\n";
 2221       }
 2222     } elsif ($displayMode eq 'Latex2HTML') {
 2223       my $wid = ($envir->{onTheFlyImageSize} || 0)+ 30;
 2224       $out = qq!\\begin{rawhtml}\n<A HREF= "$imageURL" TARGET="_blank" onclick="window.open(this.href,this.target, 'width=$wid,height=$wid,scrollbars=yes,resizable=on'); return false;"><IMG SRC="$imageURL"  WIDTH="$width" HEIGHT="$height"></A>\n
 2225       \\end{rawhtml}\n !
 2226     } elsif ($displayMode eq 'HTML' || $displayMode eq 'HTML_tth' || $displayMode eq 'HTML_dpng' ||
 2227        $displayMode eq 'HTML_img' || $displayMode eq 'HTML_jsMath' ||
 2228        $displayMode eq 'HTML_asciimath' || $displayMode eq 'HTML_LaTeXMathML') {
 2229       my $wid = ($envir->{onTheFlyImageSize} || 0) +30;
 2230       $out = qq!<A HREF= "$imageURL" TARGET="_blank" onclick="window.open(this.href,this.target, 'width=$wid,height=$wid,scrollbars=yes,resizable=on'); return false;"><IMG SRC="$imageURL"  WIDTH="$width" HEIGHT="$height" $out_options{extra_html_tags} ></A>
 2231       !
 2232     } else {
 2233       $out = "Error: PGbasicmacros: image: Unknown displayMode: $displayMode.\n";
 2234     }
 2235     push(@output_list, $out);
 2236   }
 2237   return wantarray ? @output_list : $output_list[0];
 2238 }
 2239 
 2240 # This is legacy code.
 2241 sub images {
 2242   my @in = @_;
 2243   my @outlist = ();
 2244   while (@in) {
 2245      push(@outlist,&image( shift(@in) ) );
 2246    }
 2247   @outlist;
 2248 }
 2249 
 2250 
 2251 sub caption {
 2252   my ($out) = @_;
 2253   $out = " $out \n" if $displayMode eq 'TeX';
 2254   $out = " $out  " if $displayMode eq 'HTML';
 2255   $out = " $out  " if $displayMode eq 'HTML_tth';
 2256   $out = " $out  " if $displayMode eq 'HTML_dpng';
 2257   $out = " $out  " if $displayMode eq 'HTML_img';
 2258   $out = " $out  " if $displayMode eq 'HTML_jsMath';
 2259   $out = " $out  " if $displayMode eq 'HTML_asciimath';
 2260   $out = " $out  " if $displayMode eq 'HTML_LaTeXMathML';
 2261   $out = " $out  " if $displayMode eq 'Latex2HTML';
 2262     $out;
 2263 }
 2264 
 2265 sub captions {
 2266   my @in = @_;
 2267   my @outlist = ();
 2268   while (@in) {
 2269      push(@outlist,&caption( shift(@in) ) );
 2270   }
 2271   @outlist;
 2272 }
 2273 
 2274 sub imageRow {
 2275 
 2276   my $pImages = shift;
 2277   my $pCaptions=shift;
 2278   my $out = "";
 2279   my @images = @$pImages;
 2280   my @captions = @$pCaptions;
 2281   my $number = @images;
 2282   # standard options
 2283   my %options = ( 'tex_size' => 200,  # width for fitting 4 across
 2284                   'height' => 100,
 2285                   'width' => 100,
 2286                   @_            # overwrite any default options
 2287                 );
 2288 
 2289   if ($displayMode eq 'TeX') {
 2290     $out .= "\n\\par\\smallskip\\begin{center}\\begin{tabular}{"  .  "|c" x $number .  "|} \\hline\n";
 2291     while (@images) {
 2292       $out .= &image( shift(@images),%options ) . '&';
 2293     }
 2294     chop($out);
 2295     $out .= "\\\\ \\hline \n";
 2296     while (@captions) {
 2297       $out .= &caption( shift(@captions) ) . '&';
 2298     }
 2299     chop($out);
 2300     $out .= "\\\\ \\hline \n\\end {tabular}\\end{center}\\par\\smallskip\n";
 2301   } elsif ($displayMode eq 'Latex2HTML'){
 2302 
 2303     $out .= "\n\\begin{rawhtml} <TABLE  BORDER=1><TR>\n\\end{rawhtml}\n";
 2304     while (@images) {
 2305       $out .= "\n\\begin{rawhtml} <TD>\n\\end{rawhtml}\n" . &image( shift(@images),%options )
 2306               . "\n\\begin{rawhtml} </TD>\n\\end{rawhtml}\n" ;
 2307     }
 2308 
 2309     $out .= "\n\\begin{rawhtml}</TR><TR>\\end{rawhtml}\n";
 2310     while (@captions) {
 2311       $out .= "\n\\begin{rawhtml} <TH>\n\\end{rawhtml}\n".&caption( shift(@captions) )
 2312               . "\n\\begin{rawhtml} </TH>\n\\end{rawhtml}\n" ;
 2313     }
 2314 
 2315     $out .= "\n\\begin{rawhtml} </TR> </TABLE >\n\\end{rawhtml}";
 2316   } elsif ($displayMode eq 'HTML' || $displayMode eq 'HTML_tth' || $displayMode eq 'HTML_dpng' ||
 2317      $displayMode eq 'HTML_img' || $displayMode eq 'HTML_jsMath' ||
 2318      $displayMode eq 'HTML_asciimath' || $displayMode eq 'HTML_LaTeXMathML') {
 2319     $out .= "<P>\n <TABLE BORDER=2 CELLPADDING=3 CELLSPACING=2 ><TR ALIGN=CENTER    VALIGN=MIDDLE>\n";
 2320     while (@images) {
 2321       $out .= " \n<TD>". &image( shift(@images),%options ) ."</TD>";
 2322     }
 2323     $out .= "</TR>\n<TR>";
 2324     while (@captions) {
 2325       $out .= " <TH>". &caption( shift(@captions) ) ."</TH>";
 2326     }
 2327     $out .= "\n</TR></TABLE></P>\n"
 2328   }
 2329   else {
 2330     $out = "Error: PGbasicmacros: imageRow: Unknown languageMode: $displayMode.\n";
 2331     warn $out;
 2332   }
 2333   $out;
 2334 }
 2335 
 2336 
 2337 ###########
 2338 # Auxiliary macros
 2339 
 2340 sub display_options2{
 2341   my %options = @_;
 2342   my $out_string = "";
 2343   foreach my $key (keys %options) {
 2344     $out_string .= " $key => $options{$key},<BR>";
 2345   }
 2346   $out_string;
 2347 }
 2348 
 2349 
 2350 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9