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

/*  === Grep ===
 *  Copyright 2010 Eemeli Aro <eemeli@gmail.com>
 *
 *  Use regular expressions to control what to include from a page
 *
 *  For more information, please see the online documentation at
 *  	http://www.pmwiki.org/wiki/Cookbook/Grep
 *
 *
 *  This script is free software: 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.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

$RecipeInfo['Grep']['Version'] = '2010-06-17';

Markup('grep', '<include',
	'/\\(:grep\\s+(\\S.*?):\\)/ei',
	"PRR(GrepText(\$pagename, PSS('$1')))");

function GrepText($pagename, $args) {
	global $KeepToken;
	$opt = ParseArgs($args);
	if (empty($opt[''])) { $args = "$pagename $args"; $opt['match'] = 1; }
	else if ($opt[''][0][0] == '#') $args = $pagename.ltrim($args);

	$src = IncludeText($pagename, $args);
	if (!$src || ($src[0] == $KeepToken)) return $src;
	if (empty($opt['pat'])) return $src;

	$mod = isset($opt['mod']) ? preg_replace('/[^imsuxADSUXJ]/', '', $opt['mod']) : 'm'; ## note: 'e' not allowed
	$limit = empty($opt['limit']) ? -1 : intval($opt['limit']);
	$pat = '/'.str_replace('/', '\/', $opt['pat'])."/$mod";
	$repl = empty($opt['repl']) ? '' : $opt['repl'];
	list($pat, $repl) = preg_replace(
		array('/\\\n/', '/\\\t/', '/{:(.*?):}/'),
		array(   "\n",     "\t",      '(:$1:)'),
		array($pat, $repl));

	$out = '';
	if (empty($opt['match'])) $out = preg_replace($pat, $repl, $src, $limit);
	else if (preg_match_all($pat, $src, $matches)) {
		if (!$repl) $repl = "$0\n";
		foreach ($matches[0] as $m) {
			$out .= preg_replace($pat, $repl, $m);
			if (--$limit == 0) break;
		}
	}
	return PVS($out);
}