dojox.highlight

client-side syntax highlighting for a number of languages.

NOTE: All languages listed here have working language definitions, though not all exist in the release or dojo subversion. The missing packs are not publically available. based on

Examples:

Some Python code:

@requires_authorization
def somefunc(param1, param2):
  '''A docstring'''
  if param1 > param2: # interesting
    print 'Gre\'ater'
    print ''
  return param2 - param1 + 1
  
class SomeClass:
    pass

A chunk of PHP:


$opAr = array (    "-a|--append", // a or append toggle, nothing extra
        "-i|--input:", // i or input with next input being needed
        "-l|--list:",           // l with input needed
        //"--foo",     // broken
        "-f:",           // f with no input
        "--wot:"      // wot with input, no short
        );


$op = bgetop($opAr);
if (is_array($op)) { print_r($op); }

/* here is the code: */

function bgetop($opAr=array(),$unknown=true) {

$argv = $_SERVER['argv'];
$argc = $_SERVER['argc'];
$argPos = 1; // zero is program running

// foreach arg
while ($argPos<$argc) {
    $arg = $argv[$argPos];
    if ($arg{0}=="-") {
        if ($arg{1}=="-") {
        $var = substr($arg,2,strlen($arg));
        } else { $var = $arg{1}; }
        foreach ($opAr as $opk => $opv) {
            if (!isset($return[$var])) {
            if (strpos($opv,$arg) !== FALSE) {
                // this is where the -f -foo fix needs to be,
                // the partial string exists in this record,
                // but we need to determine if it's accurate
                // somehow (i'm thinking: eregi?)
                if ($accurate=1) {
                    // we foudn the key
                    if (strpos($opv,':') !== FALSE) {
                        // next value is the one to use,
                        // then skip it in the parser.
                        if (isset($argv[$argPos+1])) {
                            $return[$var] = $argv[++$argPos];
                            } else {
                            $return[$var] = FALSE;     
                            }
                        } else {
                        // just set the toggle
                        $return[$var] = TRUE;
                        }
                    // don't check this opAr value again
                    unset($opAr[$opk]);
                    }
                } // if accurate
            } // !isset already
            } // foreach opAr    
    } else { // we weren't expecting a non-hyphened argument, possibly just a filename, or whatnot
        if ($unknown) { $return['unknown'][]=$arg; }
    }
    $argPos++;
} // while argPos < argc

if (is_array($return)) {
return $return;
} else { return 0; }

} // end function bgetop

A custom XML document:

<?xml version="1.0"?>
<response value="ok">
  <text>Ok</text>
  <comment/>
  <ns:description><![CDATA[ 
  CDATA is <not> magical. 
  ]]></ns:description>
</response>

Some HTML code:

<head>
  <title>Title</title>
<body>
  <p class="something">Something</p>
  <p class=something>Something</p>
  <!-- comment -->
  <p class>Something</p>
  <p class="something" title="p">Something</p>
</body>

HTML with Django templates:

{% if articles|length %}
{% for article in articles %}

{# Striped table #}
<tr class="{% cycle odd,even %}">
  <td>{{ article|default:"Hi... "|escape }}</td>
  <td>{{ article.date|date:"d.m.Y" }}</td>
</tr>
  
{% endfor %}
{% endif %}

{% comment %}
Comments may be long and
multiline.
{% endcomment %}

Some CSS code:

body, 
html {
  font: Tahoma, Arial, san-serif;
}

#content {
  width: 100%; /* css comment */
  height: 100%
}

p[lang=ru] {
  color: red;
}

Explicit Python highlight:

for x in [1, 2, 3]:
  count(x)

Disabled highlighting:

<div id="contents">
  <p>Hello, World!
</div>

Normal dojo-looking code


dojo.provide("some.object");
dojo.declare("some.object",null,{
	param: "value",
	_myMethod: function(/* Event */e){
		this.inherited(arguments);
	},
	// comments
	_another: function(){
		dojo.addClass("foo","hovered");
	}
});
dojo.addOnLoad(function(){
	//
	// comments with <HTML> inline
	var d = dojo;
	d.mixin(d,{
		foo: function(e){
			d.bar(e);
		},
		bar: function(e){
			alert(e);
		}
	});
});

Lazy, xhr'd code:

//>>built
define("dojo/aspect", [], function(){

// TODOC: after/before/around return object
// TODOC: after/before/around param types. 

/*=====
	dojo.aspect = {
		// summary: provides aspect oriented programming functionality, allowing for
		//		one to add before, around, or after advice on existing methods.
		//
		// example:
		//	|	define(["dojo/aspect"], function(aspect){
		//	|		var signal = aspect.after(targetObject, "methodName", function(someArgument){
		//	|			this will be called when targetObject.methodName() is called, after the original function is called
		//	|		});
		//
		// example:
		//	The returned signal object can be used to cancel the advice.
		//	|	signal.remove(); // this will stop the advice from being executed anymore
		//	|	aspect.before(targetObject, "methodName", function(someArgument){
		//	|		// this will be called when targetObject.methodName() is called, before the original function is called
		//	|	 });
		
		after: function(target, methodName, advice, receiveArguments){
			// summary: The "after" export of the aspect module is a function that can be used to attach
			//		"after" advice to a method. This function will be executed after the original method
			//		is executed. By default the function will be called with a single argument, the return
			//		value of the original method, or the the return value of the last executed advice (if a previous one exists).
			//		The fourth (optional) argument can be set to true to so the function receives the original
			//		arguments (from when the original method was called) rather than the return value.
			//		If there are multiple "after" advisors, they are executed in the order they were registered.
			// target: Object
			//		This is the target object
			// methodName: String
			//		This is the name of the method to attach to.
			// advice: Function
			//		This is function to be called after the original method
			// receiveArguments: Boolean?
			//		If this is set to true, the advice function receives the original arguments (from when the original mehtod
			//		was called) rather than the return value of the original/previous method.
			// returns:
			//		A signal object that can be used to cancel the advice. If remove() is called on this signal object, it will
			//		stop the advice function from being executed.
		},
		
		before: function(target, methodName, advice){
			// summary: The "before" export of the aspect module is a function that can be used to attach
			//		"before" advice to a method. This function will be executed before the original method
			//		is executed. This function will be called with the arguments used to call the method.
			//		This function may optionally return an array as the new arguments to use to call
			//		the original method (or the previous, next-to-execute before advice, if one exists).
			//		If the before method doesn't return anything (returns undefined) the original arguments
			//		will be preserved.
			//		If there are multiple "before" advisors, they are executed in the reverse order they were registered.
			//
			// target: Object
			//		This is the target object
			// methodName: String
			//		This is the name of the method to attach to.
			// advice: Function
			//		This is function to be called before the original method	 
		},

		around: function(target, methodName, advice){
			// summary: The "around" export of the aspect module is a function that can be used to attach
			//		"around" advice to a method. The advisor function is immediately executed when
			//		the around() is called, is passed a single argument that is a function that can be
			//		called to continue execution of the original method (or the next around advisor).
			//		The advisor function should return a function, and this function will be called whenever
			//		the method is called. It will be called with the arguments used to call the method.
			//		Whatever this function returns will be returned as the result of the method call (unless after advise changes it).
			//
			// example:
			//		If there are multiple "around" advisors, the most recent one is executed first,
			//		which can then delegate to the next one and so on. For example:
			//		|	around(obj, "foo", function(originalFoo){
			//		|		return function(){
			//		|			var start = new Date().getTime();
			//		|			var results = originalFoo.apply(this, arguments); // call the original
			//		|			var end = new Date().getTime();
			//		|			console.log("foo execution took " + (end - start) + " ms");
			//		|			return results;
			//		|		};
			//		|	});
			//
			// target: Object
			//		This is the target object
			// methodName: String
			//		This is the name of the method to attach to.
			// advice: Function
			//		This is function to be called around the original method
		}

	};
=====*/

	"use strict";
	function advise(dispatcher, type, advice, receiveArguments){
		var previous = dispatcher[type];
		var around = type == "around";
		var signal;
		if(around){
			var advised = advice(function(){
				return previous.advice(this, arguments);
			});
			signal = {
				remove: function(){
					signal.cancelled = true;
				},
				advice: function(target, args){
					return signal.cancelled ?
						previous.advice(target, args) : // cancelled, skip to next one
						advised.apply(target, args);	// called the advised function
				}
			};
		}else{
			// create the remove handler
			signal = {
				remove: function(){
					var previous = signal.previous;
					var next = signal.next;
					if(!next && !previous){
						delete dispatcher[type];
					}else{
						if(previous){
							previous.next = next;
						}else{
							dispatcher[type] = next;
						}
						if(next){
							next.previous = previous;
						}
					}
				},
				advice: advice,
				receiveArguments: receiveArguments
			};
		}
		if(previous && !around){
			if(type == "after"){
				// add the listener to the end of the list
				var next = previous;
				while(next){
					previous = next;
					next = next.next;
				}
				previous.next = signal;
				signal.previous = previous;
			}else if(type == "before"){
				// add to beginning
				dispatcher[type] = signal;
				signal.next = previous;
				previous.previous = signal;
			}
		}else{
			// around or first one just replaces
			dispatcher[type] = signal;
		}
		return signal;
	}
	function aspect(type){
		return function(target, methodName, advice, receiveArguments){
			var existing = target[methodName], dispatcher;
			if(!existing || existing.target != target){
				// no dispatcher in place
				dispatcher = target[methodName] = function(){
					// before advice
					var args = arguments;
					var before = dispatcher.before;
					while(before){
						args = before.advice.apply(this, args) || args;
						before = before.next;
					}
					// around advice
					if(dispatcher.around){
						var results = dispatcher.around.advice(this, args);
					}
					// after advice
					var after = dispatcher.after;
					while(after){
						results = after.receiveArguments ? after.advice.apply(this, args) || results :
								after.advice.call(this, results);
						after = after.next;
					}
					return results;
				};
				if(existing){
					dispatcher.around = {advice: function(target, args){
						return existing.apply(target, args);
					}};
				}
				dispatcher.target = target;
			}
			var results = advise((dispatcher || existing), type, advice, receiveArguments);
			advice = null;
			return results;
		};
	}
	return {
		before: aspect("before"),
		around: aspect("around"),
		after: aspect("after")
	};
});

Text with inlined JavaScript code: dojo.forEach(a, function(x){ console.log(x); }); — that was the inlined sample.


Markuped code (python), no language was specified:

  1. @requires_authorization 
  2. def somefunc(param1, param2)
  3.   '''A docstring''' 
  4.   if param1 > param2: # interesting 
  5.     print 'Gre\'ater' 
  6.     print '' 
  7.   return param2 - param1 + 1 
  8.    
  9. class SomeClass:<br>    pass 
  10.  
@requires_authorization
def somefunc(param1, param2):
  '''A docstring'''
  if param1 > param2: # interesting
    print 'Gre\'ater'
    print ''
  return param2 - param1 + 1
  
class SomeClass:<br>    pass

Markuped code, "python" was specified:

  1.  
  2. @requires_authorization 
  3. def somefunc(param1, param2)
  4.   '''A docstring''' 
  5.   if param1 > param2: # interesting 
  6.     print 'Gre\'ater' 
  7.     print '' 
  8.   return param2 - param1 + 1 
  9.    
  10. class SomeClass:<br>    pass 
  11.  

@requires_authorization
def somefunc(param1, param2):
  '''A docstring'''
  if param1 > param2: # interesting
    print 'Gre\'ater'
    print ''
  return param2 - param1 + 1
  
class SomeClass:<br>    pass

Some XQuery code:


declare variable $my:entityName as xs:string external;

declare variable $databaseURI := concat('jdbc://getCreditDefaultSwapsByEntityName?cd%&', $my:entityName); 
declare variable $creditDefaultSwaps := collection($databaseURI);

(: This is a comment :)

(: This is a multi-line
comment :)
declare function local:equityRows($root) {
	for $equity in $root//equity
	let $referenceEntity := $creditDefaultSwaps//fpml:referenceEntity
	where $equity/name = $referenceEntity/fpml:entityName
	return
		<tr xmlns="http://www.w3.org/1999/xhtml">
			<td>{ $equity/*:symbol/text() }</td>
			<td>{ $equity/*:name/text() }</td>
			<td>{ $equity/*:high/text() }</td>
			<td>{ $equity/*:currency/text() }</td>
		</tr>
};

<table border="1">
<tr>
	<th>Ticker Symbol</th>
	<th>Company Name</th>
	<th>High</th>
	<th>Currency</th>
</tr>
{ local:equityRows(/) }
</table>

Some Java code:


import java.io.*;
public final class DOHRobot extends Applet{
	// The last reported mouse x,y.
	// If this is different from the real one, something's up.
	private int lastMouseX;
	private int lastMouseY;
	JSObject dohrobot = null;

	final private class onvisible extends ComponentAdapter{
		public void componentShown(ComponentEvent evt){
			/* sets the security manager to fix a bug *
			 * in liveconnect in Safari on Mac        */
			if(key != -1){ return; }
			Thread thread = new Thread(){
				public void run(){
					window = (JSObject) JSObject.getWindow(applet());   
					AccessController.doPrivileged(new PrivilegedAction(){
						public Object run(){
							log("> init Robot");
							try{
								SecurityManager oldsecurity = System.getSecurityManager();
								boolean needsSecurityManager = applet().getParameter("needsSecurityManager").equals("true");
								log("Socket connections managed? "+needsSecurityManager);
								try{
									securitymanager.checkTopLevelWindow(null);
									// xdomain
									if(charMap == null){
										if(!confirm("DOH has detected that the current Web page is attempting to access DOH,\n"+
													"but belongs to a different domain than the one you agreed to let DOH automate.")){
											return null;
										}
									}
								}catch(Exception e){
									e.printStackTrace();
									securitymanager = new RobotSecurityManager(needsSecurityManager,
											oldsecurity);
									System.setSecurityManager(securitymanager);
								}
								// instantiate the Robot
								robot = new Robot();
								robot.setAutoWaitForIdle(true);
							}catch(Exception e){
								key = -2;
								e.printStackTrace();
							}
							return null;
						}
					});
					if(key == -2){
						// applet not trusted
						// start the test without it
						window.eval("doh.robot._appletDead=true;doh.run();");
					}
				}
			};
			thread.start();
		}
	}
}

A Groovy fragment:


/*
* A comment test block
* 
* ?debug
* ?nodebug
* 
*/

def settings = [
	debug: false,
	compress: true,
	console: false,
	ping: false,
	testing: false,
	profile: false
];

// function calls
init(settings);
render(settings);

def render(settings) {
	request.header = settings;
	render();
}

def init(settings) {

	// Default parameter handling.
	settings.each { key, value ->
		def onkey = "${key}";
		def offkey = "no${key}";
		if (foo("/request/params/${onkey}",null) != null) {
			settings[key] = true;
		}
		else if (foo("/request/params/${offkey}",null) != null) {
			settings[key] = false;
		}
	}

	return settings;
}