File:  [LON-CAPA] / loncom / xml / lontexconvert.pm
Revision 1.77: download - view: text, annotated - select for diffs
Wed Sep 6 19:43:22 2006 UTC (17 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- AlgParser.pm 1.15 no longer produces extra () in the bottom of a frac (BUG# 4695)

    1: # The LearningOnline Network with CAPA
    2: # TeX Conversion Module
    3: #
    4: # $Id: lontexconvert.pm,v 1.77 2006/09/06 19:43:22 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: 	return '' if $jsMath_sent_header[-1];
  188: 	$jsMath_sent_header[-1]=1;
  189: 	return
  190:             '<script type="text/javascript">
  191:                      function NoFontMessage () {}
  192:                    </script>'."\n".
  193: 	    '<script type="text/javascript" src="/adm/jsMath/jsMath.js"></script>'."\n";
  194:     }
  195:     sub jsMath_process {
  196: 	my $state = pop(@jsMath_sent_header);
  197: 	return '' if !$state;
  198: 	return '<script type="text/javascript">jsMath.Process()</script>';
  199:     }
  200: }
  201: 
  202: sub init_math_support {
  203:     &init_tth();
  204:     &Apache::lontexconvert::jsMath_push();
  205:     if ($env{'environment.texengine'} eq 'jsMath' ||
  206: 	$env{'form.texengine'}        eq 'jsMath' ) {
  207: 	return &Apache::lontexconvert::jsMath_header();
  208:     }
  209:     return;
  210: }
  211: 
  212: sub mimetex_converted {
  213:     my $texstring=shift;
  214:     my $displaystyle=&displaystyle($texstring);
  215: 
  216:     &clean_out_math_mode($texstring);
  217: 
  218:     if ($displaystyle) {
  219: 	$$texstring='\\displaystyle \\Large '.$$texstring;
  220:     }
  221:     my $result='<img src="/cgi-bin/mimetex.cgi?'.&escape($$texstring).'" />';
  222:     if ($displaystyle) {
  223: 	$result='<center>'.$result.'</center>';
  224:     }
  225:     return $result;
  226: }
  227: 
  228: sub converted {
  229:     my ($string,$mode)=@_;
  230:     if ($mode eq '') { $mode=$env{'environment.texengine'}; }
  231:     if ($mode =~ /tth/i) {
  232: 	return &tth_converted($string);
  233:     } elsif ($mode =~ /jsmath/i) {
  234: 	return &jsMath_converted($string);
  235:     } elsif ($mode =~ /mimetex/i) {
  236: 	return &mimetex_converted($string);
  237:     }
  238:     return &tth_converted($string);
  239: }
  240: 
  241: # ------------------------------------------------------------ Message display
  242: 
  243: sub to_convert {
  244:     my ($string) = @_;
  245:     $string=~s/\<br\s*\/?\>/ /gs;
  246: #    $string=~s/\s/ /gs;
  247:     $string=&HTML::Entities::decode($string);
  248:     return &converted(\$string);
  249: }
  250: 
  251: sub smiley {
  252:     my $expression=shift;
  253:     if ($env{'browser.imagesuppress'} eq 'on') { return $expression; }
  254:     my %smileys=('\:\-\)' => 'smiley',
  255: 		 '8\-\)'  => 'coolsmile',
  256: 		 '8\-(I|\|)'   => 'coolindiff',
  257: 		 ':\-(I|\|)'   => 'neutral',
  258: 		 '\:\-(o|O|\(\))' => 'shocked',
  259: 		 ':\-\('  => 'frowny',
  260: 		 '\;\-\)' => 'wink',
  261: 		 '\:\-P'  => 'baeh',
  262: 		 '\:\-(\\\|\\/)' => 'hrrm',
  263: 		 '\:\-D'  => 'bigsmile',
  264: 		 '\:\-C'  => 'angry',
  265: 		 '\:(\'|\`)\-\(' => 'cry',
  266: 		 '\:\-(X|\#)' => 'lipsrsealed',
  267: 		 '\:\-S' => 'huh');
  268:     my $iconpath=$Apache::lonnet::perlvar{'lonIconsURL'};
  269:     foreach (keys %smileys) {
  270: 	$expression=~s/$_/\<img src="$iconpath\/$smileys{$_}.gif" \/\>/gs; 
  271:     }
  272:     return $expression;
  273: }
  274: 
  275: sub msgtexconverted {
  276:     my ($message,$email) = @_;
  277:     $errorstring='';
  278:     &init_tth();
  279:     my $outmessage='';
  280:     my $tex=0;
  281:     foreach (split(/(?:\&lt\;|\<)\/*m\s*(?:\&gt\;|\>)/i,$message)) {
  282: 	if ($tex) {
  283: 	    if ($email) {
  284: 		$outmessage.='</pre><tt>'.&to_convert($_).'</tt><pre>'; $tex=0;
  285: 	    } else {
  286: 		$outmessage.=&to_convert($_); $tex=0;
  287: 	    }
  288: 	} else {
  289:             $outmessage.=&smiley($_); $tex=1;
  290: 	}
  291:     }
  292:     $message=$outmessage; $outmessage=''; $tex=0;
  293:     foreach (split(/(?:\&lt\;|\<)\/*algebra\s*(?:\&gt\;|\>)/i,$message)) {
  294: 	if ($tex) {
  295: 	    if ($email) {
  296: 		$outmessage.='</pre><tt>'.&algebra($_,'web').'</tt><pre>'; $tex=0;
  297: 	    } else {
  298: 		$outmessage.=&algebra($_,'web'); $tex=0;
  299: 	    }
  300: 	} else {
  301:             $outmessage.=$_; $tex=1;
  302: 	}
  303:     }
  304:     if (wantarray) {
  305: 	return ($outmessage,$errorstring);
  306:     } else {
  307: 	return $outmessage.$errorstring;
  308:     }
  309: }
  310: 
  311: sub algebra {
  312:     use AlgParser;
  313: 
  314:     my ($string,$target,$style)=@_;
  315:     my $parser = new AlgParserWithImplicitExpand;
  316:     $string=&prepare_algebra($string);
  317:     my $ret = $parser->parse($string);
  318:     my $result='['.&mt('Algebra unconverted due to previous errors').']';
  319:     if ( ref($ret) ) {
  320: 	#$parser->tostring();
  321: 	$parser->normalize();
  322: 	my $latex=$parser->tolatex();
  323: 	$latex=&postprocess_algebra($latex);
  324: 	if ($style eq 'display') {
  325: 	    $latex='$$'.$latex.'$$x';
  326: 	} else {
  327: 	    # style is 'inline'
  328: 	    $latex='\\ensuremath{'.$latex.'}';
  329: 	}
  330: 	if ($target eq 'web' || $target eq 'analyze') {
  331: 	    $result = &converted(\$latex);
  332: 	} else {
  333: 	    $result = $latex;
  334: 	}
  335:     } else {
  336: 	&Apache::lonxml::error($parser->{'htmlerror'});
  337:     }
  338: }
  339: 
  340: sub prepare_algebra {
  341:     my ($string)=@_;
  342: 
  343:     # makes the decision about what is a minus sign easier supposedly
  344:     $string =~ s/(\<\>|\<\=|\>\=[\=\>\<] *)-/$1 zeroplace -/g;
  345: 
  346:     return $string;
  347: }
  348: 
  349: sub postprocess_algebra {
  350:     my ($string)=@_;
  351:     
  352:     # moodle had these and I don't know why, ignoring them for now
  353:     # $string =~s/\\fun/ /g;
  354: 
  355:     # sqrt(3,4) means the 4 root of 3
  356:     $string =~s/\\sqrt{([^,]+),([^\}]+)}/\\sqrt[$2]{$1}/gs;
  357: 
  358:     # log(3,4) means the log base 4 of 3
  359:     $string =~s/\\log\\left\((.+?),(.+?)\\right\)/\\log_{$2}\\left($1\\right)/gs;
  360: 
  361:     # log(3,4) means the log base 4 of 3
  362:     $string =~s/\\((?:sin|cos|tan|sec|csc|cot)(?:h)?)\\left\((.+?),(.+?)\\right\)/\\$1^{$3}\\left($2\\right)/gs;
  363: 
  364:     # int(3,a,b) integral from a to b of 3
  365:     $string =~s/\\int\\left\((.+?),(.+?),(.+?)\\right\)/\\int_{$2}^{$3}\\left($1\\right)/gs;
  366: 
  367:     # int( ... dx) -> ...
  368:     $string =~s/\\int\\left\((.+?)d[a-z]\\right\)/$1/gs;
  369: 
  370:     # 
  371:     $string =~s/\\lim\\left\((.+?),(.+?),(.+?)\\right\)/\\lim_{$2\\to $3}$1/gs;
  372:     return $string;
  373: }
  374: 1;
  375: __END__
  376: 
  377: 
  378: 
  379: 
  380: 
  381: 
  382: 

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