Extension:SyntaxHighlight

From MediaWiki.org
Jump to navigation Jump to search
This page is a translated version of the page Extension:SyntaxHighlight and the translation is 14% complete.

Other languages:
Deutsch • ‎English • ‎Türkçe • ‎be-tarask • ‎русский • ‎中文 • ‎日本語 • ‎한국어
Erweiterung ist üblicherweise in MediaWiki 1.21 und darüber enthalten. Daher entfällt ein erneutes herunterladen. Allerdings müssen Sie ggf. trotzdem weiteren gegebenen Anleitungen folgen.
Zum Hervorheben von Syntax in Wikicode bei Verwendung des Source-Editors siehe die CodeMirror Erweiterung oder die Benutzerskripts von Remember the dot und Cacycle.
MediaWiki-Erweiterungen
Crystal Clear action run.svg
SyntaxHighlight
Erscheinungsstatus: stabil
SyntaxHighlighting with Pygments.png
Einbindung Tag
Beschreibung Erlaubt die Hervorhebung von Syntax eines Quellcodes auf Wikiseiten
Autor(en)
  • Brion Vibber,
  • Tim Starling,
  • Rob Church,
  • Ori Livneh
Letzte Version continuous updates
MediaWiki 1.25+
Datenbankänderungen Nein
Lizenz GNU General Public License 2.0 or later
Herunterladen
README
Parameter

  • $wgPygmentizePath
  • $wgSyntaxHighlightModels
Tags
<syntaxhighlight>
Verwendete Hooks
ContentGetParserOutput
ParserFirstCallInit
ApiFormatHighlight
ResourceLoaderRegisterModules
Übersetze die SyntaxHighlight Erweiterung wenn sie auf translatewiki.net verfügbar ist
Prüfe die Benutzungs- und Versionsmatrix.
Probleme Offene Aufgaben · Einen Fehler melden

Die SyntaxHighlight-Erweiterung, früher bekannt als SyntaxHighlight_GeSHi, stellt reiche Formatierung von Quellcode bei der Verwendung des Tags <syntaxhighlight> bereit. Sie wird von der Library Pygments angetrieben und unterstützt Hunderte von Programmiersprachen und Dateiformaten.

Genau wie die Tags <pre> und <poem > wird der Text verarbeitet genau wie der Text getippt wurde und bewahrt so jeglichen Leerraum.

Verwendung

Einmal installiert, kann man den "syntaxhighlight"-Tag auf Wikiseiten verwenden. Zum Beispiel

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

ist das Ergebnis des folgenden Wikitext-Markups:

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

In älteren Versionen (vor MediaWiki 1.16) benutzte die Erweiterung den Tag <source>. Dieser wird noch immer unterstützt, jedoch hilft <syntaxhighlight> Konflikte zu vermeiden, wenn der Quellcode selbst <source> Tags enthält (z.B. XML).

Gestaltung

Wenn der angezeigte Code zu groß ist, kann dieser angepasst werden, indem folgendes in die MediaWiki:Common.css Seite in Ihrem Wiki getan wird (wenn diese nicht existiert, muss sie erzeugt werden):

/* CSS, welches hier platziert wird, beeinflusst jedes Aussehen */
.mw-highlight pre {
	font-size: 90%;
}

Um Codeblocks in Kanten einzuschließen, muss eine Zeile wie border: 1px dashed blue; in die Sektion oben eingefügt werden. Kontrolle über die verwendete Schriftartfamilie kann durch Einfügen einer Zeile wie font-family: "Courier New", monospace; in die obere Sektion ausgeübt werden.

Syntax highlighting error category

The extension adds pages that have a bad lang attribute in a <source> or <syntaxhighlight> tag to 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.

The most common error that leads to pages being tagged with this category is a <syntaxhighlight> or <source> tag with no lang attribute at all, because older versions of this extension supported the definition of "$wgSyntaxHighlightDefaultLang". These can typically either be replaced with <pre>, or lang="bash" or lang="text" can be added to the tag.

The second most common error is the use of lang="sh" or lang="shell" which are unsupported. These can typically be replaced with lang="bash" or lang="shell-session".

Parameters

lang

The lang="Name" attribute defines what lexer should be used. The language affects how the extension highlights the source code. The pygments parser is case sensitive and all languages have at least one capital letter (lower case language names are reserved for gtags). See the section Supported languages 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. See the section Syntax highlighting error category in this page for details.

line

The line attribute enables line numbers.

1 def quickSort(arr):
2 	less = []
<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"). Note that the line number specification ignores any renumbering of the displayed line numbers with the start attribute.

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

is the result of

<syntaxhighlight lang="Python" highlight="1,5-7" start='3' line>
..
</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 behavior.

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 equivalent 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:

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

Is the result of:

<syntaxhighlight lang="Python" style="border:3px dashed blue">
def quickSort(arr):
	less = []
	pivotList = []
	more = []
	if len(arr) <= 1:
		return arr
	else:
		pass
</syntaxhighlight>

Supported languages

The Pygments library provides support for hundreds of computer languages and file formats. A brief list of languages is:

AppleScript, Assembly, Asymptote, Awk, bash, Befunge, Boo, BrainFuck, C, C++, C#, Clojure, CoffeeScript, ColdFusion, Common Lisp, Coq, Cryptol, Crystal, Cython, D, Dart, Delphi, Dylan, Elm, Erlang, Ezhil, Factor, Fancy, Fortran, F#, Gambas, GAP, Gherkin, GL shaders, Groovy, Haskell, IDL, Io, Java, JavaScript, Lasso, LLVM, Logtalk, Lua, Matlab, MiniD, Modelica, Modula-2, MuPad, Nemerle, Nimrod, Objective-C, Objective-J, Octave, OCaml, PHP, Perl, PovRay, PostScript, PowerShell, Prolog, Python 2.x and 3.x (incl. console sessions and tracebacks), R, REBOL, Red, Redcode, Ruby, Rust, S, S-Plus, Scala, Scheme, Scilab, Smalltalk, SNOBOL, Tcl, Vala, Verilog, VHDL, Visual Basic.NET, Visual FoxPro, XQuery, Zephir

(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

The version of this extension bundled with MediaWiki 1.31 requires Python version 3 (python3) to be installed on the server. This is a change from the version bundled with MediaWiki 1.30, which used Python version 2 (python). Note that the python3 binary must be installed in the execution PATH of the PHP interpreter.
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.
  • Füge folgenden Code am Ende deiner LocalSettings.php hinzu:
    wfLoadExtension( 'SyntaxHighlight_GeSHi' );
    
  • In Linux, set execute permissions for the pygmentize binary:
chmod a+x /path/to/extensions/SyntaxHighlight_GeSHi/pygments/pygmentize
  • Yes Erledigt – Navigiere zu Special:Version in deinem Wiki (bei Einstellung auf deutsch nach Spezial:Version), um zu prüfen, dass die Erweiterung erfolgreich installiert ist.

An Nutzer, die MediaWiki 1.24 und früher betreiben:

Die oben stehenden Anweisungen beschreiben den neuen Weg der Installation von diese Erweiterung per wfLoadExtension(). Falls du diese Erweiterung in einer dieser früheren Versionen (MediaWiki 1.24 und früher)  – an Stelle von wfLoadExtension( 'SyntaxHighlight_GeSHi' ); – installieren musst, benutze:

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 --no-dev, or when updating: composer update --no-dev.

Alternatively as well as preferably add the line "extensions/SyntaxHighlight_GeSHi/composer.json" to the "composer.local.json" file in the root directory of your wiki like e.g.
{
	"extra": {
		"merge-plugin": {
			"include": [
				"extensions/SyntaxHighlight_GeSHi/composer.json"
			]
		}
	}
}
Now run composer update --no-dev. Voilà!
When uploading the extension via FTP be sure to upload the pygments/pygmentize file with the transfer type binary.

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. For example: $wgPygmentizePath = "/usr/local/bin/pygmentize";.
  • $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 there is no pygmentize.exe run easy_install Pygments from command line inside the Scripts folder to generate the file.

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.

Troubleshooting

After updating to MediaWiki v1.26 and above, some users started reporting problems with the extension. There could be cases, when some languages, such as Lua might not get highlighted and by turning on debugging, MediaWiki would throw out the error, Notice: Failed to invoke Pygments: /usr/bin/env: python3: No such file or directory.

  • Try pointing $wgPygmentizePath in LocalSettings.php towards an external pygmentize binary.
  • In shared hosting environments with cPanel, this can be done by setting up a new Python application through the "Setup Python App" menu, and activating the virtual environment for the app through SSH (source /virtualenv/python/3.5/bin/activate). After this, the Pygments module can be added to the Python app, for which navigate to the virtual environment path (cd virtualenv/python/3.5/bin/), download and install Pygments (./pip install Pygments) and then activate the module by adding "Pygments" under the "Existing applications" section of the "Setup Python App" menu. This will create the required file at path: virtualenv/python/3.5/bin/pygmentize


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. See Extension:SyntaxHighlight/VisualEditor for details

Advanced

Unlike the <pre> and <code> tags, HTML character entities such as &nbsp; need not (and should 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="-moz-tab-size:nn; -o-tab-size:nn; tab-size:nn;"> tag (not <div>, and not using its 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 to 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

Footnotes