UPDATE: Support for Syntax Highlighter 2.0 + jQuery Listed + bitbucket Repository
The Syntaxhighlighter by Alex Gorbatchev is the best I have seen so far. As you see in this post, wordpress.com uses it, too.
But the required syntax is not xhtml-compliant (name on pre is forbidden).
<pre name="code" class="javascript"> // my code </pre>
In order to enable compliant xhtml I had to rewrite a small part anyway, so I just made a small jQuery-Plugin that just uses Alex’s scripts right away (thanks Alex!).
Beautify explicitely
<pre id="myCode"> <code> // my code </code> </pre>
Using beautyOfCode you don’t have to decorate your html in order to enable syntax highlighting. Just call beautifyCode on any selected pre or textarea
$(function(){ $.beautyOfCode.init('clipboard.swf'); $("#myCode").beautifyCode('javascript'); });
Beautify all
If you prefer to decorate your html and then just let the highlighter take care of the rest, you may use following notation.
<pre class="code"> <code class="javascript"> // my code </code> </pre> <pre class="code"> <code class="css boc-nocontrols"> body { font-size: 2em; } </code> </pre>
Make sure you have these few lines
$(function(){ $.beautyOfCode.init('clipboard.swf'); $.beautyOfCode.beautifyAll(); });
Settings
Default Settings
{ noGutter: false, // hide line numbers? addControls: true, // copy, view plain, ... collapse: false, // show controls with expand link showColumns: false, // show column numbers firstLine: 1 // start with another line number? }
Change Settings with Javascript
$(function(){ $.beautyOfCode.init('clipboard.swf', { // add global settings here firstLine: 4, collapse: true }); // change options per listing $("#myCode").beautifyCode('javascript', { noGutter: true }); });
Change Settings in Element-Decoration
Settings with in the html are added as additional classes on the code-element.
<pre class="code"> <!-- You dont have to specify default values. --> <code class="javascript boc-firstline[3] boc-nocontrols boc-nogutter boc-showcolumns boc-collapse"> // my code </code> </pre>
Source Code
Notice: beautyOfCode is using Syntaxhighlighter. You need to link in SyntaxHighlighter.css, shCore.js and the brushes you want to use.
jQuery.beautyOfCode = { initialized: false, settings: { // hide line numbers? noGutter: false, // show copy, plain, ... links addControls: true, // collapse to control bar. cant be used // with addControls set to false collapse: false, // show column numbers showColumns: false, // start with another line number? firstLine: 1 }, brushByAlias: {}, init: function (clipboardSwf, settings) { dp.SyntaxHighlighter.ClipboardSwf = clipboardSwf; if (settings) jQuery.extend(jQuery.beautyOfCode.settings, settings); if (jQuery.beautyOfCode.isInitialized) return; // creates a map of each registered brush by alias jQuery.each(dp.sh.Brushes, function (i, brush) { var aliases = brush.Aliases; if(aliases == null) return; jQuery.each(aliases, function (ii, alias) { jQuery.beautyOfCode.brushByAlias[alias] = brush; }); }); jQuery.beautyOfCode.isInitialized = true; }, addCssForBrush: function (brush, highlighter) { if (brush.isCssInitialized) return; var headNode = $("head")[0]; if(highlighter.Style && headNode) { var styleNode = document.createElement('style'); styleNode.setAttribute('type', 'text/css'); if(styleNode.styleSheet) // for IE styleNode.styleSheet.cssText = highlighter.Style; else // for everyone else $(styleNode).text(highlighter.Style); headNode.appendChild(styleNode); } brush.isCssInitialized = true; }, beautifyAll: function() { jQuery("pre.code:has(code[class])").each(function (i, item) { function getOptionValue(name, list) { var regex = new RegExp('^' + name + '\\[(\\w+)\\]$', 'gi'); var matches = null; for(var i = 0; i < list.length; i++) if((matches = regex.exec(list[i])) != null) return matches[1]; return null; } var $item = jQuery(item); var $code = $item.children("code"); var code = $code[0]; var options = code.className.split(" "); var language = options[0]; var settings = {}; if ($code.hasClass("boc-nogutter")) settings.noGutter = true; if ($code.hasClass("boc-nocontrols")) settings.addControls = false; if ($code.hasClass("boc-showcolumns")) settings.showColumns = true; if ($code.hasClass("boc-collapse")) settings.collapse = true; var firstLine = getOptionValue("boc-firstline", options, 1); if (firstLine) settings.firstLine = firstLine; $item.beautifyCode(language, settings); }); } }; jQuery.fn.beautifyCode = function (language, settings) { var saveLanguage = language; var saveSettings = settings; // iterate all elements this.each( function (i, item) { var $item = jQuery(item); var settings = jQuery.extend({}, jQuery.beautyOfCode.settings, saveSettings); var brush = jQuery.beautyOfCode.brushByAlias[saveLanguage]; if (!brush) return; // instantiate brush highlighter = new brush(); // set brush options jQuery.extend(highlighter, settings); jQuery.beautyOfCode.addCssForBrush(brush, highlighter); // IE Bug?: code in pre has to be skipped // in order to preserver line breaks. if ($item.is("pre") && ($code = $item.children("code"))) $item.text($code.text()); highlighter.Highlight($item.html()); highlighter.source = item; $item.replaceWith(highlighter.div); }); } [/sourcecode]
Would love your comments!
Hi Lars,
Have you added it to github? Would be great if you add it with your official documentation.
Check out our live customizable preview for the syntax highlighter plugin by Alex.G
http://bitconfig.com/syntax-highlighter/bitconfig_syntax_highlighter.html
Let us know if you have any more great plugins.
– Patrick
It is on bitbucket; but not really maintained anymore.
Hi Lars.
This can help:
$(function(){
$.beautyOfCode.init(‘clipboard.swf’);
$(“pre.code”).beautifyCode(‘javascript’);
});
Thanks! Bye.
Gaston, what do you mean?
Nice 😉
I think gaston means the problem with Firefox3, that “copy to clipboard” doesn’t work
Nice plugin. At first I thought about writing such wrapper myself, but found it by google. It would be much easier to find you, if you create an entry in official plugin database at http://plugins.jquery.com .
Thanks for the hint. I just added it. Vote for it, if you like it 🙂
http://plugins.jquery.com/project/beautyOfCode
Hi, just came across your post and started putting this code into use on a site I’m working on.
Just a quick question:
Where does ‘dp.SyntaxHighlight…’ on line 26 in your sourcecode is coming from? I’ve linked SyntaxHighlighter code, but still get an error on that line.
Which version of SyntaxHighlighter are you using here?
I think it’s version 1.5.1
Or you can also edit the shCore.js, and change the FindTagsByName function to match your needs!
Took 2 secondes for me remove the name=”” 😉
This id the code needed that works with the latest version of SyntaxHighlighter (2.0.296)
jQuery.beautyOfCode = {
initialized: false,
settings: {
// hide line numbers?
noGutter: false,
// show copy, plain, ... links
addControls: true,
// collapse to control bar. cant be used
// with addControls set to false
collapse: false,
// show column numbers
showColumns: false,
// start with another line number?
firstLine: 1
},
brushByAlias: {},
init: function (clipboardSwf, settings) {
SyntaxHighlighter.ClipboardSwf = clipboardSwf;
if (settings)
jQuery.extend(jQuery.beautyOfCode.settings, settings);
if (jQuery.beautyOfCode.isInitialized)
return;
// creates a map of each registered brush by alias
jQuery.each(SyntaxHighlighter.brushes, function (i, brush) {
var aliases = $(brush.aliases);
if(aliases == null)
return;
jQuery.each(aliases, function (ii, alias) {
jQuery.beautyOfCode.brushByAlias[alias] = brush;
});
});
jQuery.beautyOfCode.isInitialized = true;
},
addCssForBrush: function (brush, highlighter) {
if (brush.isCssInitialized)
return;
var headNode = $("head")[0];
if(highlighter.Style && headNode)
{
var styleNode = document.createElement('style');
styleNode.setAttribute('type', 'text/css');
if(styleNode.styleSheet) // for IE
styleNode.styleSheet.cssText = highlighter.Style;
else // for everyone else
$(styleNode).text(highlighter.Style);
headNode.appendChild(styleNode);
}
brush.isCssInitialized = true;
},
beautifyAll: function() {
jQuery("pre.code:has(code[class])").each(function (i, item) {
function getOptionValue(name, list)
{
var regex = new RegExp('^' + name + '\\[(\\w+)\\]$', 'gi');
var matches = null;
for(var i = 0; i < list.length; i++)
if((matches = regex.exec(list[i])) != null)
return matches[1];
return null;
}
var $item = jQuery(item);
var $code = $item.children("code");
var code = $code[0];
var options = code.className.split(" ");
var language = options[0];
var settings = {};
if ($code.hasClass("boc-nogutter"))
settings.noGutter = true;
if ($code.hasClass("boc-nocontrols"))
settings.addControls = false;
if ($code.hasClass("boc-showcolumns"))
settings.showColumns = true;
if ($code.hasClass("boc-collapse"))
settings.collapse = true;
var firstLine = getOptionValue("boc-firstline", options, 1);
if (firstLine)
settings.firstLine = firstLine;
$item.beautifyCode(language, settings);
});
}
};
jQuery.fn.beautifyCode = function (language, settings) {
var saveLanguage = language;
var saveSettings = settings;
// iterate all elements
this.each( function (i, item) {
var $item = jQuery(item);
var settings = jQuery.extend({}, jQuery.beautyOfCode.settings, saveSettings);
var brush = jQuery.beautyOfCode.brushByAlias[saveLanguage];
if (!brush)
return;
// instantiate brush
highlighter = new brush();
// set brush options
jQuery.extend(highlighter, settings);
jQuery.beautyOfCode.addCssForBrush(brush, highlighter);
// IE Bug?: code in pre has to be skipped
// in order to preserver line breaks.
if ($item.is("pre") && ($code = $item.children("code")))
$item.text($code.text());
highlighter.highlight($item.html());
highlighter.source = item;
$item.replaceWith(highlighter.div);
});
}
BTW: My vote also goes for putting the code on http://plugins.jquery.com
Excellent work. I love it.
Is this correct?
Line 55: if(highlighter.Style && headNode)
should that not be the following:
if(highlighter.Style && headNode)
Proposition Features:
Add callbacks before and after replacement of original code by highlighter.div
I’ve made 2 changes: here are they 🙂
* add 2 settings after line 20:
l20: firstLine: 1
—————————
// beforeUpdate Callback: launch just before the content is replaced by highlighter.div,
// params: $item: jQuery item mapped element, highlighter: the original syntax highlighter object
// return false to cancel replacement
,beforeUpdate: null,
// afterUpdate Callback: launch just after the content is replaced by highlighter.div
// params: $item: jQuery item mapped element, highlighter: the original syntax highlighter object
// adterUpdate: function ($item, highlighter)
afterUpdate: null
—————————
* Replace last line which is:
$item.replaceWith(highlighter.div);
with
—————————
if( settings.beforeUpdate )
if (settings.beforeUpdate($item, highlighter) === false) return;
$item.replaceWith(highlighter.div);
if( settings.afterUpdate )
settings.afterUpdate($item, highlighter);
});
—————————
With this callbacks, i can do such things:
(Show plain text as a textarea by swapping highlighted and textarea element without opening an extra window, which i don’t really like ;))
$.beautyOfCode.init(‘libs/syntaxHighlighter/clipboard.swf’, {
afterUpdate: function ($item, sh) {
// our personnalized ‘View Plain’ link
var newA = $(“View Plain“)
.css(“cursor”,”pointer”)
.click(function () {
var $bar = $(this).parents(“.bar”);
// highlighted code visible
if ($bar.next(“:visible”).length)){
var w = $(‘.tools’, sh.bar).width() – 1;
var h = $bar.next().height() – 5;
$bar.next().hide() // hide highlighted code
.next().show().css({
width: w+ ‘px’
,height: h + ‘px’}); // show and resize textarea source code
} else
$bar.next().show() // show highlighted code
.next().hide(); // hide textarea source code
});
// replace original created link by our personnalized one
$(‘.tools a:first’, sh.bar).replaceWith(newA);
// create textarea object and append it to the highlighter.div content
$(” + sh.code + ”).appendTo(sh.div);
}
});
Pingback: beautyOfCode – jQuery plugin for Syntax Highlighter 2.0 by Alex Gorbatchev « .Net Braindrops
looks great, i will use it on my page 🙂
Pingback: beautyOfCode: jQuery Plugin for Syntax Highlighting " .Net Braindrops | Squico
Pingback: 9 Useful Javascript Syntax Highlighting Scripts
Pingback: 9款有用的Javascript代码高亮脚本| Ajax| 前端观察
Pingback: Techflaps | 16 Javascript Syntax Highlighting Scripts
Pingback: 9 Useful Javascript Syntax Highlighting Scripts | Pdf Search colection
Pingback: 9 Useful Javascript Syntax Highlighting Scripts | Download E-Books Free Video Training Courses Softwares
Pingback: 16 Free Javascript Code Syntax Highlighters For Better Programming | Graphic and Web Design Blog - Inspiration, Resources and Tools
Pingback: Free Javascript Code Syntax Highlighters, Gift For Programmers | guidesigner.net
Pingback: 16 Free Javascript Code Syntax Highlighters For Better Programming - Programming Blog
Pingback: 16 resaltadores de sintáxis de código Javascript para tu web - elWebmaster.com
Excellent work. Works perfeclty with the latest SH-Version! Really impressive work!
hello please help i am noob in javascript ,
can you posting the code from this site this is what i search
thanks
ich meinte hier auf der seite sieht es so schön aus und ich bekomme den code nicht hin kannst du mir sagen wie der aussehen muss
Guck dir mal die neue version an. Die ist einfacher: https://startbigthinksmall.wordpress.com/2009/05/28/beautyofcode-jquery-plugin-for-syntax-highlighter-2-0-by-alex-gorbatchev/
Pingback: 有米啦 » 9 Useful Javascript Syntax Highlighting Scripts
Pingback: 幻岛|领地 - 常用的Javascript代码高亮脚本
hi
i have a problem only with html code.
after asking here i do escape and the code appears correctly. but if i update the article, the html is interpreted again, and so i need to go back again and replace the .
is there a way that it will work with no problems?
for now i just do not include html anymore.
hope someone can help.
best regards
Pingback: Free Javascript Code Syntax Highlighters « MoeMir
So I am having an issue with the way the code is getting formatted.
I am using a WYSIWYG Editor called jHtmlArea. I don’t know if that has something to do with it.. you can see what it is doing on this “Fake” blog post on my development server.
http://website.somethingjavaprojects.net/Blogs/34/Preview
let me know if you have any ideas.
Your blogging engine doesn’t understand pre… instead of leaving the text formatted, it puts
for line breaks:
Pingback: 9款有用的Javascript代码高亮脚本 | 记笔记的地方
Pingback: Equesdesign.com » Ressources #2
Pingback: beautyOfCode 开源项目 - Ajax代码大全 - Java开源项目 - ajax代码高亮highlight - beautyOfCode - Java免费软件 - 开源网
thanks for the code
Pingback: BUPOS.com » Google Prettify – Source Code Highlighting
Pingback: beautyOfCode: jQuery Plugin for Syntax Highlighting (via Struggles by Lars C.) « My Weblog
Pingback: 冰点
Pingback: 9 Useful Javascript Syntax Highlighting Scripts | WPsharing
Pingback: 9款有用的Javascript代码高亮脚本 | WEB2.0社区
Does anyone know how to get the ‘view source’, ‘print’ and so on dispalyed?
Thanks a lot
Pingback: 5 Wordpress Syntax Highlighter Plugins — I Talk Less!
Pingback: 9 Useful Javascript Syntax Highlighting Scripts | Web design Xi Yang Blog
Pingback: 9款有用的Javascript代码高亮脚本 | phpLeaf
Pingback: 9个实用的Javascript代码高亮脚本 - 博客 - 伯乐在线
hey good job.
I have a question:
what is the purpose of “clipboard.swf” in the .init method ???
In flash, by default, you can copy things to the users clipboard. Javascript instead will allways show a prompt asking to allow access to the clipboard. The clipboard.swf just gives access to the clipboard by wrapping flash clipboard access in a javascript api.
Pingback: 10 jQuery Syntax Highlighters | jQuery4u
Pingback: Onepass to syntax highlighters « OnePass
Very Cool. Thanks!
I can’t get it work proper; I would be very thankful if you could write a demo r something so people like me could use your work:-)
Pingback: 9 Useful Javascript Syntax Highlighting Scripts | JS Tips
Pingback: Best 12 Syntax Highlighters to Export Your Code Elegantly | Sky Tech Geek
Pingback: 10 Syntax Highlighter To Beautify Your Code | Inspirationshub
Pingback: 10 Syntax Highlight Javascript Plugins | ZoomZum
Pingback: 9个实用的Javascript代码高亮脚本 | 编程X资讯
While copying in the syntax highlighter, line numbers are getting copied too. How to fix this?
Pingback: 11 Syntax Highlighters To Beautify Code Presentation - DeluxeXtreme.com
Really Nice Post Dude
Is Syntaxhighlighter v3 supported?
Actually I don’t know. Just try to change the url..
You may also fork the project – I’m not actively developing it…
SH v3 is currently not supported, essentially due to the “SyntaxHighlighter.utils.findBrush” call, which is missing in SH v3.
I think you shoud use SH v2, for v3 seems not to be really finished.
Or – needless to say – fork this plugin 😉
Pingback: 9款有用的Javascript代码高亮脚本 | S9Tech
Pingback: Syntax Highlighter | Annotary
Pingback: 15 скриптів для підсвічування синтаксису коду
Pingback: Top 10 Code Syntax Highlighter jQuery Plugins
Pingback: Tutorials Junction | 10 Very Useful jQuery Plugins for Code Syntax Highlighting
Pingback: 9个实用的Javascript代码高亮脚本_Uncategorized-
Pingback: 15 Code Syntax Highlighters To Prettify Your Code | Code Geekz
Pingback: 美化代码的15个代码语法高亮工具 – jQ酷
Pingback: Beauty Tips Jquery Plugin |
Pingback: 11 resaltadores de código para nuestros sitios web - Psoluciones
Pingback: 15 Best jQuery Syntax Highlighters - GojQuery
Pingback: 果断收藏9个Javascript代码高亮脚本 – x
Pingback: 11 Script Syntax Highlighter Terbaik untuk Dekorasi Kode
Pingback: Share Snippets Easily: Code Syntax Highlight jQuery Plugins - DesignFloat