Thursday, July 3, 2014

Tip: Using syntax highlighter

I know i should've used this amazing SyntaxHighlighter (many thanks to the developer!) from the very beginning, but for some reason i got to it only now. So here is my quick glance on this beautiful product. :)

Before i begin here is a few tips:

1. SyntaxHighlighter does not work in Blogger post preview. So if you see no difference in preview remember, that you have to publish the post and open it in normal way.

2. Text, which you want to highlight, goes inside <pre></pre> tags, and this text should be html-encoded.
So your code block should look like this: <pre class="brush: [brush_name_here]"> encoded html here </pre>

Now let's add syntax highlighter to your blog:

1. Log into your blog and open template for editing.

2. Find the closing </head> tag. This is where we going to setup highlighter - right before this closing tag.

3. Insert css and scripts.

<!-- syntax highlight -->
<!-- syntax highlight core -->
<link href='http://alexgorbatchev.com/pub/sh/2.1.364/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/2.1.364/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shCore.js' type='text/javascript'>
</script>
<!-- syntax highlight brushes -->
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushCSharp.js' type='text/javascript'>
</script>
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushCss.js' type='text/javascript'>
</script>
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushJScript.js' type='text/javascript'>
</script>
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushSql.js' type='text/javascript'>
</script>
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushXml.js' type='text/javascript'>
</script>
<!-- syntax highlight init -->
<script language='javascript'>
  SyntaxHighlighter.config.bloggerMode = true;
  SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.1.364/scripts/clipboard.swf';
  SyntaxHighlighter.all();
</script>

As you can see I've added only 4 brushes. Complete list of brushes you can check out here

That's it. Go ahead and create a new post with something like this:

<pre class="brush: c-sharp">
public class Foo
{
public int Bar { get; set; }

/// &lt;summary&gt;
/// Test method
/// &lt;/summary&gt;
/// &lt;returns&gt;int&lt;/returns&gt;
public int Test()
{
return this.Bar;
}
}
</pre>

Publish the post, open and notice that the code block now looks nice and fancy:

    public class Foo
    {
        public int Bar { get; set; }

        /// <summary>
        /// Test method
        /// </summary>
        /// <returns>int</returns>
        public int Test()
        {
            return this.Bar;
        }
    }

No comments :

Post a Comment