SourceBlock

Summary: Source code syntax highlighter for PmWiki 2.x using GeSHi
Version: 2019-07-16
Status: Stable
Prerequisites: pmwiki-2.1 and Original GeSHi (tested with v1.0.8.11 19th of Aug, 2012) or GitHub continued version (v1.0.9.1), required for PHP81
Optional: Linked Resource Extras recipe for external files handling
License: MIT
Maintainer: Dfaure
Categories: Layout PHP55 PHP72 PHP81
Discussion: SourceBlock-Talk
Users: +9 (View / Edit)

Question answered by this recipe

I tried the (abandoned) Beautifier recipe to perform syntax highlighting for my source code but still wasn't very satisfied... What's next?

Description

Here you'll find SourceBlock: a script recipe dedicated to syntax highlighting, which offers more features:

  • Numbered lines on some source code.
  • Ordered lists item number preserved when mixed with source code excerpts.
  • Extra highlighting to point-out specific source lines.
  • Page layout preserved with auto/forced word wrapping of source code lines.
  • Language neutral mode without errors when the language is not specified or not recognized.
  • Link to view/download individual source code excerpts.

Notes and Comments

SourceBlock is based on GeSHi, a source code highlighting script last updated on 19th of Aug, 2012, already used in several other wiki systems. In the meantime GeSHi development and downloads have moved to https://github.com/GeSHi/geshi-1.0.

Installation

  1. Download and copy sourceblock.phpΔ to the cookbook/ directory.
  2. Download and unpack the current GeSHi distribution to a newly created cookbook/geshi directory.
    • The 'cookbook/geshi' directory should contain the geshi.php file and the geshi subdirectory containing the ~250 syntax files.
  3. Enable the recipe in your local/config.php file with:
    include_once("$FarmD/cookbook/sourceblock.php");

Markup

Once installed, it adds markup of the form:

(:source PARAMETERS... :) [@
source code
@]

and:

(:source PARAMETERS... :)
source code
(:sourceend:)

with the following optional PARAMETERS:

  • lang=LANGUAGE to select one of the supported highlighters,
  • linenum{=LINE_NUMBER} to enable line numbers and optionally specify styling alternative,
  • linestart=START_NUMBER to specify the initial line number.
  • tabwidth=TAB_WIDTH to set the number of spaces to use for tab replacement(*).
  • header=TEXT and footer=TEXT to surround the source code(*).
  • highlight='LINE_NUMBER1, LINE_NUMBER2,...' to specify the line numbers to point-out (separators are spaces, comma and semicolon).
  • -trim to disable the automatic trimming of source.
  • -link to disable the automatic generation of documentation links(*).
  • -getcode, +getcode to disable or enable the "Get Code" view/download code link (see below).
  • id=ID, class=CLASS to overload default styles definitions.
(*)Only meaningful with lang=LANGUAGE defined.

SourceBlock configures GeSHi to use <div> and style sheets then word wrapping is less problematic.

In order to be a full alternative to CodeBlock, SourceBlock provides following extra markup to generate <pre>(formatted) sections (with optional wrapping):

(:code wrap=OUTPUT_WIDTH :) [@
source code
@]

and:

(:code wrap=OUTPUT_WIDTH :)
source code
(:codeend:)

Both markups don't need to start a new line, and may be appended to list elements without altering their order.

The extra "Get Code" link provides a direct access to the unformatted code. The markup also handle the related parameters:

  • filename=<name> to provide a relevant name to the block.
  • -inline to force browsers to download the block content (ie. sole available behavior in Internet Explorer).

Blocks appearance is controlled via style sheets parts overrideable in config.php. Defaults style are given as recipe samples in the sandbox below.

An additional:

(:source langs:)

markup form is available to list all the languages supported by the GeSHi installation.

Optional external file handling

The recipe script detects any previous installation of the Linked Resource Extras recipe and if so, provide the two more markup directive to render external files:

(:source FILE_RESOURCE PARAMETERS... :)

and:

(:code FILE_RESOURCE PARAMETERS... :)

The markup parameters have the same meaning. Please refer to Linked Resource Extras recipe page for more details on the FILE_RESOURCE specification itself.

SandBox

(:source lang=css header="$HTMLStylesFmt['sourceblock'] = '" footer="';":) [=
.sourceblocklink {
  text-align: right;
  font-size: smaller;
}
.sourceblocktext {
  padding: 0.5em;
  border: 1px solid #808080;
  color: #000000;
  background-color: #F1F0ED;
}
.sourceblocktext div {
  font-family: monospace;
  font-size: small;
  line-height: 1;
  height: 1%;
}

.sourceblocktext div.head,
.sourceblocktext div.foot {
  font: italic medium serif;
  padding: 0.5em;
}=]
$HTMLStylesFmt['sourceblock'] = '
.sourceblocklink {
  text-align: right;
  font-size: smaller;
}
.sourceblocktext {
  padding: 0.5em;
  border: 1px solid #808080;
  color: #000000;
  background-color: #F1F0ED;
}
.sourceblocktext div {
  font-family: monospace;
  font-size: small;
  line-height: 1;
  height: 1%;
}

.sourceblocktext div.head,
.sourceblocktext div.foot {
  font: italic medium serif;
  padding: 0.5em;
}
';
(:source lang=css header="$HTMLStylesFmt['codeblock'] = '" footer="';":)
.codeblocklink {
  text-align: right;
  font-size: smaller;
}
.codeblocktext {
  text-align: left;
  padding: 0.5em;
  border: 1px solid #808080;
  color: #000000;
  background-color: #F1F0ED;
}
.codeblocktext pre {
  font-family: monospace;
  font-size: small;
  line-height: 1;
}
(:sourcend:)
$HTMLStylesFmt['codeblock'] = '
.codeblocklink {
  text-align: right;
  font-size: smaller;
}
.codeblocktext {
  text-align: left;
  padding: 0.5em;
  border: 1px solid #808080;
  color: #000000;
  background-color: #F1F0ED;
}
.codeblocktext pre {
  font-family: monospace;
  font-size: small;
  line-height: 1;
}
';
(:source lang=bash:)
#!/bin/sh

# petit script qui genere la cle et le certificat d'un site https
DIR=/etc/apache-ssl/ssl-cert
# nom du certif/du site
NAME=$1
SSL=`which openssl`

# check if dir is OK
if [ ! -d $DIR ]; then
        echo "Dir $DIR not found, building it."
        mkdir -p $DIR
fi
(:sourcend:)
#!/bin/sh

# petit script qui genere la cle et le certificat d'un site https
DIR=/etc/apache-ssl/ssl-cert
# nom du certif/du site
NAME=$1
SSL=`which openssl`

# check if dir is OK
if [ ! -d $DIR ]; then
        echo "Dir $DIR not found, building it."
        mkdir -p $DIR
fi
(:source lang=sql linenum tabwidth=4 :)
-- Find all Boards and the schools they Govern
-- Include the status of the school

SELECT sch.orgname AS 'SchoolName', 
	bot.orgName AS 'BoardName', 
	sch.[OrgEventStatusCode] AS Status
FROM organisation AS sch,
	orgGroup AS og ,
	organisation AS bot
WHERE bot.BusinessEntityID = og.OrgBusinessEntityID	-- get the org that is the OWNER
AND og.MemberBusinessEntityID = sch.BusinessEntityID	-- get the org that is the MEMBER
AND og.OrgGroupEndDate is NULL		-- NOT an ended group membership
AND og.orgRoleGroupCode = 'GOVERN'	-- Group for school boards
AND og.OrgRoleCode = 'SCHBRD'		-- Role for school board members
ORDER BY BoardName
(:sourcend:)
  1. -- Find all Boards and the schools they Govern
  2. -- Include the status of the school
  3.  
  4. SELECT sch.orgname AS 'SchoolName',
  5.     bot.orgName AS 'BoardName',
  6.     sch.[OrgEventStatusCode] AS STATUS
  7. FROM organisation AS sch,
  8.     orgGroup AS og ,
  9.     organisation AS bot
  10. WHERE bot.BusinessEntityID = og.OrgBusinessEntityID -- get the org that is the OWNER
  11. AND og.MemberBusinessEntityID = sch.BusinessEntityID    -- get the org that is the MEMBER
  12. AND og.OrgGroupEndDate IS NULL      -- NOT an ended group membership
  13. AND og.orgRoleGroupCode = 'GOVERN'  -- Group for school boards
  14. AND og.OrgRoleCode = 'SCHBRD'       -- Role for school board members
  15. ORDER BY BoardName
# blupp blupp blupp\\
(:source lang=php:)
<? echo "here's some code"; ?>
(:sourcend:)

# blipp blipp
  1. blupp blupp blupp
    <? echo "here's some code"; ?>
  2. blipp blipp
(:source lang=xml:)
<skos:Concept rdfs:label="root" xmlns:skos="http://www.w3.org/2004/02/skos/core"
  xmlns:my="http://www.ontologies.thomson.com/MyVocabulary" 
  xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema" tr:index="1">
</skos:Concept>
(:sourcend:)
<skos:Concept rdfs:label="root" xmlns:skos="http://www.w3.org/2004/02/skos/core"
  xmlns:my="http://www.ontologies.thomson.com/MyVocabulary"
  xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema" tr:index="1">
</skos:Concept>

Release Notes

2019-07-16
PHP 7.2 fix
2014-09-08
Fixed stupid bug
2014-08-26
Updated recipe for PHP 5.5
2012-07-06
Fixed bug in style handling (multiple blocks on the same page).
2012-07-05
Integrated suggested modifications (trimming reduced to line-breaks, sorted languages list).
2009-01-27
Fixed multiple blocks of code with different languages on the same page bug. Fixed 'linenum=...' option and introduced 'linestart=...'.
2008-09-16
Fixed the '-getcode' option handling for the (:source:) markup.
2008-06-12
Fixed bugs introduced by previous style features and some code cleanup.
2008-06-11
Added the 'id=...' and class=... style related options. Reduced PHP notice messages. Fixed bug in option handling.
2008-01-02
Added (:source langs:) markup to list supported languages.
2007-12-05
Fixed XHTML validation issue.
2007-10-18
Fixed external file handling (was limited to Attachments).
2007-09-13
Fixed trimming bug. Added ';' as highlighting line separator
2007-09-10
Added the '-getcode' option. Renamed the confusing '-attach' to '-inline' option.
2007-05-07
Added forgotten <:vspace> fix.
2007-04-30
Code cleanup. Added a fix to "Get Code" feature. Added support for external files.
2006-10-25
Added RecipeInfo data.
2006-09-07
Code cleanup. Added highlight feature.
2006-03-07
Fixed IE css glitch. Updated licensing terms.
2006-02-28
Heavily revamped to allow view/download of individual source code excerpts.
2005-09-04
Fixed <:vspace> oddities with 2.0.0 and above.
2005-06-15
Fixed bug eating last line when using source without lang attribute.
2005-04-01
Fixed bug preventing different languages on the same page.
2005-03-29
Synced with 2.0.beta27 markup directive syntax.

See Also

Cookbook /
Ape  Embed videos, maps, documents, and more in wiki pages (Stable)
Beautifier  Perform syntax highlighting for source code displayed on wiki pages
CodeMirror  An enhanced page editor for PmWiki (Stable)
Gists  Markup to allow easy embedding of syntax-highlighted github gists (active)
LinkedResourceExtras  Linked resource helper functions and scripts for recipe writers (Beta)
PITS  The PmWiki Issue Tracking System (Beta)
PmPygment  Display code highlighting using Python pygment (Stable)
Precode  General utility block markup for displaying codes with syntax highlighting (Active/Stable)
Syntaxlove  Syntax highlighting with good look and cool JavaScript-effects
ZCode  Extract and highlight source code files from 7z, TAR, ZIP, or RAR archives (Experimental)

Contributors

Comments

See discussion at SourceBlock-Talk

List of all supported languages

Geshi Version: 1.0.9.0

langfull name
4csGADV 4CS
6502acmeMOS 6502 (6510) ACME Cross Assembler format
6502kickassMOS 6502 (6510) Kick Assembler format
6502tasmMOS 6502 (6510) TASM/64TASS 1.46 Assembler format
68000devpacMotorola 68000 - HiSoft Devpac ST 2 Assembler format
abapABAP
actionscriptActionScript
actionscript3ActionScript 3
adaAda
aimmsAIMMS3
algol68ALGOL 68
apacheApache configuration
applescriptAppleScript
apt_sourcesApt sources
armARM ASSEMBLER
asmASM
aspASP
asymptoteasymptote
autoconfAutoconf
autohotkeyAutohotkey
autoitAutoIt
avisynthAviSynth
awkawk
bascomavrBASCOM AVR
bashBash
basic4glBasic4GL
batchWindows Batch file
bfBrainfuck
biblatexBibTeX
bibtexBibTeX
blitzbasicBlitzBasic
bnfbnf
booBoo
cC
c_loadrunnerC (LoadRunner)
c_macC (Mac)
c_winapiC (WinAPI)
caddclCAD DCL
cadlispCAD Lisp
ceylonCeylon
cfdgCFDG
cfmColdFusion
chaiscriptChaiScript
chapelChapel
cilCIL
clojureClojure
cmakeCMake
cobolCOBOL
coffeescriptCoffeeScript
cppC++
cpp-qtC++ (Qt)
cpp-winapiC++ (WinAPI)
csharpC#
cssCSS
cuesheetCuesheet
dD
dartDart
dclDCL
dcpu16DCPU-16 Assembly
dcsDCS
delphiDelphi
diffDiff
divDIV
dosDOS
dotdot
eE
ecmascriptECMAScript
eiffelEiffel
emaileMail (mbox)
epcEPC
erlangErlang
euphoriaEuphoria
eztEZT
f1Formula One
falconFalcon
foFO (abas-ERP)
fortranFortran
freebasicFreeBasic
freeswitchFreeSWITCH
fsharpF#
gambasGAMBAS
gdbGDB
generogenero
genieGenie
gettextGNU Gettext
glslglSlang
gmlGML
gnuplotGnuplot
goGo
groovyGroovy
gwbasicGwBasic
haskellHaskell
haxeHaxe
hicestHicEst
hq9plusHQ9+
html4strictHTML
html5HTML5
iconIcon
idlUno Idl
iniINI
innoInno
intercalINTERCAL
ioIo
ispfpanelISPF Panel
jJ
javaJava
java5Java(TM) 2 Platform Standard Edition 5.0
javascriptJavascript
jclJCL
jqueryjQuery
juliaJulia
kixtartKiXtart
klonecKLone C
klonecppKLone C++
kotlinKotlin
latexLaTeX
lbLiberty BASIC
ldifLDIF
lispLisp
llvmLLVM Intermediate Representation
locobasicLocomotive Basic
logtalkLogtalk
lolcodeLOLcode
lotusformulasLotus Notes @Formulas
lotusscriptLotusScript
lscriptLScript
lsl2LSL2
luaLua
m68kMotorola 68000 Assembler
magiksfMagikSF
makeGNU make
mapbasicMapBasic
mathematicaMathematica
matlabMatlab M
mercuryMercury
metapostMetaPost
mircmIRC Scripting
mk-61МК-61/52
mmixMMIX
modula2Modula-2
modula3Modula-3
mpasmMicrochip Assembler
mxmlMXML
mysqlMySQL
nagiosNagios
netrexxNetRexx
newlispnewlisp
nginxnginx
nimrodNimrod
nsisNSIS
oberon2Oberon-2
objcObjective-C
objeckObjeck Programming Language
ocamlOCaml
ocaml-briefOCaml (brief)
octaveGNU/Octave
oobasOpenOffice.org Basic
oorexxooRexx
oracle11Oracle 11 SQL
oracle8Oracle 8 SQL
oxygeneOxygene
ozOZ
parasailParaSail
parigpPARI/GP
pascalPascal
pcrePCRE
perper
perlPerl
perl6Perl 6
pfOpenBSD Packet Filter
phixPhix
phpPHP
php-briefPHP (brief)
pic16PIC16
pikePike
pixelbenderPixel Bender 1.0
pliPL/I
plsqlPL/SQL
postgresqlPostgreSQL
postscriptPostScript
povrayPOVRAY
powerbuilderPowerBuilder
powershellPowerShell
proftpdProFTPd configuration
progressProgress
prologProlog
propertiesPROPERTIES
providexProvideX
purebasicPureBasic
pyconPython (console mode)
pys60Python for S60
pythonPython
qq/kdb+
qbasicQBasic/QuickBASIC
qmlQML
racketRacket
railsRails
rbsRBScript
rebolREBOL
regMicrosoft Registry
rexxrexx
robotsrobots.txt
rpmspecRPM Specification File
rsplusR / S+
rubyRuby
rustRust
sasSAS
sassSass
scalaScala
schemeScheme
scilabSciLab
sclSCL
sdlbasicsdlBasic
smalltalkSmalltalk
smartySmarty
sparkSPARK
sparqlSPARQL
sqlSQL
standardmlStandardML
stonescriptStoneScript
swiftSwift
systemverilogSystemVerilog
tclTCL
tcleggTCLEGG
teratermTera Term Macro
texgraphTeXgraph
textText
thinbasicthinBasic
tsqlT-SQL
twigTwig
typoscriptTypoScript
uniconUnicon (Unified Extended Dialect of Icon)
upcUPC
urbiUrbi
uscriptUnreal Script
valaVala
vbVisual Basic
vbnetvb.net
vbscriptVBScript
veditVedit macro language
verilogVerilog
vhdlVHDL
vimVim Script
visualfoxproVisual Fox Pro
visualprologVisual Prolog
whitespaceWhitespace
whoisWhois (RPSL format)
winbatchWinbatch
xbasicXBasic
xmlXML
xojoXojo
xorg_confXorg configuration
xppX++
yamlYAML
z80ZiLOG Z80 Assembler
zxbasicZXBasic

User notes +9: If you use, used or reviewed this recipe, you can add your name. These statistics appear in the Cookbook listings and will help newcomers browsing through the wiki.