Extension:SyntaxHighlight

From MediaWiki.org
Jump to: navigation, search
This extension is bundled with MediaWiki 1.21 and above. Thus you do not have to download it again.
MediaWiki extensions manualManual:Extensions
Crystal Clear action run.png
SyntaxHighlight

Release status:Extension status stable

ImplementationTemplate:Extension#type Tag
DescriptionTemplate:Extension#description Allows source code to be syntax highlighted on the wiki pages
Author(s)Template:Extension#username Brion Vibber, Tim Starling, Rob Church, and Ori Livneh
Latest versionTemplate:Extension#version continuous updates
Database changesTemplate:Extension#needs-updatephp No
LicenseTemplate:Extension#license GNU General Public License 2.0 or later
Download
README
ParametersTemplate:Extension#parameters
  • $wgPygmentizePath
  • $wgSyntaxHighlightModels
TagsTemplate:Extension#tags
<syntaxhighlight>
Hooks usedTemplate:Extension#hook
ContentGetParserOutputManual:Hooks/ContentGetParserOutput
ParserFirstCallInitManual:Hooks/ParserFirstCallInit
ExtensionTypesManual:Hooks/ExtensionTypes

Translate the SyntaxHighlight extension if it is available at translatewiki.net

Check usage and version matrix.

IssuesPhabricator

Open tasks · Report a bug

The SyntaxHighlight extension, formerly known as SyntaxHighlight_GeSHi, provides rich formatting of source code using the <syntaxhighlight> tag. It is powered by the Pygments library and supports hundreds of different programming languages and file formats.

Like the <pre> and <poem> tags, the text is rendered exactly as it was typed, preserving any white space.

This extension was formerly known as SyntaxHighlight_GeSHi since it used GeSHi for syntax highlighting. Since June 2015 it uses Pygments.

Usage

Once installed, you can use "syntaxhighlight" tags on wiki pages. For example,

1 def quickSort(arr):
2 	less = []
3 	pivotList = []
4 	more = []
5 	if len(arr) <= 1:
6 		return arr
7 	else:
8 		pass

is the result of the following wikitext markup:

<syntaxhighlight lang="python" line>
def quickSort(arr):
	less = []
	pivotList = []
	more = []
	if len(arr) <= 1:
		return arr
	else:
		pass
</syntaxhighlight>

In older versions (before MediaWiki 1.16), the extension used the tag <source>. This is still supported, but <syntaxhighlight> may help avoid conflicts if your source code itself contains <source> tags (for example XML).

Styling

If the displayed code is too big, you can adjust it by putting the following into the MediaWiki:Common.css page in your wiki (create it if it does not exist):

/* CSS placed here will be applied to all skins */
.mw-highlight pre {
	font-size: 90%;
}

Encasing code blocks in borders can be done by inserting a line like border: 1px dashed blue; in the section above. Control over font family used can also be exercised by inserting a line like font-family: "Courier New", monospace; into the section above.

Parameters

lang

The lang="name" attribute defines what lexer should be used. This affects how the extension highlights the source code. See the section Supported languages in this page for details of supported languages.

def quickSort(arr):
    less = []
<syntaxhighlight lang="python">
..
</syntaxhighlight>

Specifying an invalid or unknown name will tag the page with a tracking category. The message key MediaWiki:syntaxhighlight-error-category determines the category name, on this wiki it is Category:Pages with syntax highlighting errors.

line

The line attribute enables line numbers.

1 int x = 0;
2 Console.WriteLine("结果是:"+ x);
<syntaxhighlight lang="python" line>
..
</syntaxhighlight>

start

The start attribute (in combination with line) defines the first line number of the code block. For example, line start="55" will make line numbering start at 55.

55 def quickSort(arr):
56     less = []
<syntaxhighlight lang="python" line start="55">
..
</syntaxhighlight>

highlight

The highlight attribute specifies one or more lines that should be marked (by highlighting those lines with a different background color). You can specify multiple line numbers separated by commas (for example, highlight="1,4,8") or ranges using two line numbers and a hyphen (for example, highlight="5-7").

def quickSort(arr):
    less = []
    pivotList = []
    more = []
    if len(arr) <= 1:
        return arr
    else:

is the result of

<syntaxhighlight lang="python" highlight="1,5-7">
..
</syntaxhighlight>

inline

MediaWiki version: 1.26

The attribute indicates that the source code should be inline as part of a paragraph (as opposed to being its own block). This option is available starting with MediaWiki 1.26. For backwards-compatibility, an enclose="none" attribute results in the same behaviour.

Note that line breaks can occur at any space between the opening and closing tags unless the source code is marked non-breakable with class=nowrap (on those wikis that support it; see below) or style=white-space:nowrap.

For example:

lambda x: x * 2 is a lambda expression in Python.

Is the result of:

<syntaxhighlight lang="python" inline>lambda x: x * 2</syntaxhighlight> is a [[w:Lambda (programming)|lambda expression]] in Python.

class

When inline is used, class=nowrap (on those wikis that support it; not on MediaWiki itself) specifies that line breaks should not occur at spaces within the code block.

For example:
Without class=nowrap:

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxlambda x: x * 2xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

With style=white-space:nowrap:

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxlambda x: x * 2xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

style

The style attribute allows CSS attributes to be included directly. This is eqivalent to enclosing the block in a <div> (not <span>) tag. The tab‑size attribute cannot be specified this way; it requires an enclosing <span> tag as described below under #Advanced.

For example:

int main()
{
	printf ("Hello world!");
	return 0;
}

Is the result of:

<source lang=c style="border:3px dashed blue">
int main()
{
	printf ("Hello world!");
	return 0;
}
</source>

Supported languages

The Pygments library provides support for hundreds of computer languages and file formats (full list and complete details in the Pygments document) and there are some mappings for some language names which were supported by GeSHi (full list).

Pygments does not yet provide a "wikitext" or "mediawiki" lexer (phab:T29828). Use "html", "xml", or "moin" instead.

Below is a partial list of languages that GeSHi could highlight, with strike-through for languages no longer supported after the switch to Pygments.

Installation

Despite its update to Pygments (and away from GeSHi) and despite its updated name, this extension internally still uses the former file names as stated below.
  • Download and place the file(s) in a directory called SyntaxHighlight_GeSHi in your extensions/ folder.
  • Add the following code at the bottom of your LocalSettings.php:
wfLoadExtension( 'SyntaxHighlight_GeSHi' );
  • YesY Done - Navigate to Special:Version on your wiki to verify that the extension is successfully installed.

To users running MediaWiki 1.24 or earlier:

The instructions above describe the new way of installing extensions using wfLoadExtension(), since MediaWiki 1.25. If you need to install this extension in earlier versions, instead of wfLoadExtension( 'SyntaxHighlight_GeSHi' );, you need to use:

require_once "$IP/extensions/SyntaxHighlight_GeSHi/SyntaxHighlight_GeSHi.php";
When installing from Git, please note that starting from MediaWiki 1.26 this extension requires Composer.

So, after installation from git change to the directory containing the extension e.g. "../extensions/SyntaxHighlight_GeSHi/" and run composer install, or when updating: composer update.

Alternatively as well as preferably add the line "extensions/SyntaxHighlight_GeSHi/composer.json" to the "composer.local.json" file it the root directory of your wiki like e.g.
{
	"extra": {
		"merge-plugin": {
			"include": [
				"extensions/SyntaxHighlight_GeSHi/composer.json"
			]
		}
	}
}

Now run composer update --prefer-source. Voilà!

Configuration

Linux
  • $wgPygmentizePath (optional): Absolute path to pygmentize of the Pygments package. The extension bundles the Pygments package and $wgPygmentizePath points to the bundled version by default, but you can point to a different version, if you want to.
  • $wgSyntaxHighlightModels: Configure the default lexer for some wiki pages. By default this will highlight javascript and css pages. Additional content models can be configured by extensions (e.g. Lua, JSON, ..).
Windows
  • If you are hosting your Mediawiki on a Windows machine, you have to set the path for the Pygmentize.exe $wgPygmentizePath = "c:\\Python27\\Scripts\\pygmentize.exe";

If you are using the bundled pygmentize binary (extensions/SyntaxHighlight_GeSHi/pygments/pygmentize), make sure your webserver is permitted to execute it. If your host does not allow you to add executables to your web directory, install python-pygments and add $wgPygmentizePath = pygmentize to LocalSettings.php.

VisualEditor integration

The plugin enables direct editing with VisualEditor. A popup is opened when a user wants to edit source or syntaxhighlight sections. For this to work, VisualEditor must be installed and configured from the latest git version, same for Parsoid. The feature randomly does not work with older Parsoid versions.

Advanced

Unlike the <pre> and <code> tags, HTML character entities such as &nbsp; need not have the & character escaped as &amp;. Like the <pre> tag but unlike the <code> tag, tags within the range (other than its’ own closing tag) need not have the < symbol escaped as &lt;, nor does wikitext need to be escaped with a <nowiki> tag.

Furthermore, while <pre> assumes tab stops every 8 characters and renders tabs using actual spaces when the rendered text is copied, <syntaxhighlight> uses 4-space tab stops (except Internet Explorer, which uses 8) and preserves the tab characters in the rendered text; the latter may be changed using an enclosing <span style="tab‑size:nn; ‑moz‑tab‑size:nn; ‑o‑tab‑size:nn"> tag (not <div>, and not using this tag’s own style attribute). The -moz- prefix is required for Firefox (from version 4.0), and the -o- prefix is required for Opera (from version 10.60, and not required from version 15).[1] (Note that the wiki editing box assumes 8-space tabs.) This applies only to actual saved pages; previews generated through an edit box or Special:ExpandTemplates may differ.


See also


Language: English  • русский
  1. http://developer.mozilla.org/en-US/docs/Web/CSS/tab-size