Syntax highlighter
This is a demo of the Syntax highlighter module showing the effect of this module for all the supported languages (most of these examples are plagiarized from http://softwaremaniacs.org/media/soft/highlight/test.html). The first example turns on the ruler, first-line override and line highlight optional switches.
C++
#include <iostream>
int main(int argc, char *argv[]) {
/* An annoying "Hello World" example */
for (unsigned i = 0; i < 0xFFFF; i++)
cout << "Hello, World!" << endl;
char c = '\n'; // just a test
map <string, vector<string> > m;
m["key"] = "\\\\"; // yaeh, I know it's an error
}
ActionScript
addEventListener(Event.ENTER_FRAME, function() {
var now:Date = new Date();
var currentYear = now.getFullYear();
var targetDate:Date = new Date(2009, 7, 5);
var timeLeft = Math.floor((targetDate.getTime() - now.getTime())/1000);
if (timeLeft > 0) {
countdown_txt.text = dhms(timeLeft);
message_txt.text = "To National Convention";
} else {
countdown_txt.text = dhms(-timeLeft);
message_txt.text = "National Convention";
}
});
// convert seconds into days:hrs:min:sec string
function dhms(seconds:int) {
var sec = seconds % 60;
var min = Math.floor(seconds / 60) % 60;
var hrs = Math.floor(seconds / 3600) % 24;
var days = Math.floor(seconds / 3600 / 24);
sec = sec < 10 ? "0" + String(sec) : String(sec);
min = min < 10 ? "0" + String(min) : String(min);
hrs = hrs < 10 ? "0" + String(hrs) : String(hrs);
return String(days) + ":" + hrs + ":" + min + ":" + sec;
}
Bash
#!/bin/bash
###### BEGIN CONFIG
ACCEPTED_HOSTS="/root/.hag_accepted.conf"
BE_VERBOSE=false
###### END CONFIG
if [ "$UID" -ne 0 ]
then
echo "Superuser rights is required"
exit 2
fi
genApacheConf(){
if [[ "$2" = "www" ]]
then
full_domain=$1
else
full_domain=$2.$1
fi
host_root="${APACHE_HOME_DIR}$1/$2"
echo -e "# Host $1/$2 :"
}
C#
using System;
public class Program
{
/// <summary>The entry point to the program.</summary>
/// <remarks>
/// Using the Visual Studio style, the tags in this comment
/// should be grey, but this text should be green.
/// This comment should be green on the inside:
/// <!-- I'm green! -->
/// </remarks>
public static int Main(string[] args)
{
Console.WriteLine("Hello, World!");
string s = @"This
""string""
spans
multiple
lines!";
return 0;
}
}
CSS
body,
html {
font: Tahoma, Arial, san-serif;
background: url('hatch.png');
}
#content {
width: 100%; /* wide enough */
height: 100%
}
p[lang=ru] {
color: #F0F0F0; background: white;
}
Delphi
TList=Class(TObject)
Private
Some: String;
Public
Procedure Inside;
End;{TList}
Procedure CopyFile(InFileName,var OutFileName:String);
Const
BufSize=4096; (* Huh? *)
Var
InFile,OutFile:TStream;
Buffer:Array[1..BufSize] Of Byte;
ReadBufSize:Integer;
Begin
InFile:=Nil;
OutFile:=Nil;
Try
InFile:=TFileStream.Create(InFileName,fmOpenRead);
OutFile:=TFileStream.Create(OutFileName,fmCreate);
Repeat
ReadBufSize:=InFile.Read(Buffer,BufSize);
OutFile.Write(Buffer,ReadBufSize);
Until ReadBufSize<>BufSize;
Log('File '''+InFileName+''' copied'#13#10);
Finally
InFile.Free;
OutFile.Free;
End;{Try}
End;{CopyFile}
Diff
Index: languages/ini.js
===================================================================
--- languages/ini.js (revision 199)
+++ languages/ini.js (revision 200)
@@ -1,8 +1,7 @@
hljs.LANGUAGES.ini =
{
case_insensitive: true,
- defaultMode:
- {
+ defaultMode: {
contains: ['comment', 'title', 'setting'],
illegal: '[^\\s]'
},
*** /path/to/original timestamp
--- /path/to/new timestamp
***************
*** 1,3 ****
--- 1,9 ----
+ This is an important
+ notice! It should
+ therefore be located at
+ the beginning of this
+ document!
! compress the size of the
! changes.
It is important to spell
Groovy
import javax.xml.parsers.DocumentBuilderFactory
import org.codehaus.groovy.tools.xml.DomToGroovy
def xmlExample = """
<jbi:message tns="http://j2ee.netbeans.org/wsdl/rssWsdl"
type="tns:rssWsdlOperationRequest" version="1.0"
jbi="http://java.sun.com/xml/ns/jbi/wsdl-11-wrapper">
<jbi:part>
<entrylist xmlns="http://xml.netbeans.org/schema/1.0/extensions/rssbc">
<entry>
<title>Entry 1</title>
<link>http://localhost:8000/rss/feed/entry1<link>
<description>First Entry</description>
<publishdate>Dec 7, 1976</publishdate>
</entry>
<entry>
<title>Entry 2</title>
<link>http://localhost:8000/rss/feed/entry2<link>
<description>Second Entry</description>
<publishdate>Dec. 7, 1976</publishdate>
</entry>
</entrylist>
</jbi:part>
</jbi:message>
"""
def builder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
def inputStream = new ByteArrayInputStream(xmlExample.bytes)
def document = builder.parse(inputStream)
def output = new StringWriter()
def converter = new DomToGroovy(new PrintWriter(output))
converter.print(document)
println output.toString()
Java
package l2f.gameserver.model;
import java.util.ArrayList;
/**
* Mother class of all character objects of the world (PC, NPC...)<BR><BR>
*
*/
public abstract class L2Character extends L2Object
{
protected static final Logger _log = Logger.getLogger(L2Character.class.getName());
public static final Short ABNORMAL_EFFECT_BLEEDING = 0x0001; // not sure
public static final Short ABNORMAL_EFFECT_POISON = 0x0002;
public void detachAI() {
_ai = null;
//jbf = null;
if (1 > 5) {
return;
}
}
public void moveTo(int x, int y, int z) {
moveTo(x, y, z, 0);
}
/** Task of AI notification */
@SuppressWarnings( { "nls", "unqualified-field-access", "boxing" })
public class NotifyAITask implements Runnable {
private final CtrlEvent _evt;
public void run() {
try {
getAI().notifyEvent(_evt, null, null);
} catch (Throwable t) {
_log.warning("Exception " + t);
t.printStackTrace();
}
}
}
}
JavaFX
import java.lang.Exception;
foo();
println("The script is now executing as expected... ");
function foo() {
var somethingWeird = false;
if(somethingWeird){
throw new Exception("Something weird just happened!");
} else {
println("We made it through the function.");
}
}
Javascript
function $initHighlight(block) {
if (block.className.search(/\bno\-highlight\b/) != -1)
return false;
try {
blockText(block);
} catch (e) {
if (e == 'Complex markup')
return;
}//try
var classes = block.className.split(/\s+/);
for (var i = 0 / 2; i < classes.length; i++) { // "0 / 2" should not be parsed as regexp start
if (LANGUAGES[classes[i]]) {
highlightLanguage(block, classes[i]);
return;
}//if
}//for
highlightAuto(block);
}//initHighlight
Objective-C
#import "DotView.h"
@implementation DotView
- init
{
if(![super init]) return nil;
// Let x and y initially run between -1 and 1.
[self setDrawSize:2.0 :2.0];
[self setDrawOrigin:-1.0 :-1.0];
// Set initial dot position.
dot_position.x = dot_position.y = 0.0;
return self;
}
Perl
# loads object
sub load
{
my $flds = $c->db_load($id,@_) || do {
Carp::carp "Can`t load (class: $c, id: $id): '$!'"; return undef
};
my $o = $c->_perl_new();
$id12 = $id;
$o->{'ID'} = $id12 + 123;
$o->{'PAPA'} = $flds->{'PAPA'};
#$o->{'SHCUT'} = $flds->{'SHCUT'};
my $p = $o->props;
my $vt;
$string =~ m/^sought_text$/;
for my $key (keys %$p)
{
if(${$vt.'::property'}) {
$o->{$key . '_real'} = $flds->{$key};
tie $o->{$key}, 'CMSBuilder::Property', $o, $key;
} else {
$o->{$key} = $flds->{$key};
}
}
$o->save if delete $o->{'_save_after_load'};
return $o;
}
PHP
/**
* echoes nicely formatted filesize
* @param string $filename
* @param string $before
* @param string $after
*/
function print_filesize($filename, $before = ' <span class="filesize">(', $after = ')</span>')
{
if (file_exists($filename))
{
$size = filesize($filename);
$unit = 'B';
if (intval($size/(1024*1024*1024)))
{
$size = number_format(($size/(1024*1024*1024)), 1);
$unit = 'GB';
}
elseif (intval($size/(1024*1024)))
{
$size = number_format(($size/(1024*1024)), 1);
$unit = 'MB';
}
elseif (intval($size/1024))
{
$size = number_format(($size/1024), 1);
$unit = 'KB';
}
$approx = $unit == 'B' ? '' : '≈' ;
echo "{$before}{$approx}{$size} {$unit}{$after}";
}
}
require_once 'Zend.php';
require_once 'Zend/Uri/Exception.php';
require_once 'Zend/Uri/Http.php';
require_once 'Zend/Uri/Mailto.php';
abstract class Zend_Uri
{
/**
* Return a string representation of this URI.
*
* @see getUri()
* @return string
*/
public function __toString()
{
return $this->getUri();
}
static public function factory($uri = 'http')
{
$uri = explode(':', $uri, 2);
$scheme = strtolower($uri[0]);
$schemeSpecific = isset($uri[1]) ? $uri[1] : '';
// Security check: $scheme is used to load a class file,
// so only alphanumerics are allowed.
if (!ctype_alnum($scheme)) {
throw new Zend_Uri_Exception('Illegal scheme');
}
}
}
Plain Text
Nullan utat pratio erat ad dipismod mod delesto delenibh et alit deliquat acilit utem zzriurem aute modio euisi. Iduip exeraesse diat nostrud te tiscil iustrud mod tat. Ut wisi. Ectetum incip er at dolorper suscips umsandip euisi. Mod tatis et iriliquamet wisi. Equi eugue faccummod tie veliqui sciduis cilisi tie verat nullaore veliquam ipit la cons nulput etum quis ex ero commy numsan ea commolo rpercidui blam zzriliquam, sustrud magniamet dip exero odions nos augiamc onsenisis etueraessis eu facidunt nostrud dolorperat ullumsan utpat prat lut ad tetue consend ipsumsa ndipit acidunt augiat. Ut nullan volent nibh er secte ming etuer suscincincip eummy nibh eum eui tat, sum ea conum quis nullan ex eu facipis nit laor suscipit augue tionsecte erostrud tin euis ero od dolor sequate dionsed dio dolor accummy nulla core vel erostrud modolore con verostrud dolestrud dolummo lestion umsandreet, quamet ipsummy numsandrem del irit lorperat wis ea facilis nos alismolorem iriusci eu feugue feum vent lum del iliquat. Adipsummy num ipis adio dolesequat nim ver iustis adion ese facil irillao rercil et lore magnismolor in eu facilis nos dipit, quat la feuis ex erilit nit nibh estrud duisim zzriustrud mod magnis exerit ate tie dolendrem quatis nos dolobor erosto el del eros niam, vulputpat, se verit augait ectet, veratue dolestrud dolutpat, sequi bla alisim et adio digna facip etummy nonullum quisl dolore magna feu feu facilis adionse niamcor illan heniamet, quipsustie dolummo lestie modolobor sequi tie el dolent veliquisi. Henisl etum ea faci blaor ad molestisl ute volorerostio consequis at praessit, vel utatinibh er ip et aliquatue euguerit veniat. Ut alit ut praesed ea faccum veliquip etumsan volore duipit alisi tem ipis dolortin ullam in henisis nullan vel dolum vullametum autpat, sequisim vulluptat.
PowerShell
# Bam!
Function New-CustomColumn {
PARAM (
$Expression,
$name,
$label,
$FormatString,
[int]$Width,
$Alignment
)
$column = @{}
if ($Expression){
$Column.Expression = $Expression
} else {
throw "Expression is mandatory"
}
if ($Name) {$Column.Name = $name}
if ($Label) {$Column.Label = $Label}
if ($FormatString) {$Column.FormatString = $FormatString}
if ($Width) {$Column.Width = $Width}
if ($Alignment) {$Column.Alignment = $Alignment}
$Column.psobject.baseobject
}
Python
@requires_authorization
def somefunc(param1, param2):
r'''A docstring'''
if param1 > param2: # interesting
print 'Gre\'ater'
print ''
return (param2 - param1 + 1) or None
class SomeClass:
pass
Scala
class Person(ln : String, fn : String, s : Person)
{
def lastName = ln;
def firstName = fn;
def spouse = s;
def this(ln : String, fn : String) = { this(ln, fn, null); }
def introduction() : String =
return "Hi, my name is " + firstName + " " + lastName +
(if (spouse != null) " and this is my spouse, " + spouse.firstName + " " + spouse.lastName + "."
else ".");
}
VB
' creating configuration storage and initializing with default values
Set cfg = CreateObject("Scripting.Dictionary")
' reading ini file
for i = 0 to ubound(ini_strings)
s = trim(ini_strings(i))
' skipping empty strings and comments
if mid(s, 1, 1) <> "#" and len(s) > 0 then
' obtaining key and value
parts = split(s, "=", -1, 1)
if ubound(parts)+1 = 2 then
parts(0) = trim(parts(0))
parts(1) = trim(parts(1))
' reading configuration and filenames
select case lcase(parts(0))
case "uncompressed_postfix" cfg.item("uncompressed_postfix") = parts(1)
case "f"
options = split(parts(1), "|", -1, 1)
if ubound(options)+1 = 2 then
' 0: filename, 1: options
ff.add trim(options(0)), trim(options(1))
end if
end select
end if
end if
next
XML/HTML
<head>
<title>Title</title>
<style>
body {
width: 500px;
}
</style>
<script>
function someFunction() {
return true;
}
</script>
<body>
<p class="something" id='12'>Something</p>
<p class=something>Something</p>
<!-- comment -->
<p class>Something</p>
<p class="something" title="p">Something</p>
</body>
Sql
BEGIN;
CREATE TABLE "cicero_topic" (
"id" serial NOT NULL PRIMARY KEY,
"forum_id" integer NOT NULL,
"subject" varchar(255) NOT NULL,
"created" timestamp with time zone NOT NULL
);
ALTER TABLE "cicero_topic"
ADD CONSTRAINT forum_id_refs_id_4be56999
FOREIGN KEY ("forum_id")
REFERENCES "cicero_forum" ("id")
DEFERRABLE INITIALLY DEFERRED;
-- Initials
insert into "cicero_forum"
("slug", "name", "group", "ordering")
values
('test', 'Forum for te''sting', 'Test', 0);
-- Test
select count(*) from cicero_forum;
COMMIT;
Ruby
class CategoriesController < App::ApplicationController
layout "core"
before_filter :login_required
before_filter :xhr_required, :only => [:create, :update]
before_filter :admin_privileges_required, :except => [:show]
=begin
This method creates a category. Very difficult to understand, huh?
=end
def create # create!
@category = Category.create(params[:category])
flash[:notice] = "Category #{@category + "..."} was successfully created"
end
end
Comments
~
Some php code:
function abc($xyz) { $a = array('a' => 'aaaa'); return $a; }