CodeColorer

Mar 31
2007 22:54 · Русский (43,856 views)

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

  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

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

  • 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
  • syntax highlighting of the code in comments
  • code protect from mangling by Wordpress (for example, quotes, double-dashes, etc would look just right as you entered)

Installation

  • Download and unpack plugin files to wp-content/plugins/codecolorer directory.
  • Enable “CodeColorer” plugin on your Plugins page in Site Admin.
  • Go to the Options/CodeColorer page in Site Admin and change plugin’s options as you wish.
  • 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 codecolorer block, but without syntax highlighting). The list of available languages you could find below.
  • 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</cc> syntax. Starting from version 0.6.0 you could specify additional CodeColorer options inside [cc] tag: [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, number 1 or 0.

Possible parameters:

  • lang (string) — source language.
  • tab_size (integer) — how many spaces would represent TAB symbol.
  • line_numbers (boolean) — when true line numbers will be added.
  • first_line (integer) — a number of the first line in the block.
  • no_links (boolean) — when false keywords will be represented as links to manual.
  • lines (integer) — how many lines would be block height without scroll; could be set to -1 to remove vertical scrollbar.
  • width (integer) — block width
  • height (integer) — height in pixels; used when lines number is greater then “lines” value.
  • theme (string) — color theme (default, blackboard, dawn, mac-classic, twitlight, vibrant).
  • no_cc (boolean) — when true the syntax in code block will not be highlighted, code will be rendered inside <code></code> tag.

All 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, blitzbasic, bnf, boo, c, c_mac, caddcl, cadlisp, cfdg, cfm, cil, cobol, cpp-qt, cpp, csharp, css-gen.cfg, css, d, delphi, diff, div, dos, dot, eiffel, email, fortran, freebasic, genero, gettext, glsl, gml, gnuplot, groovy, haskell, hq9plus, html4strict, idl, ini, inno, intercal, io, java, java5, javascript, kixtart, klonec, klonecpp, latex, lisp, lolcode, lotusformulas, lotusscript, lscript, lua, m68k, make, matlab, mirc, mpasm, mxml, mysql, nsis, objc, ocaml-brief, ocaml, oobas, oracle11, oracle8, pascal, per, perl, php-brief, php, pic16, pixelbender, plsql, povray, powershell, progress, prolog, providex, python, qbasic, rails, 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, winbatch, xml, xorg_conf, xpp, yaml, z80.

Requirements

Plugin works with Wordpress 1.5 — 2.7 as well. But I recommend you to update your Wordpress to latest version (2.7 currently), because it has many nice features.

Download

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

version0.7.3DownloadCodeColorer Plugin

If you have any propositions, want to send feedback or found bugs, please post comments. It’s very important for me!

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. Usually you would use only following CSS classes:

  • kw1, kw2, kw3 — keywords
  • co1, co2, coMULTI — comments
  • es0 — escaped chars
  • br0 — brackets
  • st0 — strings
  • nu0 — numbers
  • me0 — methods

To change colors for specific language copy default values and add language name with a period before it. For example, in this blog I’m using following color scheme for PHP:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.php .codecolorer .kw1 { color: #FF6600; font-weight: bolder; }
.php .codecolorer .kw2 { color: #339999; }
.php .codecolorer .kw3 { color: #FF6600; }
.php .codecolorer .kw4 { color: #DDE93D; }
.php .codecolorer .kw5 { color: #999966; }
.php .codecolorer .st0 { color: #66FF00; }
.php .codecolorer .es0 { color: #42A500; }
.php .codecolorer .br0 { color: Olive; }
.php .codecolorer .nu0 { color: #CCFF33; font-weight: bolder; }
.php .codecolorer .re0 { color: #339999; }
.php .codecolorer .re1 { color: #FFCC00; }
.php .codecolorer .re3 * { color: #FFFFFF; }
.php .codecolorer .re4, .php .codecolorer .re4 * { color: #64A2FF; }
.php .codecolorer .co1, .php .codecolorer .co2, .php .codecolorer .coMULTI { color: #9933CC; }

Also you could change width of the code block in the top of CSS file (there are different values for different situations, for example when you code is places under <blockquote>).

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 are should not use the visual editor when writing 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 codecolorer folder and unpack an archive with plugin again (thanks to Anatoliy ‘TLK’ Kolesnick).

Changelog

  • v0.7.3 (Jan 27, 2009)
    • Fixed problem with XHTML validation when line numbers are on (thanks to dreame4).
    • Added first_line option to code blocks.
    • Added no_cc option to disable CodeColorer for particular <code> blocks.
  • v0.7.2 (Dec 30, 2008)
    • Fixed color scheme for XML language.
    • Added custom CSS styles block to the options page.
    • Removed codecolorer.css.in file as deprecated.
    • Fixed bug wich code block paddings when line numbers are disabled.
  • v0.7.0 (Dec 29, 2008)
    • Added predefined color themes (Slush & Poppies, Blackboard, Dawn, Mac Classic, Twitlight, Vibrant Ink).
    • Added block width and height options, removed line height.
    • Fixed bug with plain text formatting.
    • Added ability to remove vertical scrollbar.
    • Line numbers will be rendered into the table, so they will not be copied to clipboard along with code.
    • Options page layout updated to Wordpress 2.7 look&feel.
    • GeSHi updated to version 1.0.8.2.
  • v0.6.0 (May 12, 2007)
    • Added ability to configure tab size.
    • Fixed problems with invalid XHTML code after highlighting.
    • Fixed bug when code sample started in the same with text.
    • Now it’s possible to configure specific code block.
    • Great code refactoring.
  • v0.5.1 (Apr 1, 2007)
    • GeSHi updated to version 1.0.7.19.
  • v0.5.0 (Mar 31, 2007)
    • Added ability to disable links to documentation on the CodeColorer options page.
    • GeSHi updated to version 1.0.7.18.
  • v0.4.0 (Mar 26, 2007)
    • Now you could insert code blocks in the comments.
    • It’s possible to use single quotes ([cc lang='php'][/cc]) now.
  • v0.3.0 (Dec 11, 2006)
    • Fixed bug with double quotes mangling.
    • Fixed problems with code block height calculation and scrollbars.
  • v0.2.0 (Nov 6, 2006)
    • CodeColorer options page implemented.
  • v0.1.0 (Nov 1, 2006)
    • Initial plugin implementation: syntax highlighting, options in the plugin file.

Other plugins

Full list of plugins I have implemented is available here.

121 Responses to this entry

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

said on 2007-04-01 at 7.32 pm

Есть ещё и отечественный http://softwaremaniacs.org/soft/highlight/

said on 2007-04-01 at 11.34 pm

Ага, но он принципиально отличается тем, что реализован на JavaScript и раскрашивает синтаксис на клиенте. Хотя признаю, решение красивое :-)

said on 2007-04-10 at 3.11 am

Несколько неудобным показалось то, что само “окошко” фиксированной высоты. я о тех случаях когда надо написать буквально пару строчек кода.
Можно было бы реализовать через min-height(expression для ИЕ) + overflow:hidden…немного гармонии так сказать ;)

said on 2007-04-10 at 9.27 am

Хм… для пары строчек высота блока не фиксируется. Вот пример:

1
2
$a = 'Hello';
echo $a . ' world';

Фиксируется только для блоков кода, высота которых больше заданной в настройках.

said on 2007-04-10 at 10.39 am

Упс,прошу прощения. Зачит, трабл с плагином где-то у меня.

said on 2007-05-01 at 5.44 pm

[...] Já no meu primeiro post tive essa dificuldade, tudo bem.. tem a tag <pre> ou até mesmo o CODE do WP, mas fala sério né.. sem nenhuma classe! Então navegando por ae, achei um plugin excelente que se chama CodeColorer. [...]

said on 2007-05-08 at 8.45 am

[...] CodeColorer — Плагин на библиотеке GeSHi (Generic Syntax Highlighter), поддерживающей несметное количество языков (71, если быть точным). Плагин прост в установке и настройке. Вот пример работы этого плагина: [...]

said on 2007-05-08 at 11.09 am

Отличный плагин! Большое спасибо!

said on 2007-05-20 at 11.59 am

Установил. Запостил статью с блоками:

1
&#91;cc lang=&quot;bash&quot;]blablabla&#91;/cc]

и

1
&#91;cc lang=&quot;php&quot;]blablabla&#91;/cc]

Вместо этого текста при просмотре сайта отображается:

::CODECOLORER_BLOCK_1::

::CODECOLORER_BLOCK_2::

В чем дело?

said on 2007-05-20 at 1.09 pm

А какая у вас версия плагина и вордпресса? И используете ли вы визуальный редактор?

said on 2007-05-21 at 12.57 am

Стоял Wordpress 2.1.0 Русская версия с сайта maxsite.org
Плагин качал с Вас вчера.

Но уже там появилась 2.2.0 - с ней все ок.

Ну а с 2.1.0. разберитесь.

said on 2007-05-21 at 12.59 am

Да и еще. Для подсветки синтаксиса конфигурационных файлов (apache, mysql, proftpd), чему лучше приравнивать параметр lang ?

said on 2007-05-21 at 1.01 am

Еще замечание:

при вставке кода между тегами

[cc][/cc]

треугольных скобок они некорректно отображается :-(

said on 2007-05-21 at 1.14 am

Mad Chicken: Большое спасибо за отзывы. Отвечу по порядку.

2.1.0 посмотрю, неожиданно как-то в нем сломалось.

Для подсветки кофигурационных файлов Apache язык apache, для конфига MySQL (если не ошибаюсь) подойдет ini, для самих запросов — mysql (либо просто sql, но тогда некоторые специфические для мускула вещи не подсветятся). Вот насчет ProFTPD — не знаю, возможно apache подсветит и его, уж больно похожи.

Насчет угловых скобок — это второй вопрос в секции ЧаВО чуть выше на странице. Съедает их вордпресс во время постинга в визуальном редакторе. Советую на время вставки примеров кода переключаться в редактор HTML (или вообще не использовать визуальный редактор ибо он от лукавого, постоянно лепит непонятные теги, причем не к месту).

Еще раз спасибо.

said on 2007-05-21 at 4.51 pm

Мне кажется что проблему с угловыми скобками можно решить в самом плагине, например производить замену < на нужный символ. К тому же угловые скобки часто встречаются в конфигурационных файлах апача, Mysql итд. Ведь даже если в 1й раз переключишся в режим редактирования кода html, то при следующем редактировании статьи - оптять косяки вылезут.

Имхо можно решить проблему.

said on 2007-05-21 at 4.56 pm

Я над этим работаю. Просто до этого времени основной задачей было исправить проблемы с XHTML и проблемами в комментариях. Сейчас образовалось немного времени на исправление этой багофичи вордпресса.

Dimox @
said on 2007-05-27 at 12.27 pm

Подскажите, пожалуйста, как выделить код прямо в строке, без переноса, так, как у вас сделано на сером фоне с пунктиром?

said on 2007-05-27 at 12.57 pm

У меня это сделано без CodeColorer, просто тег <tt>code</tt>, и в стилях поставил фон этому тегу. А за мысль спасибо, надо добавить в CodeColorer.

Dimox @
said on 2007-05-27 at 5.02 pm

Ясненько.

Спасибо за этот плагин! Очень удобная штука.

Dimox @
said on 2007-06-03 at 3.07 pm

Дмитрий, еще такой вопрос.

Если код состоит всего из одной строки и он меньше ширины страницы, т.е. не появляется горизонтальный скролл, то под этой строкой появляется отступ, который “забронирован” для скролла.

Не очень красиво это выглядит. Можно как-то исправить?

Adam
said on 2007-06-22 at 6.05 am

I’m also getting ::CODECOLORER_BLOCK_1::. Using Wordpress 2.1 without the visual editor. Could you translate your response to Mad Chicken? Thanks!

said on 2007-06-27 at 11.13 am

[...] CodeColorer color your programming posts [...]

said on 2007-06-30 at 6.12 am

I am having a few problems with CodeColorer. First off, it seems that no matter what or where I set the tab_length to it equals 4. Also, if I post some code, and then go to edit it later, all of the tabs disappear. Is there any way that the CodeColorer could automatically insert tabs where it makes sense?

said on 2007-07-06 at 3.00 am

[...] CodeColorer [...]

said on 2007-07-11 at 9.15 am

[...] Visit [...]

Bruno @
said on 2007-08-02 at 12.35 am

Hi, I have a little (but horrible) problem with this plugin in my theme.

I use Freshy theme (http://www.jide.fr/) and line numbers appears in wrong mode. Like this:

1
First line of code
2
Second line of code
….
How can I correct this?

Thanks

Jan
said on 2007-08-29 at 7.51 am
1
2
3
$awesome = "Dmytro";

echo $awesome . "rocks!!";
said on 2007-09-18 at 1.14 am

[...] Отказался от плагина colorer в пользу Highlight. Оба плагина занимаются подсветкой [...]

Cédric
said on 2007-10-07 at 4.29 pm

Here my test :

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
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
var myLoader:Loader = new Loader();
addChild(myLoader);
myLoader.load(new URLRequest('zoom_4-5.jpg'));
myLoader.contentLoaderInfo.addEventListener(Event.INIT, initListener);

function initListener(e:Event):void {
    Bitmap(myLoader.content).smoothing = true;
    stage.addEventListener(Event.RESIZE, resizeListener);
}

function resizeListener(e:Event):void {
    var scale_x = stage.stageWidth/1219;
    var scale_y = stage.stageHeight/609;
    var scale_global:Number;
    if(scale_x > scale_y) {
        scale_global = scale_y;
    }
    else {
        scale_global = scale_x;
    }
    myLoader.scaleX = scale_global;
    myLoader.scaleY = scale_global;

}
said on 2007-11-14 at 6.39 am
1
<?xml version="1.0" encoding="utf-8" ?>
said on 2007-12-07 at 11.50 pm

[...] Я использую Сагалаевский highlight.js. Есть еще CodeColorer от kpumuk’а и, думаю, еще куча разных плагинов в этой [...]

said on 2008-01-10 at 2.28 am

[...] I am posting this script at such an early stage because I wanted to test a Highlight Syntax plug-in for wordpress. Thanks to CodeColorer (http://kpumuk.info/projects/wordpress-plugins/codecolorer). [...]

Zedr0n @
said on 2008-01-17 at 1.32 pm

Спасибо, очень удобный плагин, а то <code> как-то не очень удобен для вставки кода.

P.S. OpenID(Oher OpenID) не работает - ругается на curl_init, проверь…

Rodrigo
said on 2008-01-18 at 8.27 pm

Exist a client side (javascript) version of this plugin???

said on 2008-01-25 at 11.20 pm

[...] sahip kod renklendirici arayan arkadaşlar buyrun karşınızda CodeColorer. Bu yazının orjinaline buradan ulaşabilirsiniz. Ben sadece yazıyı dilim döndüğünce affınıza sığınarak çevirmiş [...]

magik @
said on 2008-01-27 at 5.38 pm

Спасибо огромное за плагин!
Всё отлично, но поддержу Mad Chicken в его просьбе решить проблему с угловыми скобками. Посчу много шел скриптов - а там угловые скобки чуть не в каждой строчке. Переправлять каждый раз когда вносишь изменение в пост утомляет.

Ещё раз спасибо за плагин! )

said on 2008-01-29 at 12.00 pm

Thanks for this one! Installed… works like charm.

said on 2008-02-04 at 10.22 pm

Спасибо за хороший плагин. Но у меня с ним тоже возникла проблема. При написании сообщения всё нормально сохраняется и выглядит в блоге. Но когда я решаю отредактировать написанный пост - то вместо нормального кода в редакторе вордпресса я вижу уже не то, что надо (например, если у меня был в коде тэг , то в редакторе его нет, просто переход на новую строку). И при повторном сохранении код уже портится. Что делать?

said on 2008-02-04 at 10.24 pm

Тэг “br” я имел в виду, вордпресс и тут вырезал его из коммента. :)

said on 2008-02-08 at 12.25 am

[...] sahip kod renklendirici arayan arkadaşlar buyrun karşınızda CodeColorer. Bu yazının orjinaline buradan ulaşabilirsiniz. Ben sadece yazıyı dilim döndüğünce affınıza sığınarak çevirmiş [...]

said on 2008-02-09 at 3.07 pm

[...] codecolorer благин с более обширным спектором возможностей: нумерация строк автоматическая вставка ссылок на документацию вычисление размера блока кода (короткий код будет заключен в маленький блок, для более длинного высота блока будет зафиксирована, и появятся полосы прокрутки) настройка стиля блока кода в Site Admin (Панель управления) настройка подсветки синтаксиса в файле CSS подсветка кода в комментариях защита кода от искажения Wordpress’ом (например, двойные кавычки, длинные тире и т.п. будут выглядеть в точности так, как Вы их ввели) [...]

said on 2008-03-03 at 6.56 pm

[...] beberapa macam syntax hiliter yang saya cari di WordPress Plugins saya tertarik dengan codecolorer, karena sangat simpel dan mudah digunakan. Awalnya saya agak jengkel dengan plugin ini. Sebab kode [...]

said on 2008-03-14 at 6.02 am

[...] I have had poor results with Flash Text Formatter I no longer use it.  Rather I suggest  CodeColorer.  Flash Text Formatter suffers from a lack of maintenance and good web site [...]

said on 2008-03-17 at 3.47 pm

Hi, I’ve been tested this script and it show me an line with error when I activated on Plugin’s Area (WordPress 2.3.3).

Error:

1
Fatal error: Cannot redeclare class GeSHi in /home/accountname/public_html/home/wp-content/plugins/codecolorer/lib/geshi.php on line 158

Is it normal?

said on 2008-03-17 at 4.00 pm

Hi Raphael,
Looks like you have enabled another syntax highlighting plugin that uses GeSHi framework too. You must disable it before using CodeColorer.

said on 2008-03-17 at 6.21 pm

Hum, I will see.

Thanks! :)

said on 2008-03-18 at 2.14 pm

после активации плагина вкладка “плагины” админки wordpress не открывается, сносишь плагин по FTP все сразу нормально. Странный баг какой-то

said on 2008-03-21 at 12.29 am

[...] CodeColorer [...]

sergey
said on 2008-04-09 at 10.32 am

у меня почему то при активации плагина выскакивает ошибка в коде с блогом
GeSHi Error: GeSHi could not find the language lang (using path /home/domain/domains/my_domain.com/public_html/wp-content/plugins/codecolorer/lib/geshi/)

said on 2008-04-18 at 1.12 am

[...] плагином под названием CodeColorer вы можете ознакомится тут. Очень даже удобный. Его плюс, имхо, в том что он [...]

said on 2008-04-24 at 4.49 pm

[...] 其實可以搭配另一個外掛,那就是 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 2008-06-13 at 7.31 am

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

said on 2008-06-17 at 3.33 am

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 2008-06-18 at 9.10 am
1
echo('Can I use \[/cc\] in here?');
said on 2008-06-18 at 9.26 am

Yep, you can use :-)

said on 2008-06-18 at 12.12 pm

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 2008-06-23 at 12.23 pm

[...] Спасибо Dimox‘у за линк на клевый плагин для подсветки и форматирования кода в вордпрессе. [...]

said on 2008-07-05 at 11.50 pm

[...] один плагин WordPress для подсветки синтаксиса — CodeColorer. Как и многие другие плагины (напрмер, WP CodeBox Эрика [...]

said on 2008-07-08 at 6.42 pm

[...] jolies couleurs plus haut, c’est CodeColorer. Neat [...]

said on 2008-07-17 at 1.23 am

[...] que nada estaba utilizando el plugin de codecolorer hay que buscar el archivo codecolorer.php y modificar algunas [...]

said on 2008-07-21 at 3.26 am

[...] | Author: Dmytro Shteflyuk Coloring: #8 of 8 Ease of Install/Use: #8 of 8 Line Numbers: Optional PRE or CODE: CODE or [...]

said on 2008-07-25 at 12.28 am

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

said on 2008-07-25 at 4.24 pm

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 2008-07-25 at 4.25 pm

Upsss. Here one line snippet looks properly. Why?

said on 2008-09-10 at 6.52 pm

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

said on 2008-09-15 at 8.32 pm

[...] Для подсветки синтаксиса установил плагин для WordPress -  CodeColorer. Плагин поддерживает кучу языков: actionscript, ada, apache, [...]

said on 2008-09-25 at 10.10 am

[...] мы пользовались плагином CodeColorer : отличный плагин на основе GeSHi для подсветки исходных [...]

said on 2008-09-30 at 4.51 pm

[...] opierając się na opisach i ocenach postanowiłam wypróbować wtyczkę CodeColorer którą stworzył Dmytro Shteflyuk. Oczywiście nie twierdzę, że jest ona najlepsza, ale z [...]

said on 2008-10-20 at 11.26 pm

[...] 2. CodeColorer Plugin works with Wordpress 1.5 and 2.0/2.1 as well. Recommended to update your Wordpress to version 2.1 because it has many nice features. http://kpumuk.info/projects/wordpress-plugins/codecolorer/ [...]

said on 2008-12-06 at 4.12 am

[...] CodeColorer [...]

said on 2008-12-31 at 4.33 am

test highligh

1
paq8 -8 Shrek_2_US_16x9/
said on 2008-12-31 at 9.38 am
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 2009-01-01 at 3.07 am

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 2009-01-04 at 1.17 am

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 2009-01-04 at 6.19 pm

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:)

said on 2009-01-05 at 7.20 am

very good !
Thanks!

kduks
said on 2009-01-07 at 8.14 am
1
2
3
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Button id="rang" />
</mx:Application>

Good
thx!

said on 2009-01-10 at 10.56 pm
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 2009-01-16 at 12.02 am

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 2009-01-18 at 1.40 am

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 2009-01-19 at 12.09 am

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

said on 2009-01-22 at 1.26 pm

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

said on 2009-01-22 at 1.49 pm

@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 2009-01-22 at 2.17 pm

Thank you again! Just committed a fix for this problem.

said on 2009-01-27 at 6.41 pm

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

1
<code no_cc="true">some code</code>
said on 2009-01-30 at 6.09 pm

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 2009-01-31 at 4.14 pm

Look at this page: http://wordpress.sundskard.dk/archives/119

The code is not highlighted correctly.

said on 2009-01-31 at 9.56 pm

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

said on 2009-01-31 at 10.30 pm

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 2009-01-31 at 11.52 pm

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 2009-02-01 at 12.29 pm

Hey Robert,

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

Kevin @
said on 2009-02-03 at 8.54 pm

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 2009-02-03 at 10.44 pm

Hey Kevin,

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

said on 2009-02-11 at 5.18 pm

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.

Wowka @
said on 2009-02-16 at 12.00 pm

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 2009-02-22 at 3.47 am

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 2009-03-04 at 3.37 pm

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?

ChaosNo1 @
said on 2009-03-10 at 12.12 pm

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 2009-03-13 at 8.34 pm

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 2009-03-17 at 7.04 pm

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

smao
said on 2009-03-29 at 12.53 pm
1
/*REALLY a good job. :) */
Serguei
said on 2009-03-31 at 12.33 am

I have as similar issue as Kevin, nothing shows up while the html source seems valid.
This is what I am trying to display:

1
2
3
def testFunction ():
    ''' This is a test function '''
    print "Testing ..."
Serguei
said on 2009-03-31 at 1.03 am

Could it be possible that my theme is somehow overwridding the css used for displaying the code?

Serguei
said on 2009-03-31 at 1.15 am

Tested with default themes and still a no go!

said on 2009-03-31 at 10.55 am

What are the chances that you can make the output visual retranslate the < and %gt; back into > and doesnt output translated, see this post:
http://frumph.webcomicplanet.com/code-snippets/wordpress/adding-multi-user-php-free-chat-into-wpmu/

Aa
said on 2009-04-06 at 7.03 pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
piper = Baby.new(:name => 'Piper',
                 :born => '2008-06-09 18:22:00 EDT',
                 :weight => {:lbs => 6, :oz => 8},
                 :length => {:inches => 21.25})

skoglunds.children << piper

piper.daily do |p|
  8.times do
    p.eat
    p.poop
    p.sleep
  end
end
said on 2009-04-08 at 6.36 am

У меня подсветка Java кода отображается некорректно после символа @ в коде. Посмотрим, как у вас.

1
2
3
4
5
6
class Test {
    @Override
    public String toString() {
         return "Test";
    }
}
Артем
said on 2009-04-27 at 4.44 pm

Добрый день.
Есть предложение насчет улучшения плагина.
Итак хотелось бы получить такой же функционал как и в этом плагине syntaxhighlighter-plus. Т. е. менюшки сверху и такуюже тему оформления defaut.
Насчет дополнения функционала можно просто скрестить 2 плагина - так получатся менюшки.
А как перенести тему defaut в CSS еще не знаю.

kenpem @
said on 2009-05-04 at 6.46 pm

Great plug-in, really useful. Can I add a vote for width to be specified in percentage? If I make it look just right on the PC, mobile browsers have heart attacks ;)

said on 2009-05-05 at 6.05 pm

In codecolorer.php I would change

1
2
3
function addCssStyle() {
        echo '<link rel="stylesheet" href="' . get_option('siteurl') . $this->pluginLocation . 'styles.php" type="text/css" />', "\n";
  }

to

1
2
3
4
5
6
function addCssStyle() {
        if (trim(get_option('codecolorer_css_style'))!='')
                echo '<link rel="stylesheet" href="' . get_option('siteurl') . $this->pluginLocation . 'styles.php" type="text/css" />', "\n";
        else
                echo '<link rel="stylesheet" href="' . get_option('siteurl') . $this->pluginLocation . 'codecolorer.css" type="text/css" />', "\n";    
  }

because that way, the STYLES.PHP is only called if its really necessary.

And if I were you I wouldn’t store the additional CSS in the options at all but in an additional CSS-files because your “styles.php” requires “wp-load.php” and this takes a long time to load. And this only happens because you need the getoption-function.

said on 2009-05-13 at 10.48 pm

Thank you very much for this beautyful plugin!

I’m getting it to work really fine in wordpress. With enthusiasm!

Some small observations:
Setting the tabsize to less than 4 in the options panel doesn’t seem to change it, it still shows “4″ after a submit change and reload.
Then I think the stules for xml in the default theme write:

.twitlight .xml .re1 { color: #008080; }
/* Constant */
.twitlight .xml .re0 { color: #0080A0; }
- the exact same as in the twitlight theme.

Then actionscript3 misses the ‘extend’ method. I’ve written a comment on the SELD BE blog about it.

Any chance the themes not used could be ommitted in the loaded documents? It seems like a lot of css to load, then to override..

But this is fun and your plugin is wonderful!

regards and thanks
Kamilla

s1n @
said on 2009-05-14 at 7.05 am

I’m using your plugin, and noticed that it only ever seems to work on my single post pages and not the index:

Here’s an example of the single page:

http://s1n.dyndns.org/index.php/2009/05/14/more-sub-confusion/

See my main index for an example where it’s not applying the style:

http://s1n.dyndns.org

Any ideas?

said on 2009-05-20 at 10.23 am

hi, I’m simaopig.

I want know how i can set the keyword link open in new tab or new window?

Hope your mail. Thank you!

said on 2009-05-30 at 2.24 pm
1
2
3
4
5
6
7
8
#import <UIKit/UIKit.h>

int main(int argc, char *argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, nil);
    [pool release];
    return retVal;
}
said on 2009-05-30 at 2.25 pm
1
2
3
4
5
6
7
8
#import <UIKit/UIKit.h>

int main(int argc, char *argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, nil);
    [pool release];
    return retVal;
}
said on 2009-05-30 at 2.26 pm
1
2
3
4
5
6
7
8
#import <UIKit/UIKit.h>

int main(int argc, char *argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, nil);
    [pool release];
    return retVal;
}
said on 2009-05-30 at 2.27 pm
1
2
3
4
5
6
7
8
#import <UIKit/UIKit.h>

int main(int argc, char *argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, nil);
    [pool release];
    return retVal;
}
Brett Z @
said on 2009-05-31 at 4.29 am

Hi there,

Was wondering if you could just make one small fix to your very useful plugin–

Change line 135 of codecolorer.php to:

1
$table = '<table class="line-numbering"><tbody><tr><td class="line-numbers"><div>';

Then add to codecolorer.css:

1
.line-numbering {border-collapse: collapse; padding:0px;

Or something semantically named like “line-numbering”.

I’m a bit of a nut of separating formatting from structure, even if it is not 100% clear yet on whether HTML5 will remove the cellpadding and cellspacing attributes (since the spec is still in draft), I still think it’s a good practice to follow it.

And this is just an idea but, although there are no namespaces in CSS, I wonder whether using “:” or “.” in the class name might help ensure that there were no collisions when including another CSS library. Of course, that’d be more work, but just an idea. Maybe prefix the attributes with “cc:” or something?

Thank you!

Brett Z @
said on 2009-05-31 at 4.31 am

Sorry, I of course meant prefix the class attribute values, not the attribute (name).

Post a comment

You can use simple HTML-formatting tags (like <a>, <ul> and others). To format your code sample use <code lang="php">$a = "hello";</code> (allowed languages are ruby, php, yaml, html, csharp, javascript). Also you could use <code>$a = "hello";</code> and its syntax would not be highlighted. If you are not using <code> tag, replace < sign with &lt;.

Submit Comment