Creating Syntax Highlighting

Now, I spent ages and ages, well would believe "just a long time". Anyway it was too long and I was just cruising the web and listening into the conference call on CSS which runs prior to my PHP Class and I caught a word on the website along from something Claire said and "Magic Light Bulb Moment"! Ummm I have syntax highlighting in my text editor......

So I looked and then I saw it..... Export to HTML with ALL the color syntax included using spans with inline styles (CSS)!

Most Text Editors will allow you to export your page as HTML. Most but not all.

I've only really tested Kate (linux) and PSPAD (windows), but that's only two out of the alleged "Many". You should find it under File->Export or something along those lines.

Well this discovery was something... Enough where I could simply

Simply Wonderful!

This made the code stand out with next to little effort... But I hope you've realised that it's just as easy to put it on your website.

It's the same deal, just paste the result into your webpage, upload it and "Hey Presto", Syntax Highlighted HTML,CSS and PHP all in the one go.

But all that inline styling is repetitive

(just like the old table layout days <*groan*> ) so why not strip all that out and define some external css.

Easy enough!

We just have to learn what our text editor puts in for the inline styles and replace them with some CSS classes.

This takes a little research, but I'll explain the principles so you can adapt this to your editor.

Now I run on a Linux Operating System - Kubuntu using a text editor called Kate.

Creating the Script

We'll be basing this on the PHP command str_replace($Search_Array,$Replace_Array,$string);

Search_Array() will contain the inline styles that the editor creates.
Replace_Array() will contain the CSS class definitions to replace them with and
$string will contain code we want to convert.

We'll have a form with a textarea to paste in the code to convert and the result will be returned into the same textarea of the form.

If you are impatient - you can give it a try. Remember my version only works for my Kate Editor I use on Linux.

Nice and simple!


NOTE:

While this tutorial is using the Code Igniter Framework to explain this, you can use the function on its own in whatever you are using.

What I do hope that you get from this, is that using Code Igniter (or something similar) will make your life easier.

Just as you go through this - keep an eye on all the things you Dont have to do...with the forms,validation etc..


The Form View

<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');?>
<div class="login_form">
<form name="login_form" method="post" action="<?=$post_action?>" >
<fieldset>
<legend>Syntax Highlighting</legend> 
<ol>
<?=$this->validation->code_error; ?>
<li><label for="code">Code:</label>
<textarea name="code" id="code" rows="20" cols="80"><?=htmlspecialchars($code)?></textarea></li>
<input class="submit"  type="submit" name="submit" value="Convert" /></li>
</ol>
</fieldset>
</form>
</div><!-- end of form -->

The Helper Function

<?php
function convert($string)
{
$syntax_old=array(
'style="font-weight: bold;color: #000000;"',
'style="color: #5555ff;"',
'style="color: #000000;"',
'style="font-weight: bold;color: #0f0f8f;"',
'style="color: #dd0000;"',
'style="font-weight: bold;color: #0f0f8f;"',
'style="font-style: italic;color: #808080;"',
'style="color: #a1a100;"',
'style="color: #008000;"',
'style="color: #aa0000;"'
);

$syntax_new=array(
"class='sh_1'",
"class='sh_2'",
"class='sh_3'",
"class='sh_4'",
"class='sh_5'",
"class='sh_6'",
"class='sh_7'",
"class='sh_8'",
"class='sh_9'",
"class='sh_9'"
);
$string = str_replace($syntax_old,$syntax_new,$string);
return $string;
}
?>

Whoops - I tried to convert the script using the script. Guess What! It converts everything in the $syntax_old array changing it to what is in the $syntax_new array. So for now it's using the "Old Way" straight out of the editor.

The function is written in this manor with the definitions in the function to make it simpler. It's actually being saved as a CI helper function.

There is a controller for it and a view for the form and the controller takes the info from the form, converts it and redisplays the converted code.

Then I copy the result out of the form box and paste it into my webpage or where ever I need to put it. Nice!

Now the Style Sheet

Can you figure out the style sheet.

.sh_1,.sh_2,.sh_3,.sh_4,.sh_5,.sh_6,.sh_7,.sh_8,.sh_9,.sh_10,.sh_11,.sh_12,.sh_13{
font-weight: bold;
}
.sh_1 {
color: #000000;
}
.sh_2 {
color: #5555ff;
}
.sh_3 {
color: #000000;
}
.sh_4 {
color: #0f0f8f;
}
.sh_5 {
color: #dd0000;
}
.sh_6 {
color: #0f0f8f;
}
.sh_7 {
font-style: italic;color: #808080;
}
.sh_8 {
color: #a1a100;
}
.sh_9 {
color: #008000;
}
.sh_10 {
color: #aa0000;
}
.sh_11 {
color: #000080;
}
.sh_12 {
color: #800080;
}
.sh_13 {
color: #800000;
}hey nzx
.sh_hide {
color:#666666;
}

I've added in the sh_hide style so I can "unhighlight" some of the code to help emphasize other bits.

Just thinking about that a bit more, it would be simpler to just grab the section of code to highlight,export that as HTML, convert it and add in the "unhighlighted sections back in. Yes, it may be a bit fiddly but it's a one off for each section.

Something like this! (This is only a section of demo code to show the hiding and highlighting)

A Demo of highlighting a section.

		if ($this->validation->run() == TRUE)
		{
			if($this->input->post('submit')=="Convert")
				$data['content'] = "Success";			{
				$this->load->helper('highlight_convertor');
				$form_data['code'] = convert($form_data['code']);
			}
		}
			$data['content'] =$this->load->view('util/syntax_form_view.php',$form_data,True);
			$data['title'] = $this->config->item('site_name')." - ".$page_name;
			$this->load->view('lesson_template',$data,False);
	}
}
?>

The controller is called util to test this out. It has a version of the templating system I am using and it is saved as /public_html/system/application/controller/util.php and is called by typing in http://www.lookingovermyshoulder.com/util

Behind the scenes this is calling http://www.lookingovermyshoulder.com/index.php/util but using mod_rewrite we can hide the index.php part.

The Controller

<?php

class util extends Controller {

	function util()
	{
		parent::Controller();	
		$this->load->library('validation');
		$this->load->helper('url');
		$this->load->config('myconfig');
// This is our default page information to share between the controllers
		$this->load->model('page_model','cpage');
		$this->load->model('menu_model','nav');
	}

// This is our local page information to share between the controller methods
	function _get_local_page()
	{
		$data['title'] = "Utils";
		$data['keywords'] = "HTML,HTML Basics, Learning Basic HTML";
		return $data;
	}
	function index()
	{
		$data = $this->cpage->get_config();
		$data = array_merge($data,$this->_get_local_page());
		$page_name = "util";
// do  the login form
		$rules['code'] = "required";
		$this->validation->set_rules($rules);
		$this->validation->set_error_delimiters('<div class="error">', '</div>');
		$fields['code']	= 'Code';
		$this->validation->set_fields($fields);
// get the form data
		$form_data['code'] = $this->input->post('code');

		$form_data['post_action'] = 'util';
		
		if ($this->validation->run() == TRUE)
		{
			if($this->input->post('submit')=="Convert")
			{
				$data['content'] = "Success";
				$this->load->helper('highlight_convertor');
				$form_data['code'] = convert($form_data['code']);
			}
		}
			$data['content'] =$this->load->view('util/syntax_form_view.php',$form_data,True);
			$data['title'] = $this->config->item('site_name')." - ".$page_name;
			$this->load->view('lesson_template',$data,False);
	}
}
?>

The Model.

There isn't one! Code Igniter will let you Not require a Model. Which some frameworks enforce. Good or Bad, it allows you that flexibilty which is another nice feature of Code Igniter.