Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

initial import.

git-svn-id: http://svn.danwebb.net/external/CodeHighlighter/trunk@30 a686c101-5f17-0410-80e1-b267258107f6
  • Loading branch information...
commit 1887ac2f8b79fc2f060ad51a803b49c957f4f5d3 0 parents
danwebb authored
186 code_highlighter.js
@@ -0,0 +1,186 @@
+/* Unobtrustive Code Highlighter By Dan Webb 11/2005
+ Version: 0.4
+
+ Usage:
+ Add a script tag for this script and any stylesets you need to use
+ to the page in question, add correct class names to CODE elements,
+ define CSS styles for elements. That's it!
+
+ Known to work on:
+ IE 5.5+ PC
+ Firefox/Mozilla PC/Mac
+ Opera 7.23 + PC
+ Safari 2
+
+ Known to degrade gracefully on:
+ IE5.0 PC
+
+ Note: IE5.0 fails due to the use of lookahead in some stylesets. To avoid script errors
+ in older browsers use expressions that use lookahead in string format when defining stylesets.
+
+ This script is inspired by star-light by entirely cunning Dean Edwards
+ http://dean.edwards.name/star-light/.
+*/
+
+// replace callback support for safari.
+if ("a".replace(/a/, function() {return "b"}) != "b") (function(){
+ var default_replace = String.prototype.replace;
+ String.prototype.replace = function(search,replace){
+ // replace is not function
+ if(typeof replace != "function"){
+ return default_replace.apply(this,arguments)
+ }
+ var str = "" + this;
+ var callback = replace;
+ // search string is not RegExp
+ if(!(search instanceof RegExp)){
+ var idx = str.indexOf(search);
+ return (
+ idx == -1 ? str :
+ default_replace.apply(str,[search,callback(search, idx, str)])
+ )
+ }
+ var reg = search;
+ var result = [];
+ var lastidx = reg.lastIndex;
+ var re;
+ while((re = reg.exec(str)) != null){
+ var idx = re.index;
+ var args = re.concat(idx, str);
+ result.push(
+ str.slice(lastidx,idx),
+ callback.apply(null,args).toString()
+ );
+ if(!reg.global){
+ lastidx += RegExp.lastMatch.length;
+ break
+ }else{
+ lastidx = reg.lastIndex;
+ }
+ }
+ result.push(str.slice(lastidx));
+ return result.join("")
+ }
+})();
+
+var CodeHighlighter = { styleSets : new Array };
+
+CodeHighlighter.addStyle = function(name, rules) {
+ // using push test to disallow older browsers from adding styleSets
+ if ([].push) this.styleSets.push({
+ name : name,
+ rules : rules,
+ ignoreCase : arguments[2] || false
+ })
+
+ function setEvent() {
+ // set highlighter to run on load (use LowPro if present)
+ if (LowPro && Event.onReady)
+ return Event.onReady(CodeHighliter.init);
+
+ var old = window.onload;
+
+ if (typeof window.onload != 'function') {
+ window.onload = CodeHighlighter.init;
+ } else {
+ window.onload = function() {
+ oldonload();
+ CodeHighlighter.init();
+ }
+ }
+ }
+
+ // only set the event when the first style is added
+ if (this.styleSets.length==1) setEvent();
+}
+
+CodeHighlighter.init = function() {
+ if (!document.getElementsByTagName) return;
+ if ("a".replace(/a/, function() {return "b"}) != "b") return; // throw out Safari versions that don't support replace function
+ // throw out older browsers
+
+ var codeEls = document.getElementsByTagName("CODE");
+ // collect array of all pre elements
+ codeEls.filter = function(f) {
+ var a = new Array;
+ for (var i = 0; i < this.length; i++) if (f(this[i])) a[a.length] = this[i];
+ return a;
+ }
+
+ var rules = new Array;
+ rules.toString = function() {
+ // joins regexes into one big parallel regex
+ var exps = new Array;
+ for (var i = 0; i < this.length; i++) exps.push(this[i].exp);
+ return exps.join("|");
+ }
+
+ function addRule(className, rule) {
+ // add a replace rule
+ var exp = (typeof rule.exp != "string")?String(rule.exp).substr(1, String(rule.exp).length-2):rule.exp;
+ // converts regex rules to strings and chops of the slashes
+ rules.push({
+ className : className,
+ exp : "(" + exp + ")",
+ length : (exp.match(/(^|[^\\])\([^?]/g) || "").length + 1, // number of subexps in rule
+ replacement : rule.replacement || null
+ });
+ }
+
+ function parse(text, ignoreCase) {
+ // main text parsing and replacement
+ return text.replace(new RegExp(rules, (ignoreCase)?"gi":"g"), function() {
+ var i = 0, j = 1, rule;
+ while (rule = rules[i++]) {
+ if (arguments[j]) {
+ // if no custom replacement defined do the simple replacement
+ if (!rule.replacement) return "<span class=\"" + rule.className + "\">" + arguments[0] + "</span>";
+ else {
+ // replace $0 with the className then do normal replaces
+ var str = rule.replacement.replace("$0", rule.className);
+ for (var k = 1; k <= rule.length - 1; k++) str = str.replace("$" + k, arguments[j + k]);
+ return str;
+ }
+ } else j+= rule.length;
+ }
+ });
+ }
+
+ function highlightCode(styleSet) {
+ // clear rules array
+ var parsed;
+ rules.length = 0;
+
+ // get stylable elements by filtering out all code elements without the correct className
+ var stylableEls = codeEls.filter(function(item) {return (item.className.indexOf(styleSet.name)>=0)});
+
+ // add style rules to parser
+ for (var className in styleSet.rules) addRule(className, styleSet.rules[className]);
+
+
+ // replace for all elements
+ for (var i = 0; i < stylableEls.length; i++) {
+ // EVIL hack to fix IE whitespace badness if it's inside a <pre>
+ if (/MSIE/.test(navigator.appVersion) && stylableEls[i].parentNode.nodeName == 'PRE') {
+ stylableEls[i] = stylableEls[i].parentNode;
+
+ parsed = stylableEls[i].innerHTML.replace(/(<code[^>]*>)([^<]*)<\/code>/i, function() {
+ return arguments[1] + parse(arguments[2], styleSet.ignoreCase) + "</code>"
+ });
+ parsed = parsed.replace(/\n( *)/g, function() {
+ var spaces = "";
+ for (var i = 0; i < arguments[1].length; i++) spaces+= "&nbsp;";
+ return "\n" + spaces;
+ });
+ parsed = parsed.replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
+ parsed = parsed.replace(/\n(<\/\w+>)?/g, "<br />$1").replace(/<br \/>[\n\r\s]*<br \/>/g, "<p><br></p>");
+
+ } else parsed = parse(stylableEls[i].innerHTML, styleSet.ignoreCase);
+
+ stylableEls[i].innerHTML = parsed;
+ }
+ }
+
+ // run highlighter on all stylesets
+ for (var i in this.styleSets) highlightCode(this.styleSets[i]);
+}
21 css.js
@@ -0,0 +1,21 @@
+CodeHighlighter.addStyle("css", {
+ comment : {
+ exp : /\/\*[^*]*\*+([^\/][^*]*\*+)*\//
+ },
+ keywords : {
+ exp : /@\w[\w\s]*/
+ },
+ selectors : {
+ exp : "([\\w-:\\[.#][^{};>]*)(?={)"
+ },
+ properties : {
+ exp : "([\\w-]+)(?=\\s*:)"
+ },
+ units : {
+ exp : /([0-9])(em|en|px|%|pt)\b/,
+ replacement : "$1<span class=\"$0\">$2</span>"
+ },
+ urls : {
+ exp : /url\([^\)]*\)/
+ }
+ });
19 html.js
@@ -0,0 +1,19 @@
+CodeHighlighter.addStyle("html", {
+ comment : {
+ exp: /&lt;!\s*(--([^-]|[\r\n]|-[^-])*--\s*)&gt;/
+ },
+ tag : {
+ exp: /(&lt;\/?)([a-zA-Z]+\s?)/,
+ replacement: "$1<span class=\"$0\">$2</span>"
+ },
+ string : {
+ exp : /'[^']*'|"[^"]*"/
+ },
+ attribute : {
+ exp: /\b([a-zA-Z-:]+)(=)/,
+ replacement: "<span class=\"$0\">$1</span>$2"
+ },
+ doctype : {
+ exp: /&lt;!DOCTYPE([^&]|&[^g]|&g[^t])*&gt;/
+ }
+});
229 index.html
@@ -0,0 +1,229 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html>
+<head>
+ <title>Code Highlighter 0.4</title>
+ <script type="text/javascript" src="code_highlighter.js"></script>
+ <script type="text/javascript" src="javascript.js"></script>
+ <script type="text/javascript" src="css.js"></script>
+ <script type="text/javascript" src="html.js"></script>
+ <script type="text/javascript" src="ruby.js"></script>
+ <style type="text/css">
+ body {
+ background : #EEE;
+ font-family: Arial, Helvetica, sans-serif;
+ margin : 3em 5em;
+ line-height : 1.5;
+ font-size: 80%;
+ }
+
+ pre {
+ border: 1px solid black;
+ border-color: #BBB #DDD #DDD #BBB;
+ margin : 2em;
+ padding : 1em;
+ line-height: 1.5;
+ background: white;
+ overflow: auto;
+ }
+
+ code {
+ font-size: 1.2em;
+ }
+
+ h1 span {
+ font-size : 0.5em;
+ }
+
+ a {
+ color : gray;
+ }
+
+ /* end of page css - below is for the code highlighter */
+
+ .javascript .comment, .ruby .comment {
+ color : green;
+ }
+
+ .javascript .string, .ruby .string {
+ color : teal;
+ }
+
+ .javascript .keywords, .ruby .keywords {
+ color : navy;
+ }
+
+ .javascript .global {
+ color : blue;
+ }
+
+ .javascript .brackets, .ruby .brackets {
+ color : navy;
+ }
+
+ .css .comment {
+ color : gray;
+ }
+
+ .css .properties {
+ color : navy;
+ }
+
+ .css .selectors {
+ color : maroon;
+ font-weight : bold;
+ }
+
+ .css .units {
+ color :red;
+ }
+
+ .css .urls {
+ color :green;
+ }
+
+ .html .tag {
+ color : purple;
+ }
+
+ .html .comment {
+ color : gray;
+ font-style: italic;
+ }
+
+ .html .string {
+ color : navy;
+ }
+
+ .html .doctype {
+ color : teal;
+ }
+ </style>
+</head>
+
+<body>
+<h1>CodeHighlighter 0.4 <span>by <a href="http://www.danwebb.net">Dan Webb</a></span></h1>
+<p>CodeHighlighter is a lightweight, unobstrusive and fully configurable script for displaying code examples highlighted in a way similar to the way many text editors highlight code. It weighs in at just under 4K, allows users to configure their own style sets so that you can highlight any language you like and is deployable simply by attaching it to a page with the script tag and adding class names as hooks. It should also play nicely with any other scripts on your page as it has a tiny footprint on the global namespace.</p>
+<p>Many thanks to <a href="http://dean.edwards.name">Dean Edwards</a> who's star-light behaviour inspired this.</p>
+<h3>Deploying the script</h3>
+<ol>
+ <li>Add a &lt;script&gt; tag for <a href="CodeHighlighter.js">CodeHighlighter.js</a> and a script tag for each of the code types you want to highlight on your page. At this time there are only very basic style sets for <a href="javascript.js">JavaScript</a>, <a href="css.js">CSS</a> and <a href="html.js">HTML</a>. But it's easy to make your own for any language you like if you know regular expressions. Let me know if you do and I'll link to them.</li>
+ <li>Add an appropriate class to each &lt;code&gt; element that contains code. 'javascript', 'ruby', 'css' or 'html' will do the trick.</li>
+ <li>Define CSS styles for each code element, the script simply parses the code and wraps a &lt;span&gt; tag around each element with the appropriate class name. You just need to write CSS to style the code the way you want. No programming or weirdness required. See the source of this code as an example.</li>
+</ol>
+<h3>Testing</h3>
+<p>Known to work on:</p>
+<ul>
+ <li>IE 5.5+ PC</li>
+ <li>Firefox 1.0/Mozilla 1.3 + PC</li>
+ <li>Opera 7.23 + PC</li>
+ <li>Netscape 7.2 PC</li>
+</ul>
+<p>Known to degrade well on:</p>
+<ul>
+ <li>IE 5.0 PC</li>
+ <li>Safari Mac (Until it supports functions in String#replace())</li>
+</ul>
+<p>Any other feedback for any other browser would be greatly apprieciated. Please email Dan Webb at dan[at]danwebb[dot]net. Have a look through the small examples below.</p>
+<h3>Creating your own style sets for other languages</h3>
+<p>Have a look at this <a href="stylesetguide.htm">guide to creating style sets</a>.</p>
+<p>Cheers,<br /><strong>Dan</strong></p>
+<h2>Inline code</h2>
+<p>Hopefully, you should be able to put some code inline like this: <code class="javascript">document.write("bong")</code> and hopefully it should work.</p>
+<h2>JavaScript Example</h2>
+<pre><code class="javascript">/*
+This script detects external links in a page
+and attaches a behaviour to them so they open
+in a external window.
+*/
+
+function initialiseLinks() {
+ if (document.getElementsByTagName) {
+ var links = document.getElementsByTagName(&quot;A&quot;);
+ for (var i = 0; i &lt; links.length; i++) {
+ if (links[i].href.indexOf(&quot;http:&quot;)==0) {
+ // if the links URL starts with http: then we assume it's an external link
+ links[i].onclick = function() {
+ window.open(this.href);
+ return false; // stop normal link behaviour
+ }
+ }
+ }
+ }
+}
+
+window.onload = initialiseLinks();</code></pre>
+<h2>CSS Example</h2>
+<pre><code class="css">.javascript .comment {
+ color : green; /* ffbgffg */
+}
+
+.javascript .string {
+ color : maroon;
+}
+
+.javascript .keywords {
+ font-weight : bold;
+}
+
+.javascript .global {
+ color : blue;
+ font-weight: bolder;
+}
+
+.javascript .brackets {
+ color : Gray;
+}
+
+.javascript .thing {
+ font-size : 10px;
+ background : url(ghgfhfg gh f.rtjhf);
+}</code></pre>
+<h2>HTML Example</h2>
+<pre><code class="html">&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
+&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
+ &lt;head&gt;
+ &lt;title&gt;CodeHighlighter example&lt;/title&gt;
+ &lt;!-- This is all you need to do to get CodeHighlighter working --&gt;
+ &lt;script type=&quot;text/javascript&quot; src=&quot;CodeHighlighter.js&quot;&gt; &lt;/script&gt;
+ &lt;script type=&quot;text/javascript&quot; src=&quot;html.js&quot;&gt; &lt;/script&gt;
+ &lt;/head&gt;
+ &lt;body&gt;
+ &lt;p&gt;Put your pre tags here!&lt;/p&gt;
+ &lt;/body&gt;
+&lt;/html&gt;</code></pre>
+
+<h2>Ruby Example</h2>
+<pre><code class="ruby">def login
+ if !@params[:key].nil? && @attendee = Attendee.find_by_hashkey(@params[:key])
+ # coming in with valid key
+ if !@attendee.password_set?
+ # no password yet, let them in
+ @session[:attendee] = @attendee
+ redirect_to :action => 'preferences', :id => @attendee.event.uri
+ else
+ @event = @attendee.event
+ end
+ else
+ # if no key we need to know the event
+ @event = get_event_by_id_or_uri
+ end
+
+ if @request.post?
+ # posted login details
+ if @attendee = Attendee.authenticate(@event, @params[:email], @params[:password])
+ @session[:attendee] = @attendee
+ redirect_to :action => 'preferences', :id => @event.uri
+ else
+ flash['notice'] = 'Login unsuccessful.'
+ end
+ end
+
+ if @attendee.nil?
+ @email = ''
+ else
+ @email = @attendee.email
+ end
+ end</code></pre>
+</body>
+</html>
17 javascript.js
@@ -0,0 +1,17 @@
+CodeHighlighter.addStyle("javascript",{
+ comment : {
+ exp : /(\/\/[^\n]*\n)|(\/\*[^*]*\*+([^\/][^*]*\*+)*\/)/
+ },
+ brackets : {
+ exp : /\(|\)/
+ },
+ string : {
+ exp : /'[^']*'|"[^"]*"/
+ },
+ keywords : {
+ exp : /\b(arguments|break|case|continue|default|delete|do|else|false|for|function|if|in|instanceof|new|null|return|switch|this|true|typeof|var|void|while|with)\b/
+ },
+ global : {
+ exp : /\b(toString|valueOf|window|element|prototype|constructor|document|escape|unescape|parseInt|parseFloat|setTimeout|clearTimeout|setInterval|clearInterval|NaN|isNaN|Infinity)\b/
+ }
+});
14 ruby.js
@@ -0,0 +1,14 @@
+CodeHighlighter.addStyle("ruby",{
+ comment : {
+ exp : /#[^\n]+/
+ },
+ brackets : {
+ exp : /\(|\)/
+ },
+ string : {
+ exp : /'[^']*'|"[^"]*"/
+ },
+ keywords : {
+ exp : /\b(do|end|self|class|def|if|module|yield|then|else|for|until|unless|while|elsif|case|when|break|retry|redo|rescue|require|raise)\b/
+ }
+});
98 stylesetguide.html
@@ -0,0 +1,98 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html>
+<head>
+ <title>Code Highlighter 0.2 - A Guide to creating style sets</title>
+ <script type="text/javascript" src="code_highlighter.js"></script>
+ <script type="text/javascript" src="javascript.js"></script>
+ <style type="text/css">
+ body {
+ background : #EEE;
+ font-family: Arial, Helvetica, sans-serif;
+ margin : 3em 5em;
+ line-height : 1.5;
+ font-size: 80%;
+ }
+
+ pre {
+ border: 1px solid black;
+ border-color: #BBB #DDD #DDD #BBB;
+ margin : 2em;
+ padding : 1em;
+ line-height: 1.5;
+ background: white;
+ font-size : 1.2em;
+ overflow: auto;
+ }
+
+ h1 span {
+ font-size : 0.5em;
+ }
+
+ a {
+ color : gray;
+ }
+
+ /* end of page css - below is for the code highlighter */
+
+ .javascript .comment {
+ color : green;
+ }
+
+ .javascript .string {
+ color : teal;
+ }
+
+ .javascript .keywords {
+ color : navy;
+ }
+
+ .javascript .global {
+ color : blue;
+ }
+
+ .javascript .brackets {
+ color : navy;
+ }
+ </style>
+</head>
+
+<body>
+<h1>CodeHighlighter 0.2</h1>
+<h2>A guide to creating style sets</h2>
+<p>Style sets are written in JavaScript and are used by CodeHighlighter to match specific types of code and wrap them in, normally, a &lt;span&gt; tag with a specified class name. The stylesets themselves have a simple form but you may need to be a bit of a Regular Expressions badboy to create complex rules. Here's the style set for CSS:</p>
+<pre class="javascript"><code>CodeHighlighter.addStyle("css", {
+ comment : {
+ exp : /\/\*[^*]*\*+([^\/][^*]*\*+)*\//
+ },
+ keywords : {
+ exp : /@\w[\w\s]*/
+ },
+ selectors : {
+ exp : "([\\w-:\\[.#][^{};>]*)(?={)"
+ },
+ properties : {
+ exp : "([\\w-]+)(?=\\s*:)"
+ },
+ units : {
+ exp : /([0-9])(em|en|px|%|pt)\b/,
+ replacement : "$1&lt;span class=\"$0\"&gt;$2&lt;/span&gt;"
+ },
+ urls : {
+ exp : /url\([^\)]*\)/
+ }
+ });</code></pre>
+ <p>Use the CodeHighlighter.addStyle() method to add the style set rules. First define the class name that will trigger the style set, in this case 'css'. Any &lt;pre&gt; tag with the class "css" will use this style set.</p>
+ <p>The second argument to the method is an object containing the rules. Here's how a single rule goes together:</p>
+ <pre class="javascript"><code>...
+classname : {
+ exp : /a regexp/, // or a reg exp as a string
+ replacement : "$1&lt;span class=\"$0\"&gt;$2&lt;/span&gt;" // optional advanced replacement
+},
+...</code></pre>
+ <p>The property name is the class that will be applied to the matched text. The value of each property is another object containing the property <strong>exp</strong> which is mandatory and contains the RegExp (either in RegExp notation or as a string) required to match the text and a property <strong>replacement</strong> which is optional and only used for advanced replaces.</p>
+ <p>A simple replace (where no replacement property is specified) will simply wrap all of the matched text in a span tag if you need more control you can specify your own replacement rule using the replacement property. $0 will always output the class name while $1-$9 will match sub expressions in the regular way.</p>
+ <p><strong>Note:</strong> If you want to use look aheads in your regular expressions go ahead but write them as a string. This prevents older browsers that do not support lookaheads from sprouting JavaScript errors.</p>
+ <p><a href="/">Return to the examples page</a></p>
+</body>
+</html>
246 test.html
@@ -0,0 +1,246 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html>
+<head>
+ <title>Code Highlighter 0.2</title>
+ <script type="text/javascript" src="CodeHighlighter.js"></script>
+ <script type="text/javascript" src="javascript.js"></script>
+ <script type="text/javascript" src="css.js"></script>
+ <script type="text/javascript" src="html.js"></script>
+ <style type="text/css">
+ body {
+ background : #EEE;
+ font-family: Arial, Helvetica, sans-serif;
+ margin : 3em 5em;
+ line-height : 1.5;
+ font-size: 80%;
+ }
+
+ pre {
+ border: 1px solid black;
+ border-color: #BBB #DDD #DDD #BBB;
+ margin : 2em;
+ padding : 1em;
+ line-height: 1.5;
+ background: white;
+ overflow: auto;
+ }
+
+ code {
+ font-size: 1.2em;
+ }
+
+ h1 span {
+ font-size : 0.5em;
+ }
+
+ a {
+ color : gray;
+ }
+
+ /* end of page css - below is for the code highlighter */
+
+ .javascript .comment {
+ color : green;
+ }
+
+ .javascript .string {
+ color : teal;
+ }
+
+ .javascript .keywords {
+ color : navy;
+ }
+
+ .javascript .global {
+ color : blue;
+ }
+
+ .javascript .brackets {
+ color : navy;
+ }
+
+ .css .comment {
+ color : gray;
+ }
+
+ .css .properties {
+ color : navy;
+ }
+
+ .css .selectors {
+ color : maroon;
+ font-weight : bold;
+ }
+
+ .css .units {
+ color :red;
+ }
+
+ .css .urls {
+ color :green;
+ }
+
+ .html .tag {
+ color : purple;
+ }
+
+ .html .comment {
+ color : gray;
+ font-style: italic;
+ }
+
+ .html .string {
+ color : navy;
+ }
+
+ .html .doctype {
+ color : teal;
+ }
+ </style>
+</head>
+
+<body>
+<h1>CodeHighlighter 0.2 <span>by <a href="http://www.danwebb.net">Dan Webb</a></span></h1>
+<p>CodeHighlighter is a lightweight, unobstrusive and fully configurable script for displaying code examples highlighted in a way similar to the way many text editors highlight code. It weighs in at just under 4K, allows users to configure their own style sets so that you can highlight any language you like and is deployable simply by attaching it to a page with the script tag and adding class names as hooks. It should also play nicely with any other scripts on your page as it has a tiny footprint on the global namespace.</p>
+<p>Many thanks to <a href="http://dean.edwards.name">Dean Edwards</a> who's star-light behaviour inspired this.</p>
+<h3>Deploying the script</h3>
+<ol>
+ <li>Add a &lt;script&gt; tag for <a href="CodeHighlighter.js">CodeHighlighter.js</a> and a script tag for each of the code types you want to highlight on your page. At this time there are only very basic style sets for <a href="javascript.js">JavaScript</a>, <a href="css.js">CSS</a> and <a href="html.js">HTML</a>. But it's easy to make your own for any language you like if you know regular expressions. Let me know if you do and I'll link to them.</li>
+ <li>Add an appropriate class to each &lt;pre&gt; element that contains code. 'javascript', 'css' or 'html' will do the trick.</li>
+ <li>Define CSS styles for each code element, the script simply parses the code and wraps a &lt;span&gt; tag around each element with the appropriate class name. You just need to write CSS to style the code the way you want. No programming or weirdness required. See the source of this code as an example.</li>
+</ol>
+<h3>Testing</h3>
+<p>Known to work on:</p>
+<ul>
+ <li>IE 5.5+ PC</li>
+ <li>Firefox 1.0/Mozilla 1.3 + PC</li>
+ <li>Opera 7.23 + PC</li>
+ <li>Netscape 7.2 PC</li>
+</ul>
+<p>Known to degrade well on:</p>
+<ul>
+ <li>IE 5.0 PC</li>
+</ul>
+<p>Any other feedback for any other browser would be greatly apprieciated. Please email Dan Webb at dan[at]danwebb[dot]net. Have a look through the small examples below.</p>
+<h3>Creating your own style sets for other languages</h3>
+<p>Have a look at this <a href="stylesetguide.htm">guide to creating style sets</a>.</p>
+<p>Cheers,<br /><strong>Dan</strong></p>
+<h2>Inline code</h2>
+<p>Hopefully, you should be able to put some code inline like this: <code class="javascript">document.write("bong")</code> and hopefully it should work.</p>
+<h2>JavaScript Example</h2>
+<pre><code class="javascript">/*
+This script detects external links in a page
+and attaches a behaviour to them so they open
+in a external window.
+*/
+
+function initialiseLinks() {
+ if (document.getElementsByTagName) {
+ var links = document.getElementsByTagName(&quot;A&quot;);
+ for (var i = 0; i &lt; links.length; i++) {
+ if (links[i].href.indexOf(&quot;http:&quot;)==0) {
+ // if the links URL starts with http: then we assume it's an external link
+ links[i].onclick = function() {
+ window.open(this.href);
+ return false; // stop normal link behaviour
+ }
+ }
+ }
+ }
+}
+
+window.onload = initialiseLinks();</code></pre>
+<h2>CSS Example</h2>
+<pre><code class="css">.javascript .comment {
+ color : green; /* ffbgffg */
+}
+
+.javascript .string {
+ color : maroon;
+}
+
+.javascript .keywords {
+ font-weight : bold;
+}
+
+.javascript .global {
+ color : blue;
+ font-weight: bolder;
+}
+
+.javascript .brackets {
+ color : Gray;
+}
+
+.javascript .thing {
+ font-size : 10px;
+ background : url(ghgfhfg gh f.rtjhf);
+}</code></pre>
+<h2>HTML Example</h2>
+<pre><code class="javascript">
+function suckerfish(type, tag, parentId) {
+ if (window.attachEvent) {
+ window.attachEvent("onload", function() {
+ var sfEls = (parentId==null)?document.getElementsByTagName(tag):document.getElementById(parentId).getElementsByTagName(tag);
+ type(sfEls);
+ });
+ }
+}
+
+sfHover = function(sfEls) {
+ for (var i=0; i&lt;sfEls.length; i++) {
+ sfEls[i].onmouseover=function() {
+ this.className+=" sfhover";
+ }
+ sfEls[i].onmouseout=function() {
+ this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
+ }
+ }
+}
+
+sfFocus = function(sfEls) {
+ for (var i=0; i&lt;sfEls.length; i++) {
+ sfEls[i].onfocus=function() {
+ this.className+=" sffocus";
+ }
+ sfEls[i].onblur=function() {
+ this.className=this.className.replace(new RegExp(" sffocus\\b"), "");
+ }
+ }
+}
+
+sfActive = function(sfEls) {
+ for (var i=0; i&lt;sfEls.length; i++) {
+ sfEls[i].onmousedown=function() {
+ this.className+=" sfactive";
+ }
+ sfEls[i].onmouseup=function() {
+ this.className=this.className.replace(new RegExp(" sfactive\\b"), "");
+ }
+ }
+}
+
+sfTarget = function(sfEls) {
+ var aEls = document.getElementsByTagName("A");
+ document.lastTarget = null;
+ for (var i=0; i&lt;sfEls.length; i++) {
+ if (sfEls[i].id) {
+ if (location.hash==("#" + sfEls[i].id)) {
+ sfEls[i].className+=" sftarget";
+ document.lastTarget=sfEls[i];
+ }
+ for (var j=0; j&lt;aEls.length; j++) {
+ if (aEls[j].hash==("#" + sfEls[i].id)) aEls[j].targetEl = sfEls[i];
+ aEls[j].onclick = function() {
+ if (document.lastTarget) document.lastTarget.className = document.lastTarget.className.replace(new RegExp(" sftarget\\b"), "");
+ if (this.targetEl) this.targetEl.className+=" sftarget";
+ document.lastTarget=this.targetEl;
+ return true;
+ }
+ }
+ }
+ }
+}</code></pre>
+</body>
+</html>
Please sign in to comment.
Something went wrong with that request. Please try again.