naokij / dokuwiki-plugin-markdownextra

Parses PHP Markdown Extra blocks for dokuwiki with backlinks, header parser, toc support
Other
31 stars 27 forks source link

GeSHi support #14

Open benw01 opened 9 years ago

benw01 commented 9 years ago

In response to a question on https://www.dokuwiki.org/plugin:markdownextra, I had a crack at integrating GeSHi syntax highlighting.

Inside function _doFencedCodeBlocks_callback($matches) in markdown.php, I've removed

    $codeblock  = "<pre$pre_attr_str><code$code_attr_str>$codeblock</code></pre>";

and replaced it with:

    require_once(DOKU_INC.'inc/parserutils.php');
    $codeblock = p_xhtml_cached_geshi($codeblock, $classname);

The three ways I evaluated were:

        // original (gives default results, no highlighting)
        //$codeblock  = "<pre$pre_attr_str><code$code_attr_str>$codeblock</code></pre>";

        // taken from inc/parser/xhtml.php (looks good, but does not support extra classes after the code type)
        require_once(DOKU_INC.'inc/parserutils.php');
        $codeblock = p_xhtml_cached_geshi($codeblock, $classname);

        // taken from function p_xhtml_cached_geshi() in inc/parserutils.php. (No cache, looks bad.)
        /*   
        $geshi = new GeSHi($codeblock, $classname, DOKU_INC . 'inc/geshi');
        $geshi->set_encoding('utf-8');
        $geshi->enable_classes();
        $geshi->set_header_type(GESHI_HEADER_PRE);
        $geshi->set_link_target($conf['target']['extern']);

        // remove GeSHi's wrapper element (we'll replace it with our own later)
        // we need to use a GeSHi wrapper to avoid <BR> throughout the highlighted text
        $highlighted_code = trim(preg_replace('!^<pre[^>]*>|</pre>$!','',$geshi->parse_code()),"\n\r");

        $codeblock  = "<pre$pre_attr_str><code$code_attr_str>$highlighted_code</code></pre>";
        */

The version that uses p_xhtml_cached_geshi() gives the best looking results, but it doesn't support extra classes after the "~ $lang" declaration (e.g. ~ {.html #example-1}, from https://michelf.ca/projects/php-markdown/extra/#fenced-code-blocks). So it's not perfect (and I guess isn't Markdown Extra compatible), but it looks good.

xrat commented 8 years ago

Thanks for this! In order to get it working I also had to comment out the htmlspecialchars, i.e.

// $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);

And in order to avoid PHP Warning: array_keys() expects parameter 1 to be array I used

require_once(DOKU_INC.'inc/parserutils.php');
$codeblock = p_xhtml_cached_geshi($codeblock, $classname ? $classname : 'text' );
buchbend commented 8 years ago

Thanks for this as well! I tried the code by @xrat and it works for me as well.