root/trunk/plugins/syntaxhl.php

Revision 610, 2.0 KB (checked in by michiel, 15 months ago)

allow syntax highlighting in posts.
See COLOR_HIGHLIGHT.txt in the root to see how it's done.

Closes #113

Line 
1<?php
2/* include the geshi stuff */
3require_once("syntaxhl_files/geshi.php");
4
5Class syntaxhl extends MvBlog_plugin implements MvBlog_pluginiface {
6    /* variables */
7    public $name    = "Syntax color highlighter";
8    public $author  = "Michiel van Baak";
9    public $license = "GPL";
10    public $website = "http://www.mvblog.org";
11    public $description = "Provides syntax color highlighting inside posts.";
12
13    private $_mvblog;
14
15    /* methods */
16    public function __construct(&$mvblog) {
17        $this->addHook("text_output", "syntaxhighlight");
18        $this->_mvblog =& $mvblog;
19    }
20
21    public function activate() {
22        /* get data, do whatever is needed on plugin activation */
23    }
24
25    public function deactivate() {
26    }
27
28    public function syntaxhighlight($text) {
29        /* make copy of input because we are going to modify it */
30        $pluginoutput = $text;
31
32        /* find all blocks of [code:<language> .... :code] */
33        preg_match_all("/\[code:(.*):code\]/Us", $text, $matches);
34        foreach ($matches[0] as $codeblock) {
35            $data = "";
36            /* get the language for the code block */
37            preg_match("/\[code:(\w{1,})/", $codeblock, $langmatch);
38            $language = $langmatch[1];
39            /* remove the special code to identify code blocks */
40            $data = str_replace("[code:$language", "", $codeblock);
41            $data = str_replace(":code]", "", $data);
42            $data = str_replace("<br />", "", html_entity_decode($data));
43            /* use geshi to syntax highlight the code */
44            $geshi = new Geshi(trim($data), strtolower($language));
45            $geshi->enable_classes();
46            /* geshi comes with some style tags, so load the inline stylesheets */
47            $data "<style type=\"text/css\">\n";
48            $data .= $geshi->get_stylesheet();
49            $data .= "</style>\n";
50            /* enable line numbers */
51            $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
52            /* the actual highlighting is here */
53            $data .= $geshi->parse_code();
54            /* replace the original code with the highlighted code */
55            $pluginoutput = str_replace($codeblock, $data, $pluginoutput);
56        }
57        /* return the modified code with highlighting */
58        return $pluginoutput;
59    }
60}
61?>
Note: See TracBrowser for help on using the browser.