beautyOfCode: jQuery Plugin for Syntax Highlighting

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&#91;3&#93;
    boc-nocontrols
    boc-nogutter
    boc-showcolumns
    boc-collapse">
     // my code
  </code>
</pre>

kick it on DotNetKicks.com

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]

84 thoughts on “beautyOfCode: jQuery Plugin for Syntax Highlighting

  1. 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.

  2. 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=”” šŸ˜‰

  3. 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

  4. Is this correct?

    Line 55: if(highlighter.Style && headNode)

    should that not be the following:

    if(highlighter.Style && headNode)

  5. 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);
    }
    });

  6. Pingback: beautyOfCode – jQuery plugin for Syntax Highlighter 2.0 by Alex Gorbatchev « .Net Braindrops

  7. Pingback: beautyOfCode: jQuery Plugin for Syntax Highlighting " .Net Braindrops | Squico

  8. Pingback: 9 Useful Javascript Syntax Highlighting Scripts

  9. Pingback: 9ę¬¾ęœ‰ē”Øēš„Javascript代ē é«˜äŗ®č„šęœ¬| Ajax| 前ē«Æ观åƟ

  10. Pingback: Techflaps | 16 Javascript Syntax Highlighting Scripts

  11. Pingback: 9 Useful Javascript Syntax Highlighting Scripts | Pdf Search colection

  12. Pingback: 9 Useful Javascript Syntax Highlighting Scripts | Download E-Books Free Video Training Courses Softwares

  13. Pingback: 16 Free Javascript Code Syntax Highlighters For Better Programming | Graphic and Web Design Blog - Inspiration, Resources and Tools

  14. Pingback: Free Javascript Code Syntax Highlighters, Gift For Programmers | guidesigner.net

  15. Pingback: 16 Free Javascript Code Syntax Highlighters For Better Programming - Programming Blog

  16. Pingback: 16 resaltadores de sintĆ”xis de cĆ³digo Javascript para tu web - elWebmaster.com

  17. 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

  18. Pingback: ꜉ē±³å•¦ » 9 Useful Javascript Syntax Highlighting Scripts

  19. Pingback: 幻岛|领地 - åøøē”Øēš„Javascript代ē é«˜äŗ®č„šęœ¬

  20. 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

  21. Pingback: Free Javascript Code Syntax Highlighters « MoeMir

    • Your blogging engine doesn’t understand pre… instead of leaving the text formatted, it puts
      for line breaks:

      		$.beautyOfCode.init({
      brushes: ['Xml', 'JScript', 'CSharp', 'Plain', 'Php'],
      ready: function() {
      $.beautyOfCode.beautifyAll();
      $("#someCode").beautifyCode('javascript', {gutter:false});
      }
      });




  22. Pingback: 9ę¬¾ęœ‰ē”Øēš„Javascript代ē é«˜äŗ®č„šęœ¬ | č®°ē¬”č®°ēš„åœ°ę–¹

  23. Pingback: Equesdesign.com » Ressources #2

  24. Pingback: beautyOfCode 开ęŗé”¹ē›® - Ajax代ē å¤§å…Ø - Java开ęŗé”¹ē›® - ajax代ē é«˜äŗ®highlight - beautyOfCode - Javaå…č“¹č½Æ件 - 开ęŗē½‘

  25. Pingback: BUPOS.com » Google Prettify – Source Code Highlighting

  26. Pingback: beautyOfCode: jQuery Plugin for Syntax Highlighting (via Struggles by Lars C.) « My Weblog

  27. Pingback: 冰ē‚¹

  28. Pingback: 9 Useful Javascript Syntax Highlighting Scripts | WPsharing

  29. Pingback: 9ę¬¾ęœ‰ē”Øēš„Javascript代ē é«˜äŗ®č„šęœ¬ | WEB2.0ē¤¾åŒŗ

  30. Pingback: 5 Wordpress Syntax Highlighter Plugins ā€” I Talk Less!

  31. Pingback: 9 Useful Javascript Syntax Highlighting Scripts | Web design Xi Yang Blog

  32. Pingback: 9ę¬¾ęœ‰ē”Øēš„Javascript代ē é«˜äŗ®č„šęœ¬ | phpLeaf

  33. Pingback: 9äøŖ实ē”Øēš„Javascript代ē é«˜äŗ®č„šęœ¬ - 博客 - ä¼Æ乐åœØēŗæ

    • 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.

  34. Pingback: 10 jQuery Syntax Highlighters | jQuery4u

  35. Pingback: Onepass to syntax highlighters « OnePass

  36. Pingback: 9 Useful Javascript Syntax Highlighting Scripts | JS Tips

  37. Pingback: Best 12 Syntax Highlighters to Export Your Code Elegantly | Sky Tech Geek

  38. Pingback: 10 Syntax Highlighter To Beautify Your Code | Inspirationshub

  39. Pingback: 10 Syntax Highlight Javascript Plugins | ZoomZum

  40. Pingback: 9äøŖ实ē”Øēš„Javascript代ē é«˜äŗ®č„šęœ¬ | ē¼–ē؋X资č®Æ

  41. While copying in the syntax highlighter, line numbers are getting copied too. How to fix this?

  42. Pingback: 11 Syntax Highlighters To Beautify Code Presentation - DeluxeXtreme.com

    • 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 šŸ˜‰

  43. Pingback: 9ę¬¾ęœ‰ē”Øēš„Javascript代ē é«˜äŗ®č„šęœ¬ | S9Tech

  44. Pingback: Syntax Highlighter | Annotary

  45. Pingback: 15 сŠŗрŠøŠæтіŠ² Š“Š»Ń ŠæіŠ“сŠ²Ń–Ń‡ŃƒŠ²Š°Š½Š½Ń сŠøŠ½Ń‚Š°ŠŗсŠøсу ŠŗŠ¾Š“у

  46. Pingback: Top 10 Code Syntax Highlighter jQuery Plugins

  47. Pingback: Tutorials Junction | 10 Very Useful jQuery Plugins for Code Syntax Highlighting

  48. Pingback: 9äøŖ实ē”Øēš„Javascript代ē é«˜äŗ®č„šęœ¬_Uncategorized-

  49. Pingback: 15 Code Syntax Highlighters To Prettify Your Code | Code Geekz

  50. Pingback: ē¾ŽåŒ–代ē ēš„15äøŖ代ē čÆ­ę³•é«˜äŗ®å·„具 – jQ酷

  51. Pingback: Beauty Tips Jquery Plugin |

  52. Pingback: 11 resaltadores de cĆ³digo para nuestros sitios web - Psoluciones

  53. Pingback: 15 Best jQuery Syntax Highlighters - GojQuery

  54. Pingback: ęžœę–­ę”¶č—9äøŖJavascript代ē é«˜äŗ®č„šęœ¬ – x

  55. Pingback: 11 Script Syntax Highlighter Terbaik untuk Dekorasi Kode

  56. Pingback: Share Snippets Easily: Code Syntax Highlight jQuery Plugins - DesignFloat

Leave a reply to 16 Free Javascript Code Syntax Highlighters For Better Programming - Programming Blog Cancel reply