<?php if (!defined('PmWiki')) exit();
/*  Copyright 2010 Hans Bracker.
    This file is tab2table.php; 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 2 of the License, or
    (at your option) any later version. 

    This script makes it possible to import and convert tabbed tables
    from other applications (as from spreadsheet, word, rtf applications) 
    into PmWiki simple tables.  
    Highlight and copy the table cells to the clipboard, and paste into 
    the edit box of a wiki page. Then click the 'Table' GUI button to
    convert into PmWiki simple table markup.
    Numeric cells are automatically right-aligned, while other cells are left-aligned.  
    Lines in the edit window which do not contain tab characters are ignored.
*/

$RecipeInfo['ImportTabTable']['Version'] = '2010-04-14';

#tabtable style
$HTMLStylesFmt['tabtable'] = " 
	.tabtable td { vertical-align:top; border-bottom:1px dotted grey; } 
	#wikiedit a img { margin-bottom: 5px; } 
	";

#add gui button to run function
SDV($EnableGUIButtons, 1);
SDV($GUIButtons['tabtable'], array(1100, '', '', '',
  "<input type='image' name='tab2table' class='imgbutton' src='\$GUIButtonDirUrlFmt/table.gif' title='\$[Convert tabs to table]' />"));


#add edit function if tabtable GUI-button image is clicked
if (@$_POST['tab2table_x']) 
	array_unshift($EditFunctions, 'ImportTabTable');
else return;

function ImportTabTable($pagename,&$page,&$new) {
	if (!@$_POST['tab2table_x']) return;
	$text = $new['text'];
	$pos = strpos($text, 'TABLE');
	$before =  substr($text, 0, $pos);
	$after = '';
	$table =  (strstr($text,'TABLE')) ? substr(strstr($text, 'TABLE'),6) : $text;
	if (preg_match('/\\nEND/m', $table, $m, PREG_OFFSET_CAPTURE)) {
		$end = $m[0][1] + 4;
		$after = substr($table, $end);
		$table = substr($table, 0, $m[0][1]);
	}
	$rows = explode("\n",$table);
	$flag = 0;
	foreach($rows as $i=>$row) {
		if (!preg_match('/\\t/',$row)) continue;
		$row = preg_replace("/\\t/", " ||", $row);
		$row = preg_replace("/^([^|].*?)/", "||$1", $row); 
		$row = preg_replace("/(.*?[^|])$/", "$1 ||", $row); 
		if (preg_match_all("/\\|\\|((-?\\+?[\\d,]+\\.?\\d*)\\s+(?=\\|\\|))/", $row, $m ))
			foreach($m[0] as $j=>$d)
				$row = str_replace($d, "|| ".$m[2][$j], $row);
		if ($flag==1)	$rows[$i] = $row;
		else { $rows[$i] = "||class=tabtable\n".$row; $flag = 1; }
	}
	$rows = implode("\n",$rows);
	$new['text'] = $before.$rows.$after;
	$_POST['preview'] = 1;
}