[LON-CAPA-cvs] cvs: loncom /homework default_homework.lcpm

albertel lon-capa-cvs@mail.lon-capa.org
Fri, 19 Mar 2004 22:02:03 -0000


albertel		Fri Mar 19 17:02:03 2004 EDT

  Modified files:              
    /loncom/homework	default_homework.lcpm 
  Log:
  - New function &chemparse, typesets chemical formulas
  
  
Index: loncom/homework/default_homework.lcpm
diff -u loncom/homework/default_homework.lcpm:1.74 loncom/homework/default_homework.lcpm:1.75
--- loncom/homework/default_homework.lcpm:1.74	Tue Mar 16 14:47:47 2004
+++ loncom/homework/default_homework.lcpm	Fri Mar 19 17:02:03 2004
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA 
 # used by lonxml::xmlparse() as input variable $safeinit to Apache::run::run()
 #
-# $Id: default_homework.lcpm,v 1.74 2004/03/16 19:47:47 albertel Exp $
+# $Id: default_homework.lcpm,v 1.75 2004/03/19 22:02:03 albertel Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -485,11 +485,51 @@
     return $result;
 }
 
+sub chemparse {
+    my ($reaction) = @_;
+    my @tokens = split(/(\s\+|\->|<=>)/,$reaction);
+    my $formula = '';
+    foreach my $token (@tokens) {
+	if ($token eq '->' ) {
+	    $formula .= '<m>\ensuremath{\rightarrow}</m> ';
+	    next;
+	}
+	if ($token eq '<=>') {
+	    if ($external::target eq 'web' &&
+		&EXT('request.browser.unicode')) {
+		$formula .= '&#8660; ';
+	    } else {
+		$formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
+				 '&lt;=$gt; ');
+	    }
+	    next;
+	}
+	$token =~ /^\s*(\d*)(.*)/;
+	$formula .= $1 if ($1 > 1);  # stoichiometric coefficient
+	
+	my $molecule = $2;
+	# subscripts
+	$molecule =~ s|(?<=[a-zA-Z\[\s])(\d+)|<sub>$1</sub>|g;
+	# superscripts
+	$molecule =~ s|\^(\d*[+\-]*)|<sup>$1</sup>|g;
+	# strip whitespace
+	$molecule =~ s/\s*//g;
+	# forced space
+	$molecule =~ s/_/ /g;
+	$formula .= $molecule.'&nbsp;';
+    }
+    # get rid of trailing space
+    $formula =~ s/(\Q${nbsp}\E| )$//;
+    
+    return &xmlparse($formula);
+}
+
 sub prettyprint {
     my ($value,$fmt,$target)=@_;
     my $result;
     my $dollarmode;
     if (!$target) { $target = $external::target; }
+    if ($fmt =~ /chem/i) { return(&chemparse($value)); }
     if ($fmt =~ /^\$(.*)/) { $fmt=$1; $dollarmode=1; } 
     if ($fmt) { $value=sprintf('%.'.$fmt,$value); }
     if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {