Jump to content

Bộ mở rộng:SyntaxHighlight

From mediawiki.org
This page is a translated version of the page Extension:SyntaxHighlight and the translation is 20% complete.
This extension comes with MediaWiki 1.21 and later, so you do not need to download it. The remaining configuration instructions must still be followed.
Để biết thêm về tô màu cú pháp trong trình biên tập mã wiki, như trình biên tập mã nguồn, xem bộ mở rộng CodeMirror hoặc mã do người dùng Remember the dotCacycle tự viết.
Cẩm nang phần mở rộng MediaWiki
SyntaxHighlight
Trạng thái phát hành: ổn định
Cài đặt Tag
Mô tả Cho phép mã nguồn được tô màu trong các trang wiki
Tác giả
Phiên bản cập nhật liên tục
Compatibility policy Master maintains backward compatibility.
MediaWiki 1.25+
Database changes Không
Giấy phép GNU General Public License 2.0 or later
Tải xuống
README
  • $wgSyntaxHighlightMaxLines
  • $wgPygmentizePath
  • $wgSyntaxHighlightMaxBytes
‎<syntaxhighlight>
Translate the SyntaxHighlight extension
Phản hồi Open tasks · Báo cáo lỗi

Bộ mở rộng SyntaxHighlight, trước đây có tên là SyntaxHighlight_GeSHi, giúp định dạng mã nguồn một cách phong phú bằng thẻ ‎<syntaxhighlight>. Nó được hỗ trợ bởi thư viện Pygments và hỗ trợ hàng trăm ngôn ngữ lập trình và định dạng tập tin khác nhau.

Giống như thẻ ‎<pre><poem >, văn bản sẽ được hiển thị chính xác như cách nó được gõ vào, giữ nguyên các khoảng trắng.

Bộ mở rộng SyntaxaHighlight không hoạt động tại các bản cài đặt wiki được làm cứng bằng Hardened-PHP do bị thiếu proc_open, shell_exec và các tính năng khác. Xem T250763.

Thẻ ‎<syntaxhighlight> đã trở nên quá đắt đỏ từ phiên bản 1.39 khi số lượng thẻ syntaxhighlight đạt tới con số 5.000 trong một trang đơn như tại Wikibooks. Hãy tăng giá trị thời gian kết nối của máy chủ web trong môi trường trong các trường hợp quá cực đoan. (Xem T316858.)

Cách sử dụng

Sau khi được cài đặt, bạn có thể sử dụng thẻ "syntaxhighlight" tại các trang wiki. Ví dụ,

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

là kết quả của đoạn mã wiki sau:

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

Để dùng với mã nguồn được nhúng, ví dụ như trong lời gọi mô-đun, dùng bộ phân giải #tagsafesubst::[1]

{{#tag:syntaxhighlight|{{safesubst:Module:Sandbox/userName/myModule}}|lang=lua}}

Trước MediaWiki 1.16, bộ mở rộng dùng thẻ ‎<source>. Thẻ đó vẫn được hỗ trợ, nhưng đã bị coi là không phù hợp. ‎<syntaxhighlight> nên luôn được sử dụng.

Kiểu cách

Nếu mã hiển thị quá lớn, bạn có thể điều chỉnh nó bằng cách đặt những dòng sau đây vào trang MediaWiki:Common.css trong wiki của bạn (tạo nó nếu nó chưa tồn tại):

/* CSS được đặt ở đây sẽ được áp dụng cho tất cả các ngoại hình */
.mw-highlight pre {
	font-size: 90%;
    /*  Thêm thêm CSS kiểu dáng ở đây */
}

Đóng khung khối mã có thể được thực hiện bằng cách chèn một dòng như border: 1px dashed blue; trong phần phía trên. Ghi đè nhóm phông có thể thực hiện bằng cách chèn một dòng như font-family: "Courier New", monospace; vào phần phía trên.

A practical method to generate CSS code in bulk that corresponds to one of the color schemes supported by Pygments is to run the following command from within the MediaWiki installation folder. This example is for the stata-dark color scheme:

./extensions/SyntaxHighlight_GeSHi/pygments/pygmentize -S stata-dark -f html | sed 's/^/.mw-highlight /'

This will output a large chunk of CSS that looks something like:

.mw-highlight pre { line-height: 125%; }
.mw-highlight td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
.mw-highlight span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
.mw-highlight td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.mw-highlight span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.mw-highlight .hll { background-color: #49483e }
.mw-highlight .c { color: #777; font-style: italic } /* Comment */
.mw-highlight .err { color: #A61717; background-color: #E3D2D2 } /* Error */
.mw-highlight .esc { color: #CCC } /* Escape */
/* ... and so on ... */

These CSS lines can then be copy-pasted into a site-wide CSS page such as MediaWiki:Common.css, or a skin-specific one such as MediaWiki:Vector.css.

Thể loại lỗi tô màu cú pháp

Bộ mở rộng thêm trang có thuộc tính lang xấu trong một thẻ ‎<syntaxhighlight> vào một thể loại theo dõi. Khóa tin nhắn MediaWiki:syntaxhighlight-error-category xác định tên thể loại; trên wiki này nó là Category:Pages with syntax highlighting errors.

Lỗi phổ biến nhất khiến trang bị đánh dấu vào thể loại này là thẻ ‎<syntaxhighlight> hoàn toàn không có thuộc tính lang, vì các phiên bản cũ của bộ mở rộng này có hỗ trợ định nghĩa $wgSyntaxHighlightDefaultLang . Chúng thường có thể thay bằng ‎<pre>, hoặc thêm lang="text" vào thẻ. Ví dụ:

<syntaxhighlight lang="text">
...
</syntaxhighlight>

Bạn cũng có thể thêm thể loại, và nội dung sẽ được tô màu, nếu có hơn 1000 dòng hoặc văn bản hơn 100kB.[2]

Thông số

lang

Thuộc tính lang="name" định nghĩa loại từ vựng nào được sử dụng.[3] Ngôn ngữ ảnh hưởng đến cách bộ mở rộng tô màu mã nguồn. Xem #Ngôn ngữ được hỗ trợ để biết thêm chi tiết về ngôn ngữ được hỗ trợ.

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

Ghi một tên không hợp lệ hoặc không rõ sẽ đưa trang vào thể loại theo dõi. Xem mục #Thể loại lỗi tô màu cú pháp trong trang này để biết thêm chi tiết.

line

Thuộc tính line cho phép đánh số dòng.

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

start

Thuộc tính start (đi kèm với line) định nghĩa số dòng đầu tiên của khối mã. Ví dụ, line start="55" sẽ làm cho số dòng bằng đầu từ dòng thứ 55.

def quick_sort(arr):
    less = []
<syntaxhighlight lang="python" line start="55">
...
</syntaxhighlight>
Phiên bản MediaWiki:
1.36
Gerrit change 653142

Thuộc tính linelinks (đi kèm với line) sẽ thêm neo liên kết vào từng dòng của khối mã. Bạn có thể nhấn vào số dòng để nhận liên kết tô màu vào dòng được chọn, và dùng chúng trong liên kết trong hoặc ngoài. You can also hold ⇧ Shift and click on another line number to get a link that highlights the selected range of lines (Since MediaWiki 1.42change 1007640). When JavaScript is disabled, single-line highlights can be created and existing ones jump to the right location, but the highlight is missing; however, range highlights don’t work at all, so consider using single-line highlights only for accessibility if meaningfully possible. The value of the attribute is used as a prefix for the anchors, to distinguish multiple code blocks on one page.

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

Click here to jump to and highlight line 3 in the code block above. Click here to jump to and highlight lines 2-4 in the code block above.

<syntaxhighlight lang="python" line linelinks="example">
...
</syntaxhighlight>

[[#example-3|...]]
[[#example-2--example-4|...]]

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").

The line number specification ignores any renumbering of the displayed line numbers with the start attribute.
def quick_sort(arr):
    less = []
    pivot_list = []
    more = []
    if len(arr) <= 1:
        return arr

is the result of:

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

inline

Phiên bản MediaWiki:
1.26

The attribute indicates that the source code should be inline as part of a paragraph (as opposed to being its own block). (introduced in 1.26)

Using the "enclose" parameter is deprecated; if set to "none", it should be replaced with inline; otherwise, it can be removed entirely.
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:

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

Is the result of:

The following <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 quick_sort(arr):
	less = []
	pivot_list = []
	more = []
	if len(arr) <= 1:
		return arr
	else:
		pass

Is the result of:

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

copy

Phiên bản MediaWiki:
1.43

The copy attribute adds a button link that copies the content to the clipboard when clicked.

This attribute cannot be used together with the inline attribute. If both are specified, copy will be ignored.

For example:

def quick_sort(arr):
    less = []

Is the result of:

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

Supported languages

‎<syntaxhighlight> using Pygments now includes a native wikitext lexer since version 2.15.0.

Pygments library provides syntax-highlighting for hundreds of programming languages and file formats through its built-in regex-based lexing mechanism termed lexers.

Generally, lang uses the lowercase version of the language name, but many languages also have aliases or "short names" as they are called in the Pygments documentation; see Pygments lexers and SyntaxHighlight.lexers.php.

Languages previously supported by GeSHi have been mapped to equivalent Pygments lexers, see SyntaxHighlightGeSHiCompat.php.

As of January 2020, the list of programming languages supported by Pygments is:

Programming languages

  • ActionScript
  • Ada
  • Agda (incl. literate)
  • Alloy
  • AMPL
  • ANTLR
  • APL
  • AppleScript
  • Assembly (various)
  • Asymptote
  • Augeas
  • AutoIt
  • Awk
  • BBC Basic
  • Befunge
  • BlitzBasic
  • Boa
  • Boo
  • Boogie
  • BrainFuck
  • C, C++ (incl. dialects like Arduino)
  • C#
  • Chapel
  • Charm++ CI
  • Cirru
  • Clay
  • Clean
  • Clojure
  • CoffeeScript
  • ColdFusion
  • Common Lisp
  • Component Pascal
  • Coq
  • Croc (MiniD)
  • Cryptol (incl. Literate Cryptol)
  • Crystal
  • Cypher
  • Cython
  • D
  • Dart
  • DCPU-16
  • Delphi
  • Dylan (incl. console)
  • Eiffel
  • Elm
  • Emacs Lisp
  • Email
  • Erlang (incl. shell sessions)
  • Ezhil
  • Factor
  • Fancy
  • Fantom
  • Fennel
  • FloScript
  • Forth
  • Fortran
  • FreeFEM++
  • F#
  • GAP
  • Gherkin (Cucumber)
  • GLSL shaders
  • Golo
  • Gosu
  • Groovy
  • Haskell (incl. Literate Haskell)
  • HLSL
  • HSpec
  • Hy
  • IDL
  • Idris (incl. Literate Idris)
  • Igor Pro
  • Io
  • Jags
  • Java
  • JavaScript
  • Jasmin
  • Jcl
  • Julia
  • Kotlin
  • Lasso (incl. templating)
  • Limbo
  • LiveScript
  • Logtalk
  • Logos
  • Lua
  • Mathematica
  • Matlab
  • Modelica
  • Modula-2
  • Monkey
  • Monte
  • MoonScript
  • Mosel
  • MuPad
  • NASM
  • Nemerle
  • NesC
  • NewLISP
  • Nimrod
  • Nit
  • Notmuch
  • NuSMV
  • Objective-C
  • Objective-J
  • Octave
  • OCaml
  • Opa
  • OpenCOBOL
  • ParaSail
  • Pawn
  • PHP
  • Perl 5
  • Pike
  • Pony
  • PovRay
  • PostScript
  • PowerShell
  • Praat
  • Prolog
  • Python (incl. console sessions and tracebacks)
  • QBasic
  • Racket
  • Raku a.k.a. Perl 6
  • REBOL
  • Red
  • Redcode
  • Rexx
  • Ride
  • Ruby (incl. irb sessions)
  • Rust
  • S, S-Plus, R
  • Scala
  • Scdoc
  • Scheme
  • Scilab
  • SGF
  • Shell scripts (Bash, Tcsh, Fish)
  • Shen
  • Silver
  • Slash
  • Slurm
  • Smalltalk
  • SNOBOL
  • Snowball
  • Solidity
  • SourcePawn
  • Stan
  • Standard ML
  • Stata
  • Swift
  • Swig
  • SuperCollider
  • Tcl
  • Tera Term language
  • TypeScript
  • TypoScript
  • USD
  • Unicon
  • Urbiscript
  • Vala
  • VBScript
  • Verilog, SystemVerilog
  • VHDL
  • Visual Basic.NET
  • Visual FoxPro
  • Whiley
  • Xtend
  • XQuery
  • Zeek
  • Zephir
  • Zig

Template languages

  • Angular templates
  • Cheetah templates
  • ColdFusion
  • Django / Jinja templates
  • ERB (Ruby templating)
  • Evoque
  • Genshi (the Trac template language)
  • Handlebars
  • JSP (Java Server Pages)
  • Liquid
  • Myghty (the HTML::Mason based framework)
  • Mako (the Myghty successor)
  • Slim
  • Smarty templates (PHP templating)
  • Tea
  • Twig

Other markup

  • Apache config files
  • Apache Pig
  • BBCode
  • CapDL
  • Cap'n Proto
  • CMake
  • Csound scores
  • CSS
  • Debian control files
  • Diff files
  • Dockerfiles
  • DTD
  • EBNF
  • E-mail headers
  • Extempore
  • Flatline
  • Gettext catalogs
  • Gnuplot script
  • Groff markup
  • Hexdumps
  • HTML
  • HTTP sessions
  • IDL
  • Inform
  • INI-style config files
  • IRC logs (irssi style)
  • Isabelle
  • JSGF notation
  • JSON, JSON-LD
  • Lean theorem prover
  • Lighttpd config files
  • Linux kernel log (dmesg)
  • LLVM assembly
  • LSL scripts
  • Makefiles
  • MoinMoin/Trac Wiki markup
  • MQL
  • MySQL
  • NCAR command language
  • Nginx config files
  • Nix language
  • NSIS scripts
  • Notmuch
  • POV-Ray scenes
  • Puppet
  • QML
  • Ragel
  • Redcode
  • ReST
  • Roboconf
  • Robot Framework
  • RPM spec files
  • Rql
  • RSL
  • Scdoc
  • SPARQL
  • SQL, also MySQL, SQLite
  • Squid configuration
  • TADS 3
  • Terraform
  • TeX
  • Thrift
  • TOML
  • Treetop grammars
  • USD (Universal Scene Description)
  • Varnish configs
  • VGL
  • Vim Script
  • WDiff
  • Windows batch files
  • XML
  • XSLT
  • YAML
  • Windows Registry files
Since MediaWiki 1.37 more lexers were added with the update of pygments to version 2.10.0 as detailed with T280117.
  • ansys
  • apdl
  • asc
  • gcode
  • golang === go
  • gsql
  • jslt
  • julia-repl
  • kuin
  • meson
  • nestedtext
  • nodejsrepl
  • nt
  • omg-idl
  • output
  • pem
  • procfile
  • pwsh
  • smithy
  • teal
  • thingsdb
  • ti
  • wast
  • wat

Lexers previously supported by GeSHi

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

Lexers previously supported by GeSHi
Code Language
4cs GADV 4CS
6502acme MOS 6502 (6510) ACME Cross Assembler
6502kickass MOS 6502 (6510) Kick Assembler
6502tasm MOS 6502 (6510) TASM/64TASS
68000devpac Motorola 68000 - HiSoft Devpac ST 2 Assembler
abap ABAP
actionscript ActionScript
actionscript3 ActionScript3
ada Ada
algol68 ALGOL 68
apache Apache Configuration
applescript AppleScript
apt_sources Apt sources
arm ARM Assembler
asm Assembly
asp Active Server Pages (ASP)
asymptote Asymptote
autoconf Autoconf
autohotkey AutoHotkey
autoit AutoIt
avisynth AviSynth
awk AWK
bascomavr BASCOM AVR
bash Bash
basic4gl Basic4GL
bf Brainfuck
bibtex BibTeX
blitzbasic Blitz BASIC
bnf Backus–Naur Form
boo Boo
c C
c_loadrunner C Loadrunner
c_mac C (Mac)
caddcl AutoCAD DCL
cadlisp AutoLISP
cfdg CFDG
cfm ColdFusion Markup Language
chaiscript ChaiScript
cil Common Intermediate Language (CIL)
clojure Clojure
cmake CMake
cobol COBOL
coffeescript CoffeeScript
cpp C++
cpp-qt C++ (Qt toolkit)
csh C shell
csharp C#
css Cascading Style Sheets (CSS)
cuesheet Cue sheet
d D
dart Dart
dcl Data Control Language
dcpu16 DCPU-16
dcs Data Conversion System
delphi Delphi
diff Diff
div DIV
dosbatch DOS batch file
dot DOT
e E
ebnf Extended Backus–Naur Form
ecmascript ECMAScript
eiffel Eiffel
email Email (mbox / eml / RFC format)
epc Enerscript
erlang Erlang
euphoria Euphoria
f1 Formula One
falcon Falcon
fo FO
fortran Fortran
freebasic FreeBASIC
freeswitch FreeSWITCH
fsharp Fsharp
gambas Gambas
gdb GDB
genero Genero
genie Genie
gettext gettext
glsl OpenGL Shading Language (GLSL)
gml Game Maker Language (GML)
gnuplot gnuplot
go Go
groovy Groovy
gwbasic GW-BASIC
haskell Haskell
haxe Haxe
hicest HicEst
hq9plus HQ9+
html4strict HTML (use "html" instead)
html5 HTML5 (use "html" instead)
icon Icon
idl Uno IDL
ini INI
inno Inno
intercal INTERCAL
io Io
j J
java Java
java5 Java(TM) 2 Platform Standard Edition 5.0
javascript JavaScript
jquery jQuery
kixtart KiXtart
klonec Klone C
klonecpp Klone C++
kotlin Kotlin
ksh Korn shell
latex LaTeX
lb Liberty BASIC
ldif LDAP Data Interchange Format
lisp Lisp
llvm LLVM
locobasic Locomotive BASIC
logtalk Logtalk
lolcode LOLCODE
lotusformulas Formula language
lotusscript LotusScript
lscript LightWave 3D
lsl2 Linden Scripting Language
lua Lua
magiksf Magik
m68k Motorola 68000 Assembler
make make
mapbasic MapBasic
matlab MATLAB M
mirc mIRC scripting language
mmix MMIX
modula2 Modula-2
modula3 Modula-3
mpasm Microchip Assembler
mxml MXML
mysql MySQL
nagios Nagios
netrexx NetRexx
newlisp NewLISP
nsis Nullsoft Scriptable Install System (NSIS)
oberon2 Oberon-2
objc Objective-C
objeck Objeck
ocaml OCaml
ocaml-brief OCaml
octave Octave
oobas LibreOffice/OpenOffice.org Basic
oorexx Object REXX
oracle11 Oracle 11 SQL
oracle8 Oracle 8 SQL
oxygene Oxygene
oz Oz
parasail ParaSail
parigp PARI/GP
pascal Pascal
pcre Perl Compatible Regular Expressions
per per
perlpl
Perl
perl6
pl6
raku
Perl 6
pf PF
php PHP
php-brief PHP ((deprecated in phab:T94292) – no colors, odd framing)
pic16 PIC assembly language
pike Pike
pixelbender Pixel Bender
pli PL/I
plsql PL/SQL
postgresql PostgreSQL
postscript PostScript
povray Persistence of Vision Raytracer
powerbuilder PowerBuilder
powershell Windows PowerShell
proftpd ProFTPD
progress OpenEdge Advanced Business Language
prolog Prolog
properties Properties file
providex ProvideX
purebasic PureBasic
pycon Python
pys60 PyS60
python
py
python3
py3
Python
python2
py2
Python 2
q Q
qbasic QBasic/QuickBASIC
rails Rails
rebol Rebol
reg Windows Registry
rexx Rexx
robots robots.txt
rpmspec RPM Spec files
rsplus R
ruby Ruby
sas SAS
scala Scala
scheme Scheme
sh
shell
shell-session
Shell Script (POSIX)
scilab Scilab
sdlbasic SdlBasic
smalltalk Smalltalk
smarty Smarty
spark SPARK
sparql SPARQL
sql SQL
stonescript StoneScript (Scripting language for ShiVa3D)
systemverilog SystemVerilog
tcsh Tcsh
tcl Tcl
teraterm Tera Term
text Plain text
thinbasic thinBasic
ts TypeScript
tsql Transact-SQL
typoscript TypoScript
unicon Unicon
upc Unified Parallel C
urbi URBI
uscript UnrealScript
vala Vala
vb Visual Basic
vbnet Visual Basic .NET
vedit VEDIT
verilog Verilog
vhdl VHDL
vim Vim script
visualfoxpro Visual FoxPro
visualprolog Visual Prolog
whitespace Whitespace
whois Whois
winbatch Winbatch
xml XML
xorg_conf Xorg.conf
yaml YAML
xpp Microsoft Dynamics AX
z80 ZiLOG Z80 Assembler
zxbasic ZXBasic


Installation

This extension comes with MediaWiki 1.21 and later, so you do not need to download it. The remaining configuration instructions must still be followed.
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 move the extracted SyntaxHighlight_GeSHi folder to your extensions/ directory.
    Developers and code contributors should install the extension from Git instead, using:
    cd extensions/
    git clone https://gerrit.wikimedia.org/r/mediawiki/extensions/SyntaxHighlight_GeSHi
    
  • Only when installing from git, Chạy Composer để cài đặt các phần phụ thuộc PHP, bằng cách cung cấp composer install --no-dev trong thư mục phần mở rộng. (Xem T173141 để biết các xung đột có thể xảy ra.)
  • Thêm mã sau vào dưới cùng tệp $LocalSettings của bạn:
    wfLoadExtension( 'SyntaxHighlight_GeSHi' );
    
  • In Linux, set execute permissions for the pygmentize binary.

You can use an FTP client or the following shell command to do so:

chmod a+x /path/to/extensions/SyntaxHighlight_GeSHi/pygments/pygmentize
  • Yes Xong – Chuyển tới Special:Version trên wiki của bạn để xác nhận phần mở rộng được cài đặt thành công.


Vagrant installation:

  • Nếu sử dụng Vagrant , cài đặt bằng vagrant roles enable syntaxhighlight --provision
When installing from Git, please note that starting from MediaWiki 1.26, and ending with MediaWiki 1.31 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à!
Cảnh báo Cảnh báo: When uploading the extension via FTP be sure to upload the pygments/pygmentize file with the transfer type binary.

Configuration

$wgSyntaxHighlightMaxLines, $wgSyntaxHighlightMaxBytes Optional For performance reasons, blobs or pages (JS, Lua and CSS pages) larger than these values will not be highlighted. (introduced in 1.40)
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";.
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
  • See phab:T128993 on this for further suggestions and information.
  • SELinux can also prevent the extension from running with an error similar to type=AVC msg=audit(1609598265.169:225924): avc: denied { execute } for pid=2360888 comm="bash" name="pygmentize" dev="dm-0" ino=50814399 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:httpd_user_content_t:s0 tclass=file permissive=0 in your audit.log. This can be allowed with setsebool -P httpd_unified 1
  • In earlier versions of this extension, Windows would sometimes fail with an _Py_HashRandomization_Init error. This was a bug with the Windows environment not being passed to python executions. A fix was released in 1.40, with backports to 1.38 and 1.39.

VisualEditor integration

The plugin enables direct editing with VisualEditor. A popup is opened when a user wants to edit syntaxhighlight sections. For this to work, VisualEditor must be installed and configured from the latest Git version, same for Parsoid. The feature may not work with older Parsoid versions. See Extension:SyntaxHighlight/VisualEditor for details.

Using with MediaWiki-Docker

See MediaWiki-Docker/Extension/SyntaxHighlight for instructions on configuring a MediaWiki-Docker environment for SyntaxHighlight usage, development, and testing.

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.
    • Tab stop length for ‎<syntaxhighlight> may be adjusted using a ‎<span style=""> tag nested inside it that specifies the tab-size (its own style attribute cannot be used to specify the tab stops, and ‎<div> cannot be used instead): ‎<span style="-moz-tab-size: nn; -o-tab-size: nn; tab-size: nn;">
    • The -moz- prefix is required for Firefox (from version 4.0 to version 90), and the -o- prefix is required for Opera (from version 10.60 to version 15).[4]
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

  • Extensions dependent on this one:
  • Alternative extensions:
    • Extension:Highlightjs Integration syntax highlighter that uses HighlightJS library (includes support for some languages that are missing from Pygments, such as Maxima).
    • Extension:ExternalContent embed external content, such as code from GitHub, GitLab, and Bitkeeper repos with automatic rendering of Markdown files; and using syntax highlighting via the Prism.js library for nearly 300 supported languages. Content indexed by CirrusSearch


Footnotes

  1. Xem bài viết vấn đề của syntaxhighlight so với nhúng mã
  2. phab:T104109#3879800
  3. lexer: splits the source into tokens, fragments of the source that have a token type that determines what the text represents semantically (e.g., keyword, string, or comment). There is a lexer for every language or markup format that Pygments supports. See https://pygments.org/docs/quickstart/
  4. devmo:Web/CSS/tab-size