File:
[LON-CAPA] /
loncom /
xml /
lontexconvert.pm
Revision
1.93:
download - view:
text,
annotated -
select for diffs
Thu Dec 4 19:53:53 2008 UTC (15 years, 6 months ago) by
riegler
Branches:
MAIN
CVS tags:
HEAD
added call to mimetex_valign which destills the vertical alignment shift needed to vertically align mimetex-formula-images.
Note that two calls are needed to mimetex.cgi.
The first one (within mimetex_align) has the only purpose to strip the needed value from the HTTP header field. The second call gets the actual image.
According to
http://forkosh.com/mimetex.html
this currently seems to be the only way to do it.
Note, however, that the double call is not that detrimental w.r.t. to performance as mimetex on loncapa is configured such that images (and vertical alignment values) are cached.
1: # The LearningOnline Network with CAPA
2: # TeX Conversion Module
3: #
4: # $Id: lontexconvert.pm,v 1.93 2008/12/04 19:53:53 riegler 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: use LWP::UserAgent;
51:
52:
53: # ====================================================================== Header
54:
55: sub init_tth {
56: my $options=$env{'course.'.$env{'request.course.id'}.'.tthoptions'};
57: if ($options =~ /\S/) {
58: $options = ' '.$options;
59: } else {
60: undef($options);
61: }
62: if ($env{'browser.mathml'}) {
63: &tth::ttminit();
64: if ($env{'browser.unicode'}) {
65: &tth::ttmoptions('-L -u1'.$options);
66: } else {
67: &tth::ttmoptions('-L -u0'.$options);
68: }
69: } else {
70: &tth::tthinit();
71: if ($env{'browser.unicode'}) {
72: &tth::tthoptions('-L -u1'.$options);
73: } else {
74: &tth::tthoptions('-L -u0'.$options);
75: }
76: }
77: }
78:
79: # ================================================================== Conversion
80:
81: $Apache::lontexconvert::messedup=0;
82:
83:
84: sub convert_real {
85: my ($texstring)=@_;
86: my ($xmlstring,$errorstring);
87: local $SIG{SEGV}=sub { $Apache::lontexconvert::messedup=1; die; };
88: local $SIG{ALRM}=sub {
89: &Apache::lonnet::logthis("ALRM");
90: $xmlstring='['.&mt("TeX unconverted due to errors").']';
91: $Apache::lontexconvert::messedup=1;
92: die &mt("TeX unconverted due to errors");
93: };
94: &Apache::lonxml::start_alarm();
95: if ($env{'browser.mathml'}) {
96: $xmlstring=&tth::ttm($$texstring);
97: $xmlstring=~s/\<math\>/\<math xmlns=\"\&mathns\;\"\>/g;
98: $xmlstring=~s/\<br\>/\<br\/\>/g;
99: $xmlstring=~s/\<p\>/\<p\>\<\/p\>/g;
100: $errorstring.=&tth::ttmerror();
101: } else {
102: $xmlstring=&tth::tth($$texstring);
103: $errorstring.=&tth::ttherror();
104: $xmlstring=~s-</font(\s*)>-</font>-g;
105: }
106: $xmlstring=~s/^\s*\<br clear\=\"all\"/\<br/s;
107: $xmlstring=~s/^\s*//;
108: $xmlstring=~s/\s*$//;
109: #
110: # \rightleftharpoons is not converted by tth but maps
111: # reasonably well to ⇔. If we get many more of these,
112: # we're going to need to have a translation sub.
113: #
114: my $lrharpoon = pack("U", 0x21cc);
115: $xmlstring=~s/\\rightleftharpoons/$lrharpoon/g;
116:
117: &Apache::lonxml::end_alarm();
118: return ($xmlstring,$errorstring);
119: }
120:
121: sub tth_converted {
122: my $texstring=shift;
123: my $xmlstring='['.&mt('UNDISPLAYABLE').']';
124: if ($Apache::lontexconvert::messedup) {
125: return '['.&mt('TeX unconverted due to previous errors').']';
126: }
127: $$texstring ='\\documentstyle{article}'.$$texstring;
128:
129: eval(<<'ENDCONV');
130: ($xmlstring,$errorstring)=&convert_real($texstring)
131: ENDCONV
132: if ($@) {
133: $errorstring.=&mt("Evaluation Error: ").$@;
134: $Apache::lontexconvert::messedup=1;
135: }
136: if ($Apache::lontexconvert::messedup || &tth::tthmessedup() ||
137: $errorstring) {
138: &Apache::lonnet::logthis("Trying to kill myself");
139: $Apache::lontexconvert::messedup=1;
140: if (ref($Apache::lonxml::request)) {
141: $Apache::lonxml::request->child_terminate();
142: } else {
143: my $request;
144: eval { $request=Apache->request; };
145: if (!$request) {
146: eval { $request=Apache2::RequestUtil->request; };
147: }
148: if ($request) {
149: $request->child_terminate();
150: } else {
151: &Apache::lonnet::logthis("Unable to find a request to do child_terminate on");
152: }
153: }
154: }
155: return $xmlstring;
156: }
157:
158: sub clean_out_math_mode {
159: my ($texstring)=@_;
160: $$texstring=~s/(?<!\\)\$//g;
161: $$texstring=~s/\\[\)\(\]\[]//g;
162: $$texstring=~s/\\ensuremath//g;
163: return '';
164: }
165:
166: sub displaystyle {
167: my ($texstring)=@_;
168: #has a $$ or \[ or \displaystyle in it, guessinng it's display mode
169: if ($$texstring=~/[^\\]\$\$/ ||
170: $$texstring=~/\\\[/ ||
171: $$texstring=~/\\displaystyle/) { return 1; }
172: return 0;
173: }
174:
175: sub jsMath_converted {
176: my $texstring=shift;
177: my $tag='span';
178: if (&displaystyle($texstring)) { $tag='div'; }
179: &clean_out_math_mode($texstring);
180: return &jsMath_header().
181: '<'.$tag.' class="math">'.$$texstring.'</'.$tag.'>';
182: }
183:
184: {
185: my @jsMath_sent_header;
186: sub jsMath_reset {
187: undef(@jsMath_sent_header);
188: }
189: sub jsMath_push {
190: push(@jsMath_sent_header,0);
191: }
192: sub jsMath_header {
193: if (!@jsMath_sent_header) {
194: &Apache::lonnet::logthis("mismatched calls of jsMath_header and jsMath_process");
195: return '';
196: }
197: return '' if $jsMath_sent_header[-1];
198: $jsMath_sent_header[-1]=1;
199: return
200: '<script type="text/javascript">
201: function NoFontMessage () {}
202: jsMath = {Parser: {prototype: {environments: {\'eqnarray*\' :[\'Array\',null,null,\'rcl\',[5/18,5/18],3,\'D\']}}}};
203: </script>'."\n".
204: '<script type="text/javascript" src="/adm/jsMath/jsMath.js"></script>'."\n";
205: }
206: sub jsMath_process {
207: my $state = pop(@jsMath_sent_header);
208: return '' if !$state;
209: return "\n".
210: '<script type="text/javascript">jsMath.Process()</script>'."\n";
211: }
212: sub jsMath_state {
213: my ($level) = @_;
214: return $jsMath_sent_header[$level];
215: }
216: }
217:
218: sub tex_engine {
219: if (exists($env{'form.texengine'})) {
220: if ($env{'form.texengine'} ne '') {
221: return $env{'form.texengine'};
222: }
223: }
224: if ($env{'request.course.id'}
225: && exists($env{'course.'.$env{'request.course.id'}.'.texengine'})) {
226: return $env{'course.'.$env{'request.course.id'}.'.texengine'};
227: }
228: if (exists($env{'environment.texengine'})) {
229: return $env{'environment.texengine'};
230: }
231: return 'tth';
232: }
233:
234: sub init_math_support {
235: my ($inherit_jsmath) = @_;
236: &init_tth();
237: &Apache::lontexconvert::jsMath_push();
238: if (lc(&tex_engine()) eq 'jsmath' ||
239: ($inherit_jsmath && &jsMath_state(-2))) {
240: return &Apache::lontexconvert::jsMath_header();
241: }
242: return;
243: }
244:
245: sub mimetex_valign {
246: my ($texstring)=@_;
247: my $ua = LWP::UserAgent->new; #from the perldoc of LWP::UserAgent
248: $ua->timeout(10);
249: $ua->env_proxy;
250: #header without imagedata saved to response:
251: my $response = $ua->head('http://localhost.localdomain/cgi-bin/mimetex.cgi?'.$texstring);
252: if ($response->is_success) {
253: #get the valign-value:
254: return($response->headers->{'vertical-align'});}
255: else {
256: return(0); #if (error) than continue without valign
257: }
258: }
259:
260: sub mimetex_converted {
261: my $texstring=shift;
262: my $displaystyle=&displaystyle($texstring);
263:
264: &clean_out_math_mode($texstring);
265:
266: if ($displaystyle) {
267: $$texstring='\\displaystyle \\Large '.$$texstring;
268: }
269:
270: my $result='<img src="/cgi-bin/mimetex.cgi?'.&escape($$texstring).'" style="vertical-align:'.&mimetex_valign($$texstring).'px" alt="$'.$$texstring.'$" />';
271: if ($displaystyle) {
272: $result='<center>'.$result.'</center>';
273: }
274: return $result;
275: }
276:
277: sub converted {
278: my ($string,$mode)=@_;
279: if ($mode eq '') { $mode = &tex_engine(); }
280: if ($mode =~ /tth/i) {
281: return &tth_converted($string);
282: } elsif ($mode =~ /jsmath/i) {
283: return &jsMath_converted($string);
284: } elsif ($mode =~ /mimetex/i) {
285: return &mimetex_converted($string);
286: }
287: return &tth_converted($string);
288: }
289:
290: # ------------------------------------------------------------ Message display
291:
292: sub to_convert {
293: my ($string) = @_;
294: $string=~s/\<br\s*\/?\>/ /gs;
295: # $string=~s/\s/ /gs;
296: $string=&HTML::Entities::decode($string);
297: return &converted(\$string);
298: }
299:
300: sub smiley {
301: my $expression=shift;
302: if ($env{'browser.imagesuppress'} eq 'on') { return $expression; }
303: my %smileys=('\:\-\)' => 'smiley',
304: '8\-\)' => 'coolsmile',
305: '8\-(I|\|)' => 'coolindiff',
306: ':\-(I|\|)' => 'neutral',
307: '\:\-(o|O|\(\))' => 'shocked',
308: ':\-\(' => 'frowny',
309: '\;\-\)' => 'wink',
310: '\:\-P' => 'baeh',
311: '\:\-(\\\|\\/)' => 'hrrm',
312: '\:\-D' => 'bigsmile',
313: '\:\-C' => 'angry',
314: '\:(\'|\`)\-\(' => 'cry',
315: '\:\-(X|\#)' => 'lipsrsealed',
316: '\:\-S' => 'huh');
317: my $iconpath=$Apache::lonnet::perlvar{'lonIconsURL'};
318: foreach my $smiley (keys(%smileys)) {
319: $expression=~s/$smiley/\<img src="$iconpath\/$smileys{$smiley}.gif" \/\>/gs;
320: }
321: return $expression;
322: }
323:
324: sub msgtexconverted {
325: my ($message,$email) = @_;
326: $errorstring='';
327: &init_tth();
328: my $outmessage='';
329: my $tex=0;
330: foreach my $fragment (split(/(?:\<\;|\<)\/*m\s*(?:\>\;|\>)/i,$message)) {
331: if ($tex) {
332: if ($email) {
333: $outmessage.='</pre><tt>'.&to_convert($fragment).'</tt><pre>';
334: $tex=0;
335: } else {
336: $outmessage.=&to_convert($fragment);
337: $tex=0;
338: }
339: } else {
340: $outmessage.=&smiley($fragment);
341: $tex=1;
342: }
343: }
344: $message=$outmessage; $outmessage=''; $tex=0;
345: foreach my $fragment (split(/(?:\<\;|\<)\/*algebra\s*(?:\>\;|\>)/i,
346: $message)) {
347: if ($tex) {
348: if ($email) {
349: $outmessage.='</pre><tt>'.&algebra($fragment,'web').'</tt><pre>';
350: $tex=0;
351: } else {
352: $outmessage.=&algebra($fragment,'web');
353: $tex=0;
354: }
355: } else {
356: $outmessage.=$fragment;
357: $tex=1;
358: }
359: }
360: if (wantarray) {
361: return ($outmessage,$errorstring);
362: } else {
363: return $outmessage.$errorstring;
364: }
365: }
366:
367: sub algebra {
368: use AlgParser;
369:
370: my ($string,$target,$style,$parstack,$safeeval)=@_;
371: my $parser = new AlgParserWithImplicitExpand;
372: $string=&prepare_algebra($string);
373: my $ret = $parser->parse($string);
374: my $result='['.&mt('Algebra unconverted due to previous errors').']';
375: if ( ref($ret) ) {
376: #$parser->tostring();
377: $parser->normalize();
378: my $latex=$parser->tolatex();
379: $latex=&postprocess_algebra($latex);
380: if ($style eq 'display') {
381: $latex='$$'.$latex.'$$x';
382: } else {
383: # style is 'inline'
384: $latex='\\ensuremath{'.$latex.'}';
385: }
386: if ($target eq 'web' || $target eq 'analyze') {
387: my $display=&Apache::lonxml::get_param('display',$parstack,$safeeval);
388: $result = &converted(\$latex,$display);
389: # $result = &converted(\$latex);
390: } else {
391: $result = $latex;
392: }
393: } else {
394: &Apache::lonxml::error($parser->{'htmlerror'});
395: }
396: }
397:
398: sub prepare_algebra {
399: my ($string)=@_;
400:
401: # makes the decision about what is a minus sign easier supposedly
402: $string =~ s/(\<\>|\<\=|\>\=[\=\>\<] *)-/$1 zeroplace -/g;
403:
404: return $string;
405: }
406:
407: sub postprocess_algebra {
408: my ($string)=@_;
409:
410: # moodle had these and I don't know why, ignoring them for now
411: # $string =~s/\\fun/ /g;
412:
413: # sqrt(3,4) means the 4 root of 3
414: $string =~s/\\sqrt{([^,]+),([^\}]+)}/\\sqrt[$2]{$1}/gs;
415:
416: # log(3,4) means the log base 4 of 3
417: $string =~s/\\log\\left\((.+?),(.+?)\\right\)/\\log_{$2}\\left($1\\right)/gs;
418:
419: # log(3,4) means the log base 4 of 3
420: $string =~s/\\((?:sin|cos|tan|sec|csc|cot)(?:h)?)\\left\((.+?),(.+?)\\right\)/\\$1^{$3}\\left($2\\right)/gs;
421:
422: # int(3,a,b) integral from a to b of 3
423: $string =~s/\\int\\left\((.+?),(.+?),(.+?)\\right\)/\\int_{$2}^{$3}\\left($1\\right)/gs;
424:
425: # int( ... dx) -> ...
426: $string =~s/\\int\\left\((.+?)d[a-z]\\right\)/$1/gs;
427:
428: #
429: $string =~s/\\lim\\left\((.+?),(.+?),(.+?)\\right\)/\\lim_{$2\\to $3}$1/gs;
430: return $string;
431: }
432: 1;
433: __END__
434:
435:
436: =pod
437:
438: =head1 NAME
439:
440: Apache::lontexconvert;
441:
442: =head1 SYNOPSIS
443:
444: Access to tth/ttm
445:
446: This is part of the LearningOnline Network with CAPA project
447: described at http://www.lon-capa.org.
448:
449:
450: =head1 SUBROUTINES
451:
452: =over
453:
454: =item init_tth()
455:
456: Header
457:
458: =item convert_real()
459:
460: we need this routine because &converted can get called from inside
461: of the safespace (through &xmlparse('<m>stuff</m>') which doesn't
462: allow the opcode for alarm, so we need to compile this before we get
463: into the safe space since opcode checks only occur at compile time
464:
465: =item tth_converted()
466:
467:
468: =item clean_out_math_mode()
469:
470:
471: =item displaystyle()
472:
473:
474: =item jsMath_converted()
475:
476:
477: =item tex_engine()
478:
479:
480: =item init_math_support()
481:
482:
483: =item mimetex_converted()
484:
485:
486: =item converted()
487:
488:
489: =item to_convert()
490:
491: message display
492:
493: =item smiley()
494:
495: ???
496:
497: =item msgtexconverted()
498:
499: =item algebra()
500:
501: =item prepare_algebra()
502:
503: =item postprocess_algebra()
504:
505: =back
506:
507: =cut
508:
509:
510:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>