Extension:SyntaxHighlight/pt-br

Esta extensão vem com o MediaWiki 1.21 e versões superiores. The remaining configuration instructions must still be followed.
Category:Extensions bundled with MediaWiki 1.21/pt-br
Para realçar a sintaxe do wikitexto ao usar o editor de código-fonte, consulte a extensão CodeMirror ou os scripts dos usuários Remember the dot e Cacycle.
Category:GPL licensed extensions/pt-br
Manual de extensões do MediaWiki
SyntaxHighlight
Estado da versão: estávelCategory:Stable extensions/pt-br
Implementação Marcação Category:Tag extensions/pt-br
Descrição Permite que o código-fonte tenha a sintaxe destacada nas páginas wiki
Autor(es)
Última versão atualizações contínuas
Política de
compatibilidade
A master mantém a compatibilidade com versões anteriores.
MediaWiki 1.25+Category:Extensions with manual MediaWiki version/pt-br
Modifica o banco
de dados
Não
Licença GNU GPL (Licença Pública Geral) 2.0 ou superior
Download Category:Extensions in Wikimedia version control/pt-br
README
  • $wgPygmentizePath
  • $wgSyntaxHighlightMaxLines
  • $wgSyntaxHighlightMaxBytes
<syntaxhighlight>
Traduzir a extensão SyntaxHighlight
Problemas Tarefas em aberto · Relatar um bug
Category:All extensions/pt-br

A extensão SyntaxHighlight, anteriormente conhecida como SyntaxHighlight_GeSHi, fornece formatação rica de código-fonte usando a marcação <syntaxhighlight>. Ela é "alimentada" pela biblioteca Pygments e suporta centenas de diferentes linguagens de programação e formatos de arquivos.

Assim como as marcaçõess <pre> e <poem>, o texto é renderizado exatamente como foi digitado, preservando qualquer espaço em branco.

The SyntaxHighlight extension does not work on wiki installations hardened using Hardened-PHP due to the lack of proc_open, shell_exec and other functions. Veja T250763.

A marcação (tag) <syntaxhighlight> se tornou cara desde a versão 1.39 para 5.000 ou alguma outra quantidade extrema de marcações (tags) de realce de sintaxe em uma única página, como para a Wikilivros. Aumente o valor do tempo limite do servidor web em ambientes em casos extremos. (Veja T316858.)

Uso

Uma vez instalada, você pode usar marcações "syntaxhighlight" nas páginas wiki. Por exemplo,

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

é o resultado da seguinte marcação de wikitexto:

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

To use on source code that is transcluded, for example from a module call, use the #tag parser and safesubst::[1]

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

Em versões mais antigas (antes do MediaWiki 1.16), a extensão usava a marcação <source>. Isso ainda é suportado, mas está obsoleto. <syntaxhighlight> deve ser usada em seu lugar.


Estilo

Se o código exibido for muito grande, você pode ajustá-lo colocando o seguinte na página MediaWiki:Common.css em sua wiki (crie-a se não existir):

/* O código para folhas de estilos em cascatas (F.E.C., C.S.S.) colocado aqui será aplicado a todos os temas (aparências, skins) */
.mw-highlight pre {
	font-size: 90%;
    /*  Insert additional CSS styling here */
}

Encapsular blocos de código em bordas pode ser feito inserindo uma linha como border: 1px dashed blue; na seção acima. O controle sobre a família de fontes (font family) usada também pode ser exercido inserindo uma linha como font-family: "Courier New", monospace; na seção acima.


Categoria de erro de realce de sintaxe

A extensão adiciona páginas que possuem um atributo lang inválido em uma marcação <syntaxhighlight> a uma categoria de rastreamento. A chave de mensagem MediaWiki:syntaxhighlight-error-category determina o nome da categoria; nesta wiki é Category:Pages with syntax highlighting errors.

O erro mais comum que faz com que as páginas sejam marcadas com esta categoria é uma marcação <syntaxhighlight> sem nenhum atributo lang, porque as versões mais antigas desta extensão suportavam a definição de $wgSyntaxHighlightDefaultLang . Normalmente, elas podem ser substituídas por <pre>, ou $bash ou lang="text" podem ser adicionados à marcação. For example:

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

A categoria também pode ser adicionada, e o conteúdo não será destacado, se houver mais de 1000 linhas ou mais de 100 kB de texto.[2]

Parâmetros

lang

O atributo lang="name" define qual analisador sintático (lexical, "lexer") deve ser usada. A linguagem afeta como a extensão realça o código-fonte. Consulte a seção #Linguagens suportadas para obter detalhes sobre as linguagens suportadas.

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

A especificação de um nome inválido ou desconhecido marcará a página com uma categoria de rastreamento. Consulte a seção #Categoria de erro de realce de sintaxe nesta página para obter detalhes.

line

O atributo line permite números de linhas.

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

start

O atributo start (em combinação com line) define o número da primeira linha do bloco de código. Por exemplo, line start="55" fará com que a numeração das linhas comece em 55.

def quick_sort(arr):
    less = []
<syntaxhighlight lang="python" line start="55">
...
</syntaxhighlight>
Versão do MediaWiki:
1.36
Gerrit change 653142

The linelinks attribute (in combination with line) adds link anchors to each line of the code block. You can click on the line numbers to get a link that highlights the selected line, and use them in internal and external links. 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.42 change 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

O atributo highlight especifica uma ou mais linhas que devem ser marcadas (destacando essas linhas com uma cor de fundo diferente). Você pode especificar vários números de linhas separados por vírgulas (por exemplo, highlight="1,4,8") ou intervalos usando dois números de linhas e um hífen (por exemplo, highlight="5-7").

A especificação do número de linha ignora qualquer renumeração dos números de linha exibidos com o atributo start.
def quick_sort(arr):
    less = []
    pivot_list = []
    more = []
    if len(arr) <= 1:
        return arr

é o resultado de

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

inline

Versão do MediaWiki:
1.26

O atributo indica que o código-fonte deve estar embutido como parte de um parágrafo (em vez de ser seu próprio bloco). (introduzido na 1.26)

O uso do parâmetro "incluir" ("enclose") está obsoleto; se definido como "nenhum" ("none"), deve ser substituído por "embutido" ("inline"); caso contrário, ele pode ser removido totalmente.
As quebras de linhas podem ocorrer em qualquer espaço entre as marcações de abertura e fechamento, a menos que o código-fonte seja marcado como inquebrável com class="nowrap" (nas wikis que o suportam; veja abaixo) ou style="white-space:nowrap".

Por exemplo:

O lambda x: x * 2 a seguir é uma expressão lambda (em inglês) em Python.

É o resultado de:

O <syntaxhighlight lang="python" inline>lambda x: x * 2</syntaxhighlight> a seguir é uma [[w:Lambda (programming)|expressão lambda (em inglês)]] em Python.

class

Quando inline é usado, class="nowrap" (nas wikis que o suportam; não no próprio MediaWiki) especifica que as quebras de linhas não devem ocorrer em espaços dentro do bloco de código.

Por exemplo:

Sem class="nowrap":

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxlambda x: x * 2xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Com style="white-space:nowrap":

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxlambda x: x * 2xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

style

O atributo style permite que atributos de folhas de estilos em cascatas (F.E.C., C.S.S.) sejam incluídos diretamente. Isso é equivalente a colocar o bloco em uma marcação <div> (não <span>). O atributo tab‑size não pode ser especificado dessa forma; ele requer uma marcação <span> envolvente conforme descrito abaixo em Avançado.

Por exemplo:

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

É o resultado de:

<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

Versão do 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>

Línguagens suportadas

<syntaxhighlight> using Pygments now includes a native wikitext lexer.

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.

A partir de janeiro de 2020, a lista completa de linguagens suportadas pela Pygments é:

Linguagens de programação

  • 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

Outras marcações

  • Arquivos de configuração do Apache
  • Apache Pig
  • BBCode
  • CapDL
  • Cap'n Proto
  • CMake
  • Csound scores
  • CSS
  • Arquivos de controle do Debian
  • Diff files
  • Dockerfiles
  • DTD
  • EBNF
  • Cabeçalhos de e-mail
  • 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
  • Arquivos de configuração do Lighttpd
  • Registro do núcleo do Linux (dmesg)
  • LLVM assembly
  • LSL scripts
  • Makefiles
  • MoinMoin/Trac Wiki markup
  • MQL
  • MySQL
  • NCAR command language
  • Arquivos de configuração do Nginx
  • Nix language
  • NSIS scripts
  • Notmuch
  • POV-Ray scenes
  • Puppet
  • QML
  • Ragel
  • Redcode
  • ReST
  • Roboconf
  • Robot Framework
  • RPM spec files
  • Rql
  • RSL
  • Scdoc
  • SPARQL
  • SQL, também MySQL, SQLite
  • Configuração do Squid
  • TADS 3
  • Terraform
  • TeX
  • Thrift
  • TOML
  • Treetop grammars
  • USD (Universal Scene Description)
  • Varnish configs
  • VGL
  • Vim Script
  • WDiff
  • Arquivos de lote do Windows
  • XML
  • XSLT
  • YAML
  • Arquivos de registro do Windows
Desde MediaWiki 1.37 mais analisadores sintáticos (lexicais, "lexers") foram adicionados com a atualização da pygments para a versão 2.10.0 conforme detalhado com 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

Analisadores sintáticos (lexicais, "lexers") suportados anteriormente por GeSHi

Abaixo está uma lista parcial de linguagens que GeSHi poderia destacar, com tachado para linguagens que não são mais suportadas após a mudança para a Pygments.

Analisadores sintáticos (lexicais, "lexers") anteriormente suportados por GeSHi
Código Linguagem
4csGADV 4CS
6502acmeMOS 6502 (6510) ACME Cross Assembler
6502kickassMOS 6502 (6510) Kick Assembler
6502tasmMOS 6502 (6510) TASM/64TASS
68000devpacMotorola 68000 - HiSoft Devpac ST 2 Assembler
abapABAP
actionscriptActionScript
actionscript3ActionScript3
adaAda
algol68ALGOL 68
apacheApache Configuration
applescriptAppleScript
apt_sourcesApt sources
armARM Assembler
asmAssembly
aspActive Server Pages (ASP)
asymptoteAsymptote
autoconfAutoconf
autohotkeyAutoHotkey
autoitAutoIt
avisynthAviSynth
awkAWK
bascomavrBASCOM AVR
bashBash
basic4glBasic4GL
bfBrainfuck
bibtexBibTeX
blitzbasicBlitz BASIC
bnfBackus–Naur Form
booBoo
cC
c_loadrunnerC Loadrunner
c_macC (Mac)
caddclAutoCAD DCL
cadlispAutoLISP
cfdgCFDG
cfmColdFusion Markup Language
chaiscriptChaiScript
cilCommon Intermediate Language (CIL)
clojureClojure
cmakeCMake
cobolCOBOL
coffeescriptCoffeeScript
cppC++
cpp-qtC++ (Qt toolkit)
cshC shell
csharpC#
cssCascading Style Sheets (CSS)
cuesheetCue sheet
dD
dartDart
dclData Control Language
dcpu16DCPU-16
dcsData Conversion System
delphiDelphi
diffDiff
divDIV
dosbatchDOS batch file
dotDOT
eE
ebnfExtended Backus–Naur Form
ecmascriptECMAScript
eiffelEiffel
emailEmail (mbox \ eml \ RFC format)
epcEnerscript
erlangErlang
euphoriaEuphoria
f1Formula One
falconFalcon
foFO
fortranFortran
freebasicFreeBASIC
freeswitchFreeSWITCH
fsharpFsharp
gambasGambas
gdbGDB
generoGenero
genieGenie
gettextgettext
glslOpenGL Shading Language (GLSL)
gmlGame Maker Language (GML)
gnuplotgnuplot
goGo
groovyGroovy
gwbasicGW-BASIC
haskellHaskell
haxeHaxe
hicestHicEst
hq9plusHQ9+
html4strictHTML (use "html" instead)
html5HTML5 (use "html" instead)
iconIcon
idlUno IDL
iniINI
innoInno
intercalINTERCAL
ioIo
jJ
javaJava
java5Java(TM) 2 Platform Standard Edition 5.0
javascriptJavaScript
jqueryjQuery
kixtartKiXtart
klonecKlone C
klonecppKlone C++
kotlinKotlin
kshKorn shell
latexLaTeX
lbLiberty BASIC
ldifLDAP Data Interchange Format
lispLisp
llvmLLVM
locobasicLocomotive BASIC
logtalkLogtalk
lolcodeLOLCODE
lotusformulasFormula language
lotusscriptLotusScript
lscriptLightWave 3D
lsl2Linden Scripting Language
luaLua
magiksfMagik
m68kMotorola 68000 Assembler
makemake
mapbasicMapBasic
matlabMATLAB M
mircmIRC scripting language
mmixMMIX
modula2Modula-2
modula3Modula-3
mpasmMicrochip Assembler
mxmlMXML
mysqlMySQL
nagiosNagios
netrexxNetRexx
newlispNewLISP
nsisNullsoft Scriptable Install System (NSIS)
oberon2Oberon-2
objcObjective-C
objeckObjeck
ocamlOCaml
ocaml-briefOCaml
octaveOctave
oobasLibreOffice/OpenOffice.org Basic
oorexxObject REXX
oracle11Oracle 11 SQL
oracle8Oracle 8 SQL
oxygeneOxygene
ozOz
parasailParaSail
parigpPARI/GP
pascalPascal
pcrePerl Compatible Regular Expressions
perper
perlpl
Perl
perl6
pl6
raku
Perl 6
pfPF
phpPHP
php-briefPHP (deprecated no colors, odd framing)
pic16PIC assembly language
pikePike
pixelbenderPixel Bender
pliPL/I
plsqlPL/SQL
postgresqlPostgreSQL
postscriptPostScript
povrayPersistence of Vision Raytracer
powerbuilderPowerBuilder
powershellWindows PowerShell
proftpdProFTPD
progressOpenEdge Advanced Business Language
prologProlog
propertiesProperties file
providexProvideX
purebasicPureBasic
pyconPython
pys60PyS60
python
py
python3
py3
Python
python2
py2
Python 2
qQ
qbasicQBasic/QuickBASIC
railsRails
rebolRebol
regWindows Registry
rexxRexx
robotsrobots.txt
rpmspecRPM Spec files
rsplusR
rubyRuby
sasSAS
scalaScala
schemeScheme
sh
shell
shell-session
Shell Script (POSIX)
scilabScilab
sdlbasicSdlBasic
smalltalkSmalltalk
smartySmarty
sparkSPARK
sparqlSPARQL
sqlSQL
stonescriptStoneScript (Scripting language for ShiVa3D)
systemverilogSystemVerilog
tcshTcsh
tclTcl
teratermTera Term
textPlain text
thinbasicthinBasic
tsTypeScript
tsqlTransact-SQL
typoscriptTypoScript
uniconUnicon
upcUnified Parallel C
urbiURBI
uscriptUnrealScript
valaVala
vbVisual Basic
vbnetVisual Basic .NET
veditVEDIT
verilogVerilog
vhdlVHDL
vimVim script
visualfoxproVisual FoxPro
visualprologVisual Prolog
whitespaceWhitespace
whoisWhois
winbatchWinbatch
xmlXML
xorg_confXorg.conf
yamlYAML
xppMicrosoft Dynamics AX
z80ZiLOG Z80 Assembler
zxbasicZXBasic


Instalação

A versão desta extensão empacotada com MediaWiki 1.31 requer Python versão 3 (python3) para ser instalada no servidor. Esta é uma mudança da versão empacotada com MediaWiki 1.30, que usava o Python versão 2 (python). Observe que o binário python3 deve ser instalado no PATH de execução do interpretador PHP.
Apesar de sua atualização para a Pygments (e longe de GeSHi) e apesar de seu nome atualizado, esta extensão internamente ainda usa os antigos nomes de arquivos conforme indicado abaixo.
  • Baixe e mova a pasta extraída SyntaxHighlight_GeSHi ao seu diretório extensions/.
    Desenvolvedores e colaboradores de código, por outro lado, deverão instalar a extensão a partir do Git, usando:
    cd extensions/
    git clone https://gerrit.wikimedia.org/r/mediawiki/extensions/SyntaxHighlight_GeSHi
    
  • Se estiver instalando a partir do Git, execute o Composer para instalar as dependências do PHP através do comando composer install --no-dev no diretório da extensão. (Veja T173141 para possíveis complicações.)Category:Extensions requiring Composer with git/pt-br
  • Adicione o seguinte código ao final do seu arquivo LocalSettings.php :
    wfLoadExtension( 'SyntaxHighlight_GeSHi' );
    
  • No Linux, configure as permissões de execução para o binário pygmentize. Você pode usar um cliente de protocolo de transferência de arquivos (P.T.A., F.T.P.) ou o seguinte comando de shell para fazer isso:
chmod a+x /path/to/extensions/SyntaxHighlight_GeSHi/pygments/pygmentize
  • Yes Concluído – Navegue à página Special:Version em sua wiki para verificar se a instalação da extensão foi bem sucedida.


Instalação com o Vagrant:

  • Se estiver usando o Vagrant , instale com vagrant roles enable syntaxhighlight --provision
Ao instalar a partir do Git, por favor observe que a partir da versão MediaWiki 1.26 e terminando com a versão MediaWiki 1.31, esta extensão requer Composer.

Portanto, após a instalação a partir do Git, mude para o diretório que contém a extensão, por exemplo "../extensions/SyntaxHighlight_GeSHi/" e execute composer install --no-dev, ou ao atualizar: composer update --no-dev.

Alternativamente, bem como de preferência, adicione a linha "extensions/SyntaxHighlight_GeSHi/composer.json" ao arquivo "composer.local.json" no diretório raiz de sua wiki, como por exemplo
{
	"extra": {
		"merge-plugin": {
			"include": [
				"extensions/SyntaxHighlight_GeSHi/composer.json"
			]
		}
	}
}
Agora execute composer update --no-dev. Voilà!
Atenção Atenção: Ao enviar a extensão via protocolo de transferência de arquivos (P.T.A., F.T.P.), certifique-se de enviar o arquivo pygments/pygmentize com o tipo de transferência binário.

Configuração

$wgSyntaxHighlightMaxLines, $wgSyntaxHighlightMaxBytes Optional For performance reasons, blobs or pages (JS, Lua and CSS pages) larger than these values will not be highlighted. (introduzido na 1.40)
Linux
$wgPygmentizePath Optional $setting (opcional): Caminho absoluto para o pygmentize do pacote da Pygments. A extensão agrupa o pacote da Pygments e $wgPygmentizePath aponta para a versão agrupada por padrão, mas você pode apontar para uma versão diferente, se desejar. Por exemplo: $wgPygmentizePath = "/usr/local/bin/pygmentize";.
Windows
  • Se você estiver hospedando sua MediaWiki em uma máquina com Windows, você deve definir o caminho para o Pygmentize.exe $wgPygmentizePath = "c:\\Python27\\Scripts\\pygmentize.exe";
    • Se não houver pygmentize.exe, execute easy_install Pygments na linha de comando dentro da pasta Scripts para gerar o arquivo.

Se você estiver usando o binário pygmentize incluído (extensions/SyntaxHighlight_GeSHi/pygments/pygmentize), certifique-se de que seu servidor da web tenha permissão para executá-lo. Se o sua hospedagem (host) não permitir que você adicione executáveis ao seu diretório da web, instale python-pygments e adicione $wgPygmentizePath = pygmentize a LocalSettings.php.

Resolução de problemas

Depois de atualizar para MediaWiki v1.26 e superior, alguns usuários começaram a relatar problemas com a extensão. Pode haver casos em que algumas linguagens, como Lua, podem não ser destacadas e, ao ativar a depuração, a MediaWiki lançaria o erro Notice: Failed to invoke Pygments: /usr/bin/env: python3: No such file or directory.

  • Tente apontar $wgPygmentizePath em LocalSettings.php para um binário pygmentize externo.
  • Em ambientes de hospedagem compartilhada com cPanel, isso pode ser feito configurando um novo aplicativo Python por meio do menu "Configurar aplicativo Python" ("Setup Python app") e ativando o ambiente virtual do aplicativo por meio de shell seguro (Sh.S., S.Sh.) (source /virtualenv/python/3.5/bin/activate). Depois disso, o módulo da Pygments pode ser adicionado ao aplicativo Python, para o qual navegue até o caminho do ambiente virtual (cd virtualenv/python/3.5/bin/), baixe e instale a Pygments (./pip install Pygments) e ative o módulo adicionando "Pygments" no campo "Aplicativos existentes" ("Existing applications") do menu "Configurar aplicativo Python" ("Setup Python app"). Isso criará o arquivo necessário no caminho: virtualenv/python/3.5/bin/pygmentize
  • Veja phab:T128993 sobre isso para mais sugestões e informações.
  • O SELinux também pode impedir que a extensão seja executada com um erro semelhante a 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 em seu audit.log. Isso pode ser permitido com setsebool -P httpd_unified 1
  • Em versões anteriores dessa extensão, o Windows às vezes falhava com um erro _Py_HashRandomization_Init. Esta foi uma falha (bug) com o ambiente do Windows não sendo passado para execuções do python. Uma correção foi lançada na 1.40, com compatibilidade (backports) para a 1.38 e a 1.39.

Integração com o VisualEditor

O plug-in permite edição direta com o VisualEditor. Uma pop-up é aberta quando um usuário deseja editar as seções da syntaxhighlight. Para que isso funcione, o VisualEditor deve ser instalado e configurado a partir da versão mais recente do Git, o mesmo para o Parsoid. O recurso pode não funcionar com versões mais antigas do Parsoid. Veja Extension:SyntaxHighlight/VisualEditor para detalhes

Using with MediaWiki-Docker

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

Avançado

  • Diferentemente das marcações <pre> e <code>, entidades de caracteres da linguagem de marcação de hipertexto (L.M.Ht., Ht.M.L.) como &nbsp; não precisam (e não devem) ter o caractere & escapado como &amp;..
  • Como a marcação <pre>, mas diferentemente da marcação <code>, as marcações dentro do intervalo (além de sua própria marcação de fechamento) não precisam ter o símbolo < escapado como &lt;, nem o wikitexto precisa ser escapado com uma marcação <nowiki>.
  • Além disso, enquanto <pre> assume paradas de tabulação a cada 8 caracteres e renderiza tabulações usando espaços reais quando o texto renderizado é copiado, <syntaxhighlight> usa paradas de tabulação de 4 espaços (exceto Internet Explorer, que usa 8) e preserva os caracteres de tabulação no texto renderizado ; o último pode ser alterado usando uma marcação $span envolvente (não $div, e não usando seu próprio atributo $style).
    • 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;">
    • O prefixo -moz- é necessário para o Firefox (da versão 4.0 à versão 90) e o prefixo -o- é necessário para o Opera (da versão 10.60 à versão 15).[3]

(Observe que a caixa de edição da wiki assume tabulações de 8 espaços. Isso se aplica apenas às páginas salvas reais; as visualizações geradas por meio de uma caixa de edição ou Special:ExpandTemplates podem ser diferentes.)

Ver também


Notas

Category:Extensions used on Wikimedia/pt-br#SyntaxHighlight/pt-br Category:Syntax highlighting extensions/pt-br Category:GeSHi extensions/pt-br Category:Extensions with VisualEditor support/pt-br
Category:All extensions/pt-br Category:ApiFormatHighlight extensions/pt-br Category:ContentAlterParserOutput extensions/pt-br Category:Extensions available as Debian packages/pt-br Category:Extensions bundled with MediaWiki 1.21/pt-br Category:Extensions in Wikimedia version control/pt-br Category:Extensions included in BlueSpice/pt-br Category:Extensions included in Canasta/pt-br Category:Extensions included in Fandom/pt-br Category:Extensions included in Miraheze/pt-br Category:Extensions included in MyWikis/pt-br Category:Extensions included in ProWiki/pt-br Category:Extensions included in ShoutWiki/pt-br Category:Extensions included in WikiForge/pt-br Category:Extensions included in semantic::core/pt-br Category:Extensions included in wiki.gg/pt-br Category:Extensions requiring Composer with git/pt-br Category:Extensions used on Wikimedia/pt-br Category:Extensions with VisualEditor support/pt-br Category:Extensions with manual MediaWiki version/pt-br Category:GPL licensed extensions/pt-br Category:GeSHi extensions/pt-br Category:ParserFirstCallInit extensions/pt-br Category:ResourceLoaderRegisterModules extensions/pt-br Category:SoftwareInfo extensions/pt-br Category:Stable extensions/pt-br Category:Syntax highlighting extensions/pt-br Category:Tag extensions/pt-br