Интернет, компьютеры, софт и прочий Hi-Tech | |||||||||
Избранные докиМетки (все метки)internet, it, интернет, интернет сеть, информационные технологии, ит, по, программное обеспечение, сайт, софт
Подписаться через RSS2Email.ru
Дополнительномобильные, электроника, видеокарта, СКС, AXIS, аутсорсинг, интернет, сеть, радионяни, гаджеты |
Документация по GeSHiВерсия 1.0.7.18Автор: Nigel McNie Копирайт: © 2004 - 2007 Nigel McNie Email: nigel@geshi.org Вебсайт GeSHi: http://qbnz.com/highlighter Частичный перевод: Дмитрий Скоробогатов (dima@pc.uz) Это - документация по GeSHi - Общего подсветчика синтаксиса (Generic Syntax Highlighter). Самая последняя версия этой документации доступна в вебе по адресу http://qbnz.com/highlighter/documentation.php. Пожалуйста обращайтесь ко мне со всеми комментариями, вопросами, указаниями на неточности! Я нуждаюсь в полной информации, так как сам занимаюсь всеми вопросами связанными с GeSHi (включая эту документацию). Содержание
1: ВведениеНаверх | Содержание | Дальше | Назад GeSHi - акроним для Generic Syntax Highlighter (Общий подсветчик синтаксиса). При наличии языкового файла GeSHi сможет подсветить практически любой компьютерный язык, будь то скриптовый язык, объектно ориентированный, разметка или что угодно другое. GeSHi чрезвычайно гибок, - один и тот же исходник может быть подсвечен множеством способов, в различных языках. GeSHi выводит строгий XHTML код* и позволяет использовать CSS для сохраненного вывода. Что нужно для этого? Вам нужен PHP. Вот и все! *Как правило. Некоторые языки не выводят строгий XHTML код, а использование нумерации строк вместе с контейнером PRE не является правильным. Эта проблема будет решена в версии 1.2. 1.1: ВозможностиНаверх | Содержание | Дальше | Назад Вот некоторые из замечательных возможностей GeSHi:
Это позволяет вам вкусить то, что вы получите с GeSHi, - он лучший в мире подсветчик синтаксиса для веба! 1.2: О GeSHiНаверх | Содержание | Дальше | Назад GeSHi возник как мод для форумной системы phpBB, который позволял включать подсветку многих доступных языков (которых было 0 ;)). Однако, он скоро стал самостоятельным проектом. Но он и сейчас может быть доступен как мод для phpBB* и, будем надеяться, для многих форумных систем, блогов и других систем, основаных на вебе. *Я недолго работал над этим модом, но если кто то им заинтересуется, то может связаться со мной и получить больше информации. Вот несколько систем, которые сейчас используют GeSHi:
* Доступен только как плагин. Кроме того, некоторые другие системы позволяют устанавливать GeSHi как плагин. GeSHi разработан мной - Нигелем Эмсинаем (Nigel McNie). Другие люди, помогавшие мне в работе над различными аспектами GeSHi, упомянуты в файле THANKS. 1.3: БлагодарностиНаверх | Содержание | Дальше | Назад Многие люди помогали развивать GeSHi путем создания языковых файлов, пополнения багрепортов, выдвижения новых идей, или просто их указания, напоминания. Всех этих людей, помогавших улучшать GeSHi, вы можете узнать из файла THANKS. Вы хотите увидеть свое имя в этом списке? Почему бы не создать языковый файл, или не сообщить о действительном баге? Вы также можете помочь мне в добавлении фич, или посоветовать новую фичу, или портировать GeSHi в другие языки. Существует масса способов мне помочь и я нуждаюсь во всех них :) 1.4: Обратная связьНаверх | Содержание | Дальше | Назад Я нуждаюсь в обратной связи! Все, что вы хотите сказать, будет принято со вниманием, будь это вопрос, благодарность, сообщение о баге или жалоба. Я могу сделать эту программну еще лучше, и я нуждаюсь в вашей помощи! Вы можете связаться со мной следующим образом:
Помните, я буду благодарен за любую помощь :) 2: ОсновыНаверх | Содержание | Дальше | Назад В этом разделе я преподам кусочек GeSHi, - начальные сведения о том, как он работает и что использует, как его инсталлировать и как использовать для простейшей подсветки. 2.1: Приобретение GeSHiНаверх | Содержание | Дальше | Назад Если вы читаете это, но у вас нет GeSHi, то это проблема ;). Как вам получить его? Посетите http://qbnz.com/highlighter/downloads.php и скачайте последнюю версию. 2.2: Инсталляция GeSHiНаверх | Содержание | Дальше | Назад Инсталляции GeSHi должна предшествовать инсталляция PHP. Это совершенно несложно. Честно! 2.2.1: ТребованияНаверх | Содержание | Дальше | Назад Для инсталляции GeSHi должны быть удовлетворены следующие требования:
Как видите, требования очень невелики. Если GeSHi у вас НЕ работает в какой-то версии PHP, сообщите мне об этом и я его пофиксю. Библиотека доступна вам в архиве .zip, .tar.gz или .tar.bz2 формата. Пользователи *nix предпочтут, вероятно, .tar.gz или .tar.bz2 форматы, а пользователи windows - формат .zip. 2.2.2: Распаковка GeSHiНаверх | Содержание | Дальше | Назад Распаковка GeSHi в Linux (.tar.gz):
Распаковка GeSHi в Windows (.zip):
Извлечение из архива .zip вы можете осуществить с помощью специальной программы, - unzip в Linux или Winzip, Winrar и т.п. в Windows. 2.2.3: ИнсталляцияНаверх | Содержание | Дальше | Назад GeSHi - не более чем PHP-класс с поддержкой языковых файлов. Если вы знаете PHP, то из этого сразу догадаетесь, как нетрудно инсталлировать эту библиотеку: просто скопируйте ее куда-нибудь, где она может быть доступна для include. Куда вам нравится. Рекомендую вам положить языковые файлы в ту же поддиректорию, что и geshi.php. Запомните этот путь. Если вы не знаете, что такое "include path", не огорчайтесь. Просто скопируйте GeSHi на ваш вебсервер. Например, если ваш сайт есть http://mysite.com/myfolder, то можно скопировать GeSHi на ваш сайт в следующие директории: http://mysite.com/myfolder/geshi/[языковые файлы] http://mysite.com/myfolder/geshi.php Или, может быть, в следующие: http://mysite.com/myfolder/includes/geshi/[языковые файлы] http://mysite.com/myfolder/includes/geshi.php Предупреждение: Если вы используете GeSHi на действующем сайте, вам нужна только поддиректоия geshi/, а поддиректории contrib/ и docs/ не нужны. Более того, как обнаружили некоторые люди, один из файлов в contrib-е имел дыру в защите (исправлено в 1.0.7.3). Я предлягаю вам удалить эти директории с вашего действующего сайта. 2.3: Основы использованияНаверх | Содержание | Дальше | Назад Использовать GeSHi очень легко. Вот простой пример: //
Как видите, здесь всего три важных строки: include_once('geshi.php');
Эта строка подключает класс GeSHi для использования $geshi = new GeSHi($source, $language);
Эта строка создает новый объект GeSHi, указывает исходный код и язык, который вы хотите использовать для подсветки. echo $geshi->parse_code();
Эта строка выплевывает результат :) Таким образом, вы можете видеть, что однократное использование GeSHi действительно элементарно. Достаточно создать новый объект GeSHi и получить код!
Начиная с версии 1.0.2, GeSHi позволяет вызывать функцию
// Просто выводим посвеченный код
Однако, эти простые примеры не раскрывают всех возможностей GeSHi. Если вы желаете продолжить изучение, переходите к разделу 3: Дополнительные возможности. 3: Дополнительные возможностиНаверх | Содержание | Дальше | Назад Этот раздел документации посвящен дополнительным возможностям GeSHi: строгий режим, использование классов CSS, изменение стилей на лету, запрещение подсветки некоторых элементов и другое. Этот раздел содержит много отрывков кода. Во всех них предполагается, что библиотека GeSHi уже подключена, объект GeSHi был создан, и что переменная $geshi ссылается на него. Исходный код, язык и путь, как правило, опущены. 3.1: Контейнер кодаНаверх | Содержание | Дальше | Назад Контейнер кода оказывает фундаментальное влияние на формат вашего кода, является началом оформления. Что такое контейнер кода? Это - единица разметки, которая окружает ваш код и содержит его. По умолчанию ваш код взят в <pre>, но вы можете также указать <div>. Заголовок <pre> является умолчальным. Если вы знакомы с HTML, то вы знаете, что в элементе <pre> пробелы отображаются "как есть". Преимуществом использования <pre> является следующее: GeSHi не будет вставлятт в код <br />-ы и не будет заменять пробелы на , для создания отступов. В итоге ваш код будет чище и целее, и вы экономите время ваших посетителей и трафик. Но если вы не любите <pre>, или если он плохо выглядит в вашем браузере, и вы возьметесь самостоятельно иммитировать его с помощью стилей, то взамен него можете использовать <div>. Это повлечет за собой увеличение кода, так как GeSHi будет вставлять мнемоники вместо пробелов, а ваш браузер будет переносить длиные строки кода во избежание горизонтальной прокрутки. Если хотите, вы можете избежать этого запретив переносы строк. Как это выглядит вы можете посмотреть в разделе "демо" на домашней странице GeSHi. В настоящее время нет возможности обернуть код в теги <code> (если вы не используете функцию geshi_highlight). Отчасти, это следствие несообразности и непредусмотренности подсветки содержимого тегов <code>. Кроме того, <code> - это линейный элемент. Но, возможно, эта опция будет включена в будущие версии. В версии GeSHi 1.0.7.2 появился новый тип заголовка, который устанавливает, что код не должен быть заключен во что либо. Изменить заголовок вы можете с помощью метода set_header_type(): $geshi->set_header_type(GESHI_HEADER_DIV);
В set_header_type вы можете использовать только эти три аргумента. Передача чего-либо другого может привести к нарушениям в использовании контейнера кода (хотя, "по идее", это должно всего лишь привести к использованию <pre>). Но лучше не рисковать. Замечание: GESHI_HEADER_DIV, GESHI_HEADER_PRE и GESHI_HEADER_NONE являются константами, поэтому не надо выводить их как строки! Предупреждение: Умолчальные стили для <pre> и <div> являются различными, особенно, если вы используете нумерацию строк! По некоторым основаниям я установил, что шрифт в <pre> меньше, чем в <div>. Если вам надо, то можете устранить это различие с помощью set_overall_style(). Но вы должны осозновать это различие, когда беретесь изменять тип заголовка! 3.2: Нумерация строкНаверх | Содержание | Дальше | Назад Геши умеет вставлять в ваш код номера строк (смотрите демо, доступное на http://qbnz.com/highlighter/demo.php, как это будет выгладеть). Номера строк сильно помогут профессионалам разбираться в вашем коде, особенно, если вы пользуетесь возможностью разукрасить номера строк. 3.2.1: Включение нумерации строкНаверх | Содержание | Дальше | Назад Чтобы вставить номера строк в подсвеченный исходник, используйте метод enable_line_numbers(): $geshi->enable_line_numbers($flag);
Где $flag может быть одним из следующих:
Обычная нумерация позволяет вам указать стиль номеров, который будет применяться ко всем номерам. Украшенная нумерация позволяет вам указать особый стиль для каждой n-ой строки. Вы можете изменять значение n (по умолчанию - 5): $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS, 37);
Второй параметр не используется в других режимах. Установление его в 0 равносильно просто использованию обычной нумерации строк. Установление его в 1 приводит к тому, что украшенный стиль применяется к номеру каждой строки. Замечание: Указанные значения являются КОНСТАНТАМИ, - не используйте их как строки! 3.2.2: Стили нумерации строкНаверх | Содержание | Дальше | Назад Наиная с версии 1.0.2, номера строк в GeSHi добавляются с помощью нумерованных списков. Это делает стиль кода наследуемым от стилей номеров строк. Кроме того, это позволяет отделить номера строк от выделенного кода. Например, номера строк хорошо смотрятся, а теперь пытаетесь выделить код в вашем браузере и скопировать его. В старых версиях GeSHi номера строк тоже скопируются! Это не есть хорошо, и, к счастью, теперь эта проблема решена. Чего это стоит? К сожалению, это приводит к некорректному HTML. Тщательно обдумайте это, перед тем как включить нумерацию строк. Теперь о том, как устанавливать стиль нумерации строк: Для установления стилей номеров строк используйте метод set_line_style(): $geshi->set_line_style('background: #fcfcfc;');
Если вы используете режим украшенных номеров строк, вы можете ввести вторую строку для задания стиля n-го номера строки: $geshi->set_line_style('background: #fcfcfc;', 'background: #f0f0f0;');
Второй стиль имеет смысл, если вы используете режим украшенных номеров строк. По умолчанию, указанные вами стили перезаписывают текущие стили. Добавив логическое "true" после стилей, вы измените это поведение и новые стили будут дополнять текущие стили: $geshi->set_line_style('background: red;', true);
Предупреждение: Когда вы задаете стили номеров, код будет наследовать эти стили! Это имеет место для версий, начиная с 1.0.2. Если вы желаете, чтобы стиль вашего был предсказуем, используйте метод set_code_style() для решения этой проблемы. Также советую вам не изменять цвет фона номеров строк, если вы не используете set_overall_style(). Вот как вы должны делать стили:
Это есть главное изменение в GeSHi по сравнению с версией 1.0.1. Вы должны знать это, и прежде, чем перейдете с версии 1.0.1 на более новую, исправьте соответствующим образом свой код. 3.2.3: Выбор начального номераНаверх | Содержание | Дальше | Назад Начиная с версии 1.0.2 GeSHi позволяет начинать нумерацию строк с числа, отличного от 1. Эта возможность позволяет вам подсвечивать кусок кода из файла сохраняя ту же нумерацию строк что и в файле. Это является дополнительным удобством для тех, кто будет просматривать код. Установить начальный номер строки вы можете с помощью метода start_line_numbers_at(): $geshi->start_line_numbers_at($number);
$number должен быть положительным целым числом (или нулем). Если это не так, GeSHi конвертирует его самостоятельно. Если вы не включили нумерацию строк, это не даст никакого эффекта. Предупреждение: Хотя я пытался привести GeSHi к совместимости со строгим XHTML, эта возможнасть нарушает совместимость (однако совместимость с XHTML-transitional остается). Это потому, что единственным способом изменить начальное значение номеров, является использование атрибута start="number" для тега <ol>. Хотя CSS предусматривает возможность это сделать, только Opera начиная с версии 7.5 поддерживает эту возможность (Firefox все еще не поддерживает). 3.3: Использование классов CSSНаверх | Содержание | Дальше | Назад Использование CSS для подсветки вашего кода вместо встроенных style-ов имеет определенные преимущества. Не только в силу большей правильности (W3C осуждает использование атрибута style в XHTML 2.0), но и потому, что сокращается размер выводимого кода, - примерно на 50%, что имеет огромное значение для тех кто получает его через модем! 3.3.1: Включение классов CSSНаверх | Содержание | Дальше | Назад By default, GeSHi doesn't use the classes, so it's easy just to whack out some highlighted code if you need without worrying about stylesheets. However, if you're a bit more organised about it, you should use the classes ;). To turn the use of classes on, you call the enable_classes() method: $geshi->enable_classes();
If you want to turn classes OFF for some reason later: $geshi->enable_classes(false);
If classes are enabled when parse_code() is called, then the resultant source will use CSS classes in the output, otherwise it will in-line the styles. The advantages of using classes are great - the reduction in source will be very noticeable, and what's more you can use one stylesheet for several different highlights on the same page. In fact, you can even use an external stylesheet and link to that, saving even more time and source (because stylesheets are cached by browsers). Предупреждение: This should be the very first method you call after creating a new GeSHi object! That way, various other methods can act upon your choice to use classes correctly. In theory, you could call this method just before parsing the code, but this may result in unexpected behaviour. 3.3.2: Набор классов/ID CSSНаверх | Содержание | Дальше | Назад You can set an overall CSS class and id for the code. This is a good feature that allows you to use the same stylesheet for many different snippets of code. You call set_overall_class() and set_overall_id to accomplish this: $geshi->set_overall_class('mycode');
The default classname is the name of the language being used. This means you can use just the one stylesheet for all sources that use the same language, and incidentally means that you probably won't have to call these methods too often. CSS IDs are supposed to be unique, and you should use them as such. Basically, you can specify an ID for your code and then use that ID to highlight that code in a unique way. You'd do this for a block of code that you expressly wanted to be highlighted in a different way (see the section below on gettting the stylesheet for your code for an example). 3.3.3: Получение таблицы стилейНаверх | Содержание | Дальше | Назад The other half of using CSS classes is getting the stylesheet for use with the classes. GeSHi makes it very easy to get a stylesheet for your code, with one easy method call: $geshi->enable_classes();
The get_stylesheet() method gets the stylesheet for your code in one easy call. All you need to do is output it in the correct place. As you can also see, you don't even have to enable class usage to get the stylesheet nessecary either - however not enabling classes but using the stylesheet may result in problems later. By default, get_stylesheet() tries to echo the least amount of code possible. Although currently it doesn't check to see if a certain lexic is even in the source, you can expect this feature in the future. At least for the present however, if you explicitly disable the highlighting of a certain lexic, or disable line numbers, the related CSS will not be outputted. This may be a bad thing for you perhaps you're going to use the stylesheet for many blocks of code, some with line numbers, others with some lexic enabled where this source has it disabled. Or perhaps you're building an external stylesheet and want all lexics included. So to get around this problem, you do this: $geshi->get_stylesheet(false);
This turns economy mode off, and all of the stylesheet will be outputted regardless. Now lets say you have several snippets of code, using the same language. In most of them you don't mind if they're highlighted the same way (in fact, that's exactly what you want) but in one of them you'd like the source to be highlighted differently. Here's how you can do that: // assume path is the default "geshi/" relative to the current directory
Before version 1.0.2, you needed to set the class of the code you wanted to be unique to the empty string. This limitation has been removed in version 1.0.2 - if you set the ID of a block of code, all styling will be done based on that ID alone. 3.3.4: Использование внешней таблицы стилейНаверх | Содержание | Дальше | Назад An external stylesheet can reduce even more the amount of code needed to highlight some source. However there are some drawbacks with this. To use an external stylesheet, it's up to you to link it in to your document, normally with the following HTML: <html>
In your external stylesheet you put CSS declarations for your code. Then just make sure you're using the correct class (use set_overall_class() to ensure this) and this should work fine. This method is great if you don't mind the source always being highlighted the same (in particular, if you're making a plugin for a forum/wiki/other system, using an external stylesheet is a good idea!). It saves a small amount of code and your bandwidth, and it's relatively easy to just change the stylesheet should you need to. However, using this will render the methods that change the styles of the code useless, because of course the stylesheet is no longer being dynamically generated. You can still disable highlighting of certain lexics dynamically, however. Замечание: As of version 1.0.2, GeSHi comes with a contrib/ directory, which in it contains a "wizard" script for creating a stylesheet. Although this script is by no means a complete solution, it will create the necessary rules for the basic lexics - comments, strings for example. Things not included in the wizard include regular expressions for any language that uses them (PHP and XML are two languages that use them), and keyword-link styles. However, this script should take some of the tedium out of the job of making an external stylesheet. Expect a much better version of this script in version 1.2! 3.4: Изменение стилейНаверх | Содержание | Дальше | Назад Одна из самых значительных возможностей GeSHi - возможность динамически изменять стиль вывода. Зачем приковывать себя к наскучившим стилям, составленным авторами языка? Вы можете изменить почти каждый аспект подсветки кода, и можете установить одинаковую подсветку для любого кода. Если вы плохо владеете "стилями", то вам стоит обзавестись каким нибудь учебником, чтобы узнать, что и как вы можете сделать с ними. Вот ссылка на домашнюю страницу CSS: http://www.w3.org/Style/CSS. 3.4.1: Общие стилиНаверх | Содержание | Дальше | Назад The code outputted by GeSHi is either in a <div> or a <pre> (see the section entitled "The Code Container"), and this can be styled. $geshi->set_overall_style('... styles ...');
Where styles is a string containing valid CSS declarations. By default, these styles overwrite the current styles, but you can change this by adding a second parameter: $geshi->set_overall_style('color: blue;', true);
The default styles "shine through" wherever anything isn't highlighted. Also, you can apply more advanced styles, like position: (fixed|relative) etc, because a <div>/<pre> is a block level element. Замечание: Remember that a <div> will by default have a larger font size than a <pre>, as discussed in the section "The Code Container". 3.4.2: Стили номеров строкНаверх | Содержание | Дальше | Назад You may wish to refer to the section Styling Line Numbers before reading this section. As of version 1.0.2, the way line numbers are generated is different, so therefore the way that they are styled is different. In particular, now you cannot set the background style of the fancy line numbers to be different from that of the normal line numbers. Line number styles are set by using the method set_line_style: $geshi->set_line_style($style1, $style2);
$style1 is the style of the line numbers by default, and $style2 is the style of the fancy line numbers. Предупреждение: Things have changed since 1.0.1! This note is very important - please make sure you check this twice before complaining about line numbers! Because of the way that ordered lists are done in HTML, there really isn't normally a way to style the actual numbers in the list. I've cheated somewhat with GeSHi - I've made it possible to use CSS to style the foreground of the line numbers. So therefore, you can change the color, font size and type, and padding on them. If you want to have a pretty background, you must use set_overall_style() to do this, and use set_code_style() to style the actual code! This is explained in the section above: Styling Line Numbers. In addition, the styles for fancy line numbers is now the difference between the normal styles and the styles you want to achieve. For example, in GeSHi prior to 1.0.2 you may have done this to style line numbers: $geshi->set_line_style('color: red; font-weight: bold;', 'color: green; font-weight: bold');
Now you instead can do this: $geshi->set_line_style('color: red; font-weight: bold;', 'color: green;');
The font-weight: bold; will automatically carry through to the fancy styles. This is actually a small saving in code - but the difference may be confusing for anyone using 1.0.1 at first. 3.4.3: Установка стилей ключевых словНаверх | Содержание | Дальше | Назад Perhaps the most regular change you will make will be to the styles of a keyword set. In order to change the styles for a particular set, you'll have to know what the set is called first. Sets are numbered from 1 up. Typically, set 1 contains keywords like if, while, do, for, switch etc, set 2 contains null, false, true etc, set 3 contains function inbuilt into the language (echo, htmlspecialchars etc. in PHP) and set 4 contains data types and similar variable modifiers: int, double, real, static etc. However these things are not fixed, and you should check the language file to see what key you want. Having a familiarity with a language file is definately a plus for using it. To change the styles for a keyword set, call the set_keyword_group_style() method: $geshi->set_keyword_group_style($group, $styles);
Where $group is the group to change the styles for and $styles is a string containing the styles to apply to that group. By default, the styles you pass overwrite the current styles. Add a boolean "true" after the styles you specify to combine them with the current styles: $geshi->set_keyword_group_style(3, 'color: white;', true);
3.4.4: Установка стилей комментариевНаверх | Содержание | Дальше | Назад To change the styles for a comment group, call the set_comments_style() method: $geshi->set_comments_style($group, $styles);
Where $group is either a number corresponding to a single-line comment, or the string 'MULTI' to specify multiline comments: $geshi->set_comments_style(1, 'font-style: italic;');
By default, the styles you pass overwrite the current styles. Add a boolean "true" after the styles you specify to combine them with the current styles: $geshi->set_comments_style(1, 'font-weight: 100;', true);
3.4.5: Установка других стилейНаверх | Содержание | Дальше | Назад GeSHi can highlight many other aspects of your source other than just keywords and comments. Strings, Numbers, Methods and Brackets among other things can all also be highlighted. Here are the related methods: $geshi->set_escape_characters_style($styles[, $preserve_defaults]);
$styles is a string containing valid stylesheet declarations, while $preserve_defaults should be set to true if you want your styles to be merged with the previous styles. In the case of set_methods_style, you should select a group to set the styles of, check the language files for the number used for each "object splitter". 3.5: Зависимость от регистра и автоматическая установка регистраНаверх | Содержание | Дальше | Назад GeSHi позволяет легко управлять регистром выводимого исходника. Вы можете указывать регистр, в который должны переводиться ключевые слова, а также устанавливать зависимость тех или иных ключевых слов от регистра. 3.5.1: Автоматическая установка регистраНаверх | Содержание | Дальше | Назад Auto-Caps/Nocaps is a nifty little feature that capitalises or lowercases automatically certain lexics when they are styled. I dabble in QuickBASIC, a dialect of BASIC which is well known for it's capatalisation, and SQL is another language well known for using caps for readability. To change what case lexics are rendered in, you call the set_case_keywords() method: $geshi->set_case_keywords($caps_modifier);
The valid values to pass to this method are:
Предупреждение: When I say "lexic", I mean "keywords". Any keyword in any keyword array will be modified using this option! This is one small area of inflexibility I hope to fix in 1.2.X. I suspect this will only be used to specify GESHI_CAPS_NO_CHANGE to turn off autocaps for languages like SQL and BASIC variants, like so: $geshi = new GeSHi($source, 'sql');
All the same, it can be used for some interesting effects: $geshi = new GeSHi($source, 'java');
3.5.2: Установление зависимости от регистраНаверх | Содержание | Дальше | Назад Some languages, like PHP, don't mind what case function names and keywords are in, while others, like Java, depend on such pickiness to maintain their bad reputations ;). In any event, you can use the set_case_sensitivity to change the case sensitiveness of a particular keyword group from the default: $geshi->set_case_sensitivity($key, $sensitivity);
Where $key is the key of the group for which you wish to change case sensitivness for (see the language file for that language), and $sensitivity is a boolean value - true if the keyword is case sensitive, and false if not. 3.6: Изменение исходника/языка/пути/кодировкиНаверх | Содержание | Дальше | Назад Что произойдет, если вы захотите на лету изменить подсвечиваемый исходник или язык? Или если вы захотите указать какое-то из этих основных полей уже после того, как создали объект GeSHi? Хорошо, вот вам методы для этого. 3.6.1: Изменение исходного кодаНаверх | Содержание | Дальше | Назад To change the source code, you call the set_source() method: $geshi->set_source($newsource);
Example: $geshi = new GeSHi($source1, 'php');
3.6.2: Изменение языкаНаверх | Содержание | Дальше | Назад What happens if you want to change the language used for highlighting? Just call set_language(): $geshi->set_language('newlanguage');
Example: $geshi = new GeSHi($source, 'php');
Замечание: Names are case-insensitive - they will be converted to lower case to match a language file however. So if you're making a language file, remember it should have a name in lower case. Замечание: What you pass to this method is the name of a language file, minus the .php extension. If you're writing a plugin for a particular application, it's up to you to somehow convert user input into a valid language name. Предупреждение: GeSHi include()s the language file, so be careful to make sure that users can't pass some wierd language name to include any old script! GeSHi tries to strip non-valid characters out of a language name, but you should always do this your self anyway. In particular, language files are always lower-case, with either alphanumeric characters, dashes or underscores in their name. At the very least, strip "/" characters out of a language name. 3.6.3: Изменение путиНаверх | Содержание | Дальше | Назад What happens if all of a sudden you want to use language files from a different directory from the current language file location? You call the set_language_path() method: $geshi->set_language_path($newpath);
It doesn't matter whether the path has a trailing slash after it or not - only that it points to a valid folder. If it doesn't, that's your tough luck ;) 3.6.4: Изменение набора символовНаверх | Содержание | Дальше | Назад Замечание: As of GeSHi 1.0.7.18, you don't need to use this, as htmlspecialchars is not being used due to a security flaw in it (that is unpatched in even the most recent PHP4 versions, and in PHP5 < 5.2). As long as you set the encoding properly with a php header() call, your foreign characters will be displayed correctly. As of version 1.0.3, you can use the method set_encoding to specify the character set that your source is in. Valid names are those names that are valid for the PHP function htmlentities(): $geshi->set_encoding($encoding);
There is a table of valid strings for $encoding at the php.net manual linked to above. If you do not specify an encoding, or specify an invalid encoding, the character set used is ISO-8859-1. 3.6.5: Использование load_from_file для изменения языка и исходного кодаНаверх | Содержание | Дальше | Назад As of GeSHi 1.0.5, you can use the method load_from_file to load the source code and language from a file. Simply pass this method a file name and it will attempt to load the source and set the language. $geshi->load_from_file($file_name, $lookup);
$file_name is the file name to use, and $lookup is an optional parameter that contains a lookup array to use for deciding which language to choose. You can use this to override GeSHi's default lookup array, which may not contain the extension of the file you're after, or perhaps does have your extension but under a different language. The lookup array is of the form: array(
* 'lang_name' => array('extension', 'extension', ...),
* 'lang_name' ...
* );
Also, you can use the method get_language_name_from_extension if you need to convert a file extension to a valid language name. This method will return the empty string if it could not find a match in the lookup, and like load_from_file it accepts an optional second parameter that contains a lookup array. 3.7: Обработка ошибокНаверх | Содержание | Дальше | Назад What happens if you try to highlight using a language that doesn't exist? Or if GeSHi can't read a required file? The results you get may be confusing. You may check your code over and over, and never find anything wrong. GeSHi provides ways of finding out if GeSHi itself found anything wrong with what you tried to do. After highlighting, you can call the error() method: $geshi = new GeSHi('hi', 'thisLangIsNotSupported');
The error message you will get will look like this: GeSHi Error: GeSHi could not find the language thisLangIsNotSupported (using path geshi/) (code 2) The error outputted will be the last error GeSHi came across, just like how mysql_error() works. 3.8: Отключение стилей некоторых лексикНаверх | Содержание | Дальше | Назад One disadvantage of GeSHi is that for large source files using complex languages, it can be quite slow with every option turned on. Although future releases will concentrate on the speed/resource side of highlighting, for now you can gain speed increases by disabling some of the highlighting options. This is done by using a series of set_*_highlighting methods:
3.9: Установка ширины табуляцииНаверх | Содержание | Дальше | Назад Если вы используете контейнер <pre>, табуляция будет автоматически установлена вашим браузером и, как правило, вы получите хорошие результаты. А если вы используете контейнер <div>, вы можете явно задать ширину табуляции. Учтите, что табы здесь не являются обычными табами. Они не являются символами табуляции как таковыми, они заменяются специфицированным числом пробелов. Для изменения ширины таба вам нужен метод set_tab_width(): $geshi->set_tab_width($width);
Здесь $width является числом пробелов, которые должны выводиться вместо таба. 3.10: Использование строгого режимаНаверх | Содержание | Дальше | Назад Some languages like to get tricky, and jump in and out of the file that they're in. For example, the vast majority of you reading this will have used a PHP file. And you know that PHP code is only executed if it's within delimiters like <?php and ?> (there are others of course...). So what happens if you do the following in a php file? <img src="<?php echo rand(1, 100) ?>" />
Well normally using GeSHi with PHP, or using a bad highlighter, you'll end up with this: <img src="<?php echo rand(1, 100) ?>" />
What a mess! Especially if you're being slack about where you're putting your quotes, you could end up with the rest of your file as bright red. Fortunately, you can tell GeSHi to be "strict" about just when it highlights and when it does not, using the enable_strict_mode method: $geshi->enable_strict_mode($mode);
Where $mode is true or not specified to enable strict mode, or false to disable strict mode if you've already turned it and don't want it now. Here's the result: much better! <img src="<?php echo rand(1, 100) ?>" />
3.11: Добавление/удаление ключевых словНаверх | Содержание | Дальше | Назад Lets say that you're working on a large project, with many files, many classes and many functions. Perhaps also you have the source code on the web and highlighted by GeSHi, perhaps as a front end to CVS, as a learning tool, something to refer to, whatever. Well, why not highlight the names of the functions and classes *your* project uses, as well as the standard functions and classes? Or perhaps you're not interested in highlighting certain functions, and would like to remove them? Or maybe you don't mind if an entire function group goes west in the interest of speed? GeSHi can handle all of this! 3.11.1: Добавление ключевого словаНаверх | Содержание | Дальше | Назад If you want to add a keyword to an existing keyword group, you use the add_keyword method: $geshi->add_keyword($key, $word);
Where $key is the index of the group of keywords you want to add this keyword to, and $word is the word to add. This implies knowledge of the language file to know the correct index. Замечание: Keywords should contain at least two alphabetical characters (lower or upper case letters only). This is to enable GeSHi to work much faster by not bothering to try to detect keywords in parts of your source where there is no alphabetical characters. 3.11.2: Удаление ключевого словаНаверх | Содержание | Дальше | Назад Perhaps you want to remove a keyword from an existing group. Maybe you don't use it and want to save yourself some time. Whatever the reason, you can remove it using the remove_keyword method: $geshi->remove_keyword($key, $word);
Where $key is the index of the gropu of keywords that you want to remove this keyword from, and $word is the word to remove. This implies knowledge of the language file to know the correct index - most of the time the keywords you'll want to remove will be in group 3, but this is not guaranteed and you should check the language file first. This function is silent - if the keyword is not in the group you specified, nothing awful will happen ;) 3.11.3: Добавление группы ключевых словНаверх | Содержание | Дальше | Назад Lets say for your big project you have several main functions and classes that you'd like highlighted. Why not add them as their own group instead of having them highlighted the same way as other keywords? Then you can make them stand out, and people can instantly see which functions and classes are user defined or inbuilt. Furthermore, you could set the URL for this group to point at the API documentation of your project. You add a keyword group by using the add_keyword_group method: $geshi->add_keyword_group($key, $styles, $case_sensitive, $words);
Where $key is the key that you want to use to refer to this group, $styles is the styles that you want to use to style this group, $case_sensitive is true or false depending on whether you want this group of keywords to be case sensitive or not and $words is an array of words (or a string) of which words to add to this group. For example: $geshi->add_keyword_group(10, 'color: #600000;', false, array('myfunc_1', 'myfunc_2', 'myfunc_3'));
Adds a keyword group referenced by index 10, of which all keywords in the group will be dark red, each keyword can be in any case and which contains the keywords "myfunc_1", "myfunc_2" and "myfunc_3". After creating such a keyword group, you may call other GeSHi methods on it, just as you would for any other keyword group. Предупреждение: If you specify a $key for which there is already a keyword group, the old keyword group will be overwritten! Most language files don't use numbers larger than 5, so I recommend you play it safe and use a number like 10 or 42. 3.11.4: Удаление группы ключевых словНаверх | Содержание | Дальше | Назад Perhaps you *really* need speed? Why not just remove an entire keyword group? GeSHi won't have to loop through each keyword checking for its existance, saving much time. You removing a keyword group by using the remove_keyword_group method: $geshi->remove_keyword_group($key);
Where $key is the key of the group you wish to remove. This implies knowleged of the language file. 3.12: Заголовки и подписи для вашего кодаНаверх | Содержание | Дальше | Назад So you want to add some special information to the highlighted source? GeSHi can do that too! You can specify headers and footers for your code, style them, and insert information from the highlighted source into your header or footer. 3.12.1: Замена ключевого словаНаверх | Содержание | Дальше | Назад In your header and footer, you can put special keywords that will be replaced with actual configuration values for this GeSHi object. The keywords you can use are:
3.12.2: Установление содержимого заголовкаНаверх | Содержание | Дальше | Назад The header for your code is a <div>, which is inside the containing block. Therefore, it is affected by the method set_overall_style, and should contain the sort of HTML that belongs in a <div>. You may use any HTML you like, and format it as an HTML document. You should use valid HTML - convert to entities any quotemarks or angle brackets you want displayed. You set the header content using the method set_header_content: $geshi->set_header_content($content);
Where $content is the HTML you want to use for the header. 3.12.3: Установление содержимого подписиНаверх | Содержание | Дальше | Назад The footer for your code is a <div>, which is inside the containing block. Therefore, it is affected by the method set_overall_style, and should contain the sort of HTML that belongs in a <div>. You may use any HTML you like, and format it as an HTML document. You should use valid HTML - convert to entities any quotemarks or angle brackets you want displayed. You set the footer content using the method set_footer_content: $geshi->set_footer_content($content);
Where $content is the HTML you want to use for the footer. 3.12.4: Стиль содержимого заголовкаНаверх | Содержание | Дальше | Назад You can apply styles to the header content you have set with the set_header_content_style: $geshi->set_header_content_style($styles);
Where $styles is the stylesheet declarations you want to use to style the header content. 3.12.5: Стиль содержимого подписиНаверх | Содержание | Дальше | Назад You can apply styles to the footer content you have set with the set_footer_content_style: $geshi->set_footer_content_style($styles);
Where $styles is the stylesheet declarations you want to use to style the footer content. 3.13: Ссылки на ключевых словахНаверх | Содержание | Дальше | Назад As of version 1.0.2, GeSHi allows you to specify a URL for keyword groups. This URL is used by GeSHi to convert the keywords in that group into URLs to appropriate documentation. And using add_keyword_group you can add functions and classes from your own projects and use the URL functionality to provide a link to your own API documentation. 3.13.1: Установление URL для группы ключевых словНаверх | Содержание | Дальше | Назад To set the URL to be used for a keyword group, you use the set_url_for_keyword_group method: $geshi->set_url_for_keyword_group($group, $url);
Where $group is the keyword group you want to assign the URL for, and $url is the URL for this group of keywords. You may be wondering how to make each keyword in the group point to the correct URL. You do this by putting {FNAME} in the URL at the correct place. For example, PHP makes it easy by linking www.php.net/function-name to the documentation for that function, so the URL used is http://www.php.net/{FNAME}. Of course, when you get to a language like Java, that puts its class documentation in related folders, it gets a little trickier to work out an appropriate URL (see the Java language file!). I hope to provide some kind of redirection service at the GeSHi website in the future. 3.13.2: Отключение URL-ов для группы ключевых словНаверх | Содержание | Дальше | Назад It's easy to disable a URL for a keyword group: Simply use the method set_url_for_keyword_group to pass an empty string as the URL: $geshi->set_url_for_keyword_group($group, '');
3.13.3: Отключение всех URL-ов для ключевых словНаверх | Содержание | Дальше | Назад As of GeSHi 1.0.7.18, you can disable all URL linking for keywords: $geshi->enable_keyword_links(false);
3.13.4: Стиль ссылокНаверх | Содержание | Дальше | Назад You can also style the function links. You can style their default status, hovered, active and visited status. All of this is controlled by one method, set_link_styles: $geshi->set_link_styles($mode, $styles);
Where $mode is one of four values:
And $styles is the stylesheet declarations to apply to the links. 3.13.5: Установление цели (target) ссылокНаверх | Содержание | Дальше | Назад Perhaps you want to set the target of link attributes, so the manual pages open in a new window? Use the set_link_target method: $geshi->set_link_target($target, $styles);
Where $target is any valid (X)HTML target value - _blank or _top for example. 3.14: Использование контекстуальной значимостиНаверх | Содержание | Дальше | Назад Предупреждение: This functionality is not only buggy, but is proving very hard to implement in 1.1.X. Therefore, this functionality may well be removed in 1.2.0. You are hereby warned! 3.15: Выделение специальных строк "Extra"Наверх | Содержание | Дальше | Назад An alternative (and more stable) method of highlighting code that is important is to use extra highlighting by line. Although you may not know what line numbers contain the important lines, if you do this method is a much more flexible way of making important lines stand out. 3.15.1: Указание особо выделяемых строкНаверх | Содержание | Дальше | Назад To specify which lines to highlight extra, you past an array containing the line numbers to highlight_lines_extra: $geshi->highlight_lines_extra($array);
The array could be in the form array(2, 3, 4, 7, 12, 344, 4242), made from a DB query, generated from looking through the source for certain important things and working out what line those things are... however you get the line numbers, the array should simply be an array of integers. Here's an example, using the same source as before: //
Which produces: public int[][] product ( n, m )
ans[i][j] = i * j; }
What's more, as you can see the code on a highlighted line is still actually highlighted itself. Замечание: As you can see, this is a little buggy, but that is because of HTML laws (code elements should not contain div elements). This works just fine if you use line numbers. 3.15.2: Стили для выделенных строкНаверх | Содержание | Дальше | Назад Again as with contextual importance, you're not chained to the yellow theme that is the default. You can use the set_highlight_lines_extra_style method: $geshi->set_highlight_lines_extra_style($styles);
Where $styles is the stylesheet declarations that you want to apply to highlighted lines. 3.16: Добавление ID к каждой строкеНаверх | Содержание | Дальше | Назад Perhaps you're a javascript junkie? GeSHi provides a way to give each line an ID so you can access that line with javascript, or perhaps just by plain CSS (though if you want to access lines by CSS you should use the method in the previous section). To enable IDs you call the enable_ids method: $geshi->enable_ids($flag);
Where $flag is true or not present to enable IDs, and false to disable them again if you need. The ID generated is in the form {overall-css-id}-{line-number}. So for example, if you set the overall CSS id to be "mycode", then the IDs for each line would by "mycode-1", "mycode-2" etc. If there is no CSS ID set, then one is made up in the form geshi-[4 random characters], but this is not so useful for if you want to do javascript manipulation. 3.17: Получение времени обработкиНаверх | Содержание | Дальше | Назад Once you've called parse_code, you can get the time it took to run the highlighting by calling the get_time method: $geshi = new GeSHi($source, $language, $path);
4: Языковые файлыНаверх | Содержание | Дальше | Назад Теперь вы знакомы с возможностями, которые предлагает GeSHi и, возможно, желаете вмешаться в его исходный код. Или, может быть, обнаружили отсутствие поддержки для вашего любимого языка X? Ерунда! GeSHi сможет подсветить что угодно, не думаете же вы, что я сам кодировал все? ^_^ Здесь вы можете научиться самостоятельно создать языковый файл. Я обещаю, что это будет не сложно. - И если вы еще здесь, то вы в правильном месте! 4.1: Пример языкового файлаНаверх | Содержание | Дальше | Назад Let's begin by looking at an example language file - the language file for the first language ever supported, PHP. <?php /************************************************************************************* * php.php * -------- * Author: Nigel McNie (nigel@geshi.org) * Copyright: (c) 2004 Nigel McNie (http://qbnz.com/highlighter/) * Release Version: 1.0.2 * CVS Revision Version: $Revision$ * Date Started: 2004/06/20 * Last Modified: $Date$ * * PHP language file for GeSHi. * * CHANGES * ------- * 2004/XX/XX (1.0.2) * - Added URL support * - Added extra constants * 2004/08/05 (1.0.1) * - Added support for symbols * 2004/07/14 (1.0.0) * - First Release * * TODO (updated 2004/07/14) * ------------------------- * * Make sure the last few function I may have missed * (like eval()) are included for highlighting * * Split to several files - php4, php5 etc * ************************************************************************************* * * This file is part of GeSHi. * * GeSHi is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * GeSHi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GeSHi; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ************************************************************************************/ $language_data = array ( 'LANG_NAME' => 'PHP', 'COMMENT_SINGLE' => array(1 => '//', 2 => '#'), 'COMMENT_MULTI' => array('/*' => '*/'), 'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE, 'QUOTEMARKS' => array("'", '"'), 'ESCAPE_CHAR' => '\\', 'KEYWORDS' => array( 1 => array( 'include', 'require', 'include_once', 'require_once', 'for', 'foreach', 'as', 'if', 'elseif', 'else', 'while', 'do', 'endwhile', 'endif', 'switch', 'case', 'endswitch', 'return', 'break' ), 2 => array( 'null', '__LINE__', '__FILE__', 'false', '<?php', '?>', '<?', '<script language=', '</script>', 'true', 'var', 'default', 'function', 'class', 'new', '__FUNCTION__', '__CLASS__', '__METHOD__', 'PHP_VERSION', 'PHP_OS', 'DEFAULT_INCLUDE_PATH', 'PEAR_INSTALL_DIR', 'PEAR_EXTENSION_DIR', 'PHP_EXTENSION_DIR', 'PHP_BINDIR', 'PHP_LIBDIR', 'PHP_DATADIR', 'PHP_SYSCONFDIR', 'PHP_LOCALSTATEDIR', 'PHP_CONFIG_FILE_PATH', 'PHP_OUTPUT_HANDLER_START', 'PHP_OUTPUT_HANDLER_CONT', 'PHP_OUTPUT_HANDLER_END', 'E_ERROR', 'E_WARNING', 'E_PARSE', 'E_NOTICE', 'E_CORE_ERROR', 'E_CORE_WARNING', 'E_COMPILE_ERROR', 'E_COMPILE_WARNING', 'E_USER_ERROR', 'E_USER_WARNING', 'E_USER_NOTICE', 'E_ALL' ), 3 => array( 'zlib_get_coding_type','zend_version','zend_logo_guid', 'yp_order','yp_next', 'yp_match','yp_master','yp_get_default_domain','yp_first', 'yp_errno','yp_err_string', 'yp_cat','yp_all','xml_set_unparsed_entity_decl_handler', 'xml_set_start_namespace_decl_handler', 'xml_set_processing_instruction_handler','xml_set_object', 'xml_set_notation_decl_handler', 'xml_set_external_entity_ref_handler', 'xml_set_end_namespace_decl_handler','xml_set_element_handler', 'xml_set_default_handler','xml_set_character_data_handler', 'xml_parser_set_option', 'xml_parser_get_option','xml_parser_free', 'xml_parser_create_ns','xml_parser_create', 'xml_parse_into_struct', 'xml_parse','xml_get_error_code','xml_get_current_line_number', 'xml_get_current_column_number','xml_get_current_byte_index', 'xml_error_string', 'wordwrap','wddx_serialize_vars','wddx_serialize_value', 'wddx_packet_start','wddx_packet_end','wddx_deserialize', 'wddx_add_vars','vsprintf','vprintf','virtual', 'version_compare','var_export', 'var_dump','utf8_encode','utf8_decode','usort', 'usleep','user_error', 'urlencode','urldecode','unserialize', 'unregister_tick_function','unpack','unlink', 'unixtojd','uniqid','umask','uksort','ucwords','ucfirst', 'uasort','trim','trigger_error','touch', 'token_name','token_get_all', 'tmpfile','time','textdomain','tempnam','tanh','tan', 'system','syslog','symlink','substr_replace', 'substr_count','substr', 'strval','strtr','strtoupper','strtotime', 'strtolower','strtok', 'strstr','strspn','strrpos','strrev','strrchr','strpos', 'strncmp','strncasecmp','strnatcmp', 'strnatcasecmp','strlen','stristr', 'stripslashes','stripcslashes','strip_tags','strftime', 'stream_wrapper_register','stream_set_write_buffer', 'stream_set_timeout','stream_set_blocking','stream_select', 'stream_register_wrapper', 'stream_get_meta_data','stream_filter_prepend', 'stream_filter_append','stream_context_set_params', 'stream_context_set_option','stream_context_get_options', 'stream_context_create','strcspn', 'strcoll','strcmp','strchr','strcasecmp', 'str_word_count','str_shuffle', 'str_rot13','str_replace','str_repeat', 'str_pad','stat','sscanf', 'srand','sqrt','sql_regcase','sprintf','spliti','split', 'soundex','sort','socket_writev','socket_write', 'socket_strerror','socket_shutdown', 'socket_setopt','socket_set_timeout','socket_set_option', 'socket_set_nonblock','socket_set_blocking','socket_set_block', 'socket_sendto','socket_sendmsg','socket_send', 'socket_select','socket_recvmsg','socket_recvfrom', 'socket_recv','socket_readv','socket_read', 'socket_listen','socket_last_error','socket_iovec_set', 'socket_iovec_free','socket_iovec_fetch', 'socket_iovec_delete','socket_iovec_alloc', 'socket_iovec_add','socket_getsockname', 'socket_getpeername','socket_getopt','socket_get_status', 'socket_get_option','socket_create_pair','socket_create_listen', 'socket_create','socket_connect','socket_close', 'socket_clear_error','socket_bind','socket_accept', 'sleep','sizeof','sinh','sin','similar_text','shuffle', 'show_source','shmop_write','shmop_size', 'shmop_read','shmop_open','shmop_delete', 'shmop_close','shm_remove_var','shm_remove', 'shm_put_var','shm_get_var','shm_detach', 'shm_attach','shell_exec','sha1_file', 'sha1','settype','setlocale', 'setcookie','set_time_limit','set_socket_blocking', 'set_magic_quotes_runtime','set_include_path','set_file_buffer', 'set_error_handler','session_write_close','session_unset', 'session_unregister','session_start','session_set_save_handler', 'session_set_cookie_params','session_save_path', 'session_register','session_regenerate_id', 'session_name','session_module_name', 'session_is_registered','session_id', 'session_get_cookie_params', 'session_encode','session_destroy','session_decode', 'session_cache_limiter','session_cache_expire', 'serialize','sem_remove','sem_release','sem_get', 'sem_acquire','rtrim','rsort','round','rmdir','rewinddir', 'rewind','restore_include_path','restore_error_handler', 'reset','rename','register_tick_function', 'register_shutdown_function','realpath', 'readlink','readgzfile','readfile','readdir', 'read_exif_data','rawurlencode', 'rawurldecode','range','rand','rad2deg', 'quotemeta','quoted_printable_decode','putenv', 'proc_open','proc_close','printf', 'print_r','prev','preg_split', 'preg_replace_callback','preg_replace','preg_quote', 'preg_match_all','preg_match','preg_grep', 'pow','posix_uname','posix_ttyname', 'posix_times','posix_strerror','posix_setuid', 'posix_setsid','posix_setpgid','posix_setgid', 'posix_seteuid','posix_setegid','posix_mkfifo', 'posix_kill','posix_isatty','posix_getuid', 'posix_getsid','posix_getrlimit','posix_getpwuid', 'posix_getpwnam','posix_getppid','posix_getpid', 'posix_getpgrp','posix_getpgid','posix_getlogin', 'posix_getgroups','posix_getgrnam','posix_getgrgid', 'posix_getgid','posix_geteuid','posix_getegid', 'posix_getcwd','posix_get_last_error','posix_errno', 'posix_ctermid','pos','popen','pi','phpversion','phpinfo', 'phpcredits','php_uname','php_sapi_name', 'php_logo_guid','php_ini_scanned_files','pg_update', 'pg_untrace','pg_unescape_bytea','pg_tty','pg_trace', 'pg_setclientencoding','pg_set_client_encoding', 'pg_send_query','pg_select','pg_result_status', 'pg_result_seek','pg_result_error','pg_result', 'pg_query','pg_put_line','pg_port', 'pg_ping','pg_pconnect','pg_options', 'pg_numrows','pg_numfields','pg_num_rows', 'pg_num_fields','pg_meta_data','pg_lowrite', 'pg_lounlink','pg_loreadall','pg_loread', 'pg_loopen','pg_loimport','pg_loexport', 'pg_locreate','pg_loclose','pg_lo_write', 'pg_lo_unlink','pg_lo_tell','pg_lo_seek', 'pg_lo_read_all','pg_lo_read','pg_lo_open', 'pg_lo_import','pg_lo_export','pg_lo_create', 'pg_lo_close','pg_last_oid','pg_last_notice', 'pg_last_error','pg_insert','pg_host', 'pg_getlastoid','pg_get_result','pg_get_pid', 'pg_get_notify','pg_freeresult','pg_free_result', 'pg_fieldtype','pg_fieldsize','pg_fieldprtlen', 'pg_fieldnum','pg_fieldname','pg_fieldisnull', 'pg_field_type','pg_field_size','pg_field_prtlen', 'pg_field_num','pg_field_name','pg_field_is_null', 'pg_fetch_row','pg_fetch_result','pg_fetch_object', 'pg_fetch_assoc','pg_fetch_array','pg_fetch_all', 'pg_exec','pg_escape_string','pg_escape_bytea', 'pg_errormessage','pg_end_copy','pg_delete', 'pg_dbname','pg_copy_to','pg_copy_from','pg_convert', 'pg_connection_status','pg_connection_reset', 'pg_connection_busy','pg_connect','pg_cmdtuples', 'pg_close','pg_clientencoding','pg_client_encoding', 'pg_cancel_query','pg_affected_rows', 'pfsockopen','pclose','pathinfo','passthru', 'parse_url','parse_str','parse_ini_file','pack', 'overload','output_reset_rewrite_vars', 'output_add_rewrite_var','ord','openssl_x509_read', 'openssl_x509_parse','openssl_x509_free', 'openssl_x509_export_to_file', 'openssl_x509_export','openssl_x509_checkpurpose', 'openssl_x509_check_private_key','openssl_verify', 'openssl_sign','openssl_seal', 'openssl_public_encrypt','openssl_public_decrypt', 'openssl_private_encrypt','openssl_private_decrypt', 'openssl_pkey_new','openssl_pkey_get_public', 'openssl_pkey_get_private','openssl_pkey_free', 'openssl_pkey_export_to_file','openssl_pkey_export', 'openssl_pkcs7_verify','openssl_pkcs7_sign', 'openssl_pkcs7_encrypt','openssl_pkcs7_decrypt','openssl_open', 'openssl_get_publickey', 'openssl_get_privatekey','openssl_free_key', 'openssl_error_string','openssl_csr_sign','openssl_csr_new', 'openssl_csr_export_to_file','openssl_csr_export','openlog', 'opendir','octdec','ob_start','ob_list_handlers', 'ob_implicit_flush','ob_iconv_handler', 'ob_gzhandler','ob_get_status','ob_get_level', 'ob_get_length','ob_get_flush','ob_get_contents', 'ob_get_clean','ob_flush','ob_end_flush', 'ob_end_clean','ob_clean','number_format', 'nl_langinfo','nl2br','ngettext','next','natsort','natcasesort', 'mysql_unbuffered_query','mysql_thread_id','mysql_tablename', 'mysql_table_name','mysql_stat','mysql_selectdb', 'mysql_select_db','mysql_result','mysql_real_escape_string', 'mysql_query','mysql_ping','mysql_pconnect', 'mysql_numrows','mysql_numfields','mysql_num_rows', 'mysql_num_fields','mysql_listtables','mysql_listfields', 'mysql_listdbs','mysql_list_tables','mysql_list_processes', 'mysql_list_fields','mysql_list_dbs','mysql_insert_id', 'mysql_info','mysql_get_server_info','mysql_get_proto_info', 'mysql_get_host_info', 'mysql_get_client_info','mysql_freeresult', 'mysql_free_result','mysql_fieldtype','mysql_fieldtable', 'mysql_fieldname','mysql_fieldlen','mysql_fieldflags', 'mysql_field_type','mysql_field_table','mysql_field_seek', 'mysql_field_name','mysql_field_len','mysql_field_flags', 'mysql_fetch_row','mysql_fetch_object','mysql_fetch_lengths', 'mysql_fetch_field','mysql_fetch_assoc','mysql_fetch_array', 'mysql_escape_string','mysql_error','mysql_errno', 'mysql_dropdb','mysql_drop_db','mysql_dbname', 'mysql_db_query','mysql_db_name','mysql_data_seek', 'mysql_createdb','mysql_create_db','mysql_connect', 'mysql_close','mysql_client_encoding', 'mysql_affected_rows','mysql','mt_srand','mt_rand', 'mt_getrandmax','move_uploaded_file', 'money_format','mktime','mkdir','min', 'microtime','method_exists','metaphone', 'memory_get_usage','md5_file','md5', 'mbsubstr','mbstrrpos','mbstrpos', 'mbstrlen','mbstrcut','mbsplit', 'mbregex_encoding','mberegi_replace','mberegi', 'mbereg_search_setpos', 'mbereg_search_regs','mbereg_search_pos', 'mbereg_search_init','mbereg_search_getregs', 'mbereg_search_getpos','mbereg_search', 'mbereg_replace','mbereg_match', 'mbereg','mb_substr_count','mb_substr', 'mb_substitute_character','mb_strwidth','mb_strtoupper', 'mb_strtolower','mb_strrpos','mb_strpos', 'mb_strlen','mb_strimwidth','mb_strcut', 'mb_split','mb_send_mail','mb_regex_set_options', 'mb_regex_encoding','mb_preferred_mime_name','mb_parse_str', 'mb_output_handler','mb_language','mb_internal_encoding', 'mb_http_output','mb_http_input','mb_get_info', 'mb_eregi_replace','mb_eregi','mb_ereg_search_setpos', 'mb_ereg_search_regs', 'mb_ereg_search_pos','mb_ereg_search_init', 'mb_ereg_search_getregs','mb_ereg_search_getpos', 'mb_ereg_search','mb_ereg_replace','mb_ereg_match','mb_ereg', 'mb_encode_numericentity','mb_encode_mimeheader', 'mb_detect_order','mb_detect_encoding', 'mb_decode_numericentity','mb_decode_mimeheader', 'mb_convert_variables','mb_convert_kana', 'mb_convert_encoding','mb_convert_case','max','mail', 'magic_quotes_runtime','ltrim', 'lstat','long2ip','log1p','log10', 'log','localtime','localeconv','linkinfo','link','levenshtein', 'lcg_value','ksort','krsort','key_exists','key','juliantojd', 'join','jewishtojd','jdtounix', 'jdtojulian','jdtojewish','jdtogregorian', 'jdtofrench','jdmonthname','jddayofweek', 'is_writeable','is_writable','is_uploaded_file', 'is_subclass_of','is_string','is_scalar', 'is_resource','is_real','is_readable', 'is_object','is_numeric','is_null','is_nan','is_long','is_link', 'is_integer','is_int','is_infinite', 'is_float','is_finite','is_file', 'is_executable','is_double','is_dir', 'is_callable','is_bool','is_array', 'is_a','iptcparse','iptcembed','ip2long','intval','ini_set', 'ini_restore','ini_get_all','ini_get','ini_alter', 'in_array','import_request_variables', 'implode','image_type_to_mime_type','ignore_user_abort', 'iconv_set_encoding','iconv_get_encoding','iconv', 'i18n_mime_header_encode','i18n_mime_header_decode', 'i18n_ja_jp_hantozen','i18n_internal_encoding', 'i18n_http_output','i18n_http_input', 'i18n_discover_encoding','i18n_convert','hypot', 'htmlspecialchars','htmlentities','html_entity_decode', 'highlight_string','highlight_file','hexdec', 'hebrevc','hebrev','headers_sent', 'header','gzwrite','gzuncompress','gztell','gzseek','gzrewind', 'gzread','gzputs','gzpassthru','gzopen','gzinflate','gzgetss', 'gzgets','gzgetc','gzfile','gzeof','gzencode','gzdeflate', 'gzcompress','gzclose','gregoriantojd', 'gmstrftime','gmmktime','gmdate', 'glob','gettype','gettimeofday','gettext', 'getservbyport','getservbyname', 'getrusage','getrandmax','getprotobynumber', 'getprotobyname','getopt','getmyuid', 'getmypid','getmyinode','getmygid', 'getmxrr','getlastmod','getimagesize', 'gethostbynamel','gethostbyname', 'gethostbyaddr','getenv','getdate','getcwd', 'getallheaders','get_resource_type','get_required_files', 'get_parent_class','get_object_vars','get_meta_tags', 'get_magic_quotes_runtime','get_magic_quotes_gpc', 'get_loaded_extensions','get_included_files', 'get_include_path','get_html_translation_table', 'get_extension_funcs','get_defined_vars', 'get_defined_functions', 'get_defined_constants', 'get_declared_classes','get_current_user', 'get_class_vars','get_class_methods','get_class', 'get_cfg_var','get_browser','fwrite', 'function_exists','func_num_args','func_get_args', 'func_get_arg','ftruncate','ftp_systype', 'ftp_ssl_connect','ftp_size','ftp_site', 'ftp_set_option','ftp_rmdir','ftp_rename', 'ftp_rawlist','ftp_quit','ftp_pwd', 'ftp_put','ftp_pasv','ftp_nlist', 'ftp_nb_put','ftp_nb_get','ftp_nb_fput', 'ftp_nb_fget','ftp_nb_continue','ftp_mkdir', 'ftp_mdtm','ftp_login','ftp_get_option', 'ftp_get','ftp_fput','ftp_fget', 'ftp_exec','ftp_delete','ftp_connect', 'ftp_close','ftp_chdir','ftp_cdup', 'ftok','ftell','fstat','fsockopen','fseek','fscanf', 'frenchtojd','fread','fputs','fpassthru','fopen','fnmatch', 'fmod','flush','floor','flock','floatval','filetype', 'filesize','filepro_rowcount','filepro_retrieve', 'filepro_fieldwidth','filepro_fieldtype','filepro_fieldname', 'filepro_fieldcount','filepro','fileperms', 'fileowner','filemtime','fileinode', 'filegroup','filectime','fileatime', 'file_get_contents','file_exists','file', 'fgetss','fgets','fgetcsv','fgetc','fflush','feof', 'fclose','ezmlm_hash','extract', 'extension_loaded','expm1','explode', 'exp','exif_thumbnail','exif_tagname', 'exif_read_data','exif_imagetype','exec', 'escapeshellcmd','escapeshellarg','error_reporting', 'error_log','eregi_replace','eregi', 'ereg_replace','ereg','end','easter_days','easter_date','each', 'doubleval','dngettext','dl','diskfreespace', 'disk_total_space','disk_free_space', 'dirname','dir','dgettext','deg2rad', 'defined','define_syslog_variables', 'define','decoct','dechex','decbin', 'debug_zval_dump','debug_backtrace', 'deaggregate','dcngettext','dcgettext', 'dba_sync','dba_replace','dba_popen', 'dba_optimize','dba_open','dba_nextkey', 'dba_list','dba_insert','dba_handlers', 'dba_firstkey','dba_fetch','dba_exists', 'dba_delete','dba_close','date', 'current','ctype_xdigit','ctype_upper', 'ctype_space','ctype_punct','ctype_print', 'ctype_lower','ctype_graph','ctype_digit', 'ctype_cntrl','ctype_alpha','ctype_alnum', 'crypt','create_function','crc32','count_chars','count','cosh', 'cos','copy','convert_cyr_string','constant', 'connection_status','connection_aborted', 'compact','closelog','closedir', 'clearstatcache','class_exists','chunk_split', 'chr','chown','chop','chmod','chgrp','checkdnsrr', 'checkdate','chdir','ceil','call_user_method_array', 'call_user_method','call_user_func_array', 'call_user_func','cal_to_jd','cal_info', 'cal_from_jd','cal_days_in_month','bzwrite', 'bzread','bzopen','bzflush','bzerrstr','bzerror','bzerrno', 'bzdecompress','bzcompress','bzclose','bindtextdomain', 'bindec','bind_textdomain_codeset', 'bin2hex','bcsub','bcsqrt','bcscale','bcpow','bcmul', 'bcmod','bcdiv','bccomp','bcadd','basename','base_convert', 'base64_encode','base64_decode','atanh', 'atan2','atan','assert_options', 'assert','asort','asinh','asin','arsort','array_walk', 'array_values','array_unshift','array_unique', 'array_sum','array_splice','array_slice', 'array_shift','array_search','array_reverse', 'array_reduce','array_rand','array_push', 'array_pop','array_pad','array_multisort', 'array_merge_recursive','array_merge','array_map', 'array_keys','array_key_exists','array_intersect_assoc', 'array_intersect','array_flip','array_filter', 'array_fill','array_diff_assoc','array_diff', 'array_count_values','array_chunk','array_change_key_case', 'apache_setenv','apache_response_headers', 'apache_request_headers','apache_note', 'apache_lookup_uri','apache_get_version', 'apache_child_terminate','aggregation_info', 'aggregate_properties_by_regexp', 'aggregate_properties_by_list', 'aggregate_properties','aggregate_methods_by_regexp', 'aggregate_methods_by_list','aggregate_methods', 'aggregate','addslashes','addcslashes','acosh', 'acos','abs','_','echo', 'print', 'global', 'static', 'exit', 'array', 'empty', 'eval', 'isset', 'unset', 'die' ) ), 'SYMBOLS' => array( '(', ')', '[', ']', '{', '}', '!', '@', '%', '&', '*', '|', '/', '<', '>' ), 'CASE_SENSITIVE' => array( GESHI_COMMENTS => false, 1 => false, 2 => false, 3 => false, ), 'STYLES' => array( 'KEYWORDS' => array( 1 => 'color: #b1b100;', 2 => 'color: #000000; font-weight: bold;', 3 => 'color: #000066;' ), 'COMMENTS' => array( 1 => 'color: #808080; font-style: italic;', 2 => 'color: #808080; font-style: italic;', 'MULTI' => 'color: #808080; font-style: italic;' ), 'ESCAPE_CHAR' => array( 0 => 'color: #000099; font-weight: bold;' ), 'BRACKETS' => array( 0 => 'color: #66cc66;' ), 'STRINGS' => array( 0 => 'color: #ff0000;' ), 'NUMBERS' => array( 0 => 'color: #cc66cc;' ), 'METHODS' => array( 0 => 'color: #006600;' ), 'SYMBOLS' => array( 0 => 'color: #66cc66;' ), 'REGEXPS' => array( 0 => 'color: #0000ff;' ), 'SCRIPT' => array( 0 => '', 1 => '', 2 => '', 3 => '' ) ), 'URLS' => array( 1 => '', 2 => '', 3 => 'http://www.php.net/{FNAME}', 4 => '' ), 'OOLANG' => true, 'OBJECT_SPLITTER' => '->', 'REGEXPS' => array( 0 => "[\\$]{1,2}[a-zA-Z_][a-zA-Z0-9_]*" ), 'STRICT_MODE_APPLIES' => GESHI_MAYBE, 'SCRIPT_DELIMITERS' => array( 0 => array( '<?php' => '?>' ), 1 => array( '<?' => '?>' ), 2 => array( '<%' => '%>' ), 3 => array( '<script language="php">' => '</script>' ) ), 'HIGHLIGHT_STRICT_BLOCK' => array( 0 => true, 1 => true, 2 => true, 3 => true ) ); ?> If you're remotely familiar with PHP (or even if you're not), you can see that all that a language file consists of is a glorified variable assignment. Easy! All a language file does is assign a variable $language_data. Though still, there's a lot of indices to that array... but this section is here to break each index down and explain it to you. 4.2: Соглашения о языковом файлеНаверх | Содержание | Дальше | Назад There are several conventions that are used in language files. For ease of use and readability, your language files should obey the following rules:
There are more notes on each convention where it may appear in the language file sections below. 4.3: Секции языкового файлаНаверх | Содержание | Дальше | Назад This section will look at all the sections of a language file, and how they relate to the final highlighting result. 4.3.1: ЗаголовокНаверх | Содержание | Дальше | Назад The header of a language file is the first lines with the big comment and the start of the variable $language_data: <?php /************************************************************************************* * <name-of-language-file.php> * --------------------------------- * Author: <name> (<e-mail address>) * Copyright: (c) 2004 <name> (<website URL>) * Release Version: 1.0.0 * CVS Revision Version: $Revision: 918 $ * Date Started: <date started> * Last Modified: $Date: 2007-02-24 22:53:26 +1300 (Sat, 24 Feb 2007) $ * * <name-of-language> language file for GeSHi. * * <any-comments...> * * CHANGES * ------- * <date-of-release> (1.0.0) * - First Release * * TODO (updated <date-of-release>) * ------------------------- * <things-to-do> * ************************************************************************************* * * This file is part of GeSHi. * * GeSHi is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * GeSHi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GeSHi; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ************************************************************************************/ $language_data = array ( The parts in angle brackets are the parts that you change for your language file. Everything else *must* remain the same! Here are the parts you should change:
Everything should remain the same, including $Revision: 918 $ and $Date: 2007-02-24 22:53:26 +1300 (Sat, 24 Feb 2007) $ (I know these may look funny but they have their purpose for those of you who don't know about SVN). Also: I'm not sure about the copyright on a new language file. I'm not a lawyer, could someone contact me about whether the copyright for a new language file should be exclusivly the authors, or joint with me (if included in a GeSHi release)? 4.3.2: Первые индексыНаверх | Содержание | Дальше | Назад Here is an example from the php language file of the first indices: 'LANG_NAME' => 'PHP',
'COMMENT_SINGLE' => array(1 => '//', 2 => '#'),
'COMMENT_MULTI' => array('/*' => '*/'),
'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE,
'QUOTEMARKS' => array("'", '"'),
'ESCAPE_CHAR' => '\\',
The first indices are the first few lines of a language file before the KEYWORDS index. These indices specify:
4.3.3: Ключевые словаНаверх | Содержание | Дальше | Назад Keywords will make up the bulk of a language file. In this part you add keywords for your language, including inbuilt functions, data types, predefined constants etc etc. Here's a (shortened) example from the php language file: 'KEYWORDS' => array( 1 => array( 'include', 'require', 'include_once', 'require_once', 'for', 'foreach', 'as', 'if', 'elseif', 'else', 'while', 'do', 'endwhile', 'endif', 'switch', 'case', 'endswitch', 'return', 'break' ), 2 => array( 'null', '__LINE__', '__FILE__', 'false', '<?php', '?>', '<?', '<script language=', '</script>', 'true', 'var', 'default', 'function', 'class', 'new', '__FUNCTION__', '__CLASS__', '__METHOD__', 'PHP_VERSION', 'PHP_OS', 'DEFAULT_INCLUDE_PATH', 'PEAR_INSTALL_DIR', 'PEAR_EXTENSION_DIR', 'PHP_EXTENSION_DIR', 'PHP_BINDIR', 'PHP_LIBDIR', 'PHP_DATADIR', 'PHP_SYSCONFDIR', 'PHP_LOCALSTATEDIR', 'PHP_CONFIG_FILE_PATH', 'PHP_OUTPUT_HANDLER_START', 'PHP_OUTPUT_HANDLER_CONT', 'PHP_OUTPUT_HANDLER_END', 'E_ERROR', 'E_WARNING', 'E_PARSE', 'E_NOTICE', 'E_CORE_ERROR', 'E_CORE_WARNING', 'E_COMPILE_ERROR', 'E_COMPILE_WARNING', 'E_USER_ERROR', 'E_USER_WARNING', 'E_USER_NOTICE', 'E_ALL' ), 3 => array( 'zlib_get_coding_type','zend_version', 'zend_logo_guid','yp_order', 'yp_next','yp_match','yp_master', 'yp_get_default_domain','yp_first', 'yp_errno','yp_err_string','yp_cat','yp_all', 'xml_set_unparsed_entity_decl_handler', 'xml_set_start_namespace_decl_handler', 'xml_set_processing_instruction_handler','xml_set_object', 'xml_set_notation_decl_handler', 'xml_set_external_entity_ref_handler', 'xml_set_end_namespace_decl_handler','xml_set_element_handler', 'xml_set_default_handler','xml_set_character_data_handler', 'xml_parser_set_option', 'xml_parser_get_option','xml_parser_free', 'xml_parser_create_ns','xml_parser_create', 'xml_parse_into_struct' ) ), You can see that the index 'KEYWORDS' refers to an array of arrays, indexed by positive integers. In each array, there are some keywords (in the actual php language file there is in fact many more keywords in the array indexed by 3). Here are some points to note about these keywords:
4.3.4: Символы и регистрозависимостьНаверх | Содержание | Дальше | Назад So you've put all the keywords for your language in? Now for a breather before we style them :). Symbols define what symbols your language uses, these are things like colons, brackets/braces, and other such general punctuation (it's important to note that in the 1.0.X series these will not be used), and case sensitivity alludes to the previous section: here you can set which keyword groups are case sensitive. Here's an example: 'SYMBOLS' => array(
'(', ')', '[', ']', '{', '}', '!', '@', '%', '&', '*', '|', '/', '<', '>'
),
'CASE_SENSITIVE' => array(
GESHI_COMMENTS => false,
1 => false,
2 => false,
3 => false,
),
4.3.5: Стили для ваших языковых файловНаверх | Содержание | Дальше | Назад This is the fun part! Here you get to choose the colours, fonts, backgrounds and anything else you'd like for your language file. Here's an example: 'STYLES' => array( 'KEYWORDS' => array( 1 => 'color: #b1b100;', 2 => 'color: #000000; font-weight: bold;', 3 => 'color: #000066;' ), 'COMMENTS' => array( 1 => 'color: #808080; font-style: italic;', 2 => 'color: #808080; font-style: italic;', 'MULTI' => 'color: #808080; font-style: italic;' ), 'ESCAPE_CHAR' => array( 0 => 'color: #000099; font-weight: bold;' ), 'BRACKETS' => array( 0 => 'color: #66cc66;' ), 'STRINGS' => array( 0 => 'color: #ff0000;' ), 'NUMBERS' => array( 0 => 'color: #cc66cc;' ), 'METHODS' => array( 0 => 'color: #006600;' ), 'SYMBOLS' => array( 0 => 'color: #66cc66;' ), 'REGEXPS' => array( 0 => 'color: #0000ff;' ), 'SCRIPT' => array( 0 => '', 1 => '', 2 => '', 3 => '' ) ), Note that all style rules should end with a semi-colon! This is important: GeSHi may add extra rules to the rules you specify (and will do so if a user tries to change your styles on the fly), so the last semi-colon in any stylesheet rule is important. All strings here should contain valid stylesheet declarations (it's also find to have the empty string).
4.3.6: URL-ы для функцийНаверх | Содержание | Дальше | Назад This section lets you specify a url to visit for each keyword group. Useful for pointing functions at their online manual entries. Here is an example: 'URLS' => array(
1 => '',
2 => '',
3 => 'http://www.php.net/{FNAME}',
4 => ''
),
The indices of this array correspond to the keyword groups you specified in the keywords section. The string {FNAME} marks where the name of the function is substituted in. So for the example above, if the keyword being highlighted is "echo", then the keyword will be a URL pointing to http://www.php.net/echo. Because some languages (Java!) don't keep a uniform URL for functions/classes, you may have trouble in creating a URL for that language (though look in the java language file for a novel solution to it's problem) 4.3.7: Поддержка объектной ориентированностиНаверх | Содержание | Дальше | Назад Now we're reaching the most little-used section of a language file, which includes such goodies as object orientation support and context support. GeSHi can highlight methods and data fields of objects easily, all you need to do is to tell it to do so and what the "splitter" is between object/method etc. Here's an example: 'OOLANG' => true, 'OBJECT_SPLITTER' => '->', If your language has object orientation, the value of 'OOLANG' is true, otherwise it is false. If it is object orientated, in the 'OBJECT_SPLITTER' value you put the htmlentities() version of the "splitter" between objects and methods/fields. If it is not, then make this the empty string. 4.3.8: Использование регулярных выраженийНаверх | Содержание | Дальше | Назад Regular expressions are a good way to catch any other lexic that fits certain rules but can't be listed as a keyword. A good example is variables in PHP: variables always start with either one or two "$" signs, then alphanumeric characters (a simplification). This is easy to catch with regular expressions. And new to version 1.0.2, there is an advanced way of using regular expressions to catch certain things but highlight only part of those things. This is particularly useful for languages like XML. Предупреждение: Regular expressions use the PCRE syntax (perl-style), not the ereg() style! Here is an example (this time the PHP file merged with the XML file): 0 => array(
GESHI_SEARCH => '(((xml:)?[a-z\-]+))(=)',
GESHI_REPLACE => '\\1',
GESHI_MODIFIERS => '',
GESHI_BEFORE => '',
GESHI_AFTER => '\\4'
),
1 => array(
GESHI_SEARCH => '(</?[a-z0-9]*(>)?)',
GESHI_REPLACE => '\\1',
GESHI_MODIFIERS => '',
GESHI_BEFORE => '',
GESHI_AFTER => ''
),
2 => "[\\$]{1,2}[a-zA-Z_][a-zA-Z0-9_]*"
As you can see there are two formats. One is the "simple" format used in GeSHi < 1.0.2, and the other is a more advanced syntax. Firstly, the simple syntax:
And now for advanced syntax, which gives you much more control over exactly what is highlighted:
Is that totally confusing? Here's the test for if you're an android or not: If you found that perfectly understandable then you're an android ;). Here's a better example: Let's say that I'm making a language, and variables in this language always start with a dollar sign ($), are always written in lowercase letters and always end with an ampersand (&). eg: $foo& = 'bar'
I want to highlight only the text between the $ and the &. How do I do that? With simple regular expressions I can't, but with advanced, it's relatively easy: 1 => array(
GESHI_SEARCH => '(\$)([a-z]+)(&)', // search for a dollar sign,
// then one or more of the
// characters a-z, then an
// ampersand
GESHI_REPLACE => '\\2', // we wanna highlight the
// characters, which are in
// the second bracketed
// group
GESHI_MODIFIERS => '', // no modifiers, since we're
// not matching the
// "anything" regex
GESHI_BEFORE => '\\1', // before the highlighted
// characters should be the
// first bracketed group
// (always a dollar sign in
// this example)
GESHI_AFTER => '\\3' // after the highlighted
// characters should be the
// third bracketed group
// (always an ampersand in
// this example)
),
So if someone tried to highlight using my language, all cases of $foo& would turn into: $<span style="color: blue;">foo</span>&
(which would of course be viewed in a browser to get something like $foo&) 4.3.9: Контекстуальная подсветка и строгий режимНаверх | Содержание | Дальше | Назад For languages like HTML, it's good if we can highlight a tag (like <a> for example). But how do we stop every single "a" in the source getting highlighted? What about for attributes? If I've got the word "colspan" in my text I don't want that highlighted! So how do you tell GeSHi not to highlight in that case? You do it with "Strict Blocks". Here is an example: 'STRICT_MODE_APPLIES' => GESHI_MAYBE, 'SCRIPT_DELIMITERS' => array( 0 => array( '<?php' => '?>' ), 1 => array( '<?' => '?>' ), 2 => array( '<%' => '%>' ), 3 => array( '<script language="php">' => '</script>' ) ), 'HIGHLIGHT_STRICT_BLOCK' => array( 0 => true, 1 => true, 2 => true, 3 => true ) What is strict mode? Strict mode says that highlighting only occurs inside the blocks you specify. You can see from the example above that highlighting will only occur if the source is inside <?php ... ?> (though note the GESHI_MAYBE!). Here are some points about strict highlighting:
Замечание: The delimiters should be in reverse alphabetical order. Note that in the above example, <?php comes before <?. 4.3.10: ЗавершениеНаверх | Содержание | Дальше | Назад Все языковые файлы должны заканчиваться следующим образом: ); ?> 5: Справочник методов и свойствНаверх | Содержание | Дальше | Назад Сейчас я боюсь немного соврать! Дело в том, что для 1.0.7 я включил phpdoc API для исходного кода в директорию api но постоянно забываю обновить документацию! Как бы то ни было, она есть, и может помочь вам в кодировании, особенно при написании плагинов. Ну вот и все! У меня накопилось много изменений и улучшений документации начиная с версии 1.0.1, но она все же остается далекой от совершенства. Возможно, в ней содержатся ошибки, или она где-то непонятна вам. Если так, свяжитейсь со мной, и я постараюсь ее улучшить. Если вам это интересно, я закончил разработку GeSHi ветки 1.0.X. Очередные релизы этой ветки пополняются только исправлениями багов и новыми языковыми файлами. Но версия 1.0.2 была "концептуальным" релизом, - экспериментом, в котором проверялось, как далеко я смогу продвинуться в разработке идеи подсветки (а заодно и других идей). Я планирую переписать код для 1.2.X, который будет базироваться на новом движке, - на движке "psuedo-tokenizer". Надеюсь, он сильно сократит нагрузку на сервер и уменьшит время отработки (посредством почти полного устранения регулярных выражений), тогда появится еще лучший подсветчик. Но это не страшно! Интерфейс и все имена методов должны остаться теми же ^_^ (хотя я не думаю, что языковые файлы останутся прежними!) Под наконец. Двое людей спрашивали меня: как ты генерируешь эту документацию? Ответ поразителен: своими мозгами. Но, конечно, это занимает много времени, и я не рекомендую поступать также. И, конечно, вы можете заимствовать стиль, если он вам нравится, только сообщите мне на e-mail, если это делаете. Так или иначе, довольно болтать. Берите уже GeSHi в работу! :D Nigel McNie nigel@geshi.org http://qbnz.com/highlighter/ Последнее редактирование: 2007-08-07 16:19:57 Метки материала: geshi, language, php, code, highlighting, html, script, подсветки, array 4 комментария
Вопрос: |
||||||||
| 06.08.2008 19:57:00 | # |
| 07.08.2008 16:15:50 | # |
| 24.09.2011 09:37:25 | # |
© 2007-2012, Дмитрий Скоробогатов.
Разрешается воспроизводить, распространять и/или изменять материалы сайта
в соответствии с условиями GNU Free Documentation License,
версии 1.2 или любой более поздней версии, опубликованной FSF,
если только иное не указано в самих материалах.