Highlight code with symfony and Geshi


Symfony | PHP | Technical | Development | August 31, 2010

Sometimes when showing some code in the web, the usual IDE code highlighting is gone. That colors, which make visually different a variable from a string or maybe a reserved word. It would be great if that same visual advantage could be in our web page when using some code from a programming language.

Well, that's what GeSHI was done for. GeSHI is a generic syntax highlighter, which has support for a wide range of popular languages and has highly customisable output formats. You can download the last version of GeSHI from this url.

Once downloaded, we added it to the common lib/vendor folder in our symfony project (symfony 1.4/1.3). Because GeSHI does not follow the symfony autoloader convention we have to manually include it. Add the following line to the ProjectConfiguration.class.html"php">  require_once(dirname(__FILE__).'/../lib/vendor/geshi/geshi.html');  

 

Now suppose you have the following schema for a common post table:

 

 
Post:
  tableName:                           post
  actAs:
    Sluggable:                         { fields: [ title ] }
    Timestampable:
  columns:
    id:                                { type: integer  , length: 20 , primary: true    , autoincrement: true                                                  }
    user_id:                           { type: integer  , length: 20                    , notnull: true                                                        }
    title:                             { type: string   , length: 200                   , notnull: true                                                        }
    content:                           { type: string   , length: 20000                 , notnull: true                                                        }
    excerpt:                           { type: string   , length: 500                   , notnull: true                                                        }
 

 

Now add to the post form class the following methods:

 

 
  protected function updateContentColumn($content)
  {
    return preg_replace_callback('#\[(\w+)\](.*?)\[/\\1\]#s', array($this, 'processCode'), $content);
  }
 
  protected function processCode($matches)
  {
    $geshi = new GeSHi($matches[2], $matches[1]);
    $geshi->set_header_type(GESHI_HEADER_PRE);
    $geshi->enable_classes();
 
    return $geshi->parse_code();
  }
 

 

The updateContentColumn method updates the content. At each coincidence of for example [php] .... code ..... [/php], the regular expression will extract the "php" tag and it will be assigned in the processCode method as the second parameter of the GeSHI constructor, which indicate the language to use when formatting. This way we can have a [php] ..... code ..... [/php] ...... [css] ..... some code ... [/css]  ......... [python] ...... more code ....... [/python]  and each differente language will be formatted according its tag.

Now, with some stylish css files like code.css:

 
pre
{
    background-color           : #000000;
    color                      : #FFFFFF;
    font-size                  : 14px;
    line-height                : 1.3em;
    margin                     : 1em 0;
    overflow                   : auto;
    padding                    : 0.7em 0.7em 0;
}
 
.html"re1">.imp {font-weight: bold; color: red}
.html"re1">.st_h {color: #56DB3A}
.html"re1">.kw1 {color: #FF8400}
.html"re1">.kw2 {color: #FFFFFF}
.html"re1">.kw3 {color: #E2392D}
.html"re1">.kw4 {color: #1299DA}
.html"re1">.sy0 {color: #E0882F}
.html"re1">.co1 {color: #B729D9; font-style: italic}
.html"re1">.co2 {color: #BD48B3; font-style: italic}
.html"re1">.co4 {color: #ccc; font-style: italic}
.html"re1">.coMULTI {color: #BD48B3; font-style: italic}
.html"re1">.es0 {color: #ddd}
.html"re1">.br0 {color: #fff}
.html"re1">.st0 {color: #99FF00}
.html"re1">.nu0 {color: #1299DA}
.html"re1">.me1 {color: #FFFFFF}
.html"re1">.me2 {color: #FFFFFF}
.html"re1">.re0 {color: #FFFFFF}
.html"br0">{text-decoration: none}
 

 

We can get stylish php code like the one you are seeing now.

GeSHI supports a lot of languages like php, python, css, xml, java, etc; you just have to find css classes for each of this languages to show the way you want.

In this code it is assume the use of a normal textarea to fill the data, however in a normal blog system a WYSIWIG editor is use for this purpose, like TinyMCE or FCKeditor, but when pasting some code in these editors some considerations must be taken in count. All these problems will be resolved in a future post with TinyMCE editor. For now, enjoy your new highlighted symfony code.

 


Comments


Tomasz Ducin said about about 2 hours later

I recommend using the sfGeshiPlugin which is especially designed for highlighting code inside symfony projects (https://www.symfony-project.org/plugins/sfGeshiPlugin). It is well documented and should be really easy to use.

Jonathan Nieto said about about 10 hours later

Although the sfGeshiPlugin is a valuable plugin with handy methods that allow you to easily use the syntax highlighter it has limited use for complex tasks. For example if you want to configure the geshi object with methods such as set_header_type and enable_classes then you must instantiate the object by yourself. Nevertheless it should not be forgotten that the plugin can be incredibly quick and easy to use.

Tomasz Ducin said about about 11 hours later

I'll take it as a valuable suggestion about improving my plugin, thank you :) feel free to contribute to the plugin.

Jonathan Nieto said about about 20 hours later

That was my intention, :) . I'll contribute with your plugin when I understand better the functionalities of GeSHI.



Hey Stranger, leave a comment:

Last Posts

Autoloading: Symfony vs Yii

Symfony2, PhpBB4 and Drupal8

Type and boolean columns with Doctrine and Symfony

Refactoring queries with Doctrine

Extending your Doctrine Model: Template Classes

Integrating Doctrine: Symfony vs Yii

Passing parameters from the action to the view: Symfony vs Yii

Yii framework

Adding custom information to your Doctrine schema

PHP Advent Calendar 2010


My Tweets

1 day ago
Vota x lamula.pe: https://t.co/WTWMkFG via @addthis
9 days ago
Apple Pushes Past Exxon To Become The Most Valuable Public Company In The World (Temporarily) via@TechCrunchhhttps://t.co/lowONSZZ
about 1 month ago
finally this class #semester is finished, new #projects in mind
about 1 month ago
Mark Zuckerberg Explains His Law Of Social Sharing [Video]https://t.co/sqq10Ehh via@TechCrunchh
2 months ago
retomando mi #twitter #notime
3 months ago
How Facebook Can Put Google Out of Businesshttps://t.co/HqDfQGoo via@TechCrunchh
3 months ago
So why not just cut out the middle man? Microsoft.https://techcrunch.com/2011/05/15/samsung-series-5-chromebook/
3 months ago
really like to #design class hierarchies with #compositepattern
3 months ago
Similarly, Microsoft.com started to use jQuery instead of their own ASP.NET Ajax framework. They are still using Windows, for whatever XD
3 months ago
Estudiantes de la PUCP le “voltean” campaña a esposo de Keiko | yoperiodhttps://t.co/ruI9UnmI9Unm@lamulaamula
3 months ago
Reading: Apress.-.Pro.html"https://www.twitter.com/search?q=#php">#php #performance #read
4 months ago
debug_backtrace() is very important on certain situations. #php #debug
4 months ago
@alvarezrodrich felicitaciones!
4 months ago
time to do some #uml diagrams, #classdiagram
4 months ago
hoy es el día,#votaa conciente#peruu
4 months ago
@skoop @funkatron I think someone had a bad day!, #Frameworks are there but you don't have to use them.
4 months ago
making #wireframes for a new #functionality
4 months ago
so much #spam on my #blog =(
5 months ago
learning new topics and tools that I did not use before #rcp
5 months ago
aprendiendo muchos temas y herramientas que no utilizaba antes #rcp
5 months ago
#tweaking httpd.conf #virtualhost
5 months ago
thanks #symfony 1.4, even when i'm not using the entire #framework, yours classes save my life!
5 months ago
integrating with #SOA using #soap
5 months ago
It seems my most #productive working hours are on #sunday #afternoon #evening! XD
5 months ago
#ASOT 500 =)
5 months ago
installing SCA_SDO on #Centos #php
5 months ago
My web service using #soap worked!!!!! #php #SCA #SDO
5 months ago
Working in a new place since last week!, #RCP: Red Científica Peruana, the one which sells the .pe domains in#Perúú ->#happypy
5 months ago
Finally with a new #laptop: #Toshiba =)
5 months ago
@pasku1 Thanks, I will try Pivotaltracker.
5 months ago
@doolphy thanks for your answer doolphy! I'll try you!
5 months ago
@jmasson thanks for your answer! Jira + Confluence is a good combination.
5 months ago
Which is the best project management and collaboration tool right now? #projectmanagement #tool #collaboration
5 months ago
What a #voice! Sied Van Riel feat Nicole McKenna - Stealing Time (Aly & Fila Remix) + #ASOT 497 #trancefamily
6 months ago
working on a situation where #php #traits would be very useful
6 months ago
It is #awesome when you finish doing a lot of changes and nothing is broken =) #TDD #testing
6 months ago
oh, happy birthday! @mtabini o mejor dicho feliz cumpleaños!
6 months ago
why do #IE8 not accept #javascript "const" keyword?
6 months ago
Discovering there is much #more to do with #javascript ... a lot.
6 months ago
Awesome #song!: Cerf, Mitiska & Jaren - Another World (Original Vocal Mix) #ASOT 495 #trancefamily
6 months ago
My legal woman is #PHP, but I have an affair with #Javascript, overall when she wears #jQuery.
6 months ago
This presentation is one of the best I've seen about #unit #testing https://www.slideshare.net/avalanche123/clean-code-5609451
6 months ago
where to do a master on #IT: US or Spain? #survey #php #master plz RT
6 months ago
Bobina feat. Betsie Larkin - You Belong To Me: What a #beautiful voice -> #ASOT 494 #arminvanbuuren
6 months ago
OH NO, IT'S MONDAY -- 2011-02-07 https://t.co/pgaIxe5 via @gojkoadzic
6 months ago
it was not a + b, it was parserInt(a) + parseInt(b) =(, #javascript #fail
6 months ago
The models are complete representations of the system, whereas an #architectural #view focuses only on what is architecturally #significant.
7 months ago
@jmasson that would be great and finally #wikimedia, #drupal, #wordpress and maybe #joomla would push towards the same side, the #php side.
7 months ago
@jmasson Thanks!, #PHP has a bright #future ahead.
7 months ago
A new #blog post about not reinventing the #wheel: /article/symfony2_phpbb4_and_drupal8 #symfony #phpbb #drupal
7 months ago
@giorgiosironi #indeed, that's a very good #question. I think an average of 4 but also depends on how much that #developer work.
7 months ago
It seems the new platform for deploying, managing and scaling PHP apps is https://orchestra.io/ #cool
7 months ago
#Phase project planning vs #iteration project #planning - #project #management
7 months ago
#jeditable with #jquery save my life =)
7 months ago
Amazing #song -> Sied van Riel feat. Nicole McKenna - Stealing Time #ASOT 493 #trancefamily
7 months ago
I simply love "offset" #jquery function =)
7 months ago
I really don't understand why projects like #drupal does not base their components in projects like #doctrine and #symfony
7 months ago
OH NO, IT'S MONDAY -- 2011-01-17 https://t.co/37pr4Bd via @gojkoadzic
7 months ago
@alvarezrodrich me alegra ver q ya borró su cuenta Sr. Rodrich,#twitterr es malo jajja, XD
7 months ago
Acabo de hacerle a mi #brother @diegonl89 un blog para que hable de #actualidad en general: https://www.elgatotechero.com #peru
7 months ago
I just made to my #brother a #blog to talk about current #events in #peru: https://www.elgatotechero.com
7 months ago
Amazing things can be done with #javascript and #css, and of course with the help of #jQuery =)
7 months ago
An architecturally significant element is an element that is important for #understanding the #system.
7 months ago
An architecturally element has a wide impact on the #structure, #performance, #robustness, #evolvability, and #scalability of a #system.
7 months ago
@giorgiosironi Definitely!
7 months ago
Playing with #table #inheritance in #Doctrine
7 months ago
Reading about #RUP, and how addresses the #major difficulties in a new #project.
7 months ago
A new blog #post about #refactoring your queries with #Doctrine: /article/refactoring_queries_with_doctrine #symfony
7 months ago
Yandex in 2010: 43 percent revenue growth https://t.co/cpjT5Jw via @cnet
7 months ago
Going forward!!!!! =) poco a poco llegan los resultados de tanto esfuerzo #fb
7 months ago
Perfect #system with respect to the #requirements but the #wrong system with respect to the #real #problem at the time of #delivery.
7 months ago
Going #forward! =) #fb
7 months ago
A new #blog #post about integrating #Doctrine with #Yii and #Symfony: /article/integrating_doctrine_symfony_vs_yii
7 months ago
@sam_dark Ok thanks!, but I don't understand why in #Yii documentantion use $_GET and $_POST instead of CHttpRequest https://bit.ly/i5emoL