Extension:Syntax Highlighting

From MediaWiki.org
Jump to: navigation, search


Manual on MediaWiki Extensions
List of MediaWiki Extensions
Crystal Clear action run.png
Syntax Highlighting

Release status: unknown

Implementation Tag
Description A really simple way for you to add syntax highlighting to your wiki posts with support with several languages. The extension requires the Beautifier Syntax Highlighting Engine (Link broken?). What the extension does is pass the tag inputs and/or arguements to the Beautifier Highlighting engine and returns the HTML output.
Author(s) Lucas Hrabovsky
License No license specified
Download http://public.planetmirror.com/pub/sourceforge/b/be/beautifier/?fl= or this page

check usage (experimental)

Contents

[edit] About <HIGHLIGHTSYNTAX>

The highlight syntax extension is a really simple way for you to add syntax highlighting to your wiki posts with support with several languages. The extension requires the Beautifier Syntax Highlighting Engine . What the extension does is pass the tag inputs and/or arguments to the Beautifier Highlighting engine and returns the HTML output.

[edit] See also

[edit] Installation

  1. Download the Beautifier PHP Package from the Beautifier.org Site.
    • This is a dead link. But these mirrors work: mirrorservice planetmirror.
    • Use the php version which is partway down the list
  2. Extract the tarball somewhere on your remote server. (I suggest to a subdirectory of your wiki directory named "beautifierpackage")
  3. Copy all the text in the code section below into a new PHP file. (maybe you have to replace all &lt; with < and &gt; with >).
    • In the code he uses require_once("extensions/syntaxHighlightExtension.php"); so name your file as such "extensions/syntaxHighlightExtension.php".
  4. Edit the $BEAUT_PATH, LOCAL_SERVER_ROOT, and $OUTPUT_HIGHLIGHT_AS to localize the extension for your system.
  5. Save the new PHP file to your server as syntaxHighlightExtension.php in your MediaWiki extension folder.
  6. Open the LocalSettings.php file in the root of your MediaWiki and add the following to the end of the file:
#Require the php beautifier extension for syntax highlighting.
require_once("extensions/syntaxHighlightExtension.php");

That's it! You're all installed. There are a lot of tweaks you can make to customize beautifier to make things simpler and add some new functions to their framework. Enjoy.

[edit] The Code

<?php
/**
 * MediaWiki Extension for Code Syntax Highlighting with the [ http://www.beautifier.org | Beautifier Syntax Highlighting Engine].
 *
 * Parses any content defined within the <nowiki><highlightSyntax></highlightSyntax></nowiki> tag
 * with the [ http://www.beautifier.org | Beautifier Syntax Highlighting Engine] and 
 * returns the HTML output.
 * @author Lucas Hrabovsky <lucas@amie.st>
 * @copyright &copy; 2006 Amie Inc.
 * @package MediaWiki
 * @subpackage Extensions
 * @filesource
 */
/**
 * ----------------------------------------
 * Configuration Vars.
 * ----------------------------------------
 * @string BEAUT_PATH The root path to your Beatuifier installation.
 * @string LOCAL_SERVER_ROOT The root path to use when opening files on the local server for highlighting.
 * @string OUTPUT_HIGHLIGHT_AS Whether to output the HTML as CSS friendly or not.  enum('CSS','HTML')
 */
$BEAUT_PATH = "/path/to/your/beautifier/installation/";
$LOCAL_SERVER_ROOT = "/pathtoyour/public_html/or/www/directory/";
$OUTPUT_HIGHLIGHT_AS = "HTML";
/**
 * Add the syntax highlighting extension to the wgExtensionFunctions array.
 */
$wgExtensionFunctions[] = "syntaxHighlightingExtension";
/**
 * Register the syntaxHighlightingExtension with the Wiki Parser and associate 
 * the highlightSyntax tag with the syntaxHighlightingRenderHtml function.
 */
function syntaxHighlightingExtension(){
	global $wgParser;
	$wgParser->setHook("HIGHLIGHTSYNTAX","syntaxHighlightingRenderHtml");
}
/**
 * The callback function for converting the input text to HTML output.
 */
function syntaxHighlightingRenderHtml($input, $argv){
	/**
	 * Pass in the globals defined above for use in the function.
	 */
	global $BEAUT_PATH, $LOCAL_SERVER_ROOT, $OUTPUT_HIGHLIGHT_AS;
	/**
	 * Require the two main files for the beautifier.
	 */
	require_once ($BEAUT_PATH."Beautifier/Core.php");
 
        /**
         * If a specific language is requested load the relevant file and create the highlighter
         */
        $myhfile = null;
        if($argv["language"] && file_exists($BEAUT_PATH."HFile/HFile_".$argv["language"].".php") ){
                require_once ($BEAUT_PATH."HFile/HFile_".$argv["language"].".php");
 
                $className = "HFile_".$argv["language"];
                if (FALSE === ($myhfile = new $className()) ) {
                        $output .= "Error:1 Could not instantiate HFile_".$argv["language"]."()<br />";
                }
 
        }
 
        /**
         * Otherwise use php as a default
         */
        else
        {
                require_once ($BEAUT_PATH."HFile/HFile_php3.php");
                $myhfile = new HFile_php3();
        }
 
        /**
         * Set up the highlight object based on whether
         * you want the output as CSS freindly or straight HTML.
         */
        if($OUTPUT_HIGHLIGHT_AS=="CSS"){
        	require_once ($BEAUT_PATH."Output/Output_css.php");
        	$outputter = new Output_css();
        }
        else {
        	require_once ($BEAUT_PATH."Output/Output_HTML.php");
        	$outputter = new Output_Html();
        }
 
        $highlighter = new Core($myhfile, $outputter);
 
	/**
	 * The meat and potatoes...
	 */
 
	/**
	 * If the serverFile argument is passed in the tag, load the local file into the highlighter parser.
	 */ 
	if($argv["serverFile"]){
		$output .= "<div style=\"font-weight: bold;\"><pre>\n";
		$output .= $highlighter->highlight_text($highlighter->load_file($serverRoot.$argv["serverFile"]));
		$output .= "</pre></div>";
		return $output;
	/**
	 * If its a remote file, open it up and parse the returned contents.
	 */
	} else if($argv["remoteFile"]){
		$openFileName = $argv["remoteFile"];
		$fp = fopen($openFileName, "r");
		if(!$fp){
			$output = "Error: Syntax Highlighter could not open the file ".$openFileName."<br />";
		} else {
			$fileContents = fread($fp, 8096);
			fclose($fp);
			$output .= "<div style=\"font-weight: bold;\"><h1>Code from <a href=\"".$argv["remoteFile"]."\">".$argv["remoteFile"]."</a></h1><pre>\n";
			$output .= $highlighter->highlight_text($fileContents);
			$output .= "</pre></div>";
		}
		return $output;
	/**
	 * Else we just want to highlight the code within the syntaxHighlight tags.
	 */
	} else {
		$output .= "<div style=\"font-weight: bold;\"><pre>\n";
		$output .= $highlighter->highlight_text($input);
		$output .= "</pre></div>";
		return $output;
	}
}

[edit] Improving the Highlighter

The output of the highlighter as downloaded from the beautifier web site contains hard coded colours even though the highlighter classes specify colours to use. I re-wrote the HTML outputter class in our installation to use the colours specified in the highlighter file.

To do the same you will need to pass the highlighter into the output class by changing the line

 $outputter = new Output_Html();

to

 $outputter = new Output_Html($myhfile);

And then replace the Output_HTML class in Output\Output_HTML.php with the following.

        class Output_HTML
        {
        	function Output_HTML($file=undef)
        	{
        		if (!isset($file)) $file = new HFile();
 
        		$this->code		= '_WORD_';
        		$this->linecomment 	= '<font color="'. $file->linecommentcolour .'" style="font-style=italic;">_WORD_</font>';
        		$this->blockcomment 	= '<font color="'. $file->blockcommentcolour .'" style="font-style=italic;">_WORD_</font>';
        		$this->prepro 		= '<font color="purple">_WORD_</font>';
        		$this->select 		= '<font color="red"><b>_WORD_</b></font>';
        		$this->quote 		= '<font color="'. $file->quotecolour .'">_WORD_</font>';
 
        		for($i=0; $i<sizeof($file->colours); $i++)
        		{
        		   $varname = "category_".($i+1);
        		   $this->{$varname} = '<font color="'. $file->colours[$i] .'">_WORD_</font>';
        		}
        	}
        }

This only changes the HTML outputter, to change the CSS one in a similar fashion would be more complex since it relies on CSS classes to provide the different formatting. I guess you could write these classes out at the start of the block, but I'm not sure how the browser would react to having the styles redefined if you included multiple blocks using different languages.

[edit] Usage

[edit] Inline Highlighting

PHP Code

<highlightSyntax> <? print("This is my PHP Code."); ?> </highlightSyntax>

Code in a specific language

<highlightSyntax language="sqlnew"> SELECT * FROM [myTable] WHERE Field1 = 1 AND Field2 > 50 ORDER BY [date] </highlightSyntax>

[edit] Highlight a file on your local server

<highlightSyntax serverFile="myLocalPHPFile.php"></highlightSyntax>

or

<highlightSyntax serverFile="myLocalFile.xml" language="xml"></highlightSyntax>

[edit] Highlight a remote file

<highlightSyntax remoteFile="http://www.example.com/remotePHPFile.php"></highlightSyntax>

Personal tools
Namespaces
Variants
Actions
Site
Support
Download
Development
Communication
Toolbox