Jump to content

Extension:SyntaxHighlight

From mediawiki.org
Revision as of 17:35, 17 May 2009 by Ronga (talk | contribs)
MediaWiki extensions manual
SyntaxHighlight_GeSHi
Release status: stable
Implementation Tag
Description Allows source code to be syntax highlighted on the wiki pages.
Author(s) Brion Vibber, Tim Starling and Rob Church
Latest version rev:50696 (17 May 2009)
MediaWiki 1.10.0-1.14.0+
  • $wgSyntaxHighlightMaxLines
  • $wgPygmentizePath
  • $wgSyntaxHighlightMaxBytes
Licence GPLv2
Download
README
Translate the SyntaxHighlight extension if it is available at translatewiki.net

This extension adds the <source> tag to present formatted source code.

As of rev:50696, an alternative tag <syntaxhighlight> is provided. <syntaxhighlight> is recommended to avoid possible conflicts. The original syntax <source> is also used in some other languages, e.g. XML.

Introduction

The <source> tags allow the display of preformatted code modules but in addition they add coloring according to the code language settings. Like the <pre> tags and the <poem> tags, they preserve white space, that is, they depict the code module exactly as it was typed.

Usage

On the wiki page, you can now use "source" elements:

<source lang="php">
<?php
    $v = "string";    // sample initialization
?>
html text
<?
    echo $v;         // end of php code
?>
</source>

show:

<?php
    $v = "string";    // sample initialization
?>
html text
<?
    echo $v;         // end of php code
?>

Alternative Tag

<source> is also used in some other languages (for example XML). If your source code contains <source>, it will conflicts the same tag used in this extension.

As of rev:50696, an alternative tag <syntaxhighlight> is provided. <syntaxhighlight> is recommended to avoid the conflicts mentioned above.

Parameters

  • lang="??": Defines what programming language the source code is using. This affects how the extension highlights the source code. See the section "Supported languages" in this page for details of supported languages.
  • line: Type the name of the parameter to enable line numbering formatting style. Corresponds to enable_line_numbers method on GeSHi
  • line start="??": Use together with the parameter "line". Define the start number of the line. If you type line start="55", it will start counting at 55, then 56,57,58... and so on. Corresponds to start_line_numbers_at method on GeSHi
  • hightlight="??": Specifies which line is highlighted. Note that the parameter line start="??" doesn't affect how it counts the lines.
  • enclose="??": Specifies what container is used to enclose the source code. Takes values "pre" (default value), "div", "none". Corresponds to set_header_type method on GeSHi.
  • strict: Type the name of the parameter to enable the strict mode. Corresponds to enable_strict_mode method on GeSHi.

The effect and usage of these parameters can be consulted in GeSHi's documentation.

Since r22246, you can override the colors using MediaWiki:Geshi.css.

More Usage

When line numbering is added with line, long code lines will be wrapped. See the example below. When text is the selected language, and numbering is used, the behaviour resembles the use of pre tags with numbering and long-line wrapping.

The following example shows how to color an HTML code listing:

<source lang="html4strict" line start="100" highlight="5">
HTML module goes here...
</source>

A typical result is just:

<table align=center style="background: ivory;color:maroon;font-style:italic;font-family:arial;font-weight:bold;font-size:10pt;"> 
<tr><th> Heading 1 </th><th> Heading 2 </th></tr>
<tr>
<td style="padding:10px;"> This is cell 1 text </td>
<td style="padding:10px;"> This is cell 2 text </td>
</tr>
</table>

Supported languages

These are the languages known by GeSHi that can be used in the lang parameter.

Note that installed GeSHi version (can be revealed by previewing e.g. <source lang="-"></source>) might not be the most recent version; see bugzilla:10967 for Wikimedia sites.

Code Language
abap ABAP
actionscript ActionScript
ada Ada
apache Apache Log
applescript AppleScript
asm ASM
asp Active Server Pages (ASP)
autoit AutoIt
bash Bash
basic4gl Basic4GL
bf Brainfuck
blitzbasic Blitz BASIC
bnf Backus-Naur Form
c C
c_mac C (Mac)
caddcl AutoCAD DCL
cadlisp AutoLISP
cfdg CFDG
cfm ColdFusion
cil Common Intermediate Language (CIL)
cobol COBOL
cpp-qt C++ (Qt toolkit)
cpp C++
csharp C#
css Cascading Style Sheets (CSS)
d D
delphi Delphi
diff Diff
div DIV
dos DOS batch file
dot DOT
eiffel Eiffel
fortran Fortran
freebasic FreeBASIC
genero Genero
gettext GNU internationalization (i18n) library
glsl OpenGL Shading Language (GLSL)
gml Game Maker Language (GML)
gnuplot gnuplot
groovy Groovy
haskell Haskell
hq9plus HQ9+
html4strict HTML
idl Uno IDL
ini INI
inno Inno
intercal INTERCAL
io Io
java Java
java5 Java(TM) 2 Platform Standard Edition 5.0
javascript JavaScript
kixtart KiXtart
klonec Klone C
klonecpp Klone C++
latex LaTeX
lisp Lisp
lolcode LOLCODE
lotusscript LotusScript
lua Lua
Code Language
m68k Motorola 68000 Assembler
make make
matlab MATLAB M
mirc mIRC scripting language
mxml MXML
mpasm Microchip Assembler
mysql MySQL
nsis Nullsoft Scriptable Install System (NSIS)
objc Objective-C
ocaml-brief OCaml
ocaml OCaml
oobas OpenOffice.org Basic
oracle8 Oracle 8 SQL
oracle11 Oracle 11 SQL
pascal Pascal
per per
perl Perl
php-brief PHP
php PHP
pixelbender Pixel Bender
plsql PL/SQL
povray Persistence of Vision Raytracer
powershell Windows PowerShell
progress OpenEdge Advanced Business Language
prolog Prolog
providex ProvideX
python Python
qbasic QBasic/QuickBASIC
rails Rails
reg Windows Registry
robots robots.txt
ruby Ruby
sas SAS
scala Scala
scheme Scheme
scilab Scilab
sdlbasic SdlBasic
smalltalk Smalltalk
smarty Smarty
sql SQL
tcl Tcl
teraterm Tera Term
text Plain text
thinbasic thinBasic
tsql Transact-SQL
typoscript TypoScript
vb Visual Basic
vbnet Visual Basic .NET
verilog Verilog
vhdl VHDL
vim Vimscript
visualfoxpro Visual FoxPro
visualprolog Visual Prolog
whitespace Whitespace
winbatch Winbatch
xml XML
xorg_conf Xorg.conf
xpp X++
z80 ZiLOG Z80 Assembler

Extra features

Default Source Language

Added in rev:50693.

If the site mainly quote the source code of a specific programming language, it would be helpful to set a default language.

To do so, add a new variable to LocalSettings.php, just before the require_once line. We set C programming language as an example:

$wgSyntaxHighlightDefaultLang = "c";
require_once("extensions/SyntaxHighlight_GeSHi/SyntaxHighlight_GeSHi.php");

Bugs and Limitations

None so far. You may report bugs by clicking here.

Showcases

C#

<source lang="csharp">
// Hello World in Microsoft C# ("C-Sharp").

using System;

class HelloWorld
{
    public static int Main(String[] args)
    {
        Console.WriteLine("Hello, World!");
        return 0;
    }
}
</source>

Results in:

// Hello World in Microsoft C# ("C-Sharp").

using System;

class HelloWorld
{
    public static int Main(String[] args)
    {
        Console.WriteLine("Hello, World!");
        return 0;
    }
}

Java

<source lang="java">
/* This is a regular multi-
 * line comment. */
import java.io.*;

/**
 * This is a javadoc comment
 * @see java.lang.String
 */
public class Main extends Foo
{
    @Test
    public static void main(final String[] args)
    {
        // This is a one-line comment
        System.out.println("Hello, World!");
        int n = 1 + 2;
        System.out.println("One plus two is: " + n);

        Foo foo = new Foo("foo");
        List<Foo> list = new ArrayList<Foo>();
        list.add(foo);
    }
}
</source>

Results in:

/* This is a regular multi-
 * line comment. */
import java.io.*;

/**
 * This is a javadoc comment
 * @see java.lang.String
 */
public class Main extends Foo
{
    @Test
    public static void main(final String[] args)
    {
        // This is a one-line comment
        System.out.println("Hello, World!");
        int n = 1 + 2;
        System.out.println("One plus two is: " + n);

        Foo foo = new Foo("foo");
        List<Foo> list = new ArrayList<Foo>();
        list.add(foo);
    }
}

PHP

<source lang="php">
<?php
  // Hello World in PHP
  echo 'Hello World!';
?>
</source>

Results in:

<?php
  // Hello World in PHP
  echo 'Hello World!';
?>

Python

<source lang="python">
# Hello World in Python

def main():
    print "Hello World!"

if __name__ == '__main__':
    main()
</source>

Results in:

# Hello World in Python

def main():
    print "Hello World!"

if __name__ == '__main__':
    main()

Fortran

bugs:

  • comments for fortran77 do not work (line starts with C)
<source lang="fortran">
C *
C *testing this script
C *
c * comments for fortran77 do not work!

hello = "Hello World!"

if hello .eq. 'test' then
 !do nothing
else
 !do something
 x = 1
endif
</source>

Results in:

C *
C *testing this script
C *
c * comments for fortran77 do not work!

hello = "Hello World!"

if hello .eq. 'test' then
 !do nothing
else
 !do something
 x = 1
endif

SQL

<source lang=sql>
-- select some data
SELECT  a, b, COUNT(*) AS c, SUM(d) AS d
FROM    MyTable
WHERE   a > b
GROUP BY a,b
HAVING  COUNT(*) > 1
</source>

Results in:

-- select some data
SELECT  a, b, COUNT(*) AS c, SUM(d) AS d
FROM    MyTable
WHERE   a > b
GROUP BY a,b
HAVING  COUNT(*) > 1

XML

<source lang=xml>
<!-- my comment -->
<xmlroot>
  <myelement myattribute="Hello">World</myelement>
</xmlroot >
</source>

Results in:

<!-- my comment -->
<xmlroot>
  <myelement myattribute="Hello">World</myelement>
</xmlroot >

Installation

  • Step 1:

Download the 4 extension files from the Subversion repository and save them into the extensions/SyntaxHighlight_GeSHi directory of your wiki. If you have shell access to your server, you may do the following to download the extension:

cd extensions
svn co http://svn.wikimedia.org/svnroot/mediawiki/trunk/extensions/SyntaxHighlight_GeSHi
  • Step 2: Step 1 apparently now automatically checks out the 1.0.X stable release of GeSHi, rendering this step superfluous.

(Recommended) Download 1.0.X stable release of Subversion repository in SourceForge.net:

# change to the directory of the SyntaxHighlight_GeSHi extension
cd SyntaxHighlight_GeSHi
# check out a current version of GeSHi into a directory called geshi
svn co http://geshi.svn.sourceforge.net/svnroot/geshi/branches/RELEASE_1_0_X_STABLE/geshi-1.0.X/src/ geshi

The geshi.php file can also be downloaded from GeSHi, and unzip it inside the extensions/SyntaxHighlight_GeSHi directory. (Note: the zip file creates a sub-directory called geshi/, and places the file geshi.php there - Also note that GeSHi 1.1.2alpha3 does not work with this extension!)

(Note: You need both the mediawiki plugin files and the geshi files from sourceforge to make it work!)

  • Step 3.

Add this line to the end of your LocalSettings.php:

 require_once("extensions/SyntaxHighlight_GeSHi/SyntaxHighlight_GeSHi.php");
  • step 4. (Optional)

If needed, change the following line in SyntaxHighlight_GeSHi.class.php to suit the path of your geshi.php file

 require( 'geshi/geshi.php' );

Sometimes you'll need to add the absolute path to geshi (/var/www/html/.../geshi/geshi.php)

Here's a shortcut using the PHP dirname() function with the magic __FILE__ constant:

 require(dirname(__FILE__).'/geshi/geshi.php');

Problem with CSS / Border

If you want the dashed border like for <pre> tags you have to edit the SyntaxHighlight_GeSHi.class.php around line 213. Look for this:

  $css[] = ".source-$lang {line-height: normal;}";

and change it to:

  $css[] = ".source-$lang {padding: 1em; border: 1px dashed #2f6fab; color: black; background-color: #f9f9f9; line-height: 1.1em;}";

On a Unix-like system simply type this command in the directory containing "SyntaxHighlight_GeSHi.class.php":

sed -i 's/$css\[\] = ".source-$lang {line-height: normal;}";/\
$css\[\] = ".source-$lang {padding: 1em; border: 1px dashed #2f6fab; color: black; background-color: #f9f9f9; line-height: 1.1em;}";/g' \
SyntaxHighlight_GeSHi.class.php

Link to Extension Talk (2008): Extension_talk:SyntaxHighlight_GeSHi#Problem_with_CSS:_Default_style_for_pre_is_overwritten

See also