CodeColorer

Posted by Dmytro Shteflyuk on

CodeColorer is the plugin which allows you to insert code snippets into the post with nice syntax highlighting. I want to show you example first:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Feed < ActiveRecord::Base
  SOURCE_TYPES = {
    category: 0,
    tag:      1,
    user:     2,
  }
 
  define_enum :source_type, raise_on_invalid: true

  #-------------------------------------------------
  # Accessors

  def video_ids
    v = self[:video_ids]
    v.present? ? v.split(':').map(&:to_i) : []
  end
end

Plugin based on GeSHi library, which supports most languages. CodeColorer has various nice features:

  • syntax highlighting in RSS feeds
  • syntax highlighting of single line of code (inline)
  • syntax highlighting of code in comments
  • line numbers
  • automatic links to the documentation inserting
  • code block intelligent scroll detection (short code would have short block, for long one block height would be fixed and scrollbar would appear)
  • predefined color themes (Slush & Poppies, Blackboard, Dawn, Mac Classic, Twitlight, Vibrant Ink)
  • syntax colors customization in CSS file
  • code protect from mangling by WordPress (for example, quotes, double-dashes, etc would look just right as you entered)

Installation

  1. Download and unpack plugin files to wp-content/plugins/codecolorer directory.

  2. Enable CodeColorer plugin on your Plugins page in Site Admin.

  3. Go to the Options/CodeColorer page in Site Admin and change plugin’s options as you wish.

  4. Use [cc lang="lang"]code[/cc] or <code lang="lang">code</code> syntax to insert code snippet into the post (you could skip lang="lang", in this case code would be in code block, but without syntax highlighting). Also you can use [cci lang="lang"]code[/cci] to format inline code (see the “inline” option description). The list of available languages you could find below.

  5. Have fun!

Syntax

To insert code snippet into your post (or comment) you should use [cc lang="lang"]code[/cc] or <code lang="lang">code</code> syntax. Starting from version 0.6.0 you could specify additional CodeColorer options inside [cc] tag:

1
[cc lang="php" tab_size="2" lines="40"]// some code[/cc]
Note: You should always use double quotes or single quotes around the parameter value. Boolean values could be passed using string true or false, on or off, number 1 or 0.

Short codes

Starting from CodeColorer 0.8.6 you can use short codes to insert code snippets. The short code in common looks like [ccMODE_LANG], where LANG is your programming language, and MODE is the one or more of following modes:

  • iinline
  • eescaped
  • sstrict
  • nline_numbers
  • bno_border
  • wno_wrap
  • lno_links

Small letter means enabled, capital – disabled. Examples:

PHP code with links enabled and line numbers disabled:

1
2
3
[cclN_php]
echo "hello"
[/cclN_php]

Already escaped HTML code:

1
[ccie_html]<html>[/ccie_html]

Ruby code without wrapping having tab size equal to 4:

1
2
3
[ccW_ruby tab_size="4"]
attr_accessor :title
[/ccW_ruby]

More examples could be found on the CodeColorer Examples page. You can find modes explained below.

Possible parameters

  • lang (string) – source language.
  • tab_size (integer) – how many spaces would represent TAB symbol.
  • lines (integer) – how many lines would be block height without scroll; could be set to -1 to remove vertical scrollbar.
  • width (integer or string) – block width.
  • height (integer or string) – height in pixels; used when lines number is greater then “lines” value.
  • rss_width (integer or string) – block width in RSS feeds.
  • theme (string) – color theme (default, blackboard, dawn, mac-classic, twitlight, vibrant, geshi, railscasts, solarized-light, solarized-dark).
  • first_line (integer) – a number of the first line in the block.
  • highlight (string) – a comma-separated list of line numbers or ranges of line numbers to highlight (e.g. 1,5,8-11).
  • escaped (boolean) – when true special HTML sequences like &lt; or [ will be treated as encoded (in this example as < and [ respectively.)
  • line_numbers (boolean) – when true line numbers will be added.
  • no_links (boolean) – when false keywords will be represented as links to manual.
  • inline (boolean) – when true forces code block to render inside <code></code> tag. Used to paste a single line of code into the regular text.
  • strict (boolean) – when true strict mode will be enabled. By default CodeColorer tries to guess whether strict mode is needed, so this option allows to force it on or off when automatic suggestion is wrong.
  • nowrap (boolean) – when false no horizontal scrollbar will be shown; instead code will be wrapped in the end of code box.
  • noborder (boolean) – when true no border will be shown around the code block.
  • no_cc (boolean) – when true the syntax in code block will not be highlighted, code will be rendered inside <code></code> tag.
  • class (string) – additional CSS classes to add to the wrapper HTML element.
  • file (string) – when specified, code will be loaded from external file. Should be a relative to uploads folder path, only files from uploads are allowed to be embedded.

You can use special tag [cci] instead of [cc] to force inline mode: [cci lang="lang"]code[/cci]

Most of these parameters could be configured via the CodeColorer options page.

Supported languages

Here is list of supported by CodeColorer languages: abap, actionscript, actionscript3, ada, apache, applescript, apt_sources, asm, asp, autoit, avisynth, bash, basic4gl, bf, bibtex, blitzbasic, bnf, boo, c, c_mac, caddcl, cadlisp, cfdg, cfm, cil, cmake, cobol, cpp-qt, cpp, csharp, css, d, dcs, delphi, diff, div, dos, dot, eiffel, email, erlang, fo, fortran, freebasic, genero, gettext, glsl, gml, gnuplot, groovy, haskell, hq9plus, html4strict, idl, ini, inno, intercal, io, java, java5, javascript, kixtart, klonec, klonecpp, latex, lisp, locobasic, lolcode, lotusformulas, lotusscript, lscript, lsl2, lua, m68k, make, matlab, mirc, modula3, mpasm, mxml, mysql, nsis, oberon2, objc, ocaml-brief, ocaml, oobas, oracle11, oracle8, pascal, per, perl, php-brief, php, pic16, pixelbender, plsql, povray, powershell, progress, prolog, properties, providex, python, qbasic, rails, rebol, reg, robots, ruby, sas, scala, scheme, scilab, sdlbasic, smalltalk, smarty, sql, tcl, teraterm, text, thinbasic, tsql, typoscript, vb, vbnet, verilog, vhdl, vim, visualfoxpro, visualprolog, whitespace, whois, winbatch, xml, xorg_conf, xpp, yaml, z80.

Requirements

Plugin supports WordPress versions 3.5.0 and later. PHP 5.6 or newer is required (please check PHP: Supported Versions page to check if your version is still supported.)

Download

The latest version of the CodeColorer plugin is 0.9.14, and you can download it here:

version0.9.14DownloadCodeColorer Plugin

Also you can download older versions from plugin home page on WordPress.org (but do you really need this old stuff?).

Translations

Thank you all guys, who submitted translations to your language. CodeColorer is currently available in following languages:

Want to help me with translation? It’s easy!

  1. Install Poedit.

  2. Download codecolorer.pot file.

  3. Click File/New catalog from .pot file and select codecolorer.pop you’ve just downloaded.

  4. Enter project name (something like CodeColorer 0.9.8), your name and email address, select a language you want to translate to and click OK.

  5. Enter a filename like codecolorer-en_EN.po and click Save.

  6. Translate all strings one by one.

  7. Send me a .po file with a translation to [email protected]. Do not forget a link to add to CodeColorer project home page.

  8. Thank you!

To fix existing translation, just open corresponding .po file from codecolorer/languages folder in Poedit, and add missing or update existing strings.

Customization

Syntax coloring is highly customizable: you could change color scheme for all
languages or for specific language. You could find CodeColorer CSS in
wp-content/plugins/codecolorer/codecolorer.css file. To change colors for
all languages edit lines below Color scheme section.

There is simple mapping exists between Textmate color themes and CodeColorer
ones:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    /* "Slush & Poppies" color scheme (default) */
    .codecolorer-container, .codecolorer { color: #000000; background-color: #F1F1F1; }
    /* Comment */
    .codecolorer .co0, .codecolorer .co1, .codecolorer .co2, .codecolorer .co3, .codecolorer .co4, .codecolorer .coMULTI { color: #406040; font-style: italic; }
    /* Constant */
    .codecolorer .nu0, .codecolorer .re3 { color: #0080A0; }
    /* String */
    .codecolorer .st0, .codecolorer .st_h, .codecolorer .es0, .codecolorer .es1 { color: #C03030; }
    /* Entity */
    .codecolorer .me1, .codecolorer .me2 { color: #0080FF; }
    /* Keyword */
    .codecolorer .kw1, .codecolorer .kw2, .codecolorer .sy1 { color: #2060A0; }
    /* Storage */
    .codecolorer .kw3, .codecolorer .kw4, .codecolorer .kw5, .codecolorer .re2 { color: #008080; }
    /* Variable */
    .codecolorer .re0, .codecolorer .re1 { color: #A08000; }
    /* Global color */
    .codecolorer .br0, .codecolorer .sy0 { color: #000000; }

Check the codecolorer.css file to get more examples.

Frequently Asked Questions

Q. How do I can customize CodeColorer CSS rules?
A. Go to the Options/CodeColorer page in Site Admin and change the “Custom CSS Styles” option.

Q. I see &lt; instead of < (or other HTML entities like >, &, ") in my code.
A. You should use [cc escaped="true"] or [cce] in the visual editor when inserting code into the post.

Q. Does it highlights my code on server or client side?
A. CodeColorer performs code highlighting on the server, you could see HTML of the highlighted code in page source.

Q. Is it produces valid XHTML source?
A. Yes, resulting XHTML is completely valid.

Q. Could my visitors insert their code snippets in comments?
A. Yes, CodeColorer supports code highlighting in comments using the same syntax, as you use in your blog posts.

Q. How can I disable syntax highlighting for a particular <code> block?
A. Use no_cc="true" option for your code block.

Q. I have updated the plugin to the newest version and now I keep getting following warnings:

1
Warning: array_keys() [function.array-keys]: The first argument should be an array in /home/wordpress/wp-content/plugins/codecolorer/lib/geshi.php on line 3599

A. Remove all files from wp-content/plugins/codecolorer folder and unpack an archive with plugin again (thanks to Anatoliy ‘TLK’ Kolesnick).

Q. I love this plugin. How to do a favor to the author?
A. Just vote for this plugin on WordPress.org. And thank you!

Support

If you have any suggestions, found a bug, wanted to contribute a
translation to your language, or just wanted to say “thank you”,– feel free to contact me. Promise, I will answer to every message.

If you want to contribute your code, see the Development section below.

Development

Sources of this plugin are available both in SVN and Git:

Feel free to check them out, make your changes and send me patches. Promise, I will apply every patch (of course, if they add a value to the product). Email for patches, suggestions, or bug reports: [email protected]. Also you have much more ways to contact me.

Changelog

  • 0.9.14 (October 25, 2017)
    • IMPORTANT: Another line numbers column width issue for numbers bigger than 1000.
  • 0.9.13 (October 24, 2017)
    • IMPORTANT: Fixed line numbers column width issue, introduces in the previous version.
    • Fixed line numbers column position on RTL pages.
  • 0.9.12 (October 12, 2017)
    • Fixed XML syntax highlighting colors.
    • Fixed line highlighting color for dark themes.
    • Added support for TablePress plugin.
    • Line highlighting affects the whole block width, not only the code text.
  • 0.9.11 (August 8, 2017)
    • Fixed an issue with TinyMCE when CodeColorer options were removed in the editor (thanks to Jonathan Stassen for the suggestion).
    • New art for the WordPress plugins page.
    • Moved translations to https://translate.wordpress.org/projects/wp-plugins/codecolorer. WordPress should automatically download language packs now.
    • Lots of code style issues, should resolve all warnings in PHP logs.
  • 0.9.10 (July 28, 2017)
    • Fixed a bug with large code blocks margins.
    • Added Portuguese translation (thanks to Luis Coutinho).
    • Added Indonesian translation (thanks to Masino Sinaga).
    • Fixed PHP 7 compatibility issues (thanks to Steve Kamerman and Robert Felty).
    • Fixed WordPress 4+ compatibility (editor button, settings page layout).
    • Added “Solarized Light” and “Solarized Dark” themes (thanks to Matt Kirman).

Complete changelog could be found on the CodeColorer History page.

Other plugins

Full list of plugins I have implemented is available here.

228 Responses to this entry

Subscribe to comments with RSS or TrackBack to 'CodeColorer'.

said on April 24th, 2008 at 16:49 · Permalink · Reply

[…] 其實可以搭配另一個外掛,那就是 CodeColorer,這個外掛,可以讓你在寫程式的時候加上顏色喔,相當方便,他支援的語法如下: actionscript, ada, apache, applescript, asm, asp, autoit, bash, blitzbasic, bnf, c, caddcl, cadlisp, cfdg, cfm, cpp-qt, cpp, csharp, css-gen.cfg, css, c_mac, d, delphi, diff, div, dos, eiffel, fortran, freebasic, gml, groovy, html, idl, ini, inno, io, java, java5, javascript, latex, lisp, lua, matlab, mirc, mpasm, mysql, nsis, objc, ocaml-brief, ocaml, oobas, oracle8, pascal, perl, php-brief, php, plsql, python, qbasic, rails, reg, robots, ruby, sas, scheme, sdlbasic, smalltalk, smarty, sql, tcl, text, thinbasic, tsql, vb, vbnet, vhdl, visualfoxpro, winbatch, xml, xpp, z80 […]

said on June 13th, 2008 at 07:31 · Permalink · Reply

Большое спасибо, это действительно то что я искал, очень удобно и без лишнего гемора, особенно когда публикуешь фрагменты кода

said on June 17th, 2008 at 03:33 · Permalink · Reply

I have to say ‘Thank you’ first, I loooooooove this plugin!!!!

One small thing, I notice the code will remove the first spaces from the code because of ‘trim’, I use the following code instead and it fixed the problem.

p.s. it works fine with wp2.5.1

1
2
3
    $text = preg_replace("/^\s*\n/siU", "", $text);
    $text = rtrim($text);
#line 215    $text = trim($text);
said on June 18th, 2008 at 12:12 · Permalink · Reply

I think I found a small bug
in comment if wrote several \ and a ' in the cc or code block, that comment won’t be posted!
if in post wrote several \ and a ' the result will be missing one \
I make a small change

1
2
    $text = str_replace("\\"", """, $text);
#  $text = str_replace(array("\\"", '\\''), array (""", '\''), $text);
said on July 25th, 2008 at 00:28 · Permalink · Reply

[…] CodeColorer обладает также рядом дополнительных интересных свойств, например, нумерацией строк, настройкой подсветки синтаксиса, подсветкой кода в комментариях и т.п. Модуль имеет достаточно широкий спектр настроек и большой список поддерживаемых языков. Единственное, что заставляет задуматься, это требования к версии wordpress – 2.1. Поэтому гарантии безотказной работы в более старших версиях нет. Подробнее о плагине на русском языке можете почитать в этом обзоре. […]

said on July 25th, 2008 at 16:24 · Permalink · Reply

I think I found 2 bugs.

1. If code snippets has only one line, his height is to small to display code.

1
var $one_line;

2. If there are some tabs in code I must to use parameter ‘tab_size’. Is there no default value?

said on July 25th, 2008 at 16:25 · Permalink · Reply

Upsss. Here one line snippet looks properly. Why?

said on September 10th, 2008 at 18:52 · Permalink · Reply

[…] CodeColorer обладает также рядом дополнительных интересных свойств, например, нумерацией строк, настройкой подсветки синтаксиса, подсветкой кода в комментариях и т.п. Модуль имеет достаточно широкий спектр настроек и большой список поддерживаемых языков. Единственное, что заставляет задуматься, это требования к версии wordpress – 2.1. Поэтому гарантии безотказной работы в более старших версиях нет. Подробнее о плагине на русском языке можете почитать в этом обзоре. […]

said on December 31st, 2008 at 09:38 · Permalink · Reply
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Feed < ActiveRecord::Base

  SourceTypes = {
    :category => 0,
    :tag => 1
  }
 
  define_enum :source_type, :raise_on_invalid => true

  #-------------------------------------------------
  # Accessors

  def video_ids
    v = self[:video_ids]
    v ? v.split(':').map(&:to_i) : []
  end
end
said on January 1st, 2009 at 03:07 · Permalink · Reply

In SVN version of WordPress 2.8 (bleeding edge) the options page doesn’t load, just an FYI. I am not sure if it’s something you will need to change for 2.8 or a problem with wordpress guys created in the trunk by accident with loading the plugin options. If I find out I will let you know. ‘Cannot load codecolorer-options.php.’

said on January 4th, 2009 at 01:17 · Permalink · Reply

It looks like the path changed slightly to:

1
wp-admin/options-general.php?page=codecolorer/codecolorer-options.php

Instead of

1
wp-admin/options-general.php?page=codecolorer-options.php
said on January 4th, 2009 at 18:19 · Permalink · Reply

Hi there, thanks for the plugin…is the best of its kind so far. I have a question, it’s kind of dumb so please be gentile. I want to show some code but i have no idea what language is it…it’s some kind of C# but i am not shure. Is there a way to use in the code section something like “all”? Thanks:)

kduks
said on January 7th, 2009 at 08:14 · Permalink · Reply
1
2
3
 <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Button id="rang" />
</mx:Application>

Good
thx!

said on January 10th, 2009 at 22:56 · Permalink · Reply
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
// Pre-2.6 compatibility
if( !defined('WP_CONTENT_DIR') )
define( 'WP_CONTENT_DIR', ABSPATH . 'wp-content' );

if( !include( WP_CONTENT_DIR . '/wp-cache-config.php' ) )
return;
if( !defined( 'WPCACHEHOME' ) )
define('WPCACHEHOME', dirname(__FILE__).'/');

include( WPCACHEHOME . 'wp-cache-base.php');

if(defined('DOING_CRON')) {
require_once( WPCACHEHOME . 'wp-cache-phase2.php');
return;
}

$mutex_filename = 'wp_cache_mutex.lock';
$new_cache = false;

// Don't change variables behind this point

$plugins = glob( WPCACHEHOME . 'plugins/*.php' );
if( is_array( $plugins ) ) {
foreach ( $plugins as $plugin ) {
if( is_file( $plugin ) )
require_once( $plugin );
}

Тест!

rec
said on January 16th, 2009 at 00:02 · Permalink · Reply

When I try to change the options in WP2.7 (Cutline theme) the page goes into an infinite loop, I can only get out of it by moving the plugin directory. Any ideas?

said on January 18th, 2009 at 01:40 · Permalink · Reply

Are there any options to disable plugin action for marked elements? I mean sth like this: “code lang=”false”. I hope you get it :)

said on January 22nd, 2009 at 13:26 · Permalink · Reply

2dreame4: Will add this feature in next version (will be released at the end of this week).

said on January 19th, 2009 at 00:09 · Permalink · Reply

Огромное спасибо! Теперь при цитировании скриптов всё стало так аккуратно и красиво! :)

said on January 22nd, 2009 at 13:49 · Permalink · Reply

@Dmytro Shteflyuk: great information ;) And I noticed that there is a problem with validation your plugin. I mean converted <code&rt; is not validated. Do you take care of it?

said on January 27th, 2009 at 18:41 · Permalink · Reply

2 dreame4: Just released CodeColorer v0.7.3 with new option:

1
<code no_cc="true">some code</code>
said on January 30th, 2009 at 18:09 · Permalink · Reply

First – thanks for a great plugin!!
I have a minor feature request. Instead of specifying the width in pixels, I prefer to specify it in %, as my blog is not fixed width. This used to work in a previous version, but now it seems that px is hard-coded in.

Thanks.

Rob

said on January 31st, 2009 at 21:56 · Permalink · Reply

2 Andrias: looks like you forgot to add opening <php tag at the beginning of the code block.

said on January 31st, 2009 at 22:30 · Permalink · Reply

Yes I know, but that is actually intentional. The code that I show is meant to be “copy and paste” code, and I don’t want any tags at the end.

said on January 31st, 2009 at 23:52 · Permalink · Reply

Ok, I see the problem. In current version you should add opening tag at the beginning of the code. I will try to figure out this limitation in future releases. Thank you for your feedback!

said on February 1st, 2009 at 12:29 · Permalink · Reply

Hey Robert,

Your suggestion makes sense, will take a look at this problem in nearest release.

Kevin
said on February 3rd, 2009 at 20:54 · Permalink · Reply

Hi,

I seem to be having trouble, nothing shows up – the html code is there (view source) but there is nothing being shown. Just a grey bar… any ideas?

Kevin

said on February 3rd, 2009 at 22:44 · Permalink · Reply

Hey Kevin,

Looks like a link to your source was stripped out. Could you re-post it?

said on February 11th, 2009 at 17:18 · Permalink · Reply

Thanks Dmytro for the nice plugin.

Is there a way to change the font family?

I have tried changing the font-family property in the .codecolorer-container * selector, but it seems that the default font-family (Monaco, Lucida Console, monospace) is applied automatically and directly to the codecolorer div. The result is that some of the code (anything outside a span) is displayed using the default font-family, and the rest is displayed using the one I want.

Maybe there is a better way to do it, but I can’t figure it out.

said on February 16th, 2009 at 12:00 · Permalink · Reply

Funktiu addContainer bila bi lutshe wot tak (potomutshto u menja Problememi s CSS autowidth):

1
2
3
4
5
6
7
8
9
10
11
12
13
function addContainer($html, $options, $num_lines) {
    $style = 'style="overflow:auto;white-space:nowrap';
        if( $options['width'] > 0 ) {
            $style .= ';width:' . $options['width'] . 'px';
        }
    if($num_lines > $options['lines'] && $options['lines'] > 0) {
      $style .= ';height:' . $options['height'] . 'px';
    }
    $style .= '"';

    $result = '<div class="codecolorer-container ' . $options['lang'] . ' ' . $options['theme'] . '" ' . $style . '>' . $html . '</div>';
    return $result;
  }
said on February 22nd, 2009 at 03:47 · Permalink · Reply

Hi Dmytro,

I like CodeColorer very much…a big up for your work. Today I implemented a nifty view toggler utilizing JQuery. Take a look at http://wordpress.org/support/topic/246260?replies=1 where everything further can found. Maybe a potential feature in one of the future releases?

Best regards from germany,

:peter

Andrew
said on March 4th, 2009 at 15:37 · Permalink · Reply

How would I reduce the font size for the entire code block including line numbers. I’ve tried per class customization (as above), but that seems to leave some keywords/classes untouched or the code isn’t alligned with the line numbers.
Is there a master css class or set that will include everything?

said on May 20th, 2010 at 22:39 · Permalink · Reply

You could try this method to change the overall font size – try changing the codecolorer-container section of the codecolorer.css to read as below, for a 10px size, for example:

1
.codecolorer, .codecolorer *, .codecolorer-container, .codecolorer-container * { font: 10px Monaco, Lucida Console, monospace }

By the way, thanks very very much Dmytro for the excellent plugin

ChaosNo1
said on March 10th, 2009 at 12:12 · Permalink · Reply

Hi,

I really like your plugin, but i need it to get working within the simple:press forum (http://simplepressforum.com) because i would give visitors the opportunity to post colored code.

How can i do this?
Thank you!

said on March 13th, 2009 at 20:34 · Permalink · Reply

Great little plug-in, miles better than any of the other code highlighters I’ve experimented with.

One thing though, for some reason it wouldn’t pick up any of the CSS styling until I copied the codecolorer.css file to my theme’s directory and put in a link in my header.php to it.

said on March 17th, 2009 at 19:04 · Permalink · Reply

Привет. Ставлю твой плагин, активирую и белая страница, делю плагин из папки все гуд, что не так? вордпресс 2.7.1 русский.

More comments: 1 2 3 4 5

Post a comment

You can use simple HTML-formatting tags (like <a>, <strong>, <em>, <ul>, <blockquote>, and other). To format your code sample use [cc lang="php"]$a = "hello";[/cc] (allowed languages are ruby, php, yaml, html, csharp, javascript). Also you can use [cc][/cc] block and its syntax would not be highlighted.

Submit Comment