Syntax Highlighting in Yii

Site has moved

This site has moved to a new location. Visit the new site at http://programsdream.nl.

By Ronald van Belzen | April 29, 2013

Syntaxhighlighting is not difficult in Yii, but I was unable to find any examples on the web. CTextHighlighter is well documented, but a working example is sometimes helpful.

On my website I use the CKEditor with the help of the editMe extension to edit text. In the editor I enter the <pre> tag with the attribute "lang" to enclose code. For viewing the text I use the following jQuery script to change the displayed code:

function setSyntax(id) { 
  var content = $('#'+id).html(); 
  var lang = $('#'+id).attr('lang'); 
  $.ajax({ 
    url: url, 
    type: "POST", 
    dataType: "json", 
    data: {
      "id" : id, 
      "lang" : lang, 
      "content" : content 
    }, 
    success: function(data){
      $('#'+data.id).replaceWith(data.content); 
    }, 
    error: function(error){
      console.log("Error:"); console.log(error); 
    } 
  }); 
} 

$(document).ready(function(){ 
  $('pre').each(function(n) { 
    this.id = 'code_'+n; 
    setSyntax('code_'+n); 
  }); 
});

The script reads all code enclosed inside <pre> tags and sends it to the server with Ajax calls. The returned content is used to replace the <pre> tags together with their content.

On the server side the controller action handles the request:

public function actionSyntax() { 
  $json = array(); 
  $json['id'] = $_POST['id']; 
  $language = $_POST['lang']; 
  $content = $_POST['content']; 
  $content = str_replace('<br>', '', $content); 
  $content = str_replace('<p>', '', $content); 
  $content = str_replace('&lt;', '<', $content); 
  $content = str_replace('&gt;', '>', $content); 
  $highlighter = new CTextHighlighter; 
  $highlighter->showLineNumbers = true; 
  $highlighter->language = $language; 
  $content = $highlighter->highlight($content); 
  $json['content'] = $content; 
  echo json_encode($json); 
  Yii::app()->end(); 
}

After some cleaning up of the content it is CTextHighlighter that does the actual highlighting with "$highlighter->highlight($content)".