CodeColorer

· English (74,465 views)

CodeColorer – плагин, позволяющий вставлять куски кода в заметки, красиво их форматируя. Для начала хочу показать вам пример:

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

Плагин основан на библиотеке GeSHi, поддерживающей огромное количество языков. CodeColorer имеет множество приятных свойств:

  • подсветка синтаксиса в лентах RSS
  • подсветка синтаксиса строчного кода (inline)
  • подсветка кода в комментариях
  • автоматическая нумерация строк
  • автоматическая вставка ссылок на документацию
  • грамотное вычисление размера блока кода (короткий код будет заключен в маленький блок, для более длинного высота блока будет зафиксирована, и появятся полосы прокрутки)
  • Предустановленные цветовые схемы (Slush & Poppies, Blackboard, Dawn, Mac Classic, Twitlight, Vibrant Ink)
  • настройка подсветки синтаксиса в файле CSS
  • защита кода от искажения Wordpress’ом (например, двойные кавычки, длинные тире и т.п. будут выглядеть в точности так, как Вы их ввели)

Установка

  1. Загрузите и распакуйте файлы плагина в каталог wp-content/plugins/codecolorer.

  2. Включите плагин CodeColorer в Site Admin (Панель управления).

  3. Зайдите на страницу Options/CodeColorer (Настройки/CodeColorer) в Site Admin (Панель управления) и настройте его по своему вкусу.

  4. Используйте синтаксис [cc lang="lang"]код[/cc] или <code lang="lang">code</code> для вставки блока кода в заметку (вы можете опустить lang="lang", в этом случае код появится в блоке codecolorer, но без подсветки синтаксиса). Кроме того, можно использовать [cci lang="lang"]code[/cci] для форматирования строчных блоков кода (см. описание опции “inline”). Список поддерживаемых языков можно найти ниже.

  5. Наслаждайтесь!

Синтаксис

Для вставки примера кода в вашу статью (или комментарий) используйте синтаксис [cc lang="lang"]code[/cc] или <code lang="lang">code</code>. Начиная с версии 0.6.0 вы можете указать дополнительные параметры CodeColorer в теге [cc]:

1
[cc lang="php" tab_size="2" lines="40"]// какой-то код[/cc]
Примечание: Всегда используйте двойные или одинарные кавычки вокруг значений параметров. Булевые значения можно передавать как строку true или false, on или off, а также как число 1 или 0.

Короткие коды

Начиная с версии 0.8.6 CodeColorer позволяет использовать короткие коды для вставки блоков кода. В общем случае, короткий тег выглядит так: [ccMODE_LANG], где LANG — это ваш язык програмиирования, а MODE — один или несколько следующих режимов:

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

Маленькие буквы означают включено, большие – выключено. Примеры:

Код PHP с включенными ссылками и выключенными номерами строк:

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

Экранированный код HTML:

1
[ccie_html]<html>[/ccie_html]

Код на Ruby с переносом строк и размером табуляции 4:

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

Другие примеры можно найти на странице примеров использования CodeColorer. Полный список параметров представлен ниже.

Возможные праметры

  • lang (строка) – язык примера кода.
  • tab_size (число) – сколько пробелов использовать для представления символа табуляции.
  • line_numbers (булево) – когда true, будут добавлены номера строк.
  • first_line (число) – номер первой строки в блоке.
  • no_links (булево) – когда false, ключевые слова будут представлены в виде ссылок на руководство.
  • lines (число) – сколько строк в блоке отображаются без появления скроллбара; может равняться -1 – в этом случае вертикальной полосы прокрутки не будет вообще.
  • width (число или строка) – ширина блока кода.
  • height (число или строка) – высота блока кода в пикселях; используется, если код содержит больше, чем lines строк.
  • rss_width (число или строка) – ширина блока кода в RSS лентах.
  • theme (строка) – цветовая схема (default, blackboard, dawn, mac-classic, twitlight, vibrant).
  • inline ( булево ) – когда true, блок кода будет отображен в теге <code>. Используется для вставки однострочных кусков кода в обычный текст.
  • strict ( булево ) – когда true, будет включен “строгий” режим подсветки. По умолчанию CodeColorer пытается угадать, использовать этот режим или нет, а опция позволяет принудительно включить или выключить его, если предположение было сделано неверно.
  • nowrap (булево) – когда false, горизонтальная полоса прокрутки не будут отображаться. Вместо этого строка кода будет разбита на две на границе блока.
  • noborder (булево) – когда true, рамка вокруг блока кода не будет отображаться.
  • no_cc (булево) – когда true, синтаксис в блоке не будет подсвечиваться, код будет выведен внутри тега <code></code>.
  • class (строка) – дополнительные классы CSS для обрамляющего блок элемента HTML.

Вы можете использовать специальный тег [cci] вместо [cc], чтобы заставить код отображаться в строчном блоке: [cci lang="lang"]code[/cci]

Большую часть параметров можно сконфигурировать через страницу настроек CodeColorer.

Поддерживаемые языки

Вот список языков, поддерживаемых CodeColorer: 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.

Требования

Плагин работает с Wordpress 2.7.0 — 2.8.2. Эй, пользоваели WordPress 2.7.0, можете объяснить, почему вы используете эту старое глючное поделие? Используйте новое, как минимум оно выглядит лучше!

Загрузка

Последняя версия “CodeColorer” — 0.9.7, и она может быть загружена отсюда:

version0.9.7DownloadCodeColorer Plugin

Вы можете скачать более старые версии плагина с его домашней страницы на сайте WordPress.org (но действительно ли вам нужно это старье?).

Перевод

Спасибо вам, ребята, за перевод CodeColorer на другие языки. На данный момент доступны следующие локализации CodeColorer:

Хотите помочь мне с переводом? Это просто!

  1. Установите Poedit.

  2. Скачайте codecolorer.pot file.

  3. Нажмите File/New catalog from .pot file и выберете файл codecolorer.pop, который вы только что загрузили.

  4. Введите название проекта (что-то вроде CodeColorer 0.9.1), ваше имя и адрес email, выберите язык, на который хотите перевести, и нажмите OK.

  5. Введите имя файла вроде codecolorer-en_EN.po и нажмите Save.

  6. Переведите все строки одну за другой.

  7. Отправьте мне файл .po с переводом на адрес kpumuk@kpumuk.info. Не забудьте ссылку, которая будет добавлена на домашнюю страницу CodeColorer.

  8. Спасибо!

Чтобы исправить существующий перевод, просто откройте соответствующий файл .po из каталога codecolorer/languages в Poedit, и добавьте пропущенные или обновите существующие строки.

Настройка

Подсветка синтаксиса полностью настраивается: вы можете поменять цветовую схему как для всех языков сразу, так и для отдельного языка. Файл CSS плагина CodeColorer можно найти здесь: wp-content/plugins/codecolorer/codecolorer.css. Чтобы изменить цвета для всех языков, отредактируйте строки в секции Color scheme.

Существует простое отображение между классами тем для Textmate и CodeColorer:

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; }

Загляните в файл codecolorer.css, чтобы найти больше примеров.

Часто задаваемые вопросы

В. Как мне задать свои стили CSS для кода?
О. Вы можете изменить стили CSS на странице Options/CodeColorer (Настройки/CodeColorer) в Site Admin (Панель управления).

В. Я вижу &lt; вместо < (или другие сущности HTML вроде >, &, ") в коде.
О. Вы должны использовать [cc escaped="true"] или [cce] в визуальном редакторе для вставки кода в пост.

В. Код подсвечивается на сервере или на клиентском компьютере?
О. CodeColorer раскрашивает код на сервере, вы можете найти HTML подсвеченного кода в исходном коде страницы.

В. Генерируется ли валидный XHTML?
О. Да, результирующий XHTML полностью валидный.

В. Могут ли мои посетители вставлять примеры кода в комментариях?
О. Да, CodeColorer поддерживает подсветку кода в комментариях используя тот же синтаксис, что и в статьях блога.

В. Как я могу отключить подсветку синтаксиса для определенных блоков <code>?
О. Используйте опцию no_cc="true" для нужных блоков.

В. Я обновил плагин до последней версии и теперь постоянно получаю предупреждения:

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

О. Удалите все файлы из каталога codecolorer и распакуйте архив с плагином заново (спасибо Anatoliy ‘TLK’ Kolesnick).

В. Мне нравится этот плагин. Как я могу выразить признательность автору?
О. Просто проголосуйте за этот плагин на сайте WordPress.org. И спасибо вам!

Поддержка

Если у вас есть предложения, вы нашли ошибку, есть желание перевести CodeColorer на ваш язык, или просто хотите сказать “спасибо”,– не стесняйтесь связаться со мной. Обещаю, я отвечу на каждое сообщение.

Если вы хотите помочь в разработке, смотрите раздел Разработка ниже.

Разработка

Исходный код этого плагина доступен как в SVN, так и в Git:

Не бойтесь вносить изменения в код и присылать мне патчи. Обещаю, я применю каждый (естественно, если они полезны продукту). Отправляйте патчи, пожелания и информацию об ошибках: kpumuk@kpumuk.info. Кроме того, есть множество других способов связаться со мной.

Список изменений

  • 0.9.7 (19 декабря 2009)
    • Исправлена ошибка с атрибутом theme="geshi".
    • Добавлена возможность подсвечивать любой кусок кода из PHP.
    • Используется wp_enqueue_style вместо генерации простого HTML.
    • Исправлена ошибка с экранированными кусками кода, кода некоторые сущности не декодировались.
    • Добавлена совместимость с WordPress 2.9.
  • 0.9.6 (18 декабря 2009)
    • Добавлен перевод на французский (спасибо Valentin PRUGNAUD, fanta78, Sylvain Zabé и Whiler).
    • Добавлен перевод на бразильский португальский (спасибо Paulo César M. Jeveaux, Fabricio Bortoluzzi и Rodolfo Leão).
    • Добавлен перевод на шведский (спасибо LHLI).
    • Исправлены проблемы с валидацией XHTML на странице настроек CodeColorer (спасибо Brett Zamir).
    • Добавлен перевод на японский (спасибо Kuroneko Square).
    • Добавлен перевод на датский (спасибо Hans Klysner).
    • Добавлена тема GeSHi.
    • Добавлена возможность указывать дополнительные классы CSS для обрамляющего блок элемента HTML.
  • 0.9.5 (27 августа 2009)
    • Добавлен перевод на голландский (спасибо Martijn van Iersel).
    • Добавлен перевод на испанский (Аргентина) (спасибо Diego Sucaria).
    • Добавлен перевод на арабский (спасибо Amine Roukh).
    • Исправлена ошибка в сафари, возникающая когда у родительского тега выставлен CSS стиль text-align=justify.
  • 0.9.4 (24 августа 2009)
    • Версия увеличена до 0.9.4 (для WordPress.org).
  • 0.9.3 (20 августа 2009)
    • Добавлен quicktag (заменяет стандартную кнопку code).
    • Добавлен плагин TinyMCE plugin для вставки блоков кода (временно отключен).
    • Добавлен перевод на немецкий (спасибо Fabian Schulz and Michael Gutbier).
    • Добавлен перевод на испанский (спасибо Sergio Díaz).
    • Добавлен перевод на турецкий (спасибо Hasan Akgöz).
    • Добавлен перевод на польский (спасибо Andrzej Pindor).
    • Добавлен перевод на испанский (Колумбия) (спасибо Diego Alberto Bernal)
    • Добавлен перевод на иврит (спасибо Yaron Ofer).
    • Исправлена проблема с PHP 4 (спасибо Conan Chou, Алексей Таранец, Martijn van Iersel).

Полную историю изменений можно найти на странице История CodeColorer.

Другие плагины

Полный список плагинов, которые я написал, можно найти здесь.

192 Responses to this entry

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

said on 01.04.2007 at 23.34 · Permalink · Ответить

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

said on 10.04.2007 at 3.11 · Permalink · Ответить

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

said on 10.04.2007 at 9.27 · Permalink · Ответить

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

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

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

said on 10.04.2007 at 10.39 · Permalink · Ответить

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

said on 08.05.2007 at 8.45 · Permalink · Ответить

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

said on 20.05.2007 at 11.59 · Permalink · Ответить

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

1
[cc lang="bash"]blablabla[/cc]

и

1
[cc lang="php"]blablabla[/cc]

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

::CODECOLORER_BLOCK_1::

::CODECOLORER_BLOCK_2::

В чем дело?

said on 20.05.2007 at 13.09 · Permalink · Ответить

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

said on 21.05.2007 at 0.57 · Permalink · Ответить

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

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

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

said on 21.05.2007 at 0.59 · Permalink · Ответить

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

said on 21.05.2007 at 1.01 · Permalink · Ответить

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

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

[cc][/cc]

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

said on 21.05.2007 at 1.14 · Permalink · Ответить

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

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

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

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

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

said on 21.05.2007 at 16.51 · Permalink · Ответить

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

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

said on 21.05.2007 at 16.56 · Permalink · Ответить

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

said on 27.05.2007 at 12.27 · Permalink · Ответить

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

said on 27.05.2007 at 12.57 · Permalink · Ответить

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

said on 27.05.2007 at 17.02 · Permalink · Ответить

Ясненько.

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

said on 03.06.2007 at 15.07 · Permalink · Ответить

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

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

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

Adam
said on 22.06.2007 at 6.05 · Permalink · Ответить

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 30.06.2007 at 6.12 · Permalink · Ответить

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?

Bruno @
said on 02.08.2007 at 0.35 · Permalink · Ответить

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

Cédric
said on 07.10.2007 at 16.29 · Permalink · Ответить

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;

}
Zedr0n @
said on 17.01.2008 at 13.32 · Permalink · Ответить

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

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

magik @
said on 27.01.2008 at 17.38 · Permalink · Ответить

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

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

said on 04.02.2008 at 22.22 · Permalink · Ответить

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

said on 04.02.2008 at 22.24 · Permalink · Ответить

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

said on 09.02.2008 at 15.07 · Permalink · Ответить

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

said on 17.03.2008 at 15.47 · Permalink · Ответить

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 17.03.2008 at 16.00 · Permalink · Ответить

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 18.03.2008 at 14.14 · Permalink · Ответить

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

sergey
said on 09.04.2008 at 10.32 · Permalink · Ответить

у меня почему то при активации плагина выскакивает ошибка в коде с блогом
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 24.04.2008 at 16.49 · Permalink · Ответить

[...] 其實可以搭配另一個外掛,那就是 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 13.06.2008 at 7.31 · Permalink · Ответить

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

said on 17.06.2008 at 3.33 · Permalink · Ответить

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 18.06.2008 at 12.12 · Permalink · Ответить

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 25.07.2008 at 0.28 · Permalink · Ответить

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

said on 25.07.2008 at 16.24 · Permalink · Ответить

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 10.09.2008 at 18.52 · Permalink · Ответить

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

said on 31.12.2008 at 9.38 · Permalink · Ответить
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 01.01.2009 at 3.07 · Permalink · Ответить

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 04.01.2009 at 1.17 · Permalink · Ответить

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 04.01.2009 at 18.19 · Permalink · Ответить

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 07.01.2009 at 8.14 · Permalink · Ответить
1
2
3
 <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Button id="rang" />
</mx:Application>

Good
thx!

said on 10.01.2009 at 22.56 · Permalink · Ответить
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 16.01.2009 at 0.02 · Permalink · Ответить

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 18.01.2009 at 1.40 · Permalink · Ответить

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 19.01.2009 at 0.09 · Permalink · Ответить

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

said on 30.01.2009 at 18.09 · Permalink · Ответить

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 31.01.2009 at 22.30 · Permalink · Ответить

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 31.01.2009 at 23.52 · Permalink · Ответить

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!

Kevin @
said on 03.02.2009 at 20.54 · Permalink · Ответить

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 11.02.2009 at 17.18 · Permalink · Ответить

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 16.02.2009 at 12.00 · Permalink · Ответить

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;
  }
Andrew
said on 04.03.2009 at 15.37 · Permalink · Ответить

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 10.03.2009 at 12.12 · Permalink · Ответить

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 13.03.2009 at 20.34 · Permalink · Ответить

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 17.03.2009 at 19.04 · Permalink · Ответить

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

Serguei
said on 31.03.2009 at 0.33 · Permalink · Ответить

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 31.03.2009 at 1.03 · Permalink · Ответить

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

Aa
said on 06.04.2009 at 19.03 · Permalink · Ответить
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 08.04.2009 at 6.36 · Permalink · Ответить

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

1
2
3
4
5
6
class Test {
    @Override
    public String toString() {
         return "Test";
    }
}
Артем
said on 27.04.2009 at 16.44 · Permalink · Ответить

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

said on 04.05.2009 at 18.46 · Permalink · Ответить

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 05.05.2009 at 18.05 · Permalink · Ответить

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 13.05.2009 at 22.48 · Permalink · Ответить

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

said on 20.05.2009 at 10.23 · Permalink · Ответить

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 30.05.2009 at 14.24 · Permalink · Ответить
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 30.05.2009 at 14.25 · Permalink · Ответить
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 30.05.2009 at 14.26 · Permalink · Ответить
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 30.05.2009 at 14.27 · Permalink · Ответить
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 31.05.2009 at 4.29 · Permalink · Ответить

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 31.05.2009 at 4.31 · Permalink · Ответить

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

marcus
said on 26.06.2009 at 1.11 · Permalink · Ответить

hey there -

thanks for the plugin! a quick question – how do you add a “TAB symbol?”

much appreciated.

said on 13.07.2009 at 11.25 · Permalink · Ответить

After updating to Wordpress 2.8.1 i can’t access the options-page of codecolorer. Could you fix that?

said on 13.07.2009 at 17.10 · Permalink · Ответить

To codesnippet: sorry for this weird problem. Fixed in 0.8.1 (already on wordpress.org and will be available using automatic update very soon). Thank you for report.

said on 13.07.2009 at 18.20 · Permalink · Ответить

Sorry for my double post.. i found other problem… in rss feeds i see code correcly only IE but Firefox and Opera have some problem to interpret it. Is problem for firefox and Opera or is problem the script?

an other one problem, i don’t know, but, now, i can’t set the height for block.. the block of code is equal to lines of code.. and not is equal at pixel can i set on administration panel. For example, before, in this page (http://codesnippet.altervista.org/conto-alla-rovescia-in-javascript/) i have the vertical scrool.. now, for only value in the height box, i see all code.

Thank you e sorry again for my english..

said on 13.07.2009 at 18.26 · Permalink · Ответить

sorry again for triple post :D . I can traslate your script in italian language if is not problem for you.. tell me.. ;)

said on 14.07.2009 at 4.20 · Permalink · Ответить

To codesnippet: height problem has been fixed in version 0.8.2, which will be pushed out later today (or tomorrow). Italian translation would be really great!

said on 14.07.2009 at 4.26 · Permalink · Ответить

I’ve update it to 0.8 ,but i didn’t see style.php in my plugin.

So it didn’t work right,and i use the old version now..

said on 14.07.2009 at 4.30 · Permalink · Ответить

There is no need for styles.php now, because it really slows down the whole site. Instead plain old CSS file + a little of custom CSS in page head will be used. Hope you will appreciate it.

Also make sure you are installed 0.8.1 since 0.8.0 has weird bug with styles inclusion.

said on 14.07.2009 at 10.35 · Permalink · Ответить

In the last version compare two warning when i paste php code

1
2
3
Warning: preg_match() [function.preg-match]: Compilation failed: unrecognized character after (?< at offset 3 in /membri/codesnippet/wp-content/plugins/codecolorer/lib/geshi.php on line 2132

Warning: preg_match() [function.preg-match]: Compilation failed: unrecognized character after (?< at offset 3 in /membri/codesnippet/wp-content/plugins/codecolorer/lib/geshi.php on line 2132
said on 14.07.2009 at 13.49 · Permalink · Ответить

Ok. I have read the geshi source sode…

1
2
 if(!GESHI_PHP_PRE_433 && //Needs proper rewrite to work with PHP >=4.3.0; 4.3.3 is guaranteed to work.
                           preg_match($delimiters, $code, $matches_rx, PREG_OFFSET_CAPTURE, $i))

this is the interested line..

Not is an problem the script.. but my hosting using a version of PHP < 4.3.0.

said on 14.07.2009 at 13.57 · Permalink · Ответить

Looks like the easiest way for you to fix this error is to replace following lines in lib/geshi/php.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
        4 => "/(?<start><\\?(?>php\b)?)(?:".
            "(?>[^\"'?\\/<]+)|".
            "\\?(?!>)|".
            "(?>'(?>[^'\\\\]|\\\'|\\\\\\\|\\\\)*')|".
            "(?>\"(?>[^\"\\\\]|\\\\\"|\\\\\\\\|\\\\)*\")|".
            "(?>\\/\\*(?>[^\\*]|(?!\\*\\/)\\*)*\\*\\/)|".
            "\\/\\/(?>.*?$)|".
            "\\/(?=[^*\\/])|".
            "<(?!<<)|".
            "<<<(?<phpdoc>\w+)\s.*?\s\k<phpdoc>".
            ")*(?<end>\\?>|\Z)/sm",
        5 => "/(?<start><%)(?:".
            "(?>[^\"'%\\/<]+)|".
            "%(?!>)|".
            "(?>'(?>[^'\\\\]|\\\'|\\\\\\\|\\\\)*')|".
            "(?>\"(?>[^\\\"\\\\]|\\\\\"|\\\\\\\\|\\\\)*\")|".
            "(?>\\/\\*(?>[^\\*]|(?!\\*\\/)\\*)*\\*\\/)|".
            "\\/\\/(?>.*?$)|".
            "\\/(?=[^*\\/])|".
            "<(?!<<)|".
            "<<<(?<phpdoc>\w+)\s.*?\s\k<phpdoc>".
            ")*(?<end>%>)/sm",

with these:

1
2
        4 => "/(<\?(?:php)?)(?:'(?:[^'\\\\]|\\\\.)*?'|\"(?:[^\"\\\\]|\\\\.)*?\"|\/\*(?!\*\/).*?\*\/|.)*?(\?>|\Z)/sm",
        5 => "/(<%)(?:'(?:[^'\\\\]|\\\\.)*?'|\"(?:[^\"\\\\]|\\\\.)*?\"|\/\*(?!\*\/).*?\*\/|.)*?(%>|\Z)/sm"
miaow
said on 14.07.2009 at 17.54 · Permalink · Ответить

something wrong with latest version, the “disable showing lines” doesn’t work!

said on 15.07.2009 at 11.06 · Permalink · Ответить

Do you know ? The new version for mysql is wrong.

The Link is wrong ,and the code is not right.

You can test.

By the way , I like it ,So I hope it wonderful.Thank you.

said on 15.07.2009 at 11.07 · Permalink · Ответить
1
2
3
4
5
6
7
8
/*
创建一个qq表,将qq_id设为主键,且没有对其进行NOT NULl约束
*/

create table qq(
qq_id int(10),
nick_name varchar(255) not null,
primary key (qq_id)
)
said on 20.07.2009 at 10.56 · Permalink · Ответить

Hi Dmytro,

I found a bug in the latest version. In codecolorer-options.php, the following line:

1
update_option('codecolorer_tab_site', intval($_POST['codecolorer_tab_size']));

As you can see, its updating the ‘codecolorer_tab_SITE’ variable in the database instead of the ‘codecolorer_tab_SIZE’ variable. This makes it impossible to edit the default tab size in the codecolorer settings unless you manually edit the database entry. :-)

said on 20.07.2009 at 10.58 · Permalink · Ответить

Oh I forgot to tell you thank you for the great library Dmytro! Its clearly the best syntax highlighter out there for WP.

said on 24.07.2009 at 1.02 · Permalink · Ответить

>Исправлена проблема, блокирующая доступ к странице
>настроек CodeColorer в WordPress 2.8.1.

Подскажи как исправил?

said on 24.07.2009 at 1.14 · Permalink · Ответить

> Добавлена возможность задавать высоту и ширину блока в
> пикселях, em, процентах.

Огромное спасибо!

said on 24.07.2009 at 1.17 · Permalink · Ответить

Думаю, стоит добавить параметр:
* Минимальное количество строк для активации “показа номера строк”

А то когда 1-3 строки, то выводить номер строки как-то не актуально…

said on 24.07.2009 at 2.01 · Permalink · Ответить

2adw0rd: В WordPress 2.8 переработали систему безопасности, и теперь добавлять страницы настроек можно только из action’а admin_menu (раньше работало и из admin_init).

А насчет отключения номеров строк — с новыми короткими кодами, имхо, проблема разрешилась сама собой.

1
[ccN_php]тут код без номеров строк[/ccN_php]

Про короткие коды пока что можно почитать здесь, завтра обновлю эту страницу (и переведу на русский).

ЗЫ. В ближайшие дни готовится масштабное обновление (сильно переписан движок и исправлена туча мелких ошибок).

said on 24.07.2009 at 9.00 · Permalink · Ответить
В WordPress 2.8 переработали систему безопасности, и теперь добавлять страницы настроек можно только из action’а admin_menu (раньше работало и из admin_init).

Спасибо!

Я юзаю включение номера строк так: line_numbers="true" и меня устраивает :)

Jürgen
said on 29.07.2009 at 14.03 · Permalink · Ответить

Just a simple question:
How can I define the fontstyle, such as size and face?
Thanks for your reply.
Jürgen

said on 31.07.2009 at 21.43 · Permalink · Ответить

Слушай, я думаю необходимо исключать подгрузку всех css-стилей, когда нужен только один.

/wp-content/plugins/codecolorer/codecolorer.css

said on 01.08.2009 at 19.12 · Permalink · Ответить

Очень хороший плагин, спасибо.
Но у меня недавно возникла проблема… вместо подсвеченного кода появилась строка ::CODECOLORER_BLOCK_1::… до вчерашнего дня было все нормально… обновился и появился этот текст.

Версия WP – 2.8.2–ru

Erik
said on 01.08.2009 at 22.00 · Permalink · Ответить

Hi,

Is it possible to set a default language? Or would it be possible to make it such that a [cc] tag remembers the settings from the previous [cc] tag on the same page so we just have to define it somewhere once?

Jürgen
said on 03.08.2009 at 14.11 · Permalink · Ответить

Hallo,
is that the answer for my question?
I’m so sorry, i can’t understand any of your russian??? language.
OK, maybe you mean, I have to edit the codecolorer.css.
Can you give me some hints where in the Codecolorer.css-file i have to edit.
Thanks Jürgen

Thomas
said on 10.08.2009 at 15.04 · Permalink · Ответить

Hi,

all I get from CodeColorer is this one line:

::CODECOLORER_BLOCK_1::

The actual code is not printed; looks pretty much like comment #9 from Mad Chicken. I am using CodeColorer 0.9.2 on WP 2.8.3. Any idea?

Thanks in advance
Thomas

said on 11.08.2009 at 7.10 · Permalink · Ответить

The plugins doesn’t work as expected in WordPress-mu… don’t know if missconfiguration or what, but the editor everytime I try to add code (pasted or by keyboard), translates the special characters like < or " to entities… and the result page is showed with the entities…

Anon
said on 16.08.2009 at 2.53 · Permalink · Ответить

If you get this ::CODECOLORER_BLOCK_1::, you must use PHP 5 on MediaTemple servers…

ctapmex
said on 19.08.2009 at 10.18 · Permalink · Ответить

Привет.
что то не могу разобраться с tab. как его вставить в визуальный редактор? вставляю код из VS2008 , там точно таб стоит перед строкой. но при сохранении и табы и пробелы удаляются. wp 2.84

ctapmex
said on 19.08.2009 at 10.47 · Permalink · Ответить

хотя, это кажется глюк оперы и tinymce
в ie все отлично

said on 22.08.2009 at 14.35 · Permalink · Ответить

Hey, thanks for the nice plugin, but it looks like CodeColorer is broken for wordpress 2.8.4 At least all I’m getting is ::CODECOLORER_BLOCK_1:: where I expect a snippet of code.

Is this a known problem?

Bughunter @
said on 25.08.2009 at 18.50 · Permalink · Ответить

Concerning the error message ‘compilation failed…’ using PHP < 4.3.3 you need an older version of Geshi (1.0.6 seems to work)

said on 28.08.2009 at 17.51 · Permalink · Ответить

First of all, love the plugin, just one ‘request’ allow us to specify the starting line number with the CC tag.

i.e.

1
2
3
4
<?PHP
$changeme = 1;
$butnotme = 2;
?>

You should change line 2 not line 3

Change this

1
$changeme = 1;
said on 09.09.2009 at 2.19 · Permalink · Ответить

Hi! First of all, thanks for the great plugin. I’ve just got one problem with it: no matter what I do, Wordpress seems to be stripping the spaces from the start of each line of my code, so that:

class Foo {
function bar() { }
function baz() { }
function quux() {
doFoo();
}
}

comes out as:

class Foo {
function bar() { }
function baz() { }
function quux() {
doFoo();
}
}

The only way around this seems to be to use a tag, but this then messes up the formatting. What should I do?

@Buzz: There is already support to do that: see the “first_line” parameter.

said on 09.09.2009 at 2.22 · Permalink · Ответить

Well this went wrong here too. Let me try again:

1
2
3
4
5
6
7
class Foo {
  function bar() { }
  function baz() { }
  function quux() {
    doFoo();
  }
}

is what I intend, but:

1
2
3
4
5
6
7
class Foo {
function bar() { }
function baz() { }
function quux() {
doFoo();
}
}

is the output I get (when using the visual editor and either the “cc_php” or “cce_php” shortcodes.

said on 15.10.2009 at 18.30 · Permalink · Ответить

Any advice on using CodeColorer with the TinyMCE Advanced visual editor?

Seems that I get either my code right, or my paragraphs right… but not both.

I saw you had a TinyMCE plugin, but have revoked it, any thoughts on re-entering it into the codebase?

BTW:

1
echo "BIG THANKS!";
said on 16.10.2009 at 12.08 · Permalink · Ответить

Yep, TinyMCE editor is a big problem for now. I’ve started working on a TinyMCE plugin for CodeColorer, but this functionality has been disabled due to weird bugs in markup produced by rich editor. Hope, it will be fixed

dr34m3r @
said on 24.10.2009 at 17.32 · Permalink · Ответить

This is the best code highlighter plugin of all. Just voted for the plugin at wordpress.org. My highest appreciation to you my friend. Thanks a lot for this plugin.

said on 17.11.2009 at 22.06 · Permalink · Ответить

Thanks for the wonderful add-in.

I’m having a little problem. When I’m checkin the post page, the add-in works fine. However, I’m having problems on my main page where the cc blocks appear instead.

Also, I tried us the VB language and the comment don’t seem to be recognized.

Sébastien

Tsalagi @
said on 24.12.2009 at 5.10 · Permalink · Ответить

Is this plugin supported on this website. If so I need some solutions to two issues.
1. When I use <code> it removes my text from my page.
2. When I set a theme I still get no colors on the code on my page.

Thanks in advance.

Tsalagi
said on 24.12.2009 at 5.12 · Permalink · Ответить

Try again.
1. When I use no_cc="true" my text is removed from my page.

said on 24.12.2009 at 15.23 · Permalink · Ответить

Добрый день, подскажите как то можно сделать чтобы когда человек вводит
{code lang=”"}тут текст{code} (специально заменил)
не вылазила ошибка, вот такая:

1
<code>тут текст<code>

У меня стоит последняя 0.9.7 версия, версия WordPress 2.7.1

said on 24.12.2009 at 15.25 · Permalink · Ответить

странно у вас не появилась ошибка, у меня пишет:

1
GeSHi Error: GeSHi could not find the language (using path /wp-content/plugins/codecolorer/lib/geshi/) (code 2)
Douglas
said on 29.12.2009 at 5.57 · Permalink · Ответить

Hi. There is a problem in your code that appear when yout set an image as background. To verify that creates a “stripe” image (www.stripegenerator.com) and add it as background (in codecolorer.css ) and you will see a continuity break (set the width as 100% in the plugin options). I searched in the code and I saw that the cause is the way that you show the line numbers. You calculate the numbers manually and create a table to show them. So there is a conflict between the end of the table and the rest of the container that you create to apply the user options. I solved in two ways. The simplest is to put a width=”100%” in your second , so the table will fill all the container space.
The second is to use the Geshi methods to show the lines:

1
2
$geshi->start_line_numbers_at($options['first_line']);
$geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS);

deleting the creation of the table.

thanks.

said on 29.12.2009 at 12.34 · Permalink · Ответить

I don’t like Geshi line numbers because when you copy code, browser copies them too. It’s really weird thing, so I ended up with this table implementation. Your point about 100% makes sense, I’ll take a look how it will impact code blocks layout.

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.

Отправить комментарий