Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Date: 25/08/2015 Permalink: improving-code-highlighting Tags: blogging, styling, jquery, html

Improving code highlighting

Since I have turned on line-numbering for code blocks, it gets applied to all blocks of code. This has a couple of downsides

  • Numbering and syntax-highlighting gets applied to every code block regardless if it is displaying programming code or not
  • Line-numbering always starts at line 1, when sometimes the code displayed is an excerpt of a larger piece

Ideally I wanted to support the following three scenarios for code blocks

Scenario 1 - Code block

# Connect to SQLite database
con = sql.connect( '/var/sqlite/sensor-data.sqlite' )
cur = con.cursor()

Scenario 2 - Code block + syntax highlighting

# Connect to SQLite database
con = sql.connect( '/var/sqlite/sensor-data.sqlite' )
cur = con.cursor()

Scenario 3 - Code block + syntax highlighting + line-numbering

1

# Connect to SQLite database
con = sql.connect( '/var/sqlite/sensor-data.sqlite' )
cur = con.cursor()

Implementation

After some tinkering with some jQuery and CSS I can now specify to which blocks line-numbering and syntax-highlighting should be applied.

I can now add syntax highlighting by adding the tags <pp></pp> before the block of code that I wanted syntax highlighting for. If the block requires line-numbering I can add <pp>1</pp> instead. The number between the tags indicates from what the number for the first line of code should be.

You can view the Markdown code for this post here.

jQuery code

1

$('pp').each(
	function(){
		var val = $(this).text();
		if ( val ) {
			$(this).next('pre').addClass('prettyprint linenums:'+val);
		} else {          
			$(this).next('pre').addClass('prettyprint');
		}
	}
);

this code replaces the initial code mentioned under 'Changes to scripts.js' in the post Changing the styling of my blog.

Additional CSS added to 'style.css'

This is needed to hide the content of the <pp>-tag when specifying the starting line-number for code sections. 1

/* Hiding custom tags */
pp {
	display: none;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.