<?php if (!defined('PmWiki')) exit();

$RecipeInfo['tocportion']['Version'] = '2006-12-05';

/*
 *  Author: Aras 'NeARAZ' Pranckevicius
 *  Date: 2006-12-05
 */

global $TocPortionDefaultPage;
SDV($TocPortionDefaultPage,'');

Markup('(:tocportion:)','_begin', '/\(:tocportion(?:\s+(.*?))?:\)/e',
      "tocportion_process(\$pagename, '\$1')");

/*
   Get the page to which the toc refers and extract toc portion for the
   current page.
*/
function tocportion_process($curpage, $tocpage)
{
	global $TocPortionDefaultPage;
	if( $tocpage == '' )
	{
		$tocpage = $TocPortionDefaultPage;
		if( $tocpage == '' )
			return "!!%red%'''tocportion error''': toc page not given%%";
	}
	
	// get TOC page and split into lines
	$toctext = IncludeText($curpage, $tocpage);
	$toclines = explode("\n", $toctext);
	
	$curpage = str_replace('.', '/', $curpage);
	
	$res = '';
	$inside = false;
	$thisdepth = 0;
	$found = false;
	foreach( (array) $toclines as $line )
	{
		if( preg_match('/^(\*+)\s*\[\[(.+?)\]\]/', $line, $m) )
		{
			// found a line that looks like a toc link
			$depth = strlen($m[1]);
			if( $inside )
			{
				if( $depth <= $thisdepth )					
					$inside = false;
				else
					$res .= substr($line, $thisdepth) . "\n";
			}
			else
			{
				$p = str_replace(' ', '', $m[2]);
				if( $p == $curpage ) {
					$inside = true;
					$thisdepth = $depth;
					$found = true;
				}
			}
		} else {
			$inside = false;
		}
		$res .= "\n";
	}
	if( !$found )
		$res .= "!!%red%'''tocportion error''': toc for $curpage not found in '$tocpage'%%";
		
	return $res;
}