Using Gists for Code Snippets

Normally, I use Windows LiveWriter to write my blogs at BlogSpot.  And I have always used syntax highlighter plug-ins to insert code snippets.  These utilities in the past inserted a lot of html elements and style definitions in-line with the rest of the post or required setting up global stylesheets and javascript in order to work.

In the last few weeks, as I have been looking at transitioning my blog to a ruby-based engine called OctoPress, I found another mechanism for inserting code snippets - gists from GitHub.  It allows you to store your code snippets online and easily add them to your posts with one line of code.

All you need to do is:

1.  Go to http://gists.github.com

2.  Sign up for  a free GitHub account

All you have to do is click on the link in the upper, right-hand corner "Sign up for a GitHub account".  It leads you through a process.


If you don't wish to create an account, you can create gists anonymously as well.

3.  Add gist to GitHub

All you need to do in order to add a new gist is: 

a.  Create a name for the gist
b.  Create a name for the file (this is optional)
c.  Select a language 

If you give the file a name, the system will determine what the language is from the extension.

d.  Put the text of the code snippet in the body of the gist
e.  Save the gist by clicking on the Save Gist button.


4.  Add the gist in your post

In order to add the gist to your post, you will need to click on the show embed link and add the html snippet to the html content of your post.  In this case, 

<script src="https://gist.github.com/1522062.js"> </script>

Once you have added this, the code should appear in the post as below.



5.  Add line numbers via additional css styles

You may notice once using the steps above that the native gists from GitHub do not support line numbers currently, so in order to add them I found a gist that contains the .css styles that you need to add to your blog site.  Once added, all snippets appear with line numbers as you saw in point number 4. 



If you find another way to do this by adjusting settings at GitHub, let me know in the comments.

Hope this helps!