<?php
/*
 * Manlinks plugin: convert manpage descriptions to links to the manpages.
 */

if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'syntax.php');

class syntax_plugin_manlink extends DokuWiki_Syntax_Plugin {

	function getType() { return 'substition'; }
	function getPType() { return 'normal'; }
	function getSort() { return 361; }

	function connectTo($mode) {
		$this->Lexer->addSpecialPattern(
			'\!?[a-zA-Z0-9_.+\[\]-]*\([0-9]\)',
			$mode,
			'plugin_manlink');
	}

	function handle($match, $state, $pos, Doku_Handler $handler){
		if ($state != DOKU_LEXER_SPECIAL)
			return false;

		if (substr($match, 0, 1) == "!") {
			$handler->_addCall('cdata', array(substr($match, 1)), $pos);
			return true;
		}

		$mantarget = $this->getconf('mantarget');
		$manpage = preg_replace('/^([a-zA-Z0-9_+\[\].-]*)\(([0-9])\)$/', '\1', $match);
		$section = preg_replace('/^([a-zA-Z0-9_+\[\].-]*)\(([0-9])\)$/', '\2', $match);

		if ($mantarget == 'NetBSD')
			$target = 'http://mdoc.su/n/'.$manpage.'.'.$section;
		elseif ($mantarget == 'FreeBSD')
			$target = 'http://mdoc.su/f/'.$manpage.'.'.$section;
		elseif ($mantarget == 'OpenBSD')
			$target = 'http://mdoc.su/o/'.$manpage.'.'.$section;
		elseif ($mantarget == 'DragonFlyBSD')
			$target = 'http://mdoc.su/d/'.$manpage.'.'.$section;

		$handler->_addCall('externallink', array($target, $match), $pos);
		return true;
	}

	function render($format, Doku_Renderer $renderer, $data) {
		return true;
	}
}

?>
