JS Syntax Highlighter

Good software that configurable and does exactly what you want is often hard to come by. Since I've started this blog, I've always wanted a good syntax highlighter that looks nice but was flexible enough to support a large number of languages. I've tried quite a few, but each had their own annoying little quirks.

Lucky for me, a smart chap called Alex Gorbatchev has created an awesome open source syntax highlighter in Javascript. It simply searches through for all "pre" tags with a specific classname and applies the highlighting once your page is loaded.

To use it, import the following files into your HTML file within the "head" tag.

<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/>

If you do not wish to use the latest version, replace "current" with the specific version you want. Alex has been nice enough to host the files for us and make it available for public use.

The brush files extend the syntax highlighter functionality to include other languages such as C#, JS, PHP or C++. Be sure to import the files you need.

The following example imports SQL and C++ brushes for use.

<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js' type='text/javascript'/>

If you want to know what other brushes are available, they are listed here.

To configure Syntax Highlighter, you can do so by using the following:

<script type='text/javascript'>
// Makes Syntax Highlighting work for blogger.com sites
SyntaxHighlighter.config.bloggerMode = true;

// Customize tab size
SyntaxHighlighter.defaults['tab-size'] = 2;
// ... more options

// This applies the highlighting

For more configuration options, see here.

When you wish to apply the highlighting onto a specific block of code, place the code within a "pre" tag and apply a CSS class "brush: php" (if you're displaying PHP). Find the right brush alias here.

<pre class="brush: cpp;">
HWND getDesktopHandle();

// Provides visual clues on the state of the application.
void UpdateUI() {
  HMENU menu = GetMenu(m_hWnd);
  LPHIDEDESKTOPINIINFO info = m_map.open();

  CheckMenuItem(menu, ID_MENU_ENABLED, MF_BYCOMMAND | (info->hExplorerLib ? MF_CHECKED : MF_UNCHECKED));


Its also important to note that alot of WYSIWYG blog editors are not very "pre" tag friendly. Fortunately, this is configurable in Syntax Highlighter by changing the "tagName" option to something else like "div".

There you have it! Now you have fully functional, very pretty syntax highlighting.

[ Sources ]

Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog