Recent Changes - Search:

Cookbook

PmWiki

pmwiki.org

SourceBlock

Summary: Source code syntax highlighter for PmWiki 2.x using GeSHi
Version: 2008-06-12
Status: Stable
Prerequisites: pmwiki-2.1 and GeSHi (tested with v1.0.7.22)
Optional: Linked Resource Extras recipe for external files handling
Maintainer: Dfaure
Categories: Layout [Update Me] with the latest version of this recipe

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, an actively developed source code highlighting script, already used in several other wiki systems.

Installation

  1. Download and copy sourceblock.phpΔ to the cookbook/ directory.
  2. Download and unpack GeSHi distribution to a newly created cookbook/geshi directory.
  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{=START_NUMBER} to enable line numbers and optionally specify start value,
  • 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

Release Notes

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 triming 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
Synched with 2.0.beta27 markup directive syntax.

See Also

Beautifier, Linked Resource Extras.

Contributors

Comments

Would be nice if one could render code coming from a local or uploaded file, e.g. like (:source file=http://foo.com/bar.el lang=lisp:). 2006-11-30 Sts

The feature is available in the latest version --Dfaure May 01, 2007, at 02:42 AM

The [Get Code] link inserted above the code frame only works on my site if I first save the file, then open it. When clicked on, I am prompted to download a file (named: sourceblock_1.txt, type: Text Document)... If I choose Open, a file is downloaded, notepad opens and prompts "Cannot find the <path to tempInternetFiles>\sourceblock_1[1].txt file" and all I get is a blank notepad. If I choose Save, the file is saved and contains the code. I have found other sites that implement this recipe and have no problems opening the code directly from their links (not saving the file first), so it must be a configuration problem on my site and not a browser setting problem (IE6). Any ideas where to look? ejersau? April 25, 2007, at 11:48 AM

I found a site where the [Get Code] link is working for my browser and copied their (:sourcecode...:) markup into my wiki sandbox then compared the HTML source of the working site with that generated by mine. The only difference (except for the beginning of the href value) was the line <div class="lisp" style="font-family: monospace;">. The working site did not include the style parameter/argument... which shouldn't make a difference. It must be something in my local/config.php or web server (Apache on Windows). --ejersau? April 30, 2007, at 01:36 PM

While writing the recipe, IE6 has been found to handle very badly 'text/plain' file fragments, so I decided to force it to download them as they were separate files...
...which has been tested to work on IE6 and IE7 until now. A fix is available in the last release. Thanks for the bug report. --Dfaure May 01, 2007, at 02:42 AM

Looks like it was a late night for you :-). The fix works perfect! Much appreciated. --ejersau? May 01, 2007, at 12:51 PM

I was trying to set this script up on my site which uses a customized skin of my own design where the body colour is set to yellow. I added some python code using this recipe, but text that isn't recognized as language keywords are left uncoloured, so I ended up getting yellow-on-grey. If the site's body colour is set to the same colour as the grey div background, then half the text would be invisible! It's a simple fix though: just add a color:black line to the sourceblocktext css; here's a diff patch: sourceblock.diff.phpΔ (Note: this isn't strictly a php file, but I had to rename it as such to work around extension restrictions.)

fixed in the last release --Dfaure September 10, 2007, at 03:21 AM

Thank you! --nfirvine

Also, I found it kind of offputting that the end of the block is specified with "sourcend" and not "sourceend". I fought with that for hours, thinking it was permission errors or something. Just a suggestion. --nfirvine June 09, 2007, at 08:31 PM

seems to be fixed in version current at 2007-08-20 (but not in version loaded against this page)

Thanks again --nfirvine

How does the attach parameter work?

This parameter has been renamed as inline to avoid further confusions. --Dfaure September 10, 2007, at 03:21 AM

How can I use highlight option to highlight certain lines? I tried highlight='1,2,3,4,5' and it does not work. I tried it on my pmwiki 2.2.0-beta56 with geshi 1.0.7.3 and also on this page. --Roman 2007-09-10

This has been verified to work with latest version of Geshi. You may need to upgrade --Dfaure September 13, 2007, at 04:47 AM

Ah, I was confused by Geshi numbering scheme. It works with 1.0.7.20. Thanks, Roman 2007-09-13

Please comment any code changes you make when releasing a new version. I'm using a somewhat modified version of SourceBlock and keeping it in sync with your code isn't the easiest task, I hope you understand. :-) --Ted 2007-09-19

You could also give me more details on your customization that I could eventually take in account in the next version --Dfaure September 19, 2007, at 08:26 AM

It's nothing special in fact, you could call this "minimization"; I've removed "codeblock" markup, code d/l url, plus a few more options keeping just the basics to make recipe smaller and a bit faster. --Ted 2007-09-20

I like SourceBlock very much and without external files it works for me like a charm. But I just can't get external files running.

I installed LinkedResourceExtras and as an "enduser" didn't configure anything else - although this feels a little wrong because the receipe for LinkedResourceExtras says to include_once('cookbook/extlinkedres.php'); which I couldn't find in sourceblock.php. Could you please give a complete example for an external file, e.g. http://www.gnu.org/licenses/fdl.txt?
I tried [EDIT: deleted the wrong ones]
(:source http://www.gnu.org/licenses/fdl.txt :)

(:source http://www.gnu.org/licenses/fdl.txt :)

and only get empty code blocks. Thanks for any help! Frank - October 12, 2007, 7:20 PM

The LinkedResourceExtras must be includes before SourceBlock to be taken in account. Then the dedicated markup is simply (:source FILE_SPECIFICATION PARAMS:).--Dfaure October 14, 2007, at 04:40 AM

Thanks very much for the fast answer, unfortunately I still can't get external files running - please give me a little more details. All I did so far:

  • Installed SourceBlock - I guess I did that right because besides external files it is fully working
  • LinkedResourceExtras:
    • put extlinkedres.php in the cookbook-directory
    • put extlinkedres.js in the pub-directory
    • added "include_once('cookbook/extlinkedres.php');" to my local config.php some lines before "include_once("$FarmD/cookbook/sourceblock.php");" , I hope that's what you meant with "The LinkedResourceExtras must be included before SourceBlock to be taken in account", although I don't understand why this has to be done by the end user...

I tried the different versions for includin an external file as mentioned above but get empty boxes - except for the case I leave out the quotation marks around the URL. Then I get the following error:

Warning: implode(): Bad arguments. in D:\Programme\PMWiki\cookbook\sourceblock.php on line 233

Warning: Cannot modify header information - headers already sent by (output started at D:\Programme\PMWiki\cookbook\sourceblock.php:233) in D:\Programme\PMWiki\pmwiki.php on line 1049

When I only use the (:source ...:) (without (:sourcend:))Syntax I even don't get a code box, but the URL will be made a hyperlink leaving the rest of the text as regular text. I would really appreciate if you could give a very short example here on the page including whatever txt-File or other type that one can find on the internet, e.g. http://www.gnu.org/licenses/fdl.txt

I have no clue whether this is of any relevance: I use PmWiki offline with the server provided from here (Standalone). Thanks in advance for any further help! -- Frank October 18, 2007, at 09:30 AM

[EDIT] Now that I changed the server from the small one to a full server all my problems disappeared within seconds. There seems to be no need to include_once('cookbook/extlinkedres.php' in your config. Thanks for the support! -- Frank October 21, 2007, at 11:30 PM

The "regular" way to proceed is the one which gave an error message ;). The recipe has been updated to better handle this. You should also note that the standalone server seems to be unable to deliver files requested via http by the script itself (atachments and requests to external webservers have been tested to work flawlessly). Thanks for the report. --Dfaure October 18, 2007, at 07:51 AM

In XHTML documents, I get validation errors on pages with "Get Code" links.

Fixed in latest release. Thanks for the report. --Dfaure December 05, 2007, at 09:52 AM

Thanks for this recipe. Just a heads up to others that might be experiencing problems. Initially I couldn't get this recipe to work on my company's LAN. Turnout it's simply because I forgot to update file permission/ownership of the new files/dirs that I copied. -- hua

What is the recommended way of changing colors?

You may either use the id=... or class=... parameters associated with your own stylesheet definition, or alter the $GeshStyles global variable --Dfaure June 11, 2008, at 07:54 AM

Bug. Impossible to mix the following :

(:source -getcode lang=c:)[@ xxx @]

(:source -getcode lang=c:) xxx (:sourcend:)

The different (:source:) markup forms are tailored on the (:markup:) scheme, ie. changing one for the other should be transparent --Dfaure June 11, 2008, at 07:12 AM

Another bug. Sometimes, the sourceblock.php failed with an error on line +151 when I try to use too many (:source:) markup on big pages.

Should be fixed in latest version --Dfaure June 11, 2008, at 11:54 AM

It seems ok :-)
Thanks a lot for your quick answer & correction. It's really a very nice job !

Edit - History - Print - Recent Changes - Search
Page last modified on June 12, 2008, at 08:31 AM