<?php if (!defined('PmWiki')) exit();
/**
  Formula - Lightweight rendering of mathematical formulas for PmWiki
  Based on the MimeTex recipe, copyright 2004-2007 Patrick R. Michaud
  
  Written by Petko Yotov 2011-2022    www.pmwiki.org/Petko
    
  This text is written for PmWiki; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published
  by the Free Software Foundation; either version 3 of the License, or
  (at your option) any later version. See pmwiki.php for full details
  and lack of warranty.
*/
$RecipeInfo['Formula']['Version'] = '20220104';

SDVA($CustomSyntax, array(
  'Formula' => '<ws0  
    =directive>attr>keyword>*meta_nobg 
    /(\{\$)([\s\S]*?)(\$\})/g 
    /#[#a-f\d]+/i   /\\\\[a-z]+/gi   /[{}$&;]+|\\\\[^\s\w]/g',
));

SDV($FormulaUrl,"https://chart.googleapis.com/chart?cht=tx&chl=");
SDV($FormulaTextColor, "000000");
SDV($FormulaBgColor, "ffffff");

Markup('{$', 'directives', '/\\{\\$(.*?)\\$\\}/', "FmtFormula");

SDV($GUIButtons['math'],array(1000, '{$ ', ' $}', '\\\\sqrt{n}', 
  '$GUIButtonDirUrlFmt/math.gif"$[Math formula (TeX)]"'));

function FmtFormula($m) {
  global $FormulaBgColor, $FormulaTextColor, $FormulaUrl;
  $text = trim($m[1]);

  $F = $FormulaTextColor; $B = $FormulaBgColor;
  $crx = '/^#([0-9a-f]{1,8})?(#([0-9a-f]{1,8}))? /';
  if(preg_match($crx, $text, $m)) {
    $text = trim(preg_replace($crx, '', $text));
    if($m[1]>'') $F = FormulaColors($m[1]);
    if(@$m[3]>'') $B = FormulaColors($m[3]);
  }

  $r = array('/\\s+([^\\w\\s\\\\]|\\\\\\w)/'=>'$1', '/([^\\w\\s\\\\])\\s+/'=>'$1', 
    '/&lt;/'=>'<', '/&gt;/'=>'>', '/&amp;/'=>'&', '/\\s{2,}/'=>' ');

  $u = urlencode(preg_replace(array_keys($r), array_values($r), $text));
  $a = str_replace("'","&#39;",$text);
  $fc = ($F=="000000")? '' : "&chco=$F";
  $bc = ($B=="ffffff")? '' : "&chf=bg,s,$B";
  return Keep("<img class='formula' src='$FormulaUrl$u$bc$fc' alt='$a' title='$a'/>");
}

function FormulaColors($c) {
  switch(strlen($c)) {
    case 6: case 8: return $c;
    case 7: return $c.$c[6];
    case 5: return $c.$c[4];
    case 4: return $c[0].$c[0].$c[1].$c[1].$c[2].$c[2].$c[3].$c[3];
    case 3: return $c[0].$c[0].$c[1].$c[1].$c[2].$c[2];
    case 2: return str_repeat($c, 3);
    case 1: return str_repeat($c, 6);
  }
}