2015-01-18

Level Up - Blogger: How to add formatted code to post (with highlighting)

In many of my posts, I like to add code snippets. Blogger doesn't have good native support for displaying code with syntax and line highlighting, so I found a way to add that feature using GitHub Gists and gist-embed project on GitHub.

The following steps can mostly be used with any blog.

Step 1: Include jQuery and gist-embed within your header tags.

<head>
  ...
  <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/gist-embed/2.0/gist-embed.min.js"></script>
</head>


Step 2: Add a code element to where you want your Gist code to appear.

<code data-gist-id=""></code>


Example:

// Finds the sum of all the primes below one million.
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
const int NUM = 1000000;
int count = 1;
bitset<NUM> Sieve;
__int64 sum = 0;
Sieve.flip(); // Sets all bits to 1.
Sieve[0].flip(); // Sets 0 to not prime.
Sieve[1].flip(); // Sets 1 to not prime.
// Check all numbers from 2 to sqrt(NUM).
for (long i = 2; i * i < NUM; ++i)
{
if (!Sieve[i]) // If marked not prime.
{
continue;
}
else // If marked prime, set all multiples as not prime.
{
for (long j = 2 * i; j < NUM; j += i)
{
Sieve[j] = 0;
}
}
}
// Add together all primes less than NUM.
for (long i = 2; i < NUM; ++i)
{
if (Sieve[i])
{
count++;
sum += i;
}
}
cout << "Number of primes: " << count << endl;
cout << "The sum is: " << sum << endl;
}


Source:
<code data-gist-file="PrimeNumbers.cppdata-gist-hide-footer="true"
   data-gist-highlight-line="9,12,35-42" data-gist-id="5789439"></code>


Nice features also included, but not shown above:

  • Ability to show GitHub footer
  • Remove line numbers
  • Load multiple files from a Gist
  • Load a signal file from a Gist
  • Show only certain lines from a file


This article was mainly written for myself in the future, but I hope others can benefit from it, as well.

Links:



~ Danial Goodwin ~



No comments: