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:
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 size calculating (short code would have short block, for long one block height would be fixed and scrollbar would appear)
- code block style customization on Site Admin
- 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.
- If you have not used CodeColorer early, rename wp-content/plugins/codecolorer/codecolorer.css.in to wp-content/plugins/codecolorer/codecolorer.css.
- 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.
- no_links (boolean) — when false keywords will be represented as links to manual.
- lines (integer) — how many lines would be block height without scroll.
- line_height (integer) — line height in pixels to calculate block size.
All of these parameters could be configured via the CodeColorer options page.
Supported languages
Here is list of supported by CodeColorer languages: 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.
Requirements
Plugin works with Wordpress 1.5 and 2.0/2.1 as well. But I recommend you to update your Wordpress to version 2.1 because it has many nice features.
Download
The latest version of “CodeColorer” is 0.6.0, and it can be downloaded here:
version0.6.0DownloadCodeColorer 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:
.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. I have enabled plugin in Site Admin, but my code samples are not highlighted.
A. You forgot to rename codecolorer.css.in to codecolorer.css. See step 2.
Q. I see < 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.
Changelog
- 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.
Русский
English
Есть ещё и отечественный http://softwaremaniacs.org/soft/highlight/
Ага, но он принципиально отличается тем, что реализован на JavaScript и раскрашивает синтаксис на клиенте. Хотя признаю, решение красивое
Несколько неудобным показалось то, что само “окошко” фиксированной высоты. я о тех случаях когда надо написать буквально пару строчек кода.
Можно было бы реализовать через min-height(expression для ИЕ) + overflow:hidden…немного гармонии так сказать
Хм… для пары строчек высота блока не фиксируется. Вот пример:
echo $a . ' world';
Фиксируется только для блоков кода, высота которых больше заданной в настройках.
Упс,прошу прощения. Зачит, трабл с плагином где-то у меня.
[...] 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. [...]
[...] CodeColorer — Плагин на библиотеке GeSHi (Generic Syntax Highlighter), поддерживающей несметное количество языков (71, если быть точным). Плагин прост в установке и настройке. Вот пример работы этого плагина: [...]
Отличный плагин! Большое спасибо!
Установил. Запостил статью с блоками:
и
Вместо этого текста при просмотре сайта отображается:
::CODECOLORER_BLOCK_1::
::CODECOLORER_BLOCK_2::
В чем дело?
А какая у вас версия плагина и вордпресса? И используете ли вы визуальный редактор?
Стоял Wordpress 2.1.0 Русская версия с сайта maxsite.org
Плагин качал с Вас вчера.
Но уже там появилась 2.2.0 - с ней все ок.
Ну а с 2.1.0. разберитесь.
Да и еще. Для подсветки синтаксиса конфигурационных файлов (apache, mysql, proftpd), чему лучше приравнивать параметр lang ?
Еще замечание:
при вставке кода между тегами
[cc][/cc]
треугольных скобок они некорректно отображается
Mad Chicken: Большое спасибо за отзывы. Отвечу по порядку.
2.1.0 посмотрю, неожиданно как-то в нем сломалось.
Для подсветки кофигурационных файлов Apache язык apache, для конфига MySQL (если не ошибаюсь) подойдет ini, для самих запросов — mysql (либо просто sql, но тогда некоторые специфические для мускула вещи не подсветятся). Вот насчет ProFTPD — не знаю, возможно apache подсветит и его, уж больно похожи.
Насчет угловых скобок — это второй вопрос в секции ЧаВО чуть выше на странице. Съедает их вордпресс во время постинга в визуальном редакторе. Советую на время вставки примеров кода переключаться в редактор HTML (или вообще не использовать визуальный редактор ибо он от лукавого, постоянно лепит непонятные теги, причем не к месту).
Еще раз спасибо.
Мне кажется что проблему с угловыми скобками можно решить в самом плагине, например производить замену < на нужный символ. К тому же угловые скобки часто встречаются в конфигурационных файлах апача, Mysql итд. Ведь даже если в 1й раз переключишся в режим редактирования кода html, то при следующем редактировании статьи - оптять косяки вылезут.
Имхо можно решить проблему.
Я над этим работаю. Просто до этого времени основной задачей было исправить проблемы с XHTML и проблемами в комментариях. Сейчас образовалось немного времени на исправление этой багофичи вордпресса.
Подскажите, пожалуйста, как выделить код прямо в строке, без переноса, так, как у вас сделано на сером фоне с пунктиром?
У меня это сделано без CodeColorer, просто тег <tt>code</tt>, и в стилях поставил фон этому тегу. А за мысль спасибо, надо добавить в CodeColorer.
Ясненько.
Спасибо за этот плагин! Очень удобная штука.
Дмитрий, еще такой вопрос.
Если код состоит всего из одной строки и он меньше ширины страницы, т.е. не появляется горизонтальный скролл, то под этой строкой появляется отступ, который “забронирован” для скролла.
Не очень красиво это выглядит. Можно как-то исправить?
I’m also getting ::CODECOLORER_BLOCK_1::. Using Wordpress 2.1 without the visual editor. Could you translate your response to Mad Chicken? Thanks!
[...] CodeColorer color your programming posts [...]
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?
[...] CodeColorer [...]
[...] Visit [...]
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
echo $awesome . "rocks!!";
[...] Plugin - CodeColorer http://kpumuk.info/projects/wordpress-plugins/codecolorer [...]
[...] Отказался от плагина colorer в пользу Highlight. Оба плагина занимаются подсветкой [...]
Here my test :
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;
}
[...] Я использую Сагалаевский highlight.js. Есть еще CodeColorer от kpumuk’а и, думаю, еще куча разных плагинов в этой [...]
[...] 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). [...]
Спасибо, очень удобный плагин, а то <code> как-то не очень удобен для вставки кода.
P.S. OpenID(Oher OpenID) не работает - ругается на curl_init, проверь…
Exist a client side (javascript) version of this plugin???
[...] 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ş [...]
Спасибо огромное за плагин!
Всё отлично, но поддержу Mad Chicken в его просьбе решить проблему с угловыми скобками. Посчу много шел скриптов - а там угловые скобки чуть не в каждой строчке. Переправлять каждый раз когда вносишь изменение в пост утомляет.
Ещё раз спасибо за плагин! )
Thanks for this one! Installed… works like charm.
Спасибо за хороший плагин. Но у меня с ним тоже возникла проблема. При написании сообщения всё нормально сохраняется и выглядит в блоге. Но когда я решаю отредактировать написанный пост - то вместо нормального кода в редакторе вордпресса я вижу уже не то, что надо (например, если у меня был в коде тэг , то в редакторе его нет, просто переход на новую строку). И при повторном сохранении код уже портится. Что делать?
Тэг “br” я имел в виду, вордпресс и тут вырезал его из коммента.
[...] 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ş [...]
[...] codecolorer благин с более обширным спектором возможностей: нумерация строк автоматическая вставка ссылок на документацию вычисление размера блока кода (короткий код будет заключен в маленький блок, для более длинного высота блока будет зафиксирована, и появятся полосы прокрутки) настройка стиля блока кода в Site Admin (Панель управления) настройка подсветки синтаксиса в файле CSS подсветка кода в комментариях защита кода от искажения Wordpress’ом (например, двойные кавычки, длинные тире и т.п. будут выглядеть в точности так, как Вы их ввели) [...]
[...] 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 [...]
[...] 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 [...]
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:
Is it normal?
Hi Raphael,
Looks like you have enabled another syntax highlighting plugin that uses GeSHi framework too. You must disable it before using CodeColorer.
Hum, I will see.
Thanks!
после активации плагина вкладка “плагины” админки wordpress не открывается, сносишь плагин по FTP все сразу нормально. Странный баг какой-то
[...] CodeColorer [...]
у меня почему то при активации плагина выскакивает ошибка в коде с блогом
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/)
[...] плагином под названием CodeColorer вы можете ознакомится тут. Очень даже удобный. Его плюс, имхо, в том что он [...]
[...] 其實可以搭配另一個外掛,那就是 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 [...]
Большое спасибо, это действительно то что я искал, очень удобно и без лишнего гемора, особенно когда публикуешь фрагменты кода
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
$text = rtrim($text);
#line 215 $text = trim($text);
Yep, you can use
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
$text = str_replace(”\\\”", “\”", $text);
# $text = str_replace(array(”\\\”", ‘\\\”), array (”\”", ‘\”), $text);
[...] Спасибо Dimox‘у за линк на клевый плагин для подсветки и форматирования кода в вордпрессе. [...]
[...] один плагин WordPress для подсветки синтаксиса — CodeColorer. Как и многие другие плагины (напрмер, WP CodeBox Эрика [...]
[...] jolies couleurs plus haut, c’est CodeColorer. Neat [...]
[...] que nada estaba utilizando el plugin de codecolorer hay que buscar el archivo codecolorer.php y modificar algunas [...]
[...] | Author: Dmytro Shteflyuk Coloring: #8 of 8 Ease of Install/Use: #8 of 8 Line Numbers: Optional PRE or CODE: CODE or [...]
[...] CodeColorer обладает также рядом дополнительных интересных свойств, например, нумерацией строк, настройкой подсветки синтаксиса, подсветкой кода в комментариях и т.п. Модуль имеет достаточно широкий спектр настроек и большой список поддерживаемых языков. Единственное, что заставляет задуматься, это требования к версии wordpress - 2.1. Поэтому гарантии безотказной работы в более старших версиях нет. Подробнее о плагине на русском языке можете почитать в этом обзоре. [...]
I think I found 2 bugs.
1. If code snippets has only one line, his height is to small to display code.
2. If there are some tabs in code I must to use parameter ‘tab_size’. Is there no default value?
Upsss. Here one line snippet looks properly. Why?
[...] 5) CodeColorer [...]
[...] CodeColorer обладает также рядом дополнительных интересных свойств, например, нумерацией строк, настройкой подсветки синтаксиса, подсветкой кода в комментариях и т.п. Модуль имеет достаточно широкий спектр настроек и большой список поддерживаемых языков. Единственное, что заставляет задуматься, это требования к версии wordpress - 2.1. Поэтому гарантии безотказной работы в более старших версиях нет. Подробнее о плагине на русском языке можете почитать в этом обзоре. [...]
[...] Для подсветки синтаксиса установил плагин для WordPress - CodeColorer. Плагин поддерживает кучу языков: actionscript, ada, apache, [...]
[...] мы пользовались плагином CodeColorer : отличный плагин на основе GeSHi для подсветки исходных [...]
[...] 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 [...]
[...] 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/ [...]