File:  [LON-CAPA] / loncom / xml / lonplot.pm
Revision 1.156: download - view: text, annotated - select for diffs
Tue Jul 3 11:29:57 2012 UTC (11 years, 10 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
A pile of refactoring the gnu plot rendering prior to tackling
BZ 6588.

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

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