Monday, July 5, 2010

Integrating SyntaxHighlighter with Sitecore's Rich Text Editor

Some time ago I've noticed that Rich Text Editor is missing "Format Code" button in it's profiles. After initial investigation, I've found that such functionality actually exists, but it's hidden for some reason. To enable it, you should  add a new button to the profile (for example, here: /sitecore/system/Settings/Html Editor Profiles/Rich Text Full/Toolbar 1) and set it's "Click" field value to "FormatCodeBlock":

If you did everything correctly, you'll get the following button in your Text Editor toolbar:

and default RadEditor's code formatting dialog

The dialog itself looks good but html it's producing is too ugly to be used at modern websites, few lines of code result in 50+ lines of markup like:

div style="BORDER-BOTTOM: #7f9db9 1px solid; BORDER-LEFT: #7f9db9 1px solid; LINE-HEIGHT: 100% !important; BACKGROUND-COLOR: white; WIDTH: 100%; FONT-FAMILY: Courier New; HEIGHT: 132px; FONT-SIZE: 11px; OVERFLOW: auto; BORDER-TOP: #7f9db9 1px solid; BORDER-RIGHT: #7f9db9 1px solid">

So, I've decided to replace it by very popular Syntax Highlighter  module. It has a lot of features, very customizable and looks really nice 

keeping the initial markup clear.

After installing the module (copying "styles" and "scripts" folders contents into website folder), I've located the current format code dialog, by default it's stored here: sitecore\shell\RadControls\Editor\Dialogs\FormatCodeBlock.ascx. To enable SyntaxHighlighter, we need to add following lines at the beginning of the file:

Then we should add available highlighting options to the "CodingLanguage" element:

And replace the following line in existing script:

 var formattedCode = SyntaxHighlighter.HighlightAll(code, language, showLineNumbers);

with these ones: 

document.getElementById("FormattedCode").innerHTML = "<pre class="brush: " + language + ";">" + code + "</pre>";

After removing unused scripts and controls we'll get pretty simple dialog:

Resulting html will include your code wrapped with "<pre>" tag. Syntax Highlighter should be enabled at frond-end to make it look as in preview window.

In this implementation, code blocks will not be formatted in back-end, however, it can be easily achieved by adding script/css references into the following file: sitecore\shell\Controls\Rich Text Editor\Preview.aspx.

Also, it's possible to store resulting html in rich text field, avoiding additional scripts at front-end.

You can find the resulting FormatCodeBlock.aspx here. Don't hesitate to ask any questions regarding implementation.