File:  [LON-CAPA] / loncom / xml / lontexconvert.pm
Revision 1.84: download - view: text, annotated - select for diffs
Tue Aug 14 19:32:35 2007 UTC (16 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: version_2_6_X, version_2_6_3, version_2_6_2, version_2_6_1, version_2_6_0, version_2_5_X, version_2_5_99_1, version_2_5_99_0, version_2_5_2, version_2_5_1, version_2_5_0, HEAD
- BUG#5370, need the popup previous tries window to use jamath if the the problem needed jsmath, so created a means to convey that

    1: # The LearningOnline Network with CAPA
    2: # TeX Conversion Module
    3: #
    4: # $Id: lontexconvert.pm,v 1.84 2007/08/14 19:32:35 albertel 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: # Copyright for TtHfunc and TtMfunc by Ian Hutchinson. 
   29: # TtHfunc and TtMfunc (the "Code") may be compiled and linked into 
   30: # binary executable programs or libraries distributed by the 
   31: # Michigan State University (the "Licensee"), but any binaries so 
   32: # distributed are hereby licensed only for use in the context
   33: # of a program or computational system for which the Licensee is the 
   34: # primary author or distributor, and which performs substantial 
   35: # additional tasks beyond the translation of (La)TeX into HTML.
   36: # The C source of the Code may not be distributed by the Licensee
   37: # to any other parties under any circumstances.
   38: #
   39: 
   40: package Apache::lontexconvert;
   41: 
   42: use strict;
   43: use tth();
   44: use vars qw($errorstring);
   45: #use Apache::lonxml();
   46: use Apache::lonlocal;
   47: use Apache::lonnet;
   48: use lib '/home/httpd/lib/perl/';
   49: use LONCAPA;
   50:  
   51: 
   52: # ====================================================================== Header
   53: 
   54: sub init_tth {
   55:     my $options=$env{'course.'.$env{'request.course.id'}.'.tthoptions'};
   56:     if ($options =~ /\S/) {
   57: 	$options = ' '.$options;
   58:     } else {
   59: 	undef($options);
   60:     }
   61:     if ($env{'browser.mathml'}) {
   62: 	&tth::ttminit();
   63: 	if ($env{'browser.unicode'}) {
   64: 	    &tth::ttmoptions('-L -u1'.$options);
   65: 	} else {
   66: 	    &tth::ttmoptions('-L -u0'.$options);
   67: 	}
   68:     } else {
   69: 	&tth::tthinit();
   70: 	if ($env{'browser.unicode'}) {
   71: 	    &tth::tthoptions('-L -u1'.$options);
   72: 	} else {
   73: 	    &tth::tthoptions('-L -u0'.$options);
   74: 	}
   75:     }
   76: }
   77: 
   78: # ================================================================== Conversion
   79: 
   80: $Apache::lontexconvert::messedup=0;
   81: 
   82: # we need this routine because &converted can get called from inside
   83: # of the safespace (through &xmlparse('<m>stuff</m>') which doesn't
   84: # allow the opcode for alarm, so we need to compile this before we get
   85: # into the safe space since opcode checks only occur at compile time
   86: sub convert_real {
   87:     my ($texstring)=@_;
   88:     my ($xmlstring,$errorstring);
   89:     local $SIG{SEGV}=sub { $Apache::lontexconvert::messedup=1; die; };
   90:     local $SIG{ALRM}=sub { 
   91: 	&Apache::lonnet::logthis("ALRM");
   92: 	$xmlstring='['.&mt("TeX unconverted due to errors").']';
   93: 	$Apache::lontexconvert::messedup=1;
   94: 	die &mt("TeX unconverted due to errors");
   95:     };
   96:     &Apache::lonxml::start_alarm();
   97:     if ($env{'browser.mathml'}) {
   98: 	$xmlstring=&tth::ttm($$texstring);
   99: 	$xmlstring=~s/\<math\>/\<math xmlns=\"\&mathns\;\"\>/g;
  100: 	$xmlstring=~s/\<br\>/\<br\/\>/g;
  101: 	$xmlstring=~s/\<p\>/\<p\>\<\/p\>/g;
  102: 	$errorstring.=&tth::ttmerror();
  103:     } else {
  104: 	$xmlstring=&tth::tth($$texstring);
  105: 	$errorstring.=&tth::ttherror();
  106: 	$xmlstring=~s-</font(\s*)>-</font>-g;
  107:     }
  108:     $xmlstring=~s/^\s*\<br clear\=\"all\"/\<br/s;
  109:     $xmlstring=~s/^\s*//;
  110:     $xmlstring=~s/\s*$//;
  111:     &Apache::lonxml::end_alarm();
  112:     return ($xmlstring,$errorstring);
  113: }
  114: 
  115: sub tth_converted {
  116:     my $texstring=shift;
  117:     my $xmlstring='['.&mt('UNDISPLAYABLE').']';
  118:     if ($Apache::lontexconvert::messedup) {
  119: 	return '['.&mt('TeX unconverted due to previous errors').']';
  120:     }
  121:     $$texstring ='\\documentstyle{article}'.$$texstring;
  122: 
  123:     eval(<<'ENDCONV');
  124:     ($xmlstring,$errorstring)=&convert_real($texstring)
  125: ENDCONV
  126:     if ($@) {
  127: 	$errorstring.=&mt("Evaluation Error: ").$@;
  128: 	$Apache::lontexconvert::messedup=1;
  129:     }
  130:     if ($Apache::lontexconvert::messedup || &tth::tthmessedup() || 
  131: 	$errorstring) {
  132: 	&Apache::lonnet::logthis("Trying to kill myself");
  133: 	$Apache::lontexconvert::messedup=1;
  134: 	if (ref($Apache::lonxml::request)) {
  135: 	    $Apache::lonxml::request->child_terminate();
  136: 	} else {
  137: 	    my $request;
  138: 	    eval { $request=Apache->request; };
  139: 	    if (!$request) {
  140: 		eval { $request=Apache2::RequestUtil->request; };
  141: 	    }
  142: 	    if ($request) {
  143: 		$request->child_terminate();
  144: 	    } else {
  145: 		&Apache::lonnet::logthis("Unable to find a request to do child_terminate on");
  146: 	    }
  147: 	}
  148:     }
  149:     return $xmlstring;
  150: }
  151: 
  152: sub clean_out_math_mode {
  153:     my ($texstring)=@_;
  154:     $$texstring=~s/(?<!\\)\$//g;
  155:     $$texstring=~s/\\[\)\(\]\[]//g;
  156:     $$texstring=~s/\\ensuremath//g;
  157:     return '';
  158: }
  159: 
  160: sub displaystyle {
  161:     my ($texstring)=@_;
  162:     #has a $$ or \[ or \displaystyle in it, guessinng it's display mode
  163:     if ($$texstring=~/[^\\]\$\$/ ||
  164: 	$$texstring=~/\\\[/ ||
  165: 	$$texstring=~/\\displaystyle/) { return 1; }
  166:     return 0;
  167: }
  168: 
  169: sub jsMath_converted {
  170:     my $texstring=shift;
  171:     my $tag='span';
  172:     if (&displaystyle($texstring)) { $tag='div'; }
  173:     &clean_out_math_mode($texstring);
  174:     return &jsMath_header().
  175: 	'<'.$tag.' class="math">'.$$texstring.'</'.$tag.'>';
  176: }
  177: 
  178: {
  179:     my @jsMath_sent_header;
  180:     sub jsMath_reset {
  181: 	undef(@jsMath_sent_header);
  182:     }
  183:     sub jsMath_push {
  184: 	push(@jsMath_sent_header,0);
  185:     }
  186:     sub jsMath_header {
  187: 	if (!@jsMath_sent_header) {
  188: 	    &Apache::lonnet::logthis("mismatched calls of jsMath_header and jsMath_process");
  189: 	    return '';
  190: 	}
  191: 	return '' if $jsMath_sent_header[-1];
  192: 	$jsMath_sent_header[-1]=1;
  193: 	return
  194:             '<script type="text/javascript">
  195:                      function NoFontMessage () {}
  196:                      jsMath = {Parser: {prototype: {environments: {\'eqnarray*\' :[\'Array\',null,null,\'rcl\',[5/18,5/18],3,\'D\']}}}};
  197:                    </script>'."\n".
  198: 	    '<script type="text/javascript" src="/adm/jsMath/jsMath.js"></script>'."\n";
  199:     }
  200:     sub jsMath_process {
  201: 	my $state = pop(@jsMath_sent_header);
  202: 	return '' if !$state;
  203: 	return "\n".
  204: 	    '<script type="text/javascript">jsMath.Process()</script>'."\n";
  205:     }
  206:     sub jsMath_state {
  207: 	my ($level) = @_;
  208: 	return $jsMath_sent_header[$level];
  209:     }
  210: }
  211: 
  212: sub tex_engine {
  213:     if (exists($env{'form.texengine'})) {
  214: 	return $env{'form.texengine'};
  215:     }    
  216:     if ($env{'request.course.id'}
  217: 	&& exists($env{'course.'.$env{'request.course.id'}.'.texengine'})) {
  218: 	return $env{'course.'.$env{'request.course.id'}.'.texengine'};
  219:     }
  220:     if (exists($env{'environment.texengine'})) {
  221: 	return $env{'environment.texengine'};
  222:     }
  223:     return 'tth';
  224: }
  225: 
  226: sub init_math_support {
  227:     my ($inherit_jsmath) = @_;
  228:     &init_tth();
  229:     &Apache::lontexconvert::jsMath_push();
  230:     if (lc(&tex_engine()) eq 'jsmath' ||
  231: 	($inherit_jsmath && &jsMath_state(-2))) {
  232: 	return &Apache::lontexconvert::jsMath_header();
  233:     }
  234:     return;
  235: }
  236: 
  237: sub mimetex_converted {
  238:     my $texstring=shift;
  239:     my $displaystyle=&displaystyle($texstring);
  240: 
  241:     &clean_out_math_mode($texstring);
  242: 
  243:     if ($displaystyle) {
  244: 	$$texstring='\\displaystyle \\Large '.$$texstring;
  245:     }
  246:     my $result='<img src="/cgi-bin/mimetex.cgi?'.&escape($$texstring).'" />';
  247:     if ($displaystyle) {
  248: 	$result='<center>'.$result.'</center>';
  249:     }
  250:     return $result;
  251: }
  252: 
  253: sub converted {
  254:     my ($string,$mode)=@_;
  255:     if ($mode eq '') { $mode = &tex_engine(); }
  256:     if ($mode =~ /tth/i) {
  257: 	return &tth_converted($string);
  258:     } elsif ($mode =~ /jsmath/i) {
  259: 	return &jsMath_converted($string);
  260:     } elsif ($mode =~ /mimetex/i) {
  261: 	return &mimetex_converted($string);
  262:     }
  263:     return &tth_converted($string);
  264: }
  265: 
  266: # ------------------------------------------------------------ Message display
  267: 
  268: sub to_convert {
  269:     my ($string) = @_;
  270:     $string=~s/\<br\s*\/?\>/ /gs;
  271: #    $string=~s/\s/ /gs;
  272:     $string=&HTML::Entities::decode($string);
  273:     return &converted(\$string);
  274: }
  275: 
  276: sub smiley {
  277:     my $expression=shift;
  278:     if ($env{'browser.imagesuppress'} eq 'on') { return $expression; }
  279:     my %smileys=('\:\-\)' => 'smiley',
  280: 		 '8\-\)'  => 'coolsmile',
  281: 		 '8\-(I|\|)'   => 'coolindiff',
  282: 		 ':\-(I|\|)'   => 'neutral',
  283: 		 '\:\-(o|O|\(\))' => 'shocked',
  284: 		 ':\-\('  => 'frowny',
  285: 		 '\;\-\)' => 'wink',
  286: 		 '\:\-P'  => 'baeh',
  287: 		 '\:\-(\\\|\\/)' => 'hrrm',
  288: 		 '\:\-D'  => 'bigsmile',
  289: 		 '\:\-C'  => 'angry',
  290: 		 '\:(\'|\`)\-\(' => 'cry',
  291: 		 '\:\-(X|\#)' => 'lipsrsealed',
  292: 		 '\:\-S' => 'huh');
  293:     my $iconpath=$Apache::lonnet::perlvar{'lonIconsURL'};
  294:     foreach my $smiley (keys(%smileys)) {
  295: 	$expression=~s/$smiley/\<img src="$iconpath\/$smileys{$smiley}.gif" \/\>/gs; 
  296:     }
  297:     return $expression;
  298: }
  299: 
  300: sub msgtexconverted {
  301:     my ($message,$email) = @_;
  302:     $errorstring='';
  303:     &init_tth();
  304:     my $outmessage='';
  305:     my $tex=0;
  306:     foreach my $fragment (split(/(?:\&lt\;|\<)\/*m\s*(?:\&gt\;|\>)/i,$message)) {
  307: 	if ($tex) {
  308: 	    if ($email) {
  309: 		$outmessage.='</pre><tt>'.&to_convert($fragment).'</tt><pre>';
  310: 		$tex=0;
  311: 	    } else {
  312: 		$outmessage.=&to_convert($fragment);
  313: 		$tex=0;
  314: 	    }
  315: 	} else {
  316:             $outmessage.=&smiley($fragment);
  317: 	    $tex=1;
  318: 	}
  319:     }
  320:     $message=$outmessage; $outmessage=''; $tex=0;
  321:     foreach my $fragment (split(/(?:\&lt\;|\<)\/*algebra\s*(?:\&gt\;|\>)/i,
  322: 				$message)) {
  323: 	if ($tex) {
  324: 	    if ($email) {
  325: 		$outmessage.='</pre><tt>'.&algebra($fragment,'web').'</tt><pre>';
  326: 		$tex=0;
  327: 	    } else {
  328: 		$outmessage.=&algebra($fragment,'web');
  329: 		$tex=0;
  330: 	    }
  331: 	} else {
  332:             $outmessage.=$fragment;
  333: 	    $tex=1;
  334: 	}
  335:     }
  336:     if (wantarray) {
  337: 	return ($outmessage,$errorstring);
  338:     } else {
  339: 	return $outmessage.$errorstring;
  340:     }
  341: }
  342: 
  343: sub algebra {
  344:     use AlgParser;
  345: 
  346:     my ($string,$target,$style)=@_;
  347:     my $parser = new AlgParserWithImplicitExpand;
  348:     $string=&prepare_algebra($string);
  349:     my $ret = $parser->parse($string);
  350:     my $result='['.&mt('Algebra unconverted due to previous errors').']';
  351:     if ( ref($ret) ) {
  352: 	#$parser->tostring();
  353: 	$parser->normalize();
  354: 	my $latex=$parser->tolatex();
  355: 	$latex=&postprocess_algebra($latex);
  356: 	if ($style eq 'display') {
  357: 	    $latex='$$'.$latex.'$$x';
  358: 	} else {
  359: 	    # style is 'inline'
  360: 	    $latex='\\ensuremath{'.$latex.'}';
  361: 	}
  362: 	if ($target eq 'web' || $target eq 'analyze') {
  363: 	    $result = &converted(\$latex);
  364: 	} else {
  365: 	    $result = $latex;
  366: 	}
  367:     } else {
  368: 	&Apache::lonxml::error($parser->{'htmlerror'});
  369:     }
  370: }
  371: 
  372: sub prepare_algebra {
  373:     my ($string)=@_;
  374: 
  375:     # makes the decision about what is a minus sign easier supposedly
  376:     $string =~ s/(\<\>|\<\=|\>\=[\=\>\<] *)-/$1 zeroplace -/g;
  377: 
  378:     return $string;
  379: }
  380: 
  381: sub postprocess_algebra {
  382:     my ($string)=@_;
  383:     
  384:     # moodle had these and I don't know why, ignoring them for now
  385:     # $string =~s/\\fun/ /g;
  386: 
  387:     # sqrt(3,4) means the 4 root of 3
  388:     $string =~s/\\sqrt{([^,]+),([^\}]+)}/\\sqrt[$2]{$1}/gs;
  389: 
  390:     # log(3,4) means the log base 4 of 3
  391:     $string =~s/\\log\\left\((.+?),(.+?)\\right\)/\\log_{$2}\\left($1\\right)/gs;
  392: 
  393:     # log(3,4) means the log base 4 of 3
  394:     $string =~s/\\((?:sin|cos|tan|sec|csc|cot)(?:h)?)\\left\((.+?),(.+?)\\right\)/\\$1^{$3}\\left($2\\right)/gs;
  395: 
  396:     # int(3,a,b) integral from a to b of 3
  397:     $string =~s/\\int\\left\((.+?),(.+?),(.+?)\\right\)/\\int_{$2}^{$3}\\left($1\\right)/gs;
  398: 
  399:     # int( ... dx) -> ...
  400:     $string =~s/\\int\\left\((.+?)d[a-z]\\right\)/$1/gs;
  401: 
  402:     # 
  403:     $string =~s/\\lim\\left\((.+?),(.+?),(.+?)\\right\)/\\lim_{$2\\to $3}$1/gs;
  404:     return $string;
  405: }
  406: 1;
  407: __END__
  408: 
  409: 
  410: 
  411: 
  412: 
  413: 
  414: 

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