File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.157: download - view: text, annotated - select for diffs
Wed Jul 4 11:06:57 2012 UTC (11 years, 10 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
BZ6588 - First refactor and simplify the generation of gnuplot commands.
       - Second address the bug by associating a linestye with each plot
         and using that to select the plot attributes rather than cramming
         all the attributes into the plot command.
       - Finally, fix the fact that line style numbers differ between
         eps and png drivers so that now dashed lines work in eps output
         where I don't think they did before.

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

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