<?php
/**
 @brief   DokuPlusPlus Plugin: inserts automatic numbering where required
 @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
 @author  Luis Machuca Bezzaza
 */
// must be run within Dokuwiki
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_dokupp extends DokuWiki_Syntax_Plugin {

    function getType() { return 'substition'; }
    function getSort() { return 49; }
    function connectTo($mode) { 
        // setup formatting
        $this->Lexer->addSpecialPattern('@#:%[0-9]*u@', $mode, 'plugin_dokupp'); 
        // select counter
        $this->Lexer->addSpecialPattern('@#[a-z]*=\d*@', $mode, 'plugin_dokupp');
        // use current counter
        $this->Lexer->addSpecialPattern('@#@', $mode, 'plugin_dokupp');
    }

    function handle($match, $state, $pos, &$handler) {
        $match = substr($match, 1, -1); // strip markup
        static $format= '%u';
        if ('#' === $match) return array('N', $format); //< use and increment current counter
        else if (preg_match('/#[a-z]*=\d*/', $match)) { //< select counter, set amount
            //$match= explode('=', $match);
            return explode('=', $match);
        }
        else {
            list ($match, $format) = explode(':', $match);
            return array(null, $format);
        }
        return null; // we shouldn't reach here!
    }            

    function render($mode, &$renderer, $data) {
        global $ID;
        global $INFO;
        global $conf;
        static $N= array('_0' => 0);
        static $S= '';
        list ($match, $arg) = $data;
        if ('xhtml' === $mode) {
            if ('N' === $match) {
                // usage of counter
                $renderer->doc .= '<span class="dokupp-counter">';
                $renderer->doc .=sprintf($arg, $N[$S]);
                $renderer->doc .= '</span>';
                ++$N[$S];
            } else if ($match === null) { 
                // nothing to do, taken care by $format in handler
            } else {
                // $match has something, should be the name of a counter, $data has the amount
                if ($match==='') $match= '_0'; // set default counter if no name given
                if ($arg==='') $arg= $N[$match]; // preserve amount if no amount given
                $S= $match;
                $N[$S] = intval($arg); 
            }
            return true;
        }
        return false;

    }
}
