What's new? | Help | Directory | Sign in
Google
syntaxhighlighter
Free syntax highlighter written in Java Script
  
  
  
  
    
Search
for
Updated May 12, 2007 by alex.gorbatchev
Labels: Phase-Design, Featured
Usage  
How to use SyntaxHighlighter.

Usage

Placing the code

Place your code on the page and surround it with <pre> tag. Set name attribute to code and class attribute to one of the language aliases you wish to use.

<pre name="code" class="c-sharp">
... some code here ...
</pre>

NOTE: One important thing to watch out for is opening triangular bracket <. It must be replaced with an HTML equivalent of &lt; in all cases. Failure to do won't break the page, but might break the source code displayed.

An alternative to <pre> is to use <textarea> tag. There are no problems with < character in that case. The main problem is that it doesn't look as good as <pre> tag if for some reason JavaScript didn't work (in RSS feed for example).

<textarea name="code" class="c#" cols="60" rows="10">
... some code here ...
</textarea>

Extended configuration

There's a way to pass a few configuration options to the code block. It's done via colon separated arguments.

<pre name="code" class="html:collapse">
... some code here ...
</pre>

Making it work

Finally, to get the whole thing to render properly on the page, you have to add JavaScript to the page.

<link type="text/css" rel="stylesheet" href="css/SyntaxHighlighter.css"></link>
<script language="javascript" src="js/shCore.js"></script>
<script language="javascript" src="js/shBrushCSharp.js"></script>
<script language="javascript" src="js/shBrushXml.js"></script>
<script language="javascript">
dp.SyntaxHighlighter.ClipboardSwf = '/flash/clipboard.swf';
dp.SyntaxHighlighter.HighlightAll('code');
</script>

For optimal result, place this code at the very end of your page. Check HighlightAll for more details about the function.


Comment by hughdickson, Aug 04, 2007

Can't get it to work in any way, shape or form :(

Comment by alex.gorbatchev, Aug 05, 2007

Can you get included samples working? Please give more details.

Comment by klein.stephane, Aug 07, 2007

This code :

dp.SyntaxHighlighter?.ClipboardSwf? = '/flash/clipboard.swf'; dp.SyntaxHighlighter?.HighlightAll('code');

must been in onload function like this :

<script language="javascript"> window.onload = function () {

dp.SyntaxHighlighter?.ClipboardSwf? = '/flash/clipboard.swf'; dp.SyntaxHighlighter?.HighlightAll('code');
} </script>

Comment by klein.stephane, Aug 07, 2007

This code :

dp.SyntaxHighlighter?.ClipboardSwf? = '/flash/clipboard.swf'; dp.SyntaxHighlighter?.HighlightAll('code');

must been in onload function like this :

<script language="javascript"> window.onload = function () {

dp.SyntaxHighlighter?.ClipboardSwf? = '/flash/clipboard.swf'; dp.SyntaxHighlighter?.HighlightAll('code');
} </script>

Comment by klein.stephane, Aug 07, 2007

This code :

dp.SyntaxHighlighter.ClipboardSwf = '/flash/clipboard.swf';
dp.SyntaxHighlighter.HighlightAll('code');

must been in onload function like this :

<script language="javascript">
window.onload = function () {
    dp.SyntaxHighlighter.ClipboardSwf = '/flash/clipboard.swf';
    dp.SyntaxHighlighter.HighlightAll('code');
}
</script>
Comment by gotcha10...@yahoo.com, Aug 11, 2007

Awesome piece of code. Worked like a charm the first time.

Thanks Alex

mark...

Comment by gotcha10...@yahoo.com, Aug 11, 2007

Awesome piece of code. Worked like a charm the first time.

Thanks Alex

mark...

Comment by r.gennari, Aug 29, 2007

Very good, but I have some problem to make XHTML 1.1 valid pages. The problem is in <pre> tag: name is not allowed anymore for this tag. And <textarea> needs to be in a form...

Any clue?

.BoB.

Comment by robccsilva, Aug 29, 2007

Excelent! Works flawlessly! 5 stars! :D

My 1st try (took less than 5 minutes):

<html> <body>

<textarea name="code" class="html" cols="60" rows="10">

BEGIN --- This is the example code:

<link type="text/css" rel="stylesheet" href="Styles/SyntaxHighlighter.css"></link> <script language="javascript" src="Scripts/shCore.js"></script> <script language="javascript" src="Scripts/shBrushCSharp.js"></script> <script language="javascript" src="Scripts/shBrushXml.js"></script> <script language="javascript"> dp.SyntaxHighlighter?.ClipboardSwf? = 'Scripts/clipboard.swf'; dp.SyntaxHighlighter?.HighlightAll('code'); </script>

END --- This is the example code:

</textarea>

<link type="text/css" rel="stylesheet" href="Styles/SyntaxHighlighter.css"></link> <script language="javascript" src="Scripts/shCore.js"></script> <script language="javascript" src="Scripts/shBrushCSharp.js"></script> <script language="javascript" src="Scripts/shBrushXml.js"></script> <script language="javascript"> dp.SyntaxHighlighter?.ClipboardSwf? = 'Scripts/clipboard.swf'; dp.SyntaxHighlighter?.HighlightAll('code'); </script>

</body> </html>

Comment by chang112x, Aug 31, 2007

Nice, some problems with <br /> but nice.

Comment by codeworkspace, Sep 13, 2007

i soooooo.... like it!

Comment by codeworkspace, Sep 13, 2007

i sooooo... like it

Comment by codeworkspace, Sep 13, 2007

i sooooo... like it

Comment by codeworkspace, Sep 13, 2007

i sooooo... like it

Comment by sandy.pec, Oct 11, 2007

A really great piece of work! Marvelous! Just added it to my blog.

Comment by ashwin.jayaprakash, Oct 22, 2007

I found the last 2 lines to be problematic, especially if the Scripts take too long to download. It kept throwing this 'dp is undefined' error. It looked like the last script fragment namely -

<script language="javascript">
  dp.SyntaxHighlighter.ClipboardSwf = '/flash/clipboard.swf';
  dp.SyntaxHighlighter.HighlightAll('code');
</script>

used to get initiated even before the other scripts were downloaded. So I moved it to another file called shInit.js and it looks like this -

  var attempts = 0;
  var timerHandle = setTimeout("checkIfHilighterLoaded()", 350);

  function checkIfHilighterLoaded(){
    try{
      dp.SyntaxHighlighter.ClipboardSwf = '/flash/clipboard.swf';      
      dp.SyntaxHighlighter.HighlightAll('code');    
    
      clearTimeout(timerHandle);
    }
    catch(e){
      clearTimeout(timerHandle);

      if(attempts < 25){
        timerHandle = setTimeout("checkIfHilighterLoaded()", 350);
      }

      attempts++;
    }
  }

So, instead of the inline JavaScript?? I have this -

<script language="javascript" src="js/shInit.js"></script>

Comment by michael.prescott, Oct 24, 2007

Well robccsilva's example posted on Aug 29, 2007 worked well, but the following and all other attempts I've tried just fail. Firebug reveals no errors, so I'm not sure what is wrong. Any ideas:

<textarea name="code" class="java" cols="45" rows="10"> public class HelloWorld? {

public static void main(String[] args) {
System.out.println("Hello, World");
}

} </textarea>

Comment by jason.irwin, Oct 31, 2007

Is anyone able to use this on blogger? it looks to me like i need to upload a bunch of (primarily javascript) files but i dont think i can do that with blogger? anyone have any ideas?

Comment by amri.shodiq, Nov 16, 2007

Where should I write this piece of code in wordpress?

<link type="text/css" rel="stylesheet" href="css/SyntaxHighlighter.css"></link> <script language="javascript" src="js/shCore.js"></script> <script language="javascript" src="js/shBrushCSharp.js"></script> <script language="javascript" src="js/shBrushXml.js"></script> <script language="javascript"> dp.SyntaxHighlighter?.ClipboardSwf? = '/flash/clipboard.swf'; dp.SyntaxHighlighter?.HighlightAll('code'); </script>

Comment by amri.shodiq, Nov 16, 2007

Is it in the header.php in the theme or somewhere else? Please ...

Comment by sunvampire00, Nov 26, 2007

It doesn't work,man;-( I swear i did nothing wrong.I think i need a sample or more details.

Comment by george.benainous, Dec 01, 2007

I found that syntax highlighting only worked if these two lines <script class="javascript"> dp.SyntaxHighlighter?.ClipboardSwf? = '/flash/clipboard.swf'; dp.SyntaxHighlighter?.HighlightAll('code'); </script> are placed AFTER the closing </pre> tag

Comment by mortenlyhr, Dec 12, 2007

How to get syntax highlighting in Blogger with SyntaxHighlighter?

http://morten.lyhr.dk/2007/12/how-to-get-syntax-highlighting-in.html

Comment by chanceycn, Dec 16, 2007

<pre name="code" class="php"> $test = "syntax highlighter"; echo $test; </pre>

Comment by joomlers, Dec 19, 2007

When language is php,"empty" of the function is displayed double.

example: emptyempty($example)

Comment by save.nx, Dec 21, 2007

Hi, why don;t you use <code> element instead?

Comment by narendra.sisodiya, Dec 26, 2007

which is better .... your or from ,,, http://shjs.sourceforge.net/

Comment by lukev123, Jan 09, 2008

Worked first time like a charm! thanks for this!

Comment by johnstonpaulr, Jan 10, 2008

I have my own language file, and am trying to get the following to work: (this relates to my drumputer scripting language at http://www.drumputer.com)

SET KEYWORD1=VALUE1;SET KEYWORD2=VALUE2; LET VARx=VALUE

LET and SET are keywords (as is KEYWORDx) and get hilighted okay. I want to hilight the VARx part. "VARx" can be any string without spaces or an =.

I think I figured it out:

This has been added in my "Brush" file's RegexList?: { regex: new RegExp?('^LET\\s+([a-zA-Z\\-\\d\\]+)=.+', 'gmi'), css: 'vars', submatchIndex: 1, disallow: keywords } //Note the "submatchIndex" property and "disallow"

//And I redefined the following two items from shCore.js (but left shCore alone): //--------- dp.sh.Highlighter.prototype.ProcessRegexList? = function() {

var oRegExItem = null; for(var i = 0; i < this.regexList.length; i++)
if(this.regexListi?.submatchIndex == undefined) {
this.GetMatches?(this.regexListi?.regex, this.regexListi?.css);
} else {
oRegExItem = this.regexListi?; this.GetMatches?(oRegExItem.regex, oRegExItem.css, oRegExItem.submatchIndex, oRegExItem.disallow);
}
} //--------- dp.sh.Highlighter.prototype.GetMatches? = function(regex, css, submatchIndex, disallowList) {
var index = 0; var match = null; var oMatch = null; var sMain='',sSub='',iOffset=0,bAddIt=true; var oREDisallow=new RegExp?('zipdiggly\bdontfindme\b\bxx','gmi'); if(submatchIndex == undefined)
submatchIndex=0;
if(disallowList != undefined)
oREDisallow=new RegExp?(this.GetKeywords?(disallowList),'gmi');

while((match = regex.exec(this.code)) != null) {
oMatch = new dp.sh.Match(matchsubmatchIndex?, match.index, css); bAddIt = true; if(submatchIndex>0) {
sMain = match0?; sSub = matchsubmatchIndex?; if(oREDisallow.test(sSub)) {
bAddIt=false;
} else {
iOffset = sMain.indexOf(sSub,4); //must be after "LET " or "RAW " oMatch.index += iOffset;
}
} if(bAddIt) {
this.matches[this.matches.length] = oMatch;
}
}

}

// I have two special cases that this takes care of; SET INTRO=intropatternname SET TRANSITION=transitionpatternname RAW INTRO=4/4,15,15,15,25,25 RAW TRANSITION=4/4,15,15,15,25,25 In which case the SET INTRO/TRANSITION would have been handled already


Anyway, it's been an interesting day working through this. And I didn't have to alter any of the main code (but did have to co-opt it, I guess, and adapt a copy) All the above changes are in the customized Brush file

Comment by SteveKlett, Jan 13, 2008

David! This is killer! Worked perfect. Thanks, Steve

Comment by wu12402, Feb 02, 2008

let f1 and f2 be two input files of unknown length whose records are integers if the records in both files are in ascending order, the files can be merged to produce a third file f3 whose records are likewise in ascending order. the following algorithm shows how this can be done without using arrys or other costly internal data structures

funtion merge (file f1, file f2, file f3)

get next record from f1 into x get next record from f2 into y
while(not eof(f1) or not eof(f2))
if x < y then
write x to f3 get next record from f1 into x
else
write y to f3 get next record from f2 into y
end-if
end-while

end-funtion //it's merge program #include<iostream> using namespace std; const int MAX = 100; int main() {

int aMAX? = {1, 2, 8, 4, 7},
bMAX? = {7, 8, 5, 1, 3, 12}, cMAX?;
int aSize = 5,
bSize = 6, cSize;
int indexA = 0; // initialize the Array Indices
int indexB = 0; int indexC = 0;
while( (indexA < aSize) && (indexB < bSize) )
{
if (aindexA? < bindexB?) { cindexC? = aindexA?;
indexA++; //increase the index
}
else { cindexC? = bindexB?;
indexB++; //increase the index
} indexC++; //move to the next position in the new array
} int i;
for(i = 0; i < indexC; i++) { cout << ci? << ' '; }
system("pause"); return 0;
}

Comment by jdkaye, Feb 03, 2008

took me a while to figure this out. In order to get the script working, you have to put the js declaration right before the closing </body> tag.

Cool script but the instructions leave much to be desired!

Comment by andersson.mickel, Feb 08, 2008

one two three

  • ne
  • wo
  • hree
Comment by car...@webdesignpro.co.uk, Feb 13, 2008

This is WICKED!

I have one problem though, my escape chars get lost (\).

ie. the following code:

<?php echo "Carlos said \"loving this script\""; ?>

renders as:

<?php echo "Carlos said "loving this script""; ?>

which will cause a parse error.

I suspect the solution is to use a special char or string in place of the \ and dynamically replace it from within the js.

I'll post when I find the solution.

Comment by fhranz.alf, Feb 27, 2008

regarding on Comment by joomlers, Dec 19, 2007 about function empty() does anyone knows how to fix this? coz I also experience it.

--->> if ( ! emptyempty ( $STARTVIEW ) ) {

thanks

Comment by Jo...@randomize-live.de, Feb 28, 2008

that worked great...thank you! :)

Comment by dheeva, Mar 03, 2008

This is unbelievably wonderful, awesome and works perfectly for me, thank you very much. :)

Comment by diterius, Mar 17, 2008

in ff - cool, but doesn't work in opera

Comment by sh3lt3r, Mar 19, 2008

not working.

Comment by mr.joebert, Mar 19, 2008

If you're one to pay attention to standards & DOCTYPEs, you're probably cringing at the instruction to add a "name" attribute to your <pre/> elements.

Actually, if you look at the source "shCore.js" there's a comment about this which is kinda funny.

"// for some reason IE doesn't find <pre/> by name, however it does see them just fine by tag name..."

Ironicly enough that's probably got somthing to do with "name" not being a valid attribute of the <pre/> element. IE is actually behaving as it should in this case.

"dp.sh.HighlightAll" really should be rewritten so invalid attributes aren't required. I plan to do just that for my implementation of this otherwise awesome script, just wanted to leave this note for any of the scripts developers who happen to read these comments. :)

Comment by nawaf227, Mar 26, 2008

Hello,

Excellent work, does it work with tinymce? If so how to configure that?

Thanks

Comment by atish.narlawar, Mar 28, 2008

Great Piece ......!!!

I used in my site..... www.certification4career.com

Comment by austegard, Mar 31, 2008

@mr.joebert I agree - I was trying to use this with SharePoint?, which strips the name attribute from the pre tag. I modified HighlightAll to look for a compound class name instead (like "xml code", or "css code"). That said, it still failed to work...

Comment by nawaf227, Apr 06, 2008
Comment by 226617, Apr 09, 2008

how to use in mediawiki

Comment by nawaf227, Apr 10, 2008

Hello again,

I have upgraded the plug-in to work on tinymce 3.x, you can find it here

http://weblogs.asp.net/nawaf/archive/2008/04/10/syntaxhighlighter-plug-in-for-tinymce-3-x-wysiwyg-editor.aspx

Hope this helps.

Comment by Jennalcn, Apr 16, 2008

klein.stephane said: This code :

dp.SyntaxHighlighter.ClipboardSwf = '/flash/clipboard.swf';
dp.SyntaxHighlighter.HighlightAll('code');

must been in onload function like this :

<script language="javascript">window.onload = function () { dp.SyntaxHighlighter.ClipboardSwf = '/flash/clipboard.swf'; dp.SyntaxHighlighter.HighlightAll('code');}
</script> 

maybe not necessary, put the code:

<script language="javascript">
dp.SyntaxHighlighter.ClipboardSwf = '/flash/clipboard.swf'; dp.SyntaxHighlighter.HighlightAll('code');
</script>

after your pre or textarea will be fine.

Comment by creyno...@siteconstrux.com, Apr 22, 2008

I admit that I'm eccentric upfront and I don't like to place script tags outside of the head element when I don't have to. Rather than place the scripts at the bottom of the page, how about placing the defer attribute on the script element?

<script language="javascript" defer="defer">
    dp.SyntaxHighlighter.ClipboardSwf = '/scripts/clipboard.swf';
    dp.SyntaxHighlighter.BloggerMode();
    dp.SyntaxHighlighter.HighlightAll('code',true,false,false,1,false);
</script>
Comment by projektas, Apr 25, 2008

in the <head> I put

<script language="javascript" type="text/javascript" src="javascript/hl/shBrushPhp.js"></script> <script language="javascript" type="text/javascript" src="javascript/hl/shBrushJScript.js"></script> <script language="javascript" type="text/javascript" src="javascript/hl/shBrushSql.js"></script> <script language="javascript" type="text/javascript" src="javascript/hl/shBrushXml.js"></script> <script language="javascript" type="text/javascript" src="javascript/hl/shBrushCss.js"></script>

And at the botom of the page

<script language="javascript"> dp.SyntaxHighlighter?.ClipboardSwf? = 'javascript/hl/clipboard.swf'; dp.SyntaxHighlighter?.BloggerMode(); dp.SyntaxHighlighter?.HighlightAll('code',true,false,false,1,false); </script>
And its not working:
Error: dp.SyntaxHighlighter?.HighlightAll is not a function

Comment by dbjacobs, Apr 25, 2008

I can't get the following to work. I know all the files are referred to correctly, but I did mess w/ the structure to make it simpler. (the CSS file is called syntax-highlighter.css and is in the same folder as this code... all the js's and the swf are in syntax/ which is in the same folder as this code)

What am I doing wrong?


{{{<html> <head>

<title>code-test</title> <link rel="stylesheet" type="text/css" href="syntax-highlighter.css"></link> <script language="javascript" src="scripts/shBrushRuby.js"></script> <script language="javascript" src="scripts/shCore.js"></script> <script language="javascript" src="scripts/shBrushXml.js"></script> <script language="javascript" defer="defer">
dp.SyntaxHighlighter?.ClipboardSwf? = 'scripts/clipboard.swf';
dp.SyntaxHighlighter?.HighlightAll('code');
</script>
</head>

<body>

<a href='scripts/clipboard.swf'>Clipboard</a> <pre name="code" class="ruby">
require 'ruby.rb'
def this_class
puts "Here this class, #{class} is defined."
end
block
"random text"
end
</pre>
</body> </html>}}}

Comment by dbjacobs, Apr 25, 2008

Sorry... I meant the js's and swf are in the folder 'scripts'.

Comment by olaf.monien, Apr 29, 2008

Javascript should be linked that way: <script type="text/javascript" src="/synhighlighter/shBrushXml.js"></script>

In other words the "language" attribute is deprecated and does not replace the "type" attribute. Using the "language" attribute only may lead to un expected behaviour (non-working JS): <script language="javascript" src="/synhighlighter/shBrushXml.js"></script>

Comment by nthouvenin, May 02, 2008

To use SyntaxHighligter? with SPIP. You can try the plugin : http://www.touv.fr/spip.php?article141

Comment by ianatkinsonbsc, May 07, 2008

I think this needs a bit of a re-think in order to work with XHTML pages, you're not allowed to use name as that's been replaced by ID, and you can only have one ID which would limit this to one use per page (little use for tutorials). I think it needs to use the class attribute if possible...

However, visually it looks great!


Sign in to add a comment