File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.152.6.1: download - view: text, annotated - select for diffs
Wed Jul 9 15:17:32 2014 UTC (9 years, 10 months ago) by raeburn
Branches: version_2_10_X
Diff to branchpoint 1.152: preferred, unified
- For 2.10
  - gnuplot 4.4 reports an error unless "offset" is included before the x,y offset
    amount when used in "set xlabel" and"set ylabel".
    (see lonplot.pm rev. 1.169).

    1: # The LearningOnline Network with CAPA
    2: # Dynamic plot
    3: #
    4: # $Id: lonplot.pm,v 1.152.6.1 2014/07/09 15:17:32 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: 
   30: 
   31: 
   32: package Apache::lonplot;
   33: 
   34: use strict;
   35: use warnings FATAL=>'all';
   36: no warnings 'uninitialized';
   37: use Apache::File;
   38: use Apache::response;
   39: use Apache::lonxml;
   40: use Apache::edit;
   41: use Apache::lonnet;
   42: use LONCAPA;
   43:  
   44: 
   45: use vars qw/$weboutputformat $version/;
   46: 
   47: 
   48: 
   49: BEGIN {
   50:     &Apache::lonxml::register('Apache::lonplot',('gnuplot'));
   51:     #
   52:     # Determine the version of GNUPLOT
   53:     $weboutputformat = 'gif';
   54:     my $versionstring = `gnuplot --version 2>/dev/null`;
   55:     ($version) = ($versionstring =~ /^gnuplot ([\d.]+)/);
   56:     if ($version >= 4) {
   57:         $weboutputformat = 'png';
   58:     }
   59:     
   60: }
   61: 
   62: 
   63: =pod
   64: 
   65: ## 
   66: ## Description of data structures:
   67: ##
   68: ##  %plot       %key    %axis
   69: ## --------------------------
   70: ##  height      title   color
   71: ##  width       box     xmin
   72: ##  bgcolor     pos     xmax
   73: ##  fgcolor             ymin
   74: ##  transparent         ymax
   75: ##  grid
   76: ##  border
   77: ##  font
   78: ##  align
   79: ##
   80: ##  @labels: $labels[$i] = \%label
   81: ##           %label: text, xpos, ypos, justify
   82: ##
   83: ##  @curves: $curves[$i] = \%curve
   84: ##           %curve: name, linestyle, ( function | data )
   85: ##
   86: ##  $curves[$i]->{'data'} = [ [x1,x2,x3,x4],
   87: ##                            [y1,y2,y3,y4] ]
   88: ##
   89: 
   90: ###################################################################
   91: ##                                                               ##
   92: ##        Tests used in checking the validitity of input         ##
   93: ##                                                               ##
   94: ###################################################################
   95: 
   96: =cut
   97: 
   98: my $max_str_len = 50;    # if a label, title, xlabel, or ylabel text
   99:                          # is longer than this, it will be truncated.
  100: 
  101: my %linetypes =
  102:     (
  103:      solid          => 1,
  104:      dashed         => 0
  105:     );
  106: 
  107: my %linestyles = 
  108:     (
  109:      lines          => 2,     # Maybe this will be used in the future
  110:      linespoints    => 2,     # to check on whether or not they have 
  111:      dots	    => 2,     # supplied enough <data></data> fields
  112:      points         => 2,     # to use the given line style.  But for
  113:      steps	    => 2,     # now there are more important things 
  114:      fsteps	    => 2,     # for me to deal with.
  115:      histeps        => 2,
  116:      errorbars	    => 3,
  117:      xerrorbars	    => [3,4],
  118:      yerrorbars	    => [3,4],
  119:      xyerrorbars    => [4,6],
  120:      boxes          => 3,
  121:      filledcurves   => 2,
  122:      vector	    => 4
  123:     );		    
  124: 
  125: my $int_test       = sub {$_[0]=~s/\s+//g;$_[0]=~/^\d+$/};
  126: my $real_test      = 
  127:     sub {$_[0]=~s/\s+//g;$_[0]=~/^[+-]?\d*\.?\d*([eE][+-]\d+)?$/};
  128: my $pos_real_test  =
  129:     sub {$_[0]=~s/\s+//g;$_[0]=~/^[+]?\d*\.?\d*([eE][+-]\d+)?$/};
  130: my $color_test     = sub {$_[0]=~s/\s+//g;$_[0]=~/^x[\da-fA-F]{6}$/};
  131: my $onoff_test     = sub {$_[0]=~/^(on|off)$/};
  132: my $key_pos_test   = sub {$_[0]=~/^(top|bottom|right|left|outside|below| )+$/};
  133: my $sml_test       = sub {$_[0]=~/^(\d+|small|medium|large)$/};
  134: my $linestyle_test = sub {exists($linestyles{$_[0]})};
  135: my $words_test     = sub {$_[0]=~s/\s+/ /g;$_[0]=~/^([\w~!\@\#\$\%^&\*\(\)-=_\+\[\]\{\}:\;\'<>,\.\/\?\\]+ ?)+$/};
  136: 
  137: ###################################################################
  138: ##                                                               ##
  139: ##                      Attribute metadata                       ##
  140: ##                                                               ##
  141: ###################################################################
  142: my @gnuplot_edit_order = 
  143:     qw/alttag bgcolor fgcolor height width texwidth fontface font texfont
  144:     transparent grid samples 
  145:     border align plotcolor plottype gridtype lmargin rmargin
  146:     tmargin bmargin major_ticscale minor_ticscale boxwidth gridlayer fillstyle
  147:     pattern solid/;
  148: 
  149: my $margin_choices = ['default',0..20];
  150: 
  151: my %gnuplot_defaults = 
  152:     (
  153:      alttag       => {
  154: 	 default     => 'dynamically generated plot',
  155: 	 test        => $words_test,
  156: 	 description => 'Brief description of the plot',
  157:       	 edit_type   => 'entry',
  158: 	 size        => '40'
  159: 	 },
  160:      height       => {
  161: 	 default     => 300,
  162: 	 test        => $int_test,
  163: 	 description => 'Height of image (pixels)',
  164:       	 edit_type   => 'entry',
  165: 	 size        => '10'
  166: 	 },
  167:      width        => {
  168: 	 default     => 400,
  169: 	 test        => $int_test,
  170: 	 description => 'Width of image (pixels)',
  171: 	 edit_type   => 'entry',
  172: 	 size        => '10'
  173: 	 },
  174:      bgcolor      => {
  175: 	 default     => 'xffffff',
  176: 	 test        => $color_test, 
  177: 	 description => 'Background color of image (xffffff)',
  178: 	 edit_type   => 'entry',
  179: 	 size        => '10'
  180: 	 },
  181:      fgcolor      => {
  182: 	 default     => 'x000000',
  183: 	 test        => $color_test,
  184: 	 description => 'Foreground color of image (x000000)',
  185: 	 edit_type   => 'entry',
  186: 	 size        => '10'
  187: 	 },
  188:      transparent  => {
  189: 	 default     => 'off',
  190: 	 test        => $onoff_test, 
  191: 	 description => 'Transparent image',
  192: 	 edit_type   => 'onoff'
  193: 	 },
  194:      grid         => {
  195: 	 default     => 'on',
  196: 	 test        => $onoff_test, 
  197: 	 description => 'Display grid',
  198: 	 edit_type   => 'onoff'
  199: 	 },
  200:      gridlayer    => {
  201: 	 default     => 'off',
  202: 	 test        => $onoff_test, 
  203: 	 description => 'Display grid front layer over filled boxes or filled curves',
  204: 	 edit_type   => 'onoff'
  205: 	 },
  206:      box_border   => {
  207: 	 default     => 'noborder',
  208: 	 test        => sub {$_[0]=~/^(noborder|border)$/},
  209: 	 description => 'Draw border for boxes',
  210: 	 edit_type   => 'choice',
  211: 	 choices     => ['border','noborder']
  212: 	 },
  213:      border       => {
  214: 	 default     => 'on',
  215: 	 test        => $onoff_test, 
  216: 	 description => 'Draw border around plot',
  217: 	 edit_type   => 'onoff'
  218: 	 },
  219:      font         => {
  220: 	 default     => '9',
  221: 	 test        => $sml_test,
  222: 	 description => 'Font size to use in web output (pts)',
  223: 	 edit_type   => 'choice',
  224: 	 choices     => [['5','5 (small)'],'6','7','8',['9','9 (medium)'],'10',['11','11 (large)'],'12','15']
  225: 	 },
  226:      fontface     => {
  227:         default     => 'sans-serif',
  228:         test        => sub {$_[0]=~/^(sans-serif|serif|classic)$/},
  229:         description => 'Type of font to use',
  230:         edit_type   => 'choice',
  231:         choices     => ['sans-serif','serif', 'classic']
  232:         },
  233:      samples      => {
  234: 	 default     => '100',
  235: 	 test        => $int_test,
  236: 	 description => 'Number of samples for non-data plots',
  237: 	 edit_type   => 'choice',
  238: 	 choices     => ['100','200','500','1000','2000','5000']
  239: 	 },
  240:      align        => {
  241: 	 default     => 'middle',
  242: 	 test        => sub {$_[0]=~/^(left|right|middle|center)$/},
  243: 	 description => 'Alignment for image in HTML',
  244: 	 edit_type   => 'choice',
  245: 	 choices     => ['left','right','middle']
  246: 	 },
  247:      texwidth     => {
  248:          default     => '93',
  249:          test        => $int_test,
  250:          description => 'Width of plot when printed (mm)',
  251:          edit_type   => 'entry',
  252:          size        => '5'
  253:          },
  254:      texfont      => {
  255:          default     => '22',
  256:          test        => $int_test,
  257:          description => 'Font size to use in TeX output (pts):',
  258:          edit_type   => 'choice',
  259:          choices     => [qw/8 10 12 14 16 18 20 22 24 26 28 30 32 34 36/],
  260:          },
  261:      plotcolor    => {
  262:          default     => 'monochrome',
  263:          test        => sub {$_[0]=~/^(monochrome|color|colour)$/},
  264:          description => 'Color setting for printing:',
  265:          edit_type   => 'choice',
  266:          choices     => [qw/monochrome color colour/],
  267:          },
  268:      pattern      => {
  269: 	 default     => '',
  270: 	 test        => $int_test,
  271: 	 description => 'Pattern value for boxes:',
  272: 	 edit_type   => 'choice',
  273:          choices     => [0,1,2,3,4,5,6]
  274:          },
  275:      solid        => {
  276:          default     => 0,
  277:          test        => $real_test,
  278:          description => 'The density of fill style for boxes',
  279:          edit_type   => 'entry',
  280:          size        => '5'
  281:          },
  282:      fillstyle    => {
  283: 	 default     => 'empty',
  284: 	 test        => sub {$_[0]=~/^(empty|solid|pattern)$/},
  285: 	 description => 'Filled style for boxes:',
  286: 	 edit_type   => 'choice',
  287:          choices     => ['empty','solid','pattern']
  288:          },
  289:      plottype     => {
  290: 	 default     => 'Cartesian',
  291: 	 test        => sub {$_[0]=~/^(Polar|Cartesian)$/},
  292: 	 description => 'Plot type:',
  293: 	 edit_type   => 'choice',
  294:          choices     => ['Cartesian','Polar']
  295:          },
  296:      gridtype     => {
  297: 	 default     => 'Cartesian',
  298: 	 test        => sub {$_[0]=~/^(Polar|Cartesian|Linear-Log|Log-Linear|Log-Log)$/},
  299: 	 description => 'Grid type:',
  300: 	 edit_type   => 'choice',
  301:          choices     => ['Cartesian','Polar','Linear-Log','Log-Linear','Log-Log']
  302:          },
  303:      lmargin      => {
  304: 	 default     => 'default',
  305: 	 test        => sub {$_[0]=~/^(default|\d+)$/},
  306: 	 description => 'Left margin width (pts):',
  307: 	 edit_type   => 'choice',
  308:          choices     => $margin_choices,
  309:          },
  310:      rmargin      => {
  311: 	 default     => 'default',
  312: 	 test        => sub {$_[0]=~/^(default|\d+)$/},
  313: 	 description => 'Right margin width (pts):',
  314: 	 edit_type   => 'choice',
  315:          choices     => $margin_choices,
  316:          },
  317:      tmargin      => {
  318: 	 default     => 'default',
  319: 	 test        => sub {$_[0]=~/^(default|\d+)$/},
  320: 	 description => 'Top margin width (pts):',
  321: 	 edit_type   => 'choice',
  322:          choices     => $margin_choices,
  323:          },
  324:      bmargin      => {
  325: 	 default     => 'default',
  326: 	 test        => sub {$_[0]=~/^(default|\d+)$/},
  327: 	 description => 'Bottom margin width (pts):',
  328: 	 edit_type   => 'choice',
  329:          choices     => $margin_choices,
  330:          },
  331:      boxwidth     => {
  332: 	 default     => '',
  333: 	 test        => $real_test, 
  334: 	 description => 'Width of boxes, default is auto',
  335: 	 edit_type   => 'entry',
  336:          size        => '5'
  337:          },
  338:      major_ticscale  => {
  339:          default     => '1',
  340:          test        => $real_test,
  341:          description => 'Size of major tic marks (plot coordinates)',
  342:          edit_type   => 'entry',
  343:          size        => '5'
  344:          },
  345:      minor_ticscale  => {
  346:          default     => '0.5',
  347:          test        => $real_test,
  348:          description => 'Size of minor tic mark (plot coordinates)',
  349:          edit_type   => 'entry',
  350:          size        => '5'
  351:          },
  352:      );
  353: 
  354: my %key_defaults = 
  355:     (
  356:      title => { 
  357: 	 default => '',
  358: 	 test => $words_test,
  359: 	 description => 'Title of key',
  360: 	 edit_type   => 'entry',
  361: 	 size        => '40'
  362: 	 },
  363:      box   => { 
  364: 	 default => 'off',
  365: 	 test => $onoff_test,
  366: 	 description => 'Draw a box around the key?',
  367: 	 edit_type   => 'onoff'
  368: 	 },
  369:      pos   => { 
  370: 	 default => 'top right', 
  371: 	 test => $key_pos_test, 
  372: 	 description => 'Position of the key on the plot',
  373: 	 edit_type   => 'choice',
  374: 	 choices     => ['top left','top right','bottom left','bottom right',
  375: 			 'outside','below']
  376: 	 }
  377:      );
  378: 
  379: my %label_defaults = 
  380:     (
  381:      xpos    => {
  382: 	 default => 0,
  383: 	 test => $real_test,
  384: 	 description => 'X position of label (graph coordinates)',
  385: 	 edit_type   => 'entry',
  386: 	 size        => '10'
  387: 	 },
  388:      ypos    => {
  389: 	 default => 0, 
  390: 	 test => $real_test,
  391: 	 description => 'Y position of label (graph coordinates)',
  392: 	 edit_type   => 'entry',
  393: 	 size        => '10'
  394: 	 },
  395:      justify => {
  396: 	 default => 'left',    
  397: 	 test => sub {$_[0]=~/^(left|right|center)$/},
  398: 	 description => 'justification of the label text on the plot',
  399: 	 edit_type   => 'choice',
  400: 	 choices     => ['left','right','center']
  401:      },
  402:      rotate => {
  403:          default => 0,
  404:          test => $real_test,
  405:          description => 'Rotation of label (degrees)',
  406:          edit_type   => 'entry',
  407:          size        => '10',
  408:      }
  409:      );
  410: 
  411: my @tic_edit_order = ('location','mirror','start','increment','end',
  412:                       'minorfreq');
  413: my %tic_defaults =
  414:     (
  415:      location => {
  416: 	 default => 'border', 
  417: 	 test => sub {$_[0]=~/^(border|axis)$/},
  418: 	 description => 'Location of major tic marks',
  419: 	 edit_type   => 'choice',
  420: 	 choices     => ['border','axis']
  421: 	 },
  422:      mirror => {
  423: 	 default => 'on', 
  424: 	 test => $onoff_test,
  425: 	 description => 'Mirror tics on opposite axis?',
  426: 	 edit_type   => 'onoff'
  427: 	 },
  428:      start => {
  429: 	 default => '-10.0',
  430: 	 test => $real_test,
  431: 	 description => 'Start major tics at',
  432: 	 edit_type   => 'entry',
  433: 	 size        => '10'
  434: 	 },
  435:      increment => {
  436: 	 default => '1.0',
  437: 	 test => $real_test,
  438: 	 description => 'Place a major tic every',
  439: 	 edit_type   => 'entry',
  440: 	 size        => '10'
  441: 	 },
  442:      end => {
  443: 	 default => ' 10.0',
  444: 	 test => $real_test,
  445: 	 description => 'Stop major tics at ',
  446: 	 edit_type   => 'entry',
  447: 	 size        => '10'
  448: 	 },
  449:      minorfreq => {
  450: 	 default => '0',
  451: 	 test => $int_test,
  452: 	 description => 'Number of minor tics per major tic mark',
  453: 	 edit_type   => 'entry',
  454: 	 size        => '10'
  455: 	 },         
  456:      );
  457: 
  458: my @axis_edit_order = ('color','xmin','xmax','ymin','ymax','xformat', 'yformat', 'xzero', 'yzero');
  459: my %axis_defaults = 
  460:     (
  461:      color   => {
  462: 	 default => 'x000000', 
  463: 	 test => $color_test,
  464: 	 description => 'Color of grid lines (x000000)',
  465: 	 edit_type   => 'entry',
  466: 	 size        => '10'
  467: 	 },
  468:      xmin      => {
  469: 	 default => '-10.0',
  470: 	 test => $real_test,
  471: 	 description => 'Minimum x-value shown in plot',
  472: 	 edit_type   => 'entry',
  473: 	 size        => '10'
  474: 	 },
  475:      xmax      => {
  476: 	 default => ' 10.0',
  477: 	 test => $real_test,
  478: 	 description => 'Maximum x-value shown in plot',	 
  479: 	 edit_type   => 'entry',
  480: 	 size        => '10'
  481: 	 },
  482:      ymin      => {
  483: 	 default => '-10.0',
  484: 	 test => $real_test,
  485: 	 description => 'Minimum y-value shown in plot',	 
  486: 	 edit_type   => 'entry',
  487: 	 size        => '10'
  488: 	 },
  489:      ymax      => {
  490: 	 default => ' 10.0',
  491: 	 test => $real_test,
  492: 	 description => 'Maximum y-value shown in plot',	 
  493: 	 edit_type   => 'entry',
  494: 	 size        => '10'
  495:         },
  496:      xformat      => {
  497:          default     => 'on',
  498:          test        => sub {$_[0]=~/^(on|off|\d+(f|F|e|E))$/},
  499:          description => 'X-axis number formatting',
  500:          edit_type   => 'choice',
  501:          choices     => ['on', 'off', '2e', '2f'],
  502:          },
  503:      yformat      => {
  504:          default     => 'on',
  505:          test        => sub {$_[0]=~/^(on|off|\d+(f|F|e|E))$/},
  506:          description => 'Y-axis number formatting',
  507:          edit_type   => 'choice',
  508:          choices     => ['on', 'off', '2e', '2f'],
  509:          },
  510:      
  511:      xzero => {
  512:      	default => 'off',
  513:      	test	=> sub {$_[0]=~/^(off|line|thick-line|dotted)$/},
  514:      	description => 'Show x-zero (y=0) axis',
  515:      	edit_type  => 'choice',
  516:      	choices	=> ['off', 'line', 'thick-line', 'dotted'],
  517:      	},
  518:      
  519:      yzero => {
  520:      	default => 'off',
  521:      	test	=> sub {$_[0]=~/^(off|line|thick-line|dotted)$/},
  522:      	description => 'Show y-zero (x=0) axis',
  523:      	edit_type  => 'choice',
  524:      	choices	=> ['off', 'line', 'thick-line', 'dotted'],
  525:      	},
  526:      );
  527: 
  528: my @curve_edit_order = ('color','name','linestyle','linewidth','linetype','pointtype','pointsize','limit');
  529: 
  530: my %curve_defaults = 
  531:     (
  532:      color     => {
  533: 	 default => 'x000000',
  534: 	 test => $color_test,
  535: 	 description => 'Color of curve (x000000)',
  536: 	 edit_type   => 'entry',
  537: 	 size        => '10'
  538: 	 },
  539:      name      => {
  540: 	 default => '',
  541: 	 test => $words_test,
  542: 	 description => 'Name of curve to appear in key',
  543: 	 edit_type   => 'entry',
  544: 	 size        => '20'
  545: 	 },
  546:      linestyle => {
  547: 	 default => 'lines',
  548: 	 test => $linestyle_test,
  549: 	 description => 'Plot with:',
  550: 	 edit_type   => 'choice',
  551: 	 choices     => [keys(%linestyles)]
  552: 	 },
  553:      linewidth => {
  554:          default     => 1,
  555:          test        => $int_test,
  556:          description => 'Line width (may not apply to all plot styles)',
  557:          edit_type   => 'choice',
  558:          choices     => [1,2,3,4,5,6,7,8,9,10]
  559:          },
  560:      linetype => {
  561:          default     => 'solid',
  562:          test        => sub {$_[0]=~/^(solid|dashed)$/},
  563:          description => 'Line type (may not apply to all plot styles)',
  564:          edit_type   => 'choice',
  565:          choices     => ['solid', 'dashed']
  566:          }, 
  567:      pointsize => {
  568:          default     => 1,
  569:          test        => $pos_real_test,
  570:          description => 'Point size (may not apply to all plot styles)',
  571:          edit_type   => 'entry',
  572:          size        => '5'
  573:          },
  574:      pointtype => {
  575:          default     => 1,
  576:          test        => $int_test,
  577:          description => 'Point type (may not apply to all plot styles)',
  578:          edit_type   => 'choice',
  579:          choices     => [0,1,2,3,4,5,6]
  580:          },
  581:      limit     => {
  582:          default     => 'closed',
  583: 	 test        => sub {$_[0]=~/^(above|below|closed|x1|x2|y1|y2)$/},
  584:          description => 'Point to fill -- for filledcurves',
  585:          edit_type   => 'choice',
  586:          choices     => ['above', 'below', 'closed','x1','x2','y1','y2']
  587:          },
  588:      );
  589: 
  590: ###################################################################
  591: ##                                                               ##
  592: ##                    parsing and edit rendering                 ##
  593: ##                                                               ##
  594: ###################################################################
  595: 
  596: undef %Apache::lonplot::plot;
  597: my (%key,%axis,$title,$xlabel,$ylabel,@labels,@curves,%xtics,%ytics);
  598: 
  599: sub start_gnuplot {
  600:     undef(%Apache::lonplot::plot);   undef(%key);    undef(%axis);
  601:     undef($title);  undef($xlabel); undef($ylabel);
  602:     undef(@labels); undef(@curves);
  603:     undef(%xtics);  undef(%ytics);
  604:     #
  605:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  606:     my $result='';
  607:     &Apache::lonxml::register('Apache::lonplot',
  608: 	     ('title','xlabel','ylabel','key','axis','label','curve',
  609: 	      'xtics','ytics'));
  610:     push (@Apache::lonxml::namespace,'lonplot');
  611:     if ($target eq 'web' || $target eq 'tex') {
  612: 	&get_attributes(\%Apache::lonplot::plot,\%gnuplot_defaults,$parstack,$safeeval,
  613: 			$tagstack->[-1]);
  614:     } elsif ($target eq 'edit') {
  615: 	$result .= &Apache::edit::tag_start($target,$token,'GnuPlot');
  616: 	$result .= &edit_attributes($target,$token,\%gnuplot_defaults,
  617: 				    \@gnuplot_edit_order)
  618: 	    .&Apache::edit::end_row()
  619: 	    .&Apache::edit::start_spanning_row();
  620:     } elsif ($target eq 'modified') {
  621: 	my $constructtag=&Apache::edit::get_new_args
  622: 	    ($token,$parstack,$safeeval,keys(%gnuplot_defaults));
  623: 	if ($constructtag) {
  624: 	    $result = &Apache::edit::rebuild_tag($token);
  625: 	}
  626:     }
  627:     return $result;
  628: }
  629: 
  630: sub end_gnuplot {
  631:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  632:     pop @Apache::lonxml::namespace;
  633:     &Apache::lonxml::deregister('Apache::lonplot',
  634: 	('title','xlabel','ylabel','key','axis','label','curve'));
  635:     my $result = '';
  636:     my $randnumber;
  637:     # need to call rand everytime start_script would evaluate, as the
  638:     # safe space rand number generator and the global rand generator 
  639:     # are not separate
  640:     if ($target eq 'web' || $target eq 'tex' || $target eq 'grade' ||
  641: 	$target eq 'answer') {
  642:       $randnumber=int(rand(1000));
  643:     }
  644:     if ($target eq 'web' || $target eq 'tex') {
  645: 	&check_inputs(); # Make sure we have all the data we need
  646: 	##
  647: 	## Determine filename
  648: 	my $tmpdir = '/home/httpd/perl/tmp/';
  649: 	my $filename = $env{'user.name'}.'_'.$env{'user.domain'}.
  650: 	    '_'.time.'_'.$$.$randnumber.'_plot';
  651: 	## Write the plot description to the file
  652: 	&write_gnuplot_file($tmpdir,$filename,$target);
  653: 	$filename = &escape($filename);
  654: 	## return image tag for the plot
  655: 	if ($target eq 'web') {
  656: 	    $result .= <<"ENDIMAGE";
  657: <img src    = "/cgi-bin/plot.$weboutputformat?file=$filename.data" 
  658:      width  = "$Apache::lonplot::plot{'width'}"
  659:      height = "$Apache::lonplot::plot{'height'}"
  660:      align  = "$Apache::lonplot::plot{'align'}"
  661:      alt    = "$Apache::lonplot::plot{'alttag'}" />
  662: ENDIMAGE
  663:         } elsif ($target eq 'tex') {
  664: 	    &Apache::lonxml::debug(" gnuplot wid = $Apache::lonplot::plot{'width'}");
  665: 	    &Apache::lonxml::debug(" gnuplot ht  = $Apache::lonplot::plot{'height'}");
  666: 	    #might be inside the safe space, register the URL for later
  667: 	    &Apache::lonxml::register_ssi("/cgi-bin/plot.gif?file=$filename.data&output=eps");
  668: 	    $result  = "%DYNAMICIMAGE:$Apache::lonplot::plot{'width'}:$Apache::lonplot::plot{'height'}:$Apache::lonplot::plot{'texwidth'}\n";
  669: 	    $result .= '\graphicspath{{/home/httpd/perl/tmp/}}'."\n";
  670: 	    $result .= '\includegraphics[width='.$Apache::lonplot::plot{'texwidth'}.' mm]{'.&unescape($filename).'.eps}';
  671: 	}
  672:     } elsif ($target eq 'edit') {
  673: 	$result.=&Apache::edit::tag_end($target,$token);
  674:     }
  675:     return $result;
  676: }
  677: 
  678: 
  679: ##--------------------------------------------------------------- xtics
  680: sub start_xtics {
  681:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  682:     my $result='';
  683:     if ($target eq 'web' || $target eq 'tex') {
  684: 	&get_attributes(\%xtics,\%tic_defaults,$parstack,$safeeval,
  685: 		    $tagstack->[-1]);
  686:     } elsif ($target eq 'edit') {
  687: 	$result .= &Apache::edit::tag_start($target,$token,'xtics');
  688: 	$result .= &edit_attributes($target,$token,\%tic_defaults,
  689: 				    \@tic_edit_order);
  690:     } elsif ($target eq 'modified') {
  691: 	my $constructtag=&Apache::edit::get_new_args
  692: 	    ($token,$parstack,$safeeval,keys(%tic_defaults));
  693: 	if ($constructtag) {
  694: 	    $result = &Apache::edit::rebuild_tag($token);
  695: 	}
  696:     }
  697:     return $result;
  698: }
  699: 
  700: sub end_xtics {
  701:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  702:     my $result = '';
  703:     if ($target eq 'web' || $target eq 'tex') {
  704:     } elsif ($target eq 'edit') {
  705: 	$result.=&Apache::edit::tag_end($target,$token);
  706:     }
  707:     return $result;
  708: }
  709: 
  710: ##--------------------------------------------------------------- ytics
  711: sub start_ytics {
  712:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  713:     my $result='';
  714:     if ($target eq 'web' || $target eq 'tex') {
  715: 	&get_attributes(\%ytics,\%tic_defaults,$parstack,$safeeval,
  716: 		    $tagstack->[-1]);
  717:     } elsif ($target eq 'edit') {
  718: 	$result .= &Apache::edit::tag_start($target,$token,'ytics');
  719: 	$result .= &edit_attributes($target,$token,\%tic_defaults,
  720: 				    \@tic_edit_order);
  721:     } elsif ($target eq 'modified') {
  722: 	my $constructtag=&Apache::edit::get_new_args
  723: 	    ($token,$parstack,$safeeval,keys(%tic_defaults));
  724: 	if ($constructtag) {
  725: 	    $result = &Apache::edit::rebuild_tag($token);
  726: 	}
  727:     }
  728:     return $result;
  729: }
  730: 
  731: sub end_ytics {
  732:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  733:     my $result = '';
  734:     if ($target eq 'web' || $target eq 'tex') {
  735:     } elsif ($target eq 'edit') {
  736: 	$result.=&Apache::edit::tag_end($target,$token);
  737:     }
  738:     return $result;
  739: }
  740: 
  741: ##-----------------------------------------------------------------font
  742: my %font_properties =
  743:     (
  744:      'classic'    => {
  745: 	 face       => 'classic',
  746: 	 file       => 'DejaVuSansMono-Bold',
  747: 	 printname  => 'Helvetica',
  748: 	 tex_no_file => 1,
  749:      },
  750:      'sans-serif' => {
  751: 	 face       => 'sans-serif',
  752: 	 file       => 'DejaVuSans',
  753: 	 printname  => 'DejaVuSans',
  754:      },
  755:      'serif'      => {
  756: 	 face       => 'serif',
  757: 	 file       => 'DejaVuSerif',
  758: 	 printname  => 'DejaVuSerif',
  759:      },
  760:      );
  761: 
  762: sub get_font {
  763:     my ($target) = @_;
  764:     my ($size, $selected_font);
  765: 
  766:     if ( $Apache::lonplot::plot{'font'} =~ /^(small|medium|large)/) {
  767: 	$selected_font = $font_properties{'classic'};
  768: 	if ( $Apache::lonplot::plot{'font'} eq 'small') {
  769: 	    $size = '5';
  770: 	} elsif ( $Apache::lonplot::plot{'font'} eq 'medium') {
  771: 	    $size = '9';
  772: 	} elsif ( $Apache::lonplot::plot{'font'} eq 'large') {
  773: 	    $size = '11';
  774: 	} else {
  775: 	    $size = '9';
  776: 	}
  777:     } else {
  778: 	$size = $Apache::lonplot::plot{'font'};
  779: 	$selected_font = $font_properties{$Apache::lonplot::plot{'fontface'}};
  780:     }
  781:     if ($target eq 'tex' && defined($Apache::lonplot::plot{'texfont'})) {
  782: #	$selected_font = $font_properties{'classic'};
  783: 	$size = $Apache::lonplot::plot{'texfont'};
  784:     }
  785:     return ($size, $selected_font);
  786: }
  787: 
  788: ##----------------------------------------------------------------- key
  789: sub start_key {
  790:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  791:     my $result='';
  792:     if ($target eq 'web' || $target eq 'tex') {
  793: 	&get_attributes(\%key,\%key_defaults,$parstack,$safeeval,
  794: 		    $tagstack->[-1]);
  795:     } elsif ($target eq 'edit') {
  796: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Key');
  797: 	$result .= &edit_attributes($target,$token,\%key_defaults);
  798:     } elsif ($target eq 'modified') {
  799: 	my $constructtag=&Apache::edit::get_new_args
  800: 	    ($token,$parstack,$safeeval,keys(%key_defaults));
  801: 	if ($constructtag) {
  802: 	    $result = &Apache::edit::rebuild_tag($token);
  803: 	}
  804:     }
  805:     return $result;
  806: }
  807: 
  808: sub end_key {
  809:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  810:     my $result = '';
  811:     if ($target eq 'web' || $target eq 'tex') {
  812:     } elsif ($target eq 'edit') {
  813: 	$result.=&Apache::edit::tag_end($target,$token);
  814:     }
  815:     return $result;
  816: }
  817: 
  818: sub parse_label {
  819:     my ($target,$text) = @_;
  820:     my $parser=HTML::LCParser->new(\$text);
  821:     my $result;
  822:     while (my $token=$parser->get_token) {
  823: 	if ($token->[0] eq 'S') {
  824: 	    if ($token->[1] eq 'sub') {
  825: 		$result .= '_{';
  826: 	    } elsif ($token->[1] eq 'sup') {
  827: 		$result .= '^{';
  828: 	    } else {
  829: 		$result .= $token->[4];
  830: 	    }
  831: 	} elsif ($token->[0] eq 'E') {
  832: 	    if ($token->[1] eq 'sub'
  833: 		|| $token->[1] eq 'sup') {
  834: 		$result .= '}';
  835: 	    } else {
  836: 		$result .= $token->[2];
  837: 	    }
  838: 	} elsif ($token->[0] eq 'T') {
  839: 	    $result .= &replace_entities($target,$token->[1]);
  840: 	}
  841:     }
  842:     return $result;
  843: }
  844: 
  845: #
  846: #  Note that there are severe restrictions on font selection in the
  847: # ps driver now.  later in life Gnuplot is supposed to support
  848: # utf-8 fonts in the posts script driver.  When this happens,
  849: # the tex entries with comments that include the word <FIX>
  850: # should be changed to print the correct glyphs rather than some
  851: # approximation or fallback of what is intended.
  852: 
  853: my %lookup = 
  854:    (  # Greek alphabet:
  855:       
  856:       '(Alpha|#913)'    => {'tex' => '{/Symbol A}', 'web' => "\x{391}"},
  857:       '(Beta|#914)'    => {'tex' => '{/Symbol B}', 'web' => "\x{392}"},
  858:       '(Chi|#935)'     => {'tex' => '{/Symbol C}', 'web' => "\x{3A7}"},
  859:       '(Delta|#916)'   => {'tex' => '{/Symbol D}', 'web' => "\x{394}"},
  860:       '(Epsilon|#917)' => {'tex' => '{/Symbol E}', 'web' => "\x{395}"},
  861:       '(Phi|#934)'     => {'tex' => '{/Symbol F}', 'web' => "\x{3A6}"},
  862:       '(Gamma|#915)'   => {'tex' => '{/Symbol G}', 'web' => "\x{393}"},
  863:       '(Eta|#919)'     => {'tex' => '{/Symbol H}', 'web' => "\x{397}"},
  864:       '(Iota|#921)'    => {'tex' => '{/Symbol I}', 'web' => "\x{399}"},
  865:       '(Kappa|#922)'   => {'tex' => '{/Symbol K}', 'web' => "\x{39A}"},
  866:       '(Lambda|#923)'  => {'tex' => '{/Symbol L}', 'web' => "\x{39B}"},
  867:       '(Mu|#924)'      => {'tex' => '{/Symbol M}', 'web' => "\x{39C}"},
  868:       '(Nu|#925)'      => {'tex' => '{/Symbol N}', 'web' => "\x{39D}"},
  869:       '(Omicron|#927)' => {'tex' => '{/Symbol O}', 'web' => "\x{39F}"},
  870:       '(Pi|#928)'      => {'tex' => '{/Symbol P}', 'web' => "\x{3A0}"},
  871:       '(Theta|#920)'   => {'tex' => '{/Symbol Q}', 'web' => "\x{398}"},
  872:       '(Rho|#929)'     => {'tex' => '{/Symbol R}', 'web' => "\x{3A1}"},
  873:       '(Sigma|#931)'   => {'tex' => '{/Symbol S}', 'web' => "\x{3A3}"},
  874:       '(Tau|#932)'     => {'tex' => '{/Symbol T}', 'web' => "\x{3A4}"},
  875:       '(Upsilon|#933)' => {'tex' => '{/Symbol U}', 'web' => "\x{3A5}"},
  876:       '(Omega|#937)'   => {'tex' => '{/Symbol W}', 'web' => "\x{3A9}"},
  877:       '(Xi|#926)'      => {'tex' => '{/Symbol X}', 'web' => "\x{39E}"},
  878:       '(Psi|#936)'     => {'tex' => '{/Symbol Y}', 'web' => "\x{3A8}"},
  879:       '(Zeta|#918)'    => {'tex' => '{/Symbol Z}', 'web' => "\x{396}"},
  880:       '(alpha|#945)'   => {'tex' => '{/Symbol a}', 'web' => "\x{3B1}"},
  881:       '(beta|#946)'    => {'tex' => '{/Symbol b}', 'web' => "\x{3B2}"},
  882:       '(chi|#967)'     => {'tex' => '{/Symbol c}', 'web' => "\x{3C7}"},
  883:       '(delta|#948)'   => {'tex' => '{/Symbol d}', 'web' => "\x{3B4}"},
  884:       '(epsilon|#949)' => {'tex' => '{/Symbol e}', 'web' => "\x{3B5}"},
  885:       '(phi|#966)'     => {'tex' => '{/Symbol f}', 'web' => "\x{3C6}"},
  886:       '(gamma|#947)'   => {'tex' => '{/Symbol g}', 'web' => "\x{3B3}"},
  887:       '(eta|#951)'     => {'tex' => '{/Symbol h}', 'web' => "\x{3B7}"},
  888:       '(iota|#953)'    => {'tex' => '{/Symbol i}', 'web' => "\x{3B9}"},
  889:       '(kappa|#954)'   => {'tex' => '{/Symbol k}', 'web' => "\x{3BA}"},
  890:       '(lambda|#955)'  => {'tex' => '{/Symbol k}', 'web' => "\x{3BB}"},
  891:       '(mu|#956)'      => {'tex' => '{/Symbol m}', 'web' => "\x{3BC}"},
  892:       '(nu|#957)'      => {'tex' => '{/Symbol n}', 'web' => "\x{3BD}"},
  893:       '(omicron|#959)' => {'tex' => '{/Symbol o}', 'web' => "\x{3BF}"},
  894:       '(pi|#960)'      => {'tex' => '{/Symbol p}', 'web' => "\x{3C0}"},
  895:       '(theta|#952)'   => {'tex' => '{/Symbol q}', 'web' => "\x{3B8}"},
  896:       '(rho|#961)'     => {'tex' => '{/Symbol r}', 'web' => "\x{3C1}"},
  897:       '(sigma|#963)'   => {'tex' => '{/Symbol s}', 'web' => "\x{3C3}"},
  898:       '(tau|#964)'     => {'tex' => '{/Symbol t}', 'web' => "\x{3C4}"},
  899:       '(upsilon|#965)' => {'tex' => '{/Symbol u}', 'web' => "\x{3C5}"},
  900:       '(omega|#969)'   => {'tex' => '{/Symbol w}', 'web' => "\x{3C9}"},
  901:       '(xi|#958)'      => {'tex' => '{/Symbol x}', 'web' => "\x{3BE}"},
  902:       '(psi|#968)'     => {'tex' => '{/Symbol y}', 'web' => "\x{3C8}"},
  903:       '(zeta|#950)'    => {'tex' => '{/Symbol z}', 'web' => "\x{3B6}"},
  904:       '(thetasym|#977)' => {'tex' => '{/Symbol \165}', 'web' => "\x{3d1}"},
  905:       '(upsih|#978)'   => {'tex' => '{/Symbol \241}', 'web' => "\x{3d2}"},
  906:       '(piv|#982)'     => {'tex' => '{/Symbol \166}', 'web' => "\x{3d6}"},
  907: 
  908: 
  909:       # Punctuation:
  910:       
  911:       '(quot|#034)'   => {'tex' =>  '\42',            'web' => '\42'},
  912:       '(amp|#038)'    => {'tex' =>  '\46',            'web' => '\46'},
  913:       '(lt|#060)'     => {'tex' =>  '\74',            'web' => '\74'},
  914:       '(gt|#062)'     => {'tex' =>  '\76',            'web' => '\76'},
  915:       '#131'          => {'tex' =>  '{/Symbol \246}', 'web' => "\x{192}"},
  916:       '#132'          => {'tex' => '{/Text \271}',    'web' => "\x{201e}"},
  917:       '#133'          => {'tex' => '{/Symbol \274}',  'web'=> "\x{2026}"},
  918:       '#134'          => {'tex' => '{/Text \262}',    'web' => "\x{2020}"},
  919:       '#135'          => {'tex' => '{/Text \263}',    'web' => "\x{2021}"},
  920:       '#136'          => {'tex' => '\\\\^',           'web' => '\\\\^'},
  921:       '#137'          => {'tex' => '%o',              'web' => "\x{2030}"}, # Per Mille <FIX>
  922:       '#138'          => {'tex' => 'S',               'web' => "\x{160}"}, # S-Caron <FIX>
  923:       '#139'          => {'tex' => '<',               'web' => '<'},
  924:       '#140'          => {'tex' => 'AE',              'web' => "\x{152}"}, # AE ligature <FIX>
  925:       '#145'          => {'tex' => '\140',            'web' => "\x{2018}"},
  926:       '#146'          => {'tex' => '\47',             'web' => "\x{2019}"},
  927:       '#147'          => {'tex' => '\140\140',        'web' => "\x{201c}"}, # Left " <FIX>
  928:       '#148'          => {'tex' => '\47\47',          'web' => '\\"'},      # Right " <FIX>
  929:       '#149'          => {'tex' => '{/Symbol \267}',  'web' => "\x{2022}"},
  930:       '#150'          => {'tex' => '{/Text \55}',     'web' => "\x{2013}"},  # en dash
  931:       '#151'          => {'tex' => '{/Symbol \55}',   'web' => "\x{2014}"},  # em dash
  932:       '#152'          => {'tex' => '\\\\~',           'web' => '\\\\~'},
  933:       '#153'          => {'tex' => '{/Symbol \324}',  'web' => "\x{2122}"}, # trademark
  934: 
  935:       # Accented letters, and other furreign language glyphs.
  936: 
  937:       '#154'          => {'tex' => 's',               'web' => "\x{161}"}, # small s-caron no ps.
  938:       '#155'          => {'tex' => '>',               'web' => '\76'},     # >
  939:       '#156'          => {'tex' => '{/Text \366}',    'web' => "\x{153}"}, # oe ligature.<FIX>
  940:       '#159',         => {'tex' => 'Y',               'web' => "\x{178}"}, # Y-umlaut - can't print <FIX>
  941:       '(nbsp|#160)'   => {'tex' => ' ',               'web' => ' '},       # non breaking space.
  942:       '(iexcl|#161)'  => {'tex' => '{/Text \241}',    'web' => "\x{a1}"},  # inverted !
  943:       '(cent|#162)'   => {'tex' => '{/Text \242}',    'web' => "\x{a2}"},  # Cent currency.
  944:       '(pound|#163)'  => {'tex' => '{/Text \243}',    'web' => "\x{a3}"},  # GB Pound currency.
  945:       '(curren|#164)' => {'tex' => '{/ZapfDingbats \161}','web' => "\x{a4}"},  # Generic currency symb. <FIX>
  946:       '(yen|#165)'    => {'tex' => '{/Text \245}',    'web' => "\x{a5}"},  # Yen currency.
  947:       '(brvbar|#166)' => {'tex' => '{/Symbol \174}',  'web' => "\x{a6}"},  # Broken vert bar no print.
  948:       '(sect|#167)'   => {'tex' => '{\247}',          'web' => "\x{a7}"},  # Section symbol.
  949:       '(uml|#168)'    => {'tex' => '{\250}',          'web' => "\x{a8}"},  # 'naked' umlaut.
  950:       '(copy|#169)'   => {'tex' => '{/Symbol \343}',  'web' => "\x{a9}"},  # Copyright symbol.
  951:       '(ordf|#170)'   => {'tex' => '{/Text \343}',    'web' => "\x{aa}"},  # Feminine ordinal.
  952:       '(laquo|#171)'  => {'tex' => '{/Text \253}',    'web' => "\x{ab}"},  # << quotes.
  953:       '(not|#172)'    => {'tex' => '\254',            'web' => "\x{ac}"},  # Logical not.
  954:       '(shy|#173)'    => {'tex' => '\255',               'web' => "\x{ad}"},  # soft hyphen.
  955:       '(reg|#174)'    => {'tex' => '{/Symbol \342}',  'web' => "\x{ae}"},  # Registered tm.
  956:       '(macr|#175)'   => {'tex' => '^{\255}',            'web' => "\x{af}"},  # 'naked' macron (overbar).
  957:       '(deg|#176)'    => {'tex' => '{/Text \260}',    'web' => "\x{b0}"},  # Degree symbo..`
  958:       '(plusmn|#177)' => {'tex' => '{/Symbol \261}',  'web' => "\x{b1}"},  # +/- symbol.
  959:       '(sup2|#178)'   => {'tex' => '^2',              'web' => "\x{b2}"},  # Superscript 2.
  960:       '(sup3|#179)'   => {'tex' => '^3',              'web' => "\x{b3}"},  # Superscript 3.
  961:       '(acute|#180)'  => {'tex' => '{/Text \222}',    'web' => "\x{b4}"},  # 'naked' acute accent.
  962:       '(micro|#181)'  => {'tex' => '{/Symbol \155}',  'web' => "\x{b5}"},  # Micro (small mu).
  963:       '(para|#182)'   => {'tex' => '{/Text \266}',    'web' => "\x{b6}"},  # Paragraph symbol.
  964:       '(middot|#183)' => {'tex' => '\267',            'web' => "\x{b7}"},  # middle dot
  965:       '(cedil|#184)'  => {'tex' => '\233',            'web' => "\x{b8}"},  # 'naked' cedilla.
  966:       '(sup1|#185)'   => {'tex' => '^1',              'web' => "\x{b9}"},  # superscript 1.
  967:       '(ordm|#186)'   => {'tex' => '{\260}',          'web' => "\x{ba}"},  # masculine ordinal.
  968:       '(raquo|#187)', => {'tex' => '\273',            'web' => "\x{bb}"},  # Right angle quotes.
  969:       '(frac14|#188)' => {'tex' => '\274',            'web' => "\x{bc}"},  # 1/4.
  970:       '(frac12|#189)' => {'tex' => '\275',            'web' => "\x{bd}"},  # 1/2.
  971:       '(frac34|#190)' => {'tex' => '\276',            'web' => "\x{be}"},  # 3/4
  972:       '(iquest|#191)' => {'tex' => '{/Text \277}',    'web' => "\x{bf}"},  # Inverted ?
  973:       '(Agrave|#192)' => {'tex' => '\300',            'web' => "\x{c0}"},  # A Grave.
  974:       '(Aacute|#193)' => {'tex' => '\301',            'web' => "\x{c1}"},  # A Acute.
  975:       '(Acirc|#194)'  => {'tex' => '\302',            'web' => "\x{c2}"},  # A Circumflex.
  976:       '(Atilde|#195)' => {'tex' => '\303',            'web' => "\x{c3}"},  # A tilde.
  977:       '(Auml|#196)'   => {'tex' => '\304',            'web' => "\x{c4}"},  # A umlaut.
  978:       '(Aring|#197)'  => {'tex' => '\305',            'web' => "\x{c5}"},  # A ring.
  979:       '(AElig|#198)'  => {'tex' => '\306',            'web' => "\x{c6}"},  # AE ligature.
  980:       '(Ccedil|#199)' => {'tex' => '\307',            'web' => "\x{c7}"},  # C cedilla
  981:       '(Egrave|#200)' => {'tex' => '\310',            'web' => "\x{c8}"},  # E Accent grave.
  982:       '(Eacute|#201)' => {'tex' => '\311',            'web' => "\x{c9}"},  # E acute accent.
  983:       '(Ecirc|#202)'  => {'tex' => '\312',            'web' => "\x{ca}"},  # E Circumflex.
  984:       '(Euml|#203)'   => {'tex' => '\313',            'web' => "\x{cb}"},  # E umlaut.
  985:       '(Igrave|#204)' => {'tex' => '\314',            'web' => "\x{cc}"},  # I grave accent.
  986:       '(Iacute|#205)' => {'tex' => '\315',            'web' => "\x{cd}"},  # I acute accent.
  987:       '(Icirc|#206)'  => {'tex' => '\316',            'web' => "\x{ce}"},  # I circumflex.
  988:       '(Iuml|#207)'   => {'tex' => '\317',            'web' => "\x{cf}"},  # I umlaut.
  989:       '(ETH|#208)'    => {'tex' => '\320',            'web' => "\x{d0}"},  # Icelandic Cap eth.
  990:       '(Ntilde|#209)' => {'tex' => '\321',            'web' => "\x{d1}"},  # Ntilde (enyan).
  991:       '(Ograve|#210)' => {'tex' => '\322',            'web' => "\x{d2}"},  # O accent grave.
  992:       '(Oacute|#211)' => {'tex' => '\323',            'web' => "\x{d3}"},  # O accent acute.
  993:       '(Ocirc|#212)'  => {'tex' => '\324',            'web' => "\x{d4}"},  # O circumflex.
  994:       '(Otilde|#213)' => {'tex' => '\325',            'web' => "\x{d5}"},  # O tilde.
  995:       '(Ouml|#214)'   => {'tex' => '\326',            'web' => "\x{d6}"},  # O umlaut.
  996:       '(times|#215)'  => {'tex' => '\327',            'web' => "\x{d7}"},  # Times symbol.
  997:       '(Oslash|#216)' => {'tex' => '\330',            'web' => "\x{d8}"},  # O slash.
  998:       '(Ugrave|#217)' => {'tex' => '\331',            'web' => "\x{d9}"},  # U accent grave.
  999:       '(Uacute|#218)' => {'tex' => '\332',            'web' => "\x{da}"},  # U accent acute.
 1000:       '(Ucirc|#219)'  => {'tex' => '\333',            'web' => "\x{db}"},  # U circumflex.
 1001:       '(Uuml|#220)'   => {'tex' => '\334',            'web' => "\x{dc}"},  # U umlaut.
 1002:       '(Yacute|#221)' => {'tex' => '\335',            'web' => "\x{dd}"},  # Y accent acute.
 1003:       '(THORN|#222)'  => {'tex' => '\336',            'web' => "\x{de}"},  # Icelandic thorn.
 1004:       '(szlig|#223)'  => {'tex' => '\337',            'web' => "\x{df}"},  # German sharfes s.
 1005:       '(agrave|#224)' => {'tex' => '\340',            'web' => "\x{e0}"},  # a accent grave.
 1006:       '(aacute|#225)' => {'tex' => '\341',            'web' => "\x{e1}"},  # a grave.
 1007:       '(acirc|#226)'  => {'tex' => '\342',            'web' => "\x{e2}"},  # a circumflex.
 1008:       '(atilde|#227)' => {'tex' => '\343',            'web' => "\x{e3}"},  # a tilde.
 1009:       '(auml|#228)'   => {'tex' => '\344',            'web' => "\x{e4}"},  # a umlaut
 1010:       '(aring|#229)'  => {'tex' => '\345',            'web' => "\x{e5}"},  # a ring on top.
 1011:       '(aelig|#230)'  => {'tex' => '\346',            'web' => "\x{e6}"},  # ae ligature.
 1012:       '(ccedil|#231)' => {'tex' => '\347',            'web' => "\x{e7}"},  # C cedilla
 1013:       '(egrave|#232)' => {'tex' => '\350',            'web' => "\x{e8}"},  # e accent grave.
 1014:       '(eacute|#233)' => {'tex' => '\351',            'web' => "\x{e9}"},  # e accent acute.
 1015:       '(ecirc|#234)'  => {'tex' => '\352',            'web' => "\x{ea}" }, # e circumflex.
 1016:       '(euml|#235)'   => {'tex' => '\353',            'web' => "\x{eb}"},  # e umlaut.
 1017:       '(igrave|#236)' => {'tex' => '\354',            'web' => "\x{ec}"},  # i grave.
 1018:       '(iacute|#237)' => {'tex' => '\355',            'web' => "\x{ed}"},  # i acute.
 1019:       '(icirc|#238)'  => {'tex' => '\356',            'web' => "\x{ee}"},  # i circumflex.
 1020:       '(iuml|#239)'   => {'tex' => '\357',            'web' => "\x{ef}"},  # i umlaut.
 1021:       '(eth|#240)'    => {'tex' => '\360',            'web' => "\x{f0}"},  # Icelandic eth.
 1022:       '(ntilde|#241)' => {'tex' => '\361',            'web' => "\x{f1}"},  # n tilde.
 1023:       '(ograve|#242)' => {'tex' => '\362',            'web' => "\x{f2}"},  # o grave.
 1024:       '(oacute|#243)' => {'tex' => '\363',            'web' => "\x{f3}"},  # o acute.
 1025:       '(ocirc|#244)'  => {'tex' => '\364',            'web' => "\x{f4}"},  # o circumflex.
 1026:       '(otilde|#245)' => {'tex' => '\365',            'web' => "\x{f5}"},  # o tilde.
 1027:       '(ouml|#246)'   => {'tex' => '\366',            'web' => "\x{f6}"},  # o umlaut.
 1028:       '(divide|#247)' => {'tex' => '\367',            'web' => "\x{f7}"},  # division symbol
 1029:       '(oslash|#248)' => {'tex' => '\370',            'web' => "\x{f8}"},  # o slashed.
 1030:       '(ugrave|#249)' => {'tex' => '\371',            'web' => "\x{f9}"},  # u accent grave.
 1031:       '(uacute|#250)' => {'tex' => '\372',            'web' => "\x{fa}"},  # u acute.
 1032:       '(ucirc|#251)'  => {'tex' => '\373',            'web' => "\x{fb}"},  # u circumflex.
 1033:       '(uuml|#252)'   => {'tex' => '\374',            'web' => "\x{fc}"},  # u umlaut.
 1034:       '(yacute|#253)' => {'tex' => '\375',            'web' => "\x{fd}"},  # y acute accent.
 1035:       '(thorn|#254)'  => {'tex' => '\376',            'web' => "\x{fe}"},  # small thorn (icelandic).
 1036:       '(yuml|#255)'   => {'tex' => '\377',            'web' => "\x{ff}"},  # y umlaut.
 1037:       
 1038:       # Latin extended A entities:
 1039: 
 1040:       '(OElig|#338)'  => {'tex' => '{/Text \326}',   'web' => "\x{152}"},  # OE ligature.
 1041:       '(oelig|#339)'  => {'tex' => '{/Text \366}',   'web' => "\x{153}"},  # oe ligature.
 1042:       '(Scaron|#352)' => {'tex' => 'S',              'web' => "\x{160}"},  # S caron no printable.
 1043:       '(scaron|#353)' => {'tex' => 's',              'web' => "\x{161}"},  # s caron no printable.
 1044:       '(Yuml|#376)'   => {'tex' => 'Y',              'web' => "\x{178}"},  # Y umlaut - no printable.
 1045: 
 1046:       # Latin extended B.
 1047: 
 1048:       '(fnof|#402)'  => {'tex' =>'{/Symbol \246}',    'web' => "\x{192}"},  # f with little hook.
 1049: 
 1050:       # Standalone accents:
 1051: 
 1052:       '(circ|#710)'  => {'tex' => '^',               'web' => '^'},        # circumflex.
 1053:       '(tilde|#732)' => {'tex' => '~',               'web' => '~'},        # tilde.
 1054: 
 1055:       # General punctuation.  We're not able to make a distinction between
 1056:       # the various length spacings in the print version. (e.g. en/em/thin).
 1057:       # the various joiners will be empty strings in the print version too.
 1058: 
 1059: 
 1060:       '(ensp|#8194)'   => {'tex' => ' ',              'web' => "\x{2002}"}, # en space.
 1061:       '(emsp|#8195)'   => {'tex' => ' ',              'web' => "\x{2003}"}, # em space.
 1062:       '(thinsp|#8201)' => {'tex' => ' ',              'web' => "\x{2009}"}, # thin space.
 1063:       '(zwnj|#8204)'   => {'tex' => ' ',               'web' => "\x{200c}"}, # Zero width non joiner.
 1064:       '(zwj|#8205)'    => {'tex' => ' ',               'web' => "\x{200d}"}, # Zero width joiner.
 1065:       '(lrm|#8206)'    => {'tex' => ' ',               'web' => "\x{200e}"}, # Left to right mark
 1066:       '(rlm|#8207)'    => {'tex' => ' ',               'web' => "\x{200f}"}, # right to left mark.
 1067:       '(ndash|#8211)'  => {'tex' => '{/Text \55}',    'web' => "\x{2013}"}, # en dash.
 1068:       '(mdash|#8212)'  => {'tex' => '{/Symbol \55}',  'web' => "\x{2014}"}, # em dash.
 1069:       '(lsquo|#8216)'  => {'tex' => '{/Text \140}',   'web' => "\x{2018}"}, # Left single quote.
 1070:       '(rsquo|#8217)'  => {'tex' => '\47',            'web' => "\x{2019}"}, # Right single quote.
 1071:       '(sbquo|#8218)'  => {'tex' => '\54',             'web' => "\x{201a}"}, # Single low-9 quote.
 1072:       '(ldquo|#8220)'  => {'tex' => '\42',   'web' => "\x{201c}"}, # Left double quote.
 1073:       '(rdquo|#8221)'  => {'tex' => '\42',   'web' => "\x{201d}"}, # Right double quote.
 1074:       '(bdquo|#8222)'  => {'tex' => ',',              'web' => "\x{201e}"}, # Double low-9 quote.
 1075:       '(dagger|#8224)' => {'tex' => '+',   'web' => "\x{2020}"}, # Is this a dagger I see before me now?
 1076:       '(Dagger|#8225)' => {'tex' => '\261',   'web' => "\x{2021}"}, # it's handle pointing towards my heart?
 1077:       '(bull|#8226)'   => {'tex' => '\267',           'web' => "\x{2022}"}, # Bullet.
 1078:       '(hellep|#8230)' => {'tex' => '{/Symbol \274}',   'web' => "\x{2026}"}, # Ellipses.
 1079:       '(permil|#8240)' => {'tex' => '%_o',            'web' => "\x{2031}"}, # Per mille.
 1080:       '(prime|#8242)'  => {'tex' => '\264',           'web' => "\x{2032}"}, # Prime.
 1081:       '(Prime|#8243)'  => {'tex' => '{/Symbol \262}', 'web' => "\x{2033}"}, # double prime.
 1082:       '(lsaquo|#8249)' => {'tex' => '<',              'web' => "\x{2039}"}, # < quote.
 1083:       '(rsaquo|#8250)' => {'tex' => '\74',              'web' => "\x{203a}"}, # > quote.
 1084:       '(oline|#8254)'  => {'tex' => '{/Symbol \140}', 'web' => "\x{203e}"}, # Overline.
 1085:       '(frasl|#8260)'  => {'tex' => '/',              'web' => "\x{2044}"}, # Fraction slash.
 1086:       '(euro|#8364)'   => {'tex' => '{/Symbol \240}', 'web' => "\x{20ac}"}, # Euro currency.
 1087:       
 1088:       # Letter like symbols.
 1089: 
 1090:       '(weierp|#8472)'  => {'tex' => '{/Symbol \303}', 'web' => "\x{2118}"}, # Power set symbol
 1091:       '(image|#8465)'   => {'tex' => '{/Symbol \301}', 'web' => "\x{2111}"}, # Imaginary part
 1092:       '(real|#8476)'    => {'tex' => '{/Symbol \302}', 'web' => "\x{211c}"}, # Real part.
 1093:       '(trade|#8482)'   => {'tex' => '{/Symbol \344}', 'web' => "\x{2122}"}, # trademark symbol.
 1094:       '(alefsym|#8501)' => {'tex' => '{/Symbol \300}', 'web' => "\x{2135}"}, # Hebrew alef.
 1095: 
 1096:       # Arrows  of various types and directions.
 1097:       '(larr|#8592)'    => {'tex' => '{/Symbol \254}', 'web' => "\x{2190}"}, # <--
 1098:       '(uarr|#8593)'    => {'tex' => '{/Symbol \255}', 'web' => "\x{2191}"}, # up arrow.
 1099:       '(rarr|#8594)'    => {'tex' => '{/Symbol \256}', 'web' => "\x{2192}"}, # -->
 1100:       '(darr|#8595)'    => {'tex' => '{/Symbol \257}', 'web' => "\x{2193}"}, # down arrow.
 1101:       '(harr|#8596)'    => {'tex' => '{/Symbol \253}', 'web' => "\x{2194}"}, # <-->
 1102:       '(crarr|#8629)'   => {'tex' => '{/Symbol \277}', 'web' => "\x{21b5}"}, # corner arrow down and right.
 1103:       '(lArr|#8656)'    => {'tex' => '{/Symbol \334}', 'web' => "\x{21d0}"}, # <==
 1104:       '(uArr|#8657)'    => {'tex' => '{/Symbol \335}', 'web' => "\x{21d1}"}, # Up double arrow.
 1105:       '(rArr|#8658)'    => {'tex' => '{/Symbol \336}', 'web' => "\x{21d2}"}, # ==>
 1106:       '(dArr|#8659)'    => {'tex' => '{/Symbol \337}', 'web' => "\x{21d3}"}, # Down double arrow.
 1107:       '(hArr|#8660)'    => {'tex' => '{/Symbol \333}', 'web' => "\x{21d4}"}, # <==>
 1108: 
 1109:       # Mathematical operators. For some of these we do the best we can in printing.
 1110: 
 1111:       '(forall|#8704)'  => {'tex' => '{/Symbol \42}',   'web' => "\x{2200}"}, # For all.
 1112:       '(part|#8706)'    => {'tex' => '{/Symbol d}',     'web' => "\x{2202}"}, # partial derivative
 1113:       '(exist|#8707)'   => {'tex' => '{/Symbol \44}',   'web' => "\x{2203}"}, # There exists.
 1114:       '(empty|#8709)'   => {'tex' => '{/Symbol \306}',  'web' => "\x{2205}"}, # Null set.
 1115:       '(nabla|#8711)'   => {'tex' => '{/Symbol \321}',  'web' => "\x{2207}"}, # Gradient e.g.
 1116:       '(isin|#8712)'    => {'tex' => '{/Symbol \316}',  'web' => "\x{2208}"}, # Element of the set.
 1117:       '(notin|#8713)'   => {'tex' => '{/Symbol \317}',  'web' => "\x{2209}"}, # Not an element of
 1118:       '(ni|#8715)'      => {'tex' => '{/Symbol \47}',   'web' => "\x{220b}"}, # Contains as a member
 1119:       '(prod|#8719)'    => {'tex' => '{/Symbol \325}',  'web' => "\x{220f}"}, # Product 
 1120:       '(sum|#8721)'     => {'tex' => '{/Symbol \345}',  'web' => "\x{2211}"}, # Sum of.
 1121:       '(minus|#8722)'   => {'tex' => '{/Symbol \55}',   'web' => "\x{2212}"}, # - sign.
 1122:       '(lowast|#8727)'  => {'tex' => '*',               'web' => "\x{2217}"}, # * 
 1123:       '(radic|#8730)'   => {'tex' => '{/Symbol \326}',  'web' => "\x{221a}"}, # Square root. 
 1124:       '(prop|#8733)'    => {'tex' => '{/Symbol \265}',  'web' => "\x{221d}"}, # Proportional to.
 1125:       '(infin|#8734)'   => {'tex' => '{/Symbol \245}',  'web' => "\x{221e}"}, # Infinity.
 1126:       '(ang|#8736)'     => {'tex' => '{/Symbol \320}',  'web' => "\x{2220}"}, # Angle .
 1127:       '(and|#8743)'     => {'tex' => '{/Symbol \331}',  'web' => "\x{2227}"}, # Logical and.
 1128:       '(or|#8744)'      => {'tex' => '{/Symbol \332}',  'web' => "\x{2228}"}, # Logical or.
 1129:       '(cap|#8745)'     => {'tex' => '{/Symbol \307}',  'web' => "\x{2229}"}, # Set intersection.
 1130:       '(cup|#8746)'     => {'tex' => '{/Symbol \310}',  'web' => "\x{222a}"}, # Set union.
 1131:       '(int|8747)'      => {'tex' => '{/Symbol \362}',  'web' => "\x{222b}"}, # Integral.
 1132: 
 1133:       # Some gnuplot guru will have to explain to me why the next three
 1134:       # require the extra slashes... else they print very funkily.
 1135: 
 1136:       '(there4|#8756)'  => {'tex' => '{/Symbol \\\134}',  'web' => "\x{2234}"}, # Therefore triple dots.
 1137:       '(sim|#8764)'     => {'tex' => '\\\176',               'web' => "\x{223c}"}, # Simlar to.
 1138:       '(cong|#8773)'    => {'tex' => '{/Symbol \\\100}','web' => "\x{2245}"}, # Congruent to/with.
 1139: 
 1140:       '(asymp|#8776)'   => {'tex' => '{/Symbol \273}',  'web' => "\x{2248}"}, # Asymptotic to.
 1141:       '(ne|#8800)'      => {'tex' => '{/Symbol \271}',  'web' => "\x{2260}"}, # not equal to.
 1142:       '(equiv|#8801)'   => {'tex' => '{/Symbol \272}',  'web' => "\x{2261}"}, # Equivalent to.
 1143:       '(le|8804)'       => {'tex' => '{/Symbol \243}',  'web' => "\x{2264}"}, # Less than or equal to.
 1144:       '(ge|8805)'       => {'tex' => '{/Symbol \263}',  'web' => "\x{2265}"}, # Greater than or equal to
 1145:       '(sub|8834)'      => {'tex' => '{/Symbol \314}',  'web' => "\x{2282}"}, # Subset of.
 1146:       '(sup|8835)'      => {'tex' => '{/Symbol \311}',  'web' => "\x{2283}"}, # Super set of.
 1147:       '(nsub|8836)'     => {'tex' => '{/Symbol \313}',  'web' => "\x{2284}"}, # not subset of.
 1148:       '(sube|8838)'     => {'tex' => '{/Symbol \315}',  'web' => "\x{2286}"}, # Subset or equal.
 1149:       '(supe|8839)'     => {'tex' => '{/Symbol \312}',  'web' => "\x{2287}"}, # Superset or equal
 1150:       '(oplus|8853)'    => {'tex' => '{/Symbol \305}',  'web' => "\x{2295}"}, # O with plus inside
 1151:       '(otimes|8855)'   => {'tex' => '{/Symbol \304}',  'web' => "\x{2297}"}, # O with times.
 1152:       '(perp|8869)'     => {'tex' => '{/Symbol \136}',  'web' => "\x{22a5}"}, # Perpendicular.
 1153:       '(sdot|8901)'     => {'tex' => '{/Symbol \227}',  'web' => "\x{22c5}"}, # Dot operator.
 1154: 
 1155:       # Misc. technical symbols:
 1156: 
 1157:       '(lceil|8698)'    => {'tex' => '{/Symbol \351}',  'web' => "\x{2308}"}, # Left ceiling.
 1158:       '(rceil|8969)'    => {'tex' => '{/Symbol \371}',  'web' => "\x{2309}"}, # Right ceiling.
 1159:       '(lfloor|8970)'   => {'tex' => '{/Symbol \353}',  'web' => "\x{230a}"}, # Left floor.
 1160:       '(rfloor|8971)'   => {'tex' => '{/Symbol \373}',  'web' => "\x{230b}"}, # Right floor.
 1161: 
 1162:       # The gnuplot png font evidently does not have the big angle brackets at
 1163:       # positions 0x2329, 0x232a so use ordinary brackets.
 1164: 
 1165:       '(lang|9001)'     => {'tex' => '{/Symbol \341}',  'web' => '<'}, # Left angle bracket.
 1166:       '(rang|9002)'     => {'tex' => '{/Symbol \361}',  'web' => '>'}, # Right angle bracket.
 1167: 
 1168:       # Gemoetric shapes.
 1169: 
 1170:       '(loz|9674)'      => {'tex' => '{/Symbol \340}',  'web' => "\x{25ca}"}, # Lozenge.
 1171: 
 1172:       # Misc. symbols
 1173: 
 1174:       '(spades|9824)'   => {'tex' => '{/Symbol \252}', 'web' => "\x{2660}"}, 
 1175:       '(clubs|9827)'    => {'tex' => '{/Symbol \247}', 'web' => "\x{2663}"}, 
 1176:       '(hearts|9829)'   => {'tex' => '{/Symbol \251}', 'web' => "\x{2665}"}, 
 1177:       '(diams|9830)'    => {'tex' => '{/Symbol \250}', 'web' => "\x{2666}"}
 1178: 
 1179:     );
 1180: 
 1181: 
 1182: sub replace_entities {
 1183:     my ($target,$text) = @_;
 1184:     $text =~ s{([_^~\{\}]|\\\\)}{\\\\$1}g;
 1185:     while (my ($re, $replace) = each(%lookup)) {
 1186: 	my $repl = $replace->{$target};
 1187: 	$text =~ s/&$re;/$replace->{$target}/g;
 1188:     }
 1189:     $text =~ s{(&)}{\\\\$1}g;
 1190:     return $text;
 1191: }
 1192: 
 1193: ##------------------------------------------------------------------- title
 1194: sub start_title {
 1195:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1196:     my $result='';
 1197:     if ($target eq 'web' || $target eq 'tex') {
 1198: 	$title = &Apache::lonxml::get_all_text("/title",$parser,$style);
 1199: 	$title=&Apache::run::evaluate($title,$safeeval,$$parstack[-1]);
 1200: 	$title =~ s/\n/ /g;
 1201: 	if (length($title) > $max_str_len) {
 1202: 	    $title = substr($title,0,$max_str_len);
 1203: 	}
 1204: 	$title = &parse_label($target,$title);
 1205:     } elsif ($target eq 'edit') {
 1206: 	$result.=&Apache::edit::tag_start($target,$token,'Plot Title');
 1207: 	my $text=&Apache::lonxml::get_all_text("/title",$parser,$style);
 1208: 	$result.=&Apache::edit::editline('',$text,'',60);
 1209:     } elsif ($target eq 'modified') {
 1210: 	$result.=&Apache::edit::rebuild_tag($token);
 1211: 	$result.=&Apache::edit::modifiedfield("/title",$parser);
 1212:     }
 1213:     return $result;
 1214: }
 1215: 
 1216: sub end_title {
 1217:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1218:     my $result = '';
 1219:     if ($target eq 'web' || $target eq 'tex') {
 1220:     } elsif ($target eq 'edit') {
 1221: 	$result.=&Apache::edit::tag_end($target,$token);
 1222:     }
 1223:     return $result;
 1224: }
 1225: ##------------------------------------------------------------------- xlabel
 1226: sub start_xlabel {
 1227:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1228:     my $result='';
 1229:     if ($target eq 'web' || $target eq 'tex') {
 1230: 	$xlabel = &Apache::lonxml::get_all_text("/xlabel",$parser,$style);
 1231: 	$xlabel=&Apache::run::evaluate($xlabel,$safeeval,$$parstack[-1]);
 1232: 	$xlabel =~ s/\n/ /g;
 1233: 	if (length($xlabel) > $max_str_len) {
 1234: 	    $xlabel = substr($xlabel,0,$max_str_len);
 1235: 	}
 1236: 	$xlabel = &parse_label($target,$xlabel);
 1237:     } elsif ($target eq 'edit') {
 1238: 	$result.=&Apache::edit::tag_start($target,$token,'Plot Xlabel');
 1239: 	my $text=&Apache::lonxml::get_all_text("/xlabel",$parser,$style);
 1240: 	$result.=&Apache::edit::editline('',$text,'',60);
 1241:     } elsif ($target eq 'modified') {
 1242: 	$result.=&Apache::edit::rebuild_tag($token);	
 1243: 	$result.=&Apache::edit::modifiedfield("/xlabel",$parser);
 1244:     }
 1245:     return $result;
 1246: }
 1247: 
 1248: sub end_xlabel {
 1249:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1250:     my $result = '';
 1251:     if ($target eq 'web' || $target eq 'tex') {
 1252:     } elsif ($target eq 'edit') {
 1253: 	$result.=&Apache::edit::tag_end($target,$token);
 1254:     }
 1255:     return $result;
 1256: }
 1257: 
 1258: ##------------------------------------------------------------------- ylabel
 1259: sub start_ylabel {
 1260:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1261:     my $result='';
 1262:     if ($target eq 'web' || $target eq 'tex') {
 1263: 	$ylabel = &Apache::lonxml::get_all_text("/ylabel",$parser,$style);
 1264: 	$ylabel = &Apache::run::evaluate($ylabel,$safeeval,$$parstack[-1]);
 1265: 	$ylabel =~ s/\n/ /g;
 1266: 	if (length($ylabel) > $max_str_len) {
 1267: 	    $ylabel = substr($ylabel,0,$max_str_len);
 1268: 	}
 1269: 	$ylabel = &parse_label($target,$ylabel);
 1270:     } elsif ($target eq 'edit') {
 1271: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Ylabel');
 1272: 	my $text = &Apache::lonxml::get_all_text("/ylabel",$parser,$style);
 1273: 	$result .= &Apache::edit::editline('',$text,'',60);
 1274:     } elsif ($target eq 'modified') {
 1275: 	$result.=&Apache::edit::rebuild_tag($token);
 1276: 	$result.=&Apache::edit::modifiedfield("/ylabel",$parser);
 1277:     }
 1278:     return $result;
 1279: }
 1280: 
 1281: sub end_ylabel {
 1282:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1283:     my $result = '';
 1284:     if ($target eq 'web' || $target eq 'tex') {
 1285:     } elsif ($target eq 'edit') {
 1286: 	$result.=&Apache::edit::tag_end($target,$token);
 1287:     }
 1288:     return $result;
 1289: }
 1290: 
 1291: ##------------------------------------------------------------------- label
 1292: sub start_label {
 1293:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1294:     my $result='';
 1295:     if ($target eq 'web' || $target eq 'tex') {
 1296: 	my %label;
 1297: 	&get_attributes(\%label,\%label_defaults,$parstack,$safeeval,
 1298: 		    $tagstack->[-1]);
 1299: 	my $text = &Apache::lonxml::get_all_text("/label",$parser,$style);
 1300: 	$text = &Apache::run::evaluate($text,$safeeval,$$parstack[-1]);
 1301: 	$text =~ s/\n/ /g;
 1302: 	$text = substr($text,0,$max_str_len) if (length($text) > $max_str_len);
 1303: 	$label{'text'} = &parse_label($target,$text);
 1304: 	push(@labels,\%label);
 1305:     } elsif ($target eq 'edit') {
 1306: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Label');
 1307: 	$result .= &edit_attributes($target,$token,\%label_defaults);
 1308: 	my $text = &Apache::lonxml::get_all_text("/label",$parser,$style);
 1309: 	$result .= &Apache::edit::end_row().
 1310: 	    &Apache::edit::start_spanning_row().
 1311: 	    &Apache::edit::editline('',$text,'',60);
 1312:     } elsif ($target eq 'modified') {
 1313: 	&Apache::edit::get_new_args
 1314: 	    ($token,$parstack,$safeeval,keys(%label_defaults));
 1315: 	$result.=&Apache::edit::rebuild_tag($token);
 1316: 	$result.=&Apache::edit::modifiedfield("/label",$parser);
 1317:     }
 1318:     return $result;
 1319: }
 1320: 
 1321: sub end_label {
 1322:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1323:     my $result = '';
 1324:     if ($target eq 'web' || $target eq 'tex') {
 1325:     } elsif ($target eq 'edit') {
 1326: 	$result.=&Apache::edit::tag_end($target,$token);
 1327:     }
 1328:     return $result;
 1329: }
 1330: 
 1331: ##------------------------------------------------------------------- curve
 1332: sub start_curve {
 1333:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1334:     my $result='';
 1335:     &Apache::lonxml::register('Apache::lonplot',('function','data'));
 1336:     push (@Apache::lonxml::namespace,'curve');
 1337:     if ($target eq 'web' || $target eq 'tex') {
 1338: 	my %curve;
 1339: 	&get_attributes(\%curve,\%curve_defaults,$parstack,$safeeval,
 1340: 		    $tagstack->[-1]);
 1341: 	push (@curves,\%curve);
 1342:     } elsif ($target eq 'edit') {
 1343: 	$result .= &Apache::edit::tag_start($target,$token,'Curve');
 1344: 	$result .= &edit_attributes($target,$token,\%curve_defaults,
 1345:                                     \@curve_edit_order)
 1346: 	    .&Apache::edit::end_row()
 1347: 	    .&Apache::edit::start_spanning_row();
 1348: 
 1349:     } elsif ($target eq 'modified') {
 1350: 	my $constructtag=&Apache::edit::get_new_args
 1351: 	    ($token,$parstack,$safeeval,keys(%curve_defaults));
 1352: 	if ($constructtag) {
 1353: 	    $result = &Apache::edit::rebuild_tag($token);
 1354: 	}
 1355:     }
 1356:     return $result;
 1357: }
 1358: 
 1359: sub end_curve {
 1360:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1361:     my $result = '';
 1362:     pop @Apache::lonxml::namespace;
 1363:     &Apache::lonxml::deregister('Apache::lonplot',('function','data'));
 1364:     if ($target eq 'web' || $target eq 'tex') {
 1365:     } elsif ($target eq 'edit') {
 1366: 	$result.=&Apache::edit::tag_end($target,$token);
 1367:     }
 1368:     return $result;
 1369: }
 1370: 
 1371: ##------------------------------------------------------------ curve function
 1372: sub start_function {
 1373:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1374:     my $result='';
 1375:     if ($target eq 'web' || $target eq 'tex') {
 1376: 	if (exists($curves[-1]->{'data'})) {
 1377: 	    &Apache::lonxml::warning
 1378:                 ('Use of the <b>curve function</b> tag precludes use of '.
 1379:                  ' the <b>curve data</b> tag.  '.
 1380:                  'The curve data tag will be omitted in favor of the '.
 1381:                  'curve function declaration.');
 1382: 	    delete $curves[-1]->{'data'} ;
 1383: 	}
 1384:         my $function = &Apache::lonxml::get_all_text("/function",$parser,
 1385: 						     $style);
 1386: 	$function = &Apache::run::evaluate($function,$safeeval,$$parstack[-1]);
 1387:         $function=~s/\^/\*\*/gs;
 1388: 	$curves[-1]->{'function'} = $function; 
 1389:     } elsif ($target eq 'edit') {
 1390: 	$result .= &Apache::edit::tag_start($target,$token,'Gnuplot compatible curve function');
 1391: 	my $text = &Apache::lonxml::get_all_text("/function",$parser,$style);
 1392: 	$result .= &Apache::edit::editline('',$text,'',60);
 1393:     } elsif ($target eq 'modified') {
 1394: 	$result.=&Apache::edit::rebuild_tag($token);
 1395: 	$result.=&Apache::edit::modifiedfield("/function",$parser);
 1396:     }
 1397:     return $result;
 1398: }
 1399: 
 1400: sub end_function {
 1401:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1402:     my $result = '';
 1403:     if ($target eq 'web' || $target eq 'tex') {
 1404:     } elsif ($target eq 'edit') {
 1405: 	$result .= &Apache::edit::end_table();
 1406:     }
 1407:     return $result;
 1408: }
 1409: 
 1410: ##------------------------------------------------------------ curve  data
 1411: sub start_data {
 1412:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1413:     my $result='';
 1414:     if ($target eq 'web' || $target eq 'tex') {
 1415: 	if (exists($curves[-1]->{'function'})) {
 1416: 	    &Apache::lonxml::warning
 1417:                 ('Use of the <b>curve function</b> tag precludes use of '.
 1418:                  ' the <b>curve data</b> tag.  '.
 1419:                  'The curve function tag will be omitted in favor of the '.
 1420:                  'curve data declaration.');
 1421: 	    delete($curves[-1]->{'function'});
 1422: 	}
 1423: 	my $datatext = &Apache::lonxml::get_all_text("/data",$parser,$style);
 1424: 	$datatext=&Apache::run::evaluate($datatext,$safeeval,$$parstack[-1]);
 1425: 	# Deal with cases where we're given an array...
 1426: 	if ($datatext =~ /^\@/) {
 1427: 	    $datatext = &Apache::run::run('return "'.$datatext.'"',
 1428: 					  $safeeval,1);
 1429: 	}
 1430: 	$datatext =~ s/\s+/ /g;
 1431: 	# Need to do some error checking on the @data array - 
 1432: 	# make sure it's all numbers and make sure each array 
 1433: 	# is of the same length.
 1434: 	my @data;
 1435: 	if ($datatext =~ /,/) { # comma deliminated
 1436: 	    @data = split /,/,$datatext;
 1437: 	} else { # Assume it's space separated.
 1438: 	    @data = split / /,$datatext;
 1439: 	}
 1440: 	for (my $i=0;$i<=$#data;$i++) {
 1441: 	    # Check that it's non-empty
 1442: 	    if (! defined($data[$i])) {
 1443: 		&Apache::lonxml::warning(
 1444: 		    'undefined curve data value.  Replacing with '.
 1445: 		    ' pi/e = 1.15572734979092');
 1446: 		$data[$i] = 1.15572734979092;
 1447: 	    }
 1448: 	    # Check that it's a number
 1449: 	    if (! &$real_test($data[$i]) & ! &$int_test($data[$i])) {
 1450: 		&Apache::lonxml::warning(
 1451: 		    'Bad curve data value of '.$data[$i].'  Replacing with '.
 1452: 		    ' pi/e = 1.15572734979092');
 1453: 		$data[$i] = 1.15572734979092;
 1454: 	    }
 1455: 	}
 1456: 	# complain if the number of data points is not the same as
 1457: 	# in previous sets of data.
 1458: 	if (($curves[-1]->{'data'}) && ($#data != $#{$curves[-1]->{'data'}->[0]})){
 1459: 	    &Apache::lonxml::warning
 1460: 		('Number of data points is not consistent with previous '.
 1461: 		 'number of data points');
 1462: 	}
 1463: 	push  @{$curves[-1]->{'data'}},\@data;
 1464:     } elsif ($target eq 'edit') {
 1465: 	$result .= &Apache::edit::tag_start($target,$token,'Comma or space deliminated curve data');
 1466: 	my $text = &Apache::lonxml::get_all_text("/data",$parser,$style);
 1467: 	$result .= &Apache::edit::editline('',$text,'',60);
 1468:     } elsif ($target eq 'modified') {
 1469: 	$result.=&Apache::edit::rebuild_tag($token);
 1470: 	$result.=&Apache::edit::modifiedfield("/data",$parser);
 1471:     }
 1472:     return $result;
 1473: }
 1474: 
 1475: sub end_data {
 1476:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1477:     my $result = '';
 1478:     if ($target eq 'web' || $target eq 'tex') {
 1479:     } elsif ($target eq 'edit') {
 1480: 	$result .= &Apache::edit::end_table();
 1481:     }
 1482:     return $result;
 1483: }
 1484: 
 1485: ##------------------------------------------------------------------- axis
 1486: sub start_axis {
 1487:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1488:     my $result='';
 1489:     if ($target eq 'web' || $target eq 'tex') {
 1490: 	&get_attributes(\%axis,\%axis_defaults,$parstack,$safeeval,
 1491: 			$tagstack->[-1]);
 1492:     } elsif ($target eq 'edit') {
 1493: 	$result .= &Apache::edit::tag_start($target,$token,'Plot Axes');
 1494: 	$result .= &edit_attributes($target,$token,\%axis_defaults,
 1495: 				    \@axis_edit_order);
 1496:     } elsif ($target eq 'modified') {
 1497: 	my $constructtag=&Apache::edit::get_new_args
 1498: 	    ($token,$parstack,$safeeval,keys(%axis_defaults));
 1499: 	if ($constructtag) {
 1500: 	    $result = &Apache::edit::rebuild_tag($token);
 1501: 	}
 1502:     }
 1503:     return $result;
 1504: }
 1505: 
 1506: sub end_axis {
 1507:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1508:     my $result = '';
 1509:     if ($target eq 'web' || $target eq 'tex') {
 1510:     } elsif ($target eq 'edit') {
 1511: 	$result.=&Apache::edit::tag_end($target,$token);
 1512:     } elsif ($target eq 'modified') {
 1513:     }
 1514:     return $result;
 1515: }
 1516: 
 1517: ###################################################################
 1518: ##                                                               ##
 1519: ##        Utility Functions                                      ##
 1520: ##                                                               ##
 1521: ###################################################################
 1522: 
 1523: ##----------------------------------------------------------- set_defaults
 1524: sub set_defaults {
 1525:     my ($var,$defaults) = @_;
 1526:     my $key;
 1527:     foreach $key (keys(%$defaults)) {
 1528: 	$var->{$key} = $defaults->{$key}->{'default'};
 1529:     }
 1530: }
 1531: 
 1532: ##------------------------------------------------------------------- misc
 1533: sub get_attributes{
 1534:     my ($values,$defaults,$parstack,$safeeval,$tag) = @_;
 1535:     foreach my $attr (keys(%{$defaults})) {
 1536: 	if ($attr eq 'texwidth' || $attr eq 'texfont') {
 1537: 	    $values->{$attr} = 
 1538: 		&Apache::lonxml::get_param($attr,$parstack,$safeeval,undef,1);
 1539: 	} else {
 1540: 	    $values->{$attr} = 
 1541: 		&Apache::lonxml::get_param($attr,$parstack,$safeeval);
 1542: 	}
 1543: 	if ($values->{$attr} eq '' | !defined($values->{$attr})) {
 1544: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
 1545: 	    next;
 1546: 	}
 1547: 	my $test = $defaults->{$attr}->{'test'};
 1548: 	if (! &$test($values->{$attr})) {
 1549: 	    &Apache::lonxml::warning
 1550: 		($tag.':'.$attr.': Bad value.'.'Replacing your value with : '
 1551: 		 .$defaults->{$attr}->{'default'} );
 1552: 	    $values->{$attr} = $defaults->{$attr}->{'default'};
 1553: 	}
 1554:     }
 1555:     return ;
 1556: }
 1557: 
 1558: ##------------------------------------------------------- write_gnuplot_file
 1559: sub write_gnuplot_file {
 1560:     my ($tmpdir,$filename,$target)= @_;
 1561:     my ($fontsize, $font_properties) =  &get_font($target);
 1562:     my $gnuplot_input = '';
 1563:     my $curve;
 1564:     #
 1565:     # Check to be sure we do not have any empty curves
 1566:     my @curvescopy;
 1567:     foreach my $curve (@curves) {
 1568:         if (exists($curve->{'function'})) {
 1569:             if ($curve->{'function'} !~ /^\s*$/) {
 1570:                 push(@curvescopy,$curve);
 1571:             }
 1572:         } elsif (exists($curve->{'data'})) {
 1573:             foreach my $data (@{$curve->{'data'}}) {
 1574:                 if (scalar(@$data) > 0) {
 1575:                     push(@curvescopy,$curve);
 1576:                     last;
 1577:                 }
 1578:             }
 1579:         }
 1580:     }
 1581:     @curves = @curvescopy;
 1582:     # Collect all the colors
 1583:     my @Colors;
 1584:     push @Colors, $Apache::lonplot::plot{'bgcolor'};
 1585:     push @Colors, $Apache::lonplot::plot{'fgcolor'}; 
 1586:     push @Colors, (defined($axis{'color'})?$axis{'color'}:$Apache::lonplot::plot{'fgcolor'});
 1587:     foreach $curve (@curves) {
 1588: 	push @Colors, ($curve->{'color'} ne '' ? 
 1589: 		       $curve->{'color'}       : 
 1590: 		       $Apache::lonplot::plot{'fgcolor'}        );
 1591:     }
 1592:     # set term
 1593:     if ($target eq 'web') {
 1594: 	$gnuplot_input .= 'set terminal png enhanced nocrop ';
 1595: 	$gnuplot_input .= 'transparent ' if ($Apache::lonplot::plot{'transparent'} eq 'on');
 1596: 	$gnuplot_input .= 'font "'.$Apache::lonnet::perlvar{'lonFontsDir'}.
 1597: 	    '/'.$font_properties->{'file'}.'.ttf" ';
 1598: 	$gnuplot_input .= $fontsize;
 1599: 	$gnuplot_input .= ' size '.$Apache::lonplot::plot{'width'}.','.$Apache::lonplot::plot{'height'}.' ';
 1600: 	$gnuplot_input .= "@Colors\n";
 1601: 	# set output
 1602: 	$gnuplot_input .= "set output\n";
 1603:     } elsif ($target eq 'tex') {
 1604: 	$gnuplot_input .= "set term postscript eps enhanced $Apache::lonplot::plot{'plotcolor'} solid ";
 1605: 	if (!$font_properties->{'tex_no_file'}) {
 1606: 	    $gnuplot_input .=
 1607: 		'fontfile "'.$Apache::lonnet::perlvar{'lonFontsDir'}.
 1608: 		'/'.$font_properties->{'file'}.'.pfb" ';
 1609: 	}
 1610: 	$gnuplot_input .= ' "'.$font_properties->{'printname'}.'" ';
 1611: 	$gnuplot_input .= $fontsize;
 1612: 	$gnuplot_input .= "\nset output \"/home/httpd/perl/tmp/".
 1613: 	    &unescape($filename).".eps\"\n";
 1614: 	$gnuplot_input .= "set encoding iso_8859_1\n"; # Get access to extended font.
 1615: 
 1616:     }
 1617:     # cartesian or polar plot?
 1618:     if (lc($Apache::lonplot::plot{'plottype'}) eq 'polar') {
 1619:         $gnuplot_input .= 'set polar'.$/;
 1620:     } else {
 1621:         # Assume Cartesian
 1622:     }
 1623:     # cartesian or polar grid?
 1624:     if (lc($Apache::lonplot::plot{'gridtype'}) eq 'polar') {
 1625:         $gnuplot_input .= 'set grid polar'.$/;
 1626:     } elsif (lc($Apache::lonplot::plot{'gridtype'}) eq 'linear-log') {
 1627:         $gnuplot_input .= 'set logscale x'.$/;
 1628:     } elsif (lc($Apache::lonplot::plot{'gridtype'}) eq 'log-linear') {
 1629:         $gnuplot_input .= 'set logscale y'.$/;
 1630:     } elsif (lc($Apache::lonplot::plot{'gridtype'}) eq 'log-log') {
 1631:         $gnuplot_input .= 'set logscale x'.$/;
 1632:         $gnuplot_input .= 'set logscale y'.$/;
 1633:     } else {
 1634:         # Assume Cartesian
 1635:     }
 1636:     # solid or pattern for boxes?
 1637:     if (lc($Apache::lonplot::plot{'fillstyle'}) eq 'solid') {
 1638:         $gnuplot_input .= 'set style fill solid '.
 1639: 	    $Apache::lonplot::plot{'solid'}.$Apache::lonplot::plot{'box_border'}.$/;
 1640:     } elsif (lc($Apache::lonplot::plot{'fillstyle'}) eq 'pattern') {
 1641:         $gnuplot_input .= 'set style fill pattern '.$Apache::lonplot::plot{'pattern'}.$Apache::lonplot::plot{'box_border'}.$/;
 1642:     } elsif (lc($Apache::lonplot::plot{'fillstyle'}) eq 'empty') {
 1643:     }
 1644:     # margin
 1645:     if (lc($Apache::lonplot::plot{'lmargin'}) ne 'default') {
 1646:         $gnuplot_input .= 'set lmargin '.$Apache::lonplot::plot{'lmargin'}.$/;
 1647:     }
 1648:     if (lc($Apache::lonplot::plot{'rmargin'}) ne 'default') {
 1649:         $gnuplot_input .= 'set rmargin '.$Apache::lonplot::plot{'rmargin'}.$/;
 1650:     }
 1651:     if (lc($Apache::lonplot::plot{'tmargin'}) ne 'default') {
 1652:         $gnuplot_input .= 'set tmargin '.$Apache::lonplot::plot{'tmargin'}.$/;
 1653:     }
 1654:     if (lc($Apache::lonplot::plot{'bmargin'}) ne 'default') {
 1655:         $gnuplot_input .= 'set bmargin '.$Apache::lonplot::plot{'bmargin'}.$/;
 1656:     }
 1657: 
 1658:     # tic scales
 1659:     if ($version > 4) {
 1660: 	$gnuplot_input .= 'set tics scale '.
 1661: 	    $Apache::lonplot::plot{'major_ticscale'}.', '.$Apache::lonplot::plot{'minor_ticscale'}.$/;
 1662:     } else {
 1663:     	$gnuplot_input .= 'set ticscale '.
 1664: 	    $Apache::lonplot::plot{'major_ticscale'}.' '.$Apache::lonplot::plot{'minor_ticscale'}.$/;
 1665:     }
 1666:     #boxwidth
 1667:     if (lc($Apache::lonplot::plot{'boxwidth'}) ne '') {
 1668: 	$gnuplot_input .= 'set boxwidth '.$Apache::lonplot::plot{'boxwidth'}.$/;
 1669:     }
 1670:     # gridlayer
 1671:     $gnuplot_input .= 'set grid noxtics noytics front '.$/ 
 1672: 	if ($Apache::lonplot::plot{'gridlayer'} eq 'on');
 1673: 
 1674:     # grid
 1675:     $gnuplot_input .= 'set grid'.$/ if ($Apache::lonplot::plot{'grid'} eq 'on');
 1676:     # border
 1677:     $gnuplot_input .= ($Apache::lonplot::plot{'border'} eq 'on'?
 1678: 		       'set border'.$/           :
 1679: 		       'set noborder'.$/         );
 1680:     # sampling rate for non-data curves
 1681:     $gnuplot_input .= "set samples $Apache::lonplot::plot{'samples'}\n";
 1682:     # title, xlabel, ylabel
 1683:     # titles
 1684:     my $offset;
 1685:     if ($version >= 4.4) {
 1686:         $offset = 'offset ';
 1687:     }
 1688:     my $extra_space_x = ($xtics{'location'} eq 'axis') ? ' '.$offset.'0, -0.5 ' : '';
 1689:     my $extra_space_y = ($ytics{'location'} eq 'axis') ? ' '.$offset.'-0.5, 0 ' : '';
 1690: 
 1691:     if ($target eq 'tex') {
 1692: 	$gnuplot_input .= "set title  \"$title\"          font \"".$font_properties->{'printname'}.",".$fontsize."pt\"\n" if (defined($title)) ;
 1693: 	$gnuplot_input .= "set xlabel \"$xlabel\" $extra_space_x font \"".$font_properties->{'printname'}.",".$fontsize."pt\"\n" if (defined($xlabel));
 1694: 	$gnuplot_input .= "set ylabel \"$ylabel\" $extra_space_y font \"".$font_properties->{'printname'}.",".$fontsize."pt\"\n" if (defined($ylabel));
 1695:     } else {
 1696:         $gnuplot_input .= "set title  \"$title\"          \n" if (defined($title)) ;
 1697:         $gnuplot_input .= "set xlabel \"$xlabel\" $extra_space_x \n" if (defined($xlabel));
 1698:         $gnuplot_input .= "set ylabel \"$ylabel\" $extra_space_y \n" if (defined($ylabel));
 1699:     }
 1700:     # tics
 1701:     if (%xtics) {    
 1702: 	$gnuplot_input .= "set xtics $xtics{'location'} ";
 1703: 	$gnuplot_input .= ( $xtics{'mirror'} eq 'on'?"mirror ":"nomirror ");
 1704: 	$gnuplot_input .= "$xtics{'start'}, ";
 1705: 	$gnuplot_input .= "$xtics{'increment'}, ";
 1706: 	$gnuplot_input .= "$xtics{'end'} ";
 1707: 	if ($target eq 'tex') {
 1708: 	    $gnuplot_input .= 'font "Helvetica,22"';     # Needed in iso 8859-1 enc.
 1709: 	}
 1710: 	$gnuplot_input .= "\n";
 1711:         if ($xtics{'minorfreq'} != 0) {
 1712:             $gnuplot_input .= "set mxtics ".$xtics{'minorfreq'}."\n";
 1713:         } 
 1714:     } else {
 1715: 	if ($target eq 'tex') {
 1716: 	    $gnuplot_input .= 'set xtics font "Helvetica,22"'."\n"; # needed in iso 8859-1 enc
 1717: 	}
 1718:     }
 1719:     if (%ytics) {    
 1720: 	$gnuplot_input .= "set ytics $ytics{'location'} ";
 1721: 	$gnuplot_input .= ( $ytics{'mirror'} eq 'on'?"mirror ":"nomirror ");
 1722: 	$gnuplot_input .= "$ytics{'start'}, ";
 1723: 	$gnuplot_input .= "$ytics{'increment'}, ";
 1724:         $gnuplot_input .= "$ytics{'end'} ";
 1725:         if ($target eq 'tex') {
 1726:             $gnuplot_input .= 'font "Helvetica,22"'; # Needed in iso-8859-1 encoding.
 1727:         }
 1728:         $gnuplot_input .= "\n";
 1729:         if ($ytics{'minorfreq'} != 0) {
 1730:             $gnuplot_input .= "set mytics ".$ytics{'minorfreq'}."\n";
 1731:         } 
 1732:     } else {
 1733: 	if ($target eq 'tex') {
 1734: 	    $gnuplot_input .= 'set ytics font "Helvetica,22"'."\n"; # Needed for iso 8859-1 enc.
 1735: 	}
 1736:     }
 1737:     # axis
 1738:     if (%axis) {
 1739:         if ($axis{'xformat'} ne 'on') {
 1740:             $gnuplot_input .= "set format x ";
 1741:             if ($axis{'xformat'} eq 'off') {
 1742:                 $gnuplot_input .= "\"\"\n";
 1743:             } else {
 1744:                 $gnuplot_input .= "\"\%.".$axis{'xformat'}."\"\n";
 1745:             }
 1746:         }
 1747:         if ($axis{'yformat'} ne 'on') {
 1748:             $gnuplot_input .= "set format y ";
 1749:             if ($axis{'yformat'} eq 'off') {
 1750:                 $gnuplot_input .= "\"\"\n";
 1751:             } else {
 1752:                 $gnuplot_input .= "\"\%.".$axis{'yformat'}."\"\n";
 1753:             }
 1754:         }
 1755: 	$gnuplot_input .= "set xrange \[$axis{'xmin'}:$axis{'xmax'}\]\n";
 1756: 	$gnuplot_input .= "set yrange \[$axis{'ymin'}:$axis{'ymax'}\]\n";
 1757: 		if ($axis{'xzero'} ne 'off') {
 1758: 			$gnuplot_input .= "set xzeroaxis ";
 1759: 			if ($axis{'xzero'} eq 'line' || $axis{'xzero'} eq 'thick-line') {
 1760: 				$gnuplot_input .= "lt -1 ";
 1761: 				if ($axis{'xzero'} eq 'thick-line') {
 1762: 					$gnuplot_input .= "lw 3 ";
 1763: 				}
 1764: 			}
 1765: 			$gnuplot_input .= "\n";
 1766: 		}
 1767: 		if ($axis{'yzero'} ne 'off') {
 1768: 			$gnuplot_input .= "set yzeroaxis ";
 1769: 			if ($axis{'yzero'} eq 'line' || $axis{'yzero'} eq 'thick-line') {
 1770: 				$gnuplot_input .= "lt -1 ";
 1771: 				if ($axis{'yzero'} eq 'thick-line') {
 1772: 					$gnuplot_input .= "lw 3 ";
 1773: 				}
 1774: 			}
 1775: 			$gnuplot_input .= "\n";
 1776: 		}
 1777:     }
 1778:     # Key
 1779:     if (%key) {
 1780: 	$gnuplot_input .= 'set key '.$key{'pos'}.' ';
 1781: 	if ($key{'title'} ne '') {
 1782: 	    $gnuplot_input .= 'title "'.$key{'title'}.'" ';
 1783: 	} 
 1784: 	$gnuplot_input .= ($key{'box'} eq 'on' ? 'box ' : 'nobox ').$/;
 1785:     } else {
 1786: 	$gnuplot_input .= 'set nokey'.$/;
 1787:     }
 1788:     # labels
 1789:     my $label;
 1790:     foreach $label (@labels) {
 1791: 	$gnuplot_input .= 'set label "'.$label->{'text'}.'" at '.
 1792:                           $label->{'xpos'}.','.$label->{'ypos'};
 1793:         if ($label->{'rotate'} ne '') {
 1794:             $gnuplot_input .= ' rotate by '.$label->{'rotate'};
 1795:         }
 1796:         $gnuplot_input .= ' '.$label->{'justify'};
 1797: 
 1798:         if ($target eq 'tex') {
 1799: 	    $gnuplot_input .=' font "'.$font_properties->{'printname'}.','.$fontsize.'pt"' ;
 1800:         }
 1801:         $gnuplot_input .= $/;
 1802:     }
 1803:     if ($target eq 'tex') {
 1804:         $gnuplot_input .="set size 1,".$Apache::lonplot::plot{'height'}/$Apache::lonplot::plot{'width'}*1.38;
 1805:         $gnuplot_input .="\n";
 1806:     }
 1807:     # curves
 1808:     $gnuplot_input .= 'plot ';
 1809:     for (my $i = 0;$i<=$#curves;$i++) {
 1810: 	$curve = $curves[$i];
 1811: 	$gnuplot_input.= ', ' if ($i > 0);
 1812: 	if ($target eq 'tex') {
 1813: 	    $curve->{'linewidth'} *= 2;
 1814: 	}
 1815: 	if (exists($curve->{'function'})) {
 1816: 	    $gnuplot_input.= 
 1817: 		$curve->{'function'}.' title "'.
 1818: 		$curve->{'name'}.'" with '.
 1819:                 $curve->{'linestyle'};
 1820: 
 1821:             if (($curve->{'linestyle'} eq 'points')      ||
 1822:                 ($curve->{'linestyle'} eq 'linespoints') ||
 1823:                 ($curve->{'linestyle'} eq 'errorbars')   ||
 1824:                 ($curve->{'linestyle'} eq 'xerrorbars')  ||
 1825:                 ($curve->{'linestyle'} eq 'yerrorbars')  ||
 1826:                 ($curve->{'linestyle'} eq 'xyerrorbars')) {
 1827:                 $gnuplot_input.=' pointtype '.$curve->{'pointtype'};
 1828:                 $gnuplot_input.=' pointsize '.$curve->{'pointsize'};
 1829:             } elsif ($curve->{'linestyle'} eq 'filledcurves') { 
 1830:                 $gnuplot_input.= ' '.$curve->{'limit'};
 1831:             } elsif ($curve->{'linetype'} ne '' &&
 1832:                      $curve->{'linestyle'} eq 'lines') {
 1833:                 $gnuplot_input.= ' linetype ';
 1834:                 $gnuplot_input.= $linetypes{$curve->{'linetype'}};
 1835:                 $gnuplot_input.= ' linecolor rgb "';
 1836:                 # convert color from xaaaaaa to #aaaaaa
 1837:                 $curve->{'color'} =~ s/^x/#/;
 1838:                 $gnuplot_input.= $curve->{'color'}.'"';
 1839:             }
 1840:             $gnuplot_input.= ' linewidth '.$curve->{'linewidth'};
 1841: 
 1842: 	} elsif (exists($curve->{'data'})) {
 1843: 	    # Store data values in $datatext
 1844: 	    my $datatext = '';
 1845: 	    #   get new filename
 1846: 	    my $datafilename = "$tmpdir/$filename.data.$i";
 1847: 	    my $fh=Apache::File->new(">$datafilename");
 1848: 	    # Compile data
 1849: 	    my @Data = @{$curve->{'data'}};
 1850: 	    my @Data0 = @{$Data[0]};
 1851: 	    for (my $i =0; $i<=$#Data0; $i++) {
 1852: 		my $dataset;
 1853: 		foreach $dataset (@Data) {
 1854: 		    $datatext .= $dataset->[$i] . ' ';
 1855: 		}
 1856: 		$datatext .= $/;
 1857: 	    }
 1858: 	    #   write file
 1859: 	    print $fh $datatext;
 1860: 	    close($fh);
 1861: 	    #   generate gnuplot text
 1862: 	    $gnuplot_input.= '"'.$datafilename.'" title "'.
 1863: 		$curve->{'name'}.'" with '.
 1864: 		$curve->{'linestyle'};
 1865:             if (($curve->{'linestyle'} eq 'points')      ||
 1866:                 ($curve->{'linestyle'} eq 'linespoints') ||
 1867:                 ($curve->{'linestyle'} eq 'errorbars')   ||
 1868:                 ($curve->{'linestyle'} eq 'xerrorbars')  ||
 1869:                 ($curve->{'linestyle'} eq 'yerrorbars')  ||
 1870:                 ($curve->{'linestyle'} eq 'xyerrorbars')) {
 1871:                 $gnuplot_input.=' pointtype '.$curve->{'pointtype'};
 1872:                 $gnuplot_input.=' pointsize '.$curve->{'pointsize'};
 1873:             } elsif ($curve->{'linestyle'} eq 'filledcurves') { 
 1874:                 $gnuplot_input.= ' '.$curve->{'limit'};
 1875:             } elsif ($curve->{'linetype'} ne '' &&
 1876:                      $curve->{'linestyle'} eq 'lines') {
 1877:                 $gnuplot_input.= ' linetype ';
 1878:                 $gnuplot_input.= $linetypes{$curve->{'linetype'}};
 1879:                 $gnuplot_input.= ' linecolor rgb "';
 1880:                 # convert color from xaaaaaa to #aaaaaa
 1881:                 $curve->{'color'} =~ s/^x/#/;
 1882:                 $gnuplot_input.= $curve->{'color'}.'"';
 1883:             }
 1884:                 $gnuplot_input.= ' linewidth '.$curve->{'linewidth'}; 
 1885: 	}
 1886:     }
 1887:     # Write the output to a file.
 1888:     open (my $fh,">$tmpdir$filename.data");
 1889:     binmode($fh, ":utf8");
 1890:     print $fh $gnuplot_input;
 1891:     close($fh);
 1892:     # That's all folks.
 1893:     return ;
 1894: }
 1895: 
 1896: #---------------------------------------------- check_inputs
 1897: sub check_inputs {
 1898:     ## Note: no inputs, no outputs - this acts only on global variables.
 1899:     ## Make sure we have all the input we need:
 1900:     if (! %Apache::lonplot::plot) { &set_defaults(\%Apache::lonplot::plot,\%gnuplot_defaults); }
 1901:     if (! %key ) {} # No key for this plot, thats okay
 1902: #    if (! %axis) { &set_defaults(\%axis,\%axis_defaults); }
 1903:     if (! defined($title )) {} # No title for this plot, thats okay
 1904:     if (! defined($xlabel)) {} # No xlabel for this plot, thats okay
 1905:     if (! defined($ylabel)) {} # No ylabel for this plot, thats okay
 1906:     if ($#labels < 0) { }      # No labels for this plot, thats okay
 1907:     if ($#curves < 0) { 
 1908: 	&Apache::lonxml::warning("No curves specified for plot!!!!");
 1909: 	return '';
 1910:     }
 1911:     my $curve;
 1912:     foreach $curve (@curves) {
 1913: 	if (!defined($curve->{'function'})&&!defined($curve->{'data'})){
 1914: 	    &Apache::lonxml::warning("One of the curves specified did not contain any curve data or curve function declarations\n");
 1915: 	    return '';
 1916: 	}
 1917:     }
 1918: }
 1919: 
 1920: #------------------------------------------------ make_edit
 1921: sub edit_attributes {
 1922:     my ($target,$token,$defaults,$keys) = @_;
 1923:     my ($result,@keys);
 1924:     if ($keys && ref($keys) eq 'ARRAY') {
 1925:         @keys = @$keys;
 1926:     } else {
 1927: 	@keys = sort(keys(%$defaults));
 1928:     }
 1929:     foreach my $attr (@keys) {
 1930: 	# append a ' ' to the description if it doesn't have one already.
 1931: 	my $description = $defaults->{$attr}->{'description'};
 1932: 	$description .= ' ' if ($description !~ / $/);
 1933: 	if ($defaults->{$attr}->{'edit_type'} eq 'entry') {
 1934: 	    $result .= &Apache::edit::text_arg
 1935: 		($description,$attr,$token,
 1936: 		 $defaults->{$attr}->{'size'});
 1937: 	} elsif ($defaults->{$attr}->{'edit_type'} eq 'choice') {
 1938: 	    $result .= &Apache::edit::select_or_text_arg
 1939: 		($description,$attr,$defaults->{$attr}->{'choices'},$token);
 1940: 	} elsif ($defaults->{$attr}->{'edit_type'} eq 'onoff') {
 1941: 	    $result .= &Apache::edit::select_or_text_arg
 1942: 		($description,$attr,['on','off'],$token);
 1943: 	}
 1944: 	$result .= '<br />';
 1945:     }
 1946:     return $result;
 1947: }
 1948: 
 1949: 
 1950: ###################################################################
 1951: ##                                                               ##
 1952: ##           Insertion functions for editing plots               ##
 1953: ##                                                               ##
 1954: ###################################################################
 1955: 
 1956: sub insert_gnuplot {
 1957:     my $result = '';
 1958:     #  plot attributes
 1959:     $result .= "\n<gnuplot ";
 1960:     foreach my $attr (keys(%gnuplot_defaults)) {
 1961: 	$result .= "\n     $attr=\"$gnuplot_defaults{$attr}->{'default'}\"";
 1962:     }
 1963:     $result .= ">";
 1964:     # Add the components (most are commented out for simplicity)
 1965:     # $result .= &insert_key();
 1966:     # $result .= &insert_axis();
 1967:     # $result .= &insert_title();    
 1968:     # $result .= &insert_xlabel();    
 1969:     # $result .= &insert_ylabel();    
 1970:     $result .= &insert_curve();
 1971:     # close up the <gnuplot>
 1972:     $result .= "\n</gnuplot>";
 1973:     return $result;
 1974: }
 1975: 
 1976: sub insert_tics {
 1977:     my $result;
 1978:     $result .= &insert_xtics() . &insert_ytics;
 1979:     return $result;
 1980: }
 1981: 
 1982: sub insert_xtics {
 1983:     my $result;
 1984:     $result .= "\n    <xtics ";
 1985:     foreach my $attr (keys(%tic_defaults)) {
 1986: 	$result .= "\n        $attr=\"$tic_defaults{$attr}->{'default'}\" ";
 1987:     }
 1988:     $result .= "/>";
 1989:     return $result;
 1990: }
 1991: 
 1992: sub insert_ytics {
 1993:     my $result;
 1994:     $result .= "\n    <ytics ";
 1995:     foreach my $attr (keys(%tic_defaults)) {
 1996: 	$result .= "\n        $attr=\"$tic_defaults{$attr}->{'default'}\" ";
 1997:     }
 1998:     $result .= "/>";
 1999:     return $result;
 2000: }
 2001: 
 2002: sub insert_key {
 2003:     my $result;
 2004:     $result .= "\n    <key ";
 2005:     foreach my $attr (keys(%key_defaults)) {
 2006: 	$result .= "\n         $attr=\"$key_defaults{$attr}->{'default'}\"";
 2007:     }
 2008:     $result .= " />";
 2009:     return $result;
 2010: }
 2011: 
 2012: sub insert_axis{
 2013:     my $result;
 2014:     $result .= "\n    <axis ";
 2015:    foreach my $attr (keys(%axis_defaults)) {
 2016: 	$result .= "\n         $attr=\"$axis_defaults{$attr}->{'default'}\"";
 2017:     }
 2018:     $result .= " />";
 2019:     return $result;
 2020: }
 2021: 
 2022: sub insert_title  { return "\n    <title></title>"; }
 2023: sub insert_xlabel { return "\n    <xlabel></xlabel>"; }
 2024: sub insert_ylabel { return "\n    <ylabel></ylabel>"; }
 2025: 
 2026: sub insert_label {
 2027:     my $result;
 2028:     $result .= "\n    <label ";
 2029:     foreach my $attr (keys(%label_defaults)) {
 2030: 	$result .= "\n         $attr=\"".
 2031:             $label_defaults{$attr}->{'default'}."\"";
 2032:     }
 2033:     $result .= "></label>";
 2034:     return $result;
 2035: }
 2036: 
 2037: sub insert_curve {
 2038:     my $result;
 2039:     $result .= "\n    <curve ";
 2040:     foreach my $attr (keys(%curve_defaults)) {
 2041: 	$result .= "\n         $attr=\"".
 2042: 	    $curve_defaults{$attr}->{'default'}."\"";
 2043:     }
 2044:     $result .= " >";
 2045:     $result .= &insert_data().&insert_data()."\n    </curve>";
 2046: }
 2047: 
 2048: sub insert_function {
 2049:     my $result;
 2050:     $result .= "\n        <function></function>";
 2051:     return $result;
 2052: }
 2053: 
 2054: sub insert_data {
 2055:     my $result;
 2056:     $result .= "\n        <data></data>";
 2057:     return $result;
 2058: }
 2059: 
 2060: ##----------------------------------------------------------------------
 2061: 1;
 2062: __END__
 2063: 
 2064: 
 2065: =head1 NAME
 2066: 
 2067: Apache::lonplot.pm
 2068: 
 2069: =head1 SYNOPSIS
 2070: 
 2071: XML-based plotter of graphs
 2072: 
 2073: This is part of the LearningOnline Network with CAPA project
 2074: described at http://www.lon-capa.org.
 2075: 
 2076: 
 2077: =head1 SUBROUTINES (parsing and edit rendering)
 2078: 
 2079: =over
 2080: 
 2081: =item start_gnuplot()
 2082: 
 2083: =item end_gnuplot()
 2084: 
 2085: =item start_xtics()
 2086: 
 2087: =item end_xtics()
 2088: 
 2089: =item start_ytics()
 2090: 
 2091: =item end_ytics()
 2092: 
 2093: =item get_font()
 2094: 
 2095: =item start_key()
 2096: 
 2097: =item end_key()
 2098: 
 2099: =item parse_label()
 2100: 
 2101: =item replace_entities()
 2102: 
 2103: =item start_title()
 2104: 
 2105: =item end_title()
 2106: 
 2107: =item start_xlabel()
 2108: 
 2109: =item end_xlabel()
 2110: 
 2111: =item start_ylabel()
 2112: 
 2113: =item end_label()
 2114: 
 2115: =item start_curve()
 2116: 
 2117: =item end_curve()
 2118: 
 2119: =item start_function()
 2120: 
 2121: =item end_function()
 2122: 
 2123: =item start_data()
 2124: 
 2125: =item end_data()
 2126: 
 2127: =item start_axis()
 2128: 
 2129: =item end_axis
 2130: 
 2131: =back
 2132: 
 2133: =head1 SUBROUTINES (Utility)
 2134: 
 2135: =over
 2136: 
 2137: =item set_defaults()
 2138: 
 2139: =item get_attributes()
 2140: 
 2141: =item write_gnuplot_file()
 2142: 
 2143: =item check_inputs()
 2144: 
 2145: =item edit_attributes()
 2146: 
 2147: =back
 2148: 
 2149: =head1 SUBROUTINES (Insertion functions for editing plots)
 2150: 
 2151: =over
 2152: 
 2153: =item insert_gnuplot()
 2154: 
 2155: =item insert_tics()
 2156: 
 2157: =item insert_xtics()
 2158: 
 2159: =item insert_key()
 2160: 
 2161: =item insert_axis()
 2162: 
 2163: =item insert_title()
 2164: 
 2165: =item insert_xlabel()
 2166: 
 2167: =item insert_ylabel()
 2168: 
 2169: =item insert_label()
 2170: 
 2171: =item insert_curve()
 2172: 
 2173: =item insert_function()
 2174: 
 2175: =item insert_data()
 2176: 
 2177: =back
 2178: 
 2179: =cut

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>