File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.154: download - view: text, annotated - select for diffs
Mon Feb 13 11:24:16 2012 UTC (12 years, 3 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
BZ 874 - Make color entries of class 'colorchooser'  this would allow some
javascript color choosr widget to be bound to them (e.g. jPicker).

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

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