|
Banned
Регистрация: 30.03.2007
Сообщений: 344
Провел на форуме: 5149122
Репутация:
2438
|
|
Cкрипт подцветки кода Pascal
PHP код:
<?php
error_reporting(1);
// Обработка строк
function StringProc($input, $pos) {
$pos_one = $pos;
$pos_two = $pos;
for ($i=$pos_one+1; $i<strlen($input); $i++) {
if ($input[$i]=="'") {
$pos_two = $i;
break;
}
}
$pos = $pos_two; // Вернем позицию конца строки
$res[0] = "<font color=blue>".substr($input, $pos_one, $pos_two-$pos_one+1)."</font>";
$res[1] = $pos_two;
return $res;
}
// Обработка комментариев в виде гнутой скобки
function CommentProc1($input, $pos) {
$pos_one = $pos;
$pos_two = $pos;
for ($i=$pos_one+1; $i<strlen($input); $i++) {
if ($input[$i]=="}") {
$pos_two = $i;
break;
}
}
$pos = $pos_two; // Вернем позицию конца строки
$res[0] = "<font color=gray>".substr($input, $pos_one, $pos_two-$pos_one+1)."</font>";
$res[1] = $pos_two;
return $res;
}
// Обработка комментариев в виде скобки и звездочки
function CommentProc2($input, $pos) {
$pos_one = $pos;
$pos_two = $pos;
for ($i=$pos_one+1; $i<strlen($input); $i++) {
if (($input[$i]==")") & ($input[$i-1]=="*")) {
$pos_two = $i;
break;
}
}
$pos = $pos_two; // Вернем позицию конца строки
$res[0] = "<font color=gray>".substr($input, $pos_one, $pos_two-$pos_one+1)."</font>";
$res[1] = $pos_two;
return $res;
}
// Обработка однострочных комментариев в виде двойного слеша
function CommentProc3($input, $pos) {
$pos_one = $pos;
$pos_two = $pos;
for ($i=$pos_one+1; $i<strlen($input); $i++) {
if ($input[$i]=="\n") {
$pos_two = $i;
break;
}
}
$pos = $pos_two; // Вернем позицию конца строки
$res[0] = "<font color=gray>".substr($input, $pos_one, $pos_two-$pos_one+1)."</font>";
$res[1] = $pos_two;
return $res;
}
// Обработка цифр и HEX кодов
function NumberProc($input, $pos) {
$pos_one = $pos;
$pos_two = $pos;
for ($i=$pos_one+1; $i<strlen($input); $i++) {
if (!ereg('[0-9,a-f,A-F]', $input[$i])) {
$pos_two = $i;
break;
}
}
$pos = $pos_two; // Вернем позицию конца строки
$res[0] = "<font color=red>".substr($input, $pos_one, $pos_two-$pos_one)."</font>";
$res[1] = $pos_two-1;
return $res;
}
// Обработка ключевых слов
function KeyWordProc($input, $pos, $key, $_words, $_keys) {
$strlen = strlen($input);
for ($i=$pos; $i<$strlen; $i++)
if (eregi('[^a-z,A-Z]', $input[$i])) break;
$res[0] = substr($input, $pos, $i-$pos);
$res[1] = $pos+strlen($res[0])-1; // Вернем позицию конца строки
for ($i=$_keys[$key][1]; $_words[$i][0]==$_keys[$key][0]; $i++) {
if (eregi(substr($input, $pos, strlen($_words[$i])), $_words[$i]) &
eregi('[^a-z,A-Z,0-9]', $input[$pos+strlen($_words[$i])])) {
$res[0] = "<b>".$_words[$i]."</b>";
$res[1] = $pos+strlen($_words[$i])-1;
break;
}
} // Если это не ключевое слово - передадим его целиком
return $res;
}
// *************************************************************
// Основная функция раскраски кода *
// *************************************************************
function DrawCodePas($input) {
// Выделение ключевых слов
// Выделяемые слова
$key_words = "abstract/and/array/as/asm/begin/case/class/const/constructor/cdecl/default/destructor/do/div/dynamic/else/end/except/external/finally/for/function/finalization/if/implementation/interface/initialization/message/mod/nil/not/name/of/or/overload/override/package/packed/pascal/private/procedure/program/property/protected/public/published/raise/read/record/shl/shr/stdcall/string/then/to/try/type/type/unit/until/uses/var/virtual/where/while/with/write/xor";
// Заполняем их в массив
$key_words = explode('/', $key_words);
// При добавлении новых ключевых слов откомментировать, выполнить под отладкой
// и заменить потом $key_words вычесленным значением $e_key_words (удалить завершающий слеш)
// sort($key_words);
// for ($j=0; $j<count($key_words); $j++) {
// $e_key_words .= $key_words[$j]."/";
// }
// Составим список буква - первое слово, начинающиеся с этой буквы в $key_words
for ($j=0; $j<count($key_words); $j++) {
//$key_words[$j] = trim($key_words[$j]);
// Добавим символ и ссылку на слово в массив
$new_item[0] = $key_words[$j][0];
$new_item[1] = $j;
$first_chars[] = $new_item;
// Теперь пропустим все слова с этой же буквы
for ($i=$j+1; $i<count($key_words); $i++) {
if ($key_words[$i][0] != $key_words[$j][0]) break;
}
$j = $i-1;
}
$result = "";
$input = ' '.$input.' ';
// Разукрашивание
for ($i=1; $i<strlen($input); $i++) {
if ($input[$i]=="'") {
$in_str = StringProc($input, $i);
$result .= $in_str[0];
$i = $in_str[1];
} elseif ($input[$i]=="{") {
$in_str = CommentProc1($input, $i);
$result .= $in_str[0];
$i = $in_str[1];
} elseif (($input[$i]=="(") & ($input[$i+1]=="*")) {
$in_str = CommentProc2($input, $i);
$result .= $in_str[0];
$i = $in_str[1];
} elseif (($input[$i]=="/") & ($input[$i+1]=="/")) {
$in_str = CommentProc3($input, $i);
$result .= $in_str[0];
$i = $in_str[1];
} elseif ((ereg('[0-9]', $input[$i]) & ereg("[\n\( ,.\[;]", $input[$i-1])) |
(ereg('[-]', $input[$i-1]) & ereg("[0-9]", $input[$i])) |
(ereg('[\$]', $input[$i]) & ereg("[\n\( ,-;.]", $input[$i-1]) & ereg("[0-9,a-f,A-F]", $input[$i+1]))) {
$in_str = NumberProc($input, $i);
$result .= $in_str[0];
$i = $in_str[1];
} elseif
// Проверим не начинается ли с текущей буквы какое-то ключевое слово,
// а перед этим проверим, чтобы перед ней стоял пробел, запятая или что-то вроде этого
(eregi('[^a-z,A-Z_,0-9]', $input[$i-1]) & eregi('[a-z,A-Z]', $input[$i])) {
$check = false;
for ($j=0; $j<count($first_chars); $j++) {
if (strtolower($input[$i])==strtolower($first_chars[$j][0])) {
$in_str = KeyWordProc($input, $i, $j, $key_words, $first_chars);
$result .= $in_str[0];
$i = $in_str[1];
$j = count($first_chars)-1; // Чтобы цикл остановился
$check = true; // Пометка, что первая буква была в словаре,
} // т.е слово было обработанно
}
if ($check==false) { $result .= $input[$i]; }
} else {
$result .= $input[$i];
}
}
return trim($result);
}
// Обработчик обратного вызова из preg_replace_callback, используемого для
// обработки Паскаль-кода
function pas_preg_callback($matches) {
return "<pre class=\"code\">".DrawCodePas($matches[1])."</pre>";
}
error_reporting(0);
?>
|