1. Syntax highlighting in your Tumblr blog with highlight.js

    While setting up my Tumblr blog I wondered if it was possible to set up syntax highlighting for new blog posts that contain code snippets.

    This is what it looks like with some sample C code in it.

    #include <stdio.h>
    /* print Celsius-Fahrenheit table
    for celsius = 0, 20, ...300 floating point version
    */
    main()
    {	
    	float fahr, celsius;
    	int lower, upper, step;
    
    	lower = 0;    //lower limit of temperature table
    	upper = 300; //upper limit of temperature table
    	step = 20;   //step size
    	celsius = lower;
    	printf("Celsius\t Fahrenheit\n");
    
    	while (celsius <= upper) {
    		fahr = (celsius * 9/5) + 32.0;
    		printf("%f \t\t %f\n", celsius, fahr);
    		celsius = celsius + step;
    	}
    }
    
    By the way, the sample C code is an exercise taken from “The C programming language, second edition” by Brian W. Kernighan and Dennis M.Ritchie. An excellent book if you want to learn C.

    Ok, without further ado, this is how I did it.

    Go to: Tumblr Preferences and set “Edit posts using” to “plain text/HTML”

    Now go to: http://softwaremaniacs.org/soft/highlight/en/download/ and copy the link to the prebuilt version of highlight.js and paste it in between the head tags of your Tumblr theme. Make sure it’s loaded after jQuery.

    Next: Copy the link of the theme you like in a new browser window. I chose for sunburst: http://yandex.st/highlightjs/6.1/styles/sunburst.min.css

    This is what I pasted in the head of my Tumblr theme until so far
    <!-- Include highlight.js -->
        <script type="text/javascript" src="http://yandex.st/highlightjs/6.1/highlight.min.js"></script>
     <!-- End-->
    <!-- Include Sunburst theme CSS from highlight.js -->
    <link rel="stylesheet" type="text/css" href="http://yandex.st/highlightjs/6.1/styles/sunburst.min.css" />
    <style type="text/css">
    /* Added to regulate font-size of the syntax snippets */
    code 
        {font-size: 12px}
    </style>
    <!-- End-->

    Now let’s initialize the highlight function:
        <script type="text/javascript">
        $(document).ready(function() {
            $('pre code').each(function(i, e) {hljs.highlightBlock(e, '    ')});
        });
        </script>

    To be able to post a code snippet you need to convert the reserved HTML characters in it to HTML entities. I use a handy tool for this made by Elliot Swan, thank you for creating that:
    http://www.elliotswan.com/postable/.

    After you converted the code snippet you can paste it in your blog posts placing it between
    <pre><code>
    your code..
    </code></pre>

    That’s it! Hopefully this was useful.
    1. icmcshane reblogged this from luisroman
    2. luisroman posted this