copyright (c) 2014 c61 http://c61.no-ip.org <c61@yandex.ru>
license http://opensource.org/licenses/gpl-license.php GNU Public License
Мод предназначен для расширения фунционала ББ-кода code, в том числе:
- сохранения кодов табуляции в публикуемом коде (в немодифицированной конференции табуляции заменятся на пробелы)
- добавления возможности расширения окошка кода по вертикали (при появлении прокрутки) и горизонтали
- добавления возможности нумерации строк
- подсветки синтаксиса кода с указанием языка (по умолчанию автоматическое разпознавание языка отключено)
Части кода этого мода были взяты из модов CodeEnhancements_1.0.2, highlight.js, randomessence-highlight.js и др., а также с http://phpbbguru.net (в том числе сообщения Кнопка "Развернуть" в {code} ). Спасибо Авторам !
Установка:
1) Скачать highlight.js с http://highlightjs.org/download/ . Актуальная на момент создания этого мода версия 8.0. Набор языков можно оставить по умолчанию либо какие-то убрать/добавить.
Разархивировать highlight.zip и переписать его содержимое в styles/highlight (каталог предварительно создать).
2) В includes/bbcode.php найти
Код: Выделить всё
static $replacements = array(Код: Выделить всё
'code_open' => array('{LANGUAGE}' => '$1'),Код: Выделить всё
// when using the /e modifier, preg_replace slashes double-quotes but does not
// seem to slash anything else
$code = str_replace('\"', '"', $code);
$code = str_replace("\n", "\r", $code);
// remove newline(s) at the beginning
while (!empty($code))
{
if (!($code[0] == "\r")) break;
$code = substr($code, 1);
}
// Autohighlight ON
//if ($type == 'off')
// Autohighlight OFF
if (empty($type) || ($type == 'off'))
{
$type = 'no-highlight';
}
// Autohighlight AUTO
if ($type == 'auto')
{
$type = '';
}
$code_open = str_replace('$1', $type, $this->bbcode_tpl('code_open'));
$code = $code_open . $code . $this->bbcode_tpl('code_close');
return $code;3) В includes/message_parser.php найти
Код: Выделить всё
case 'php':
$remove_tags = false;
$str_from = array('<', '>', '[', ']', '.', ':', ':');
$str_to = array('<', '>', '[', ']', '.', ':', ':');
$code = str_replace($str_from, $str_to, $code);
if (!preg_match('/\<\?.*?\?\>/is', $code))
{
$remove_tags = true;
$code = "<?php $code ?>";
}
$conf = array('highlight.bg', 'highlight.comment', 'highlight.default', 'highlight.html', 'highlight.keyword', 'highlight.string');
foreach ($conf as $ini_var)
{
@ini_set($ini_var, str_replace('highlight.', 'syntax', $ini_var));
}
// Because highlight_string is specialcharing the text (but we already did this before), we have to reverse this in order to get correct results
$code = htmlspecialchars_decode($code);
$code = highlight_string($code, true);
$str_from = array('<span style="color: ', '<font color="syntax', '</font>', '<code>', '</code>','[', ']', '.', ':');
$str_to = array('<span class="', '<span class="syntax', '</span>', '', '', '[', ']', '.', ':');
if ($remove_tags)
{
$str_from[] = '<span class="syntaxdefault"><?php </span>';
$str_to[] = '';
$str_from[] = '<span class="syntaxdefault"><?php ';
$str_to[] = '<span class="syntaxdefault">';
}
$code = str_replace($str_from, $str_to, $code);
$code = preg_replace('#^(<span class="[a-z_]+">)\n?(.*?)\n?(</span>)$#is', '$1$2$3', $code);
if ($remove_tags)
{
$code = preg_replace('#(<span class="[a-z]+">)?\?>(</span>)#', '$1 $2', $code);
}
$code = preg_replace('#^<span class="[a-z]+"><span class="([a-z]+)">(.*)</span></span>#s', '<span class="$1">$2</span>', $code);
$code = preg_replace('#(?:\s++| )*+</span>$#u', '</span>', $code);
// remove newline at the end
if (!empty($code) && substr($code, -1) == "\n")
{
$code = substr($code, 0, -1);
}Код: Выделить всё
case 'off': // Highlight OFF
case 'auto': // Highlight Auto
case '1c':
case 'actionscript':
case 'apache':
case 'applescript':
case 'asciidoc':
case 'autohotkey':
case 'avrasm':
case 'axapta':
case 'bash':
case 'brainfuck':
case 'clojure':
case 'cmake':
case 'coffeescript':
case 'cpp':
case 'cs':
case 'css':
case 'd':
case 'delphi':
case 'diff':
case 'django':
case 'dos':
case 'elixir':
case 'erlang-repl':
case 'erlang':
case 'fix':
case 'fsharp':
case 'glsl':
case 'go':
case 'haml':
case 'handlebars':
case 'haskell':
case 'html':
case 'http':
case 'ini':
case 'java':
case 'javascript':
case 'json':
case 'lasso':
case 'lisp':
case 'livecodeserver':
case 'lua':
case 'makefile':
case 'markdown':
case 'mathematica':
case 'matlab':
case 'mel':
case 'mizar':
case 'nginx':
case 'nix':
case 'nsis':
case 'objectivec':
case 'ocaml':
case 'oxygene':
case 'parser3':
case 'perl':
case 'php':
case 'profile':
case 'protobuf':
case 'python':
case 'r':
case 'rib':
case 'rsl':
case 'ruby':
case 'ruleslanguage':
case 'rust':
case 'scala':
case 'scilab':
case 'scss':
case 'smalltalk':
case 'sql':
case 'tex':
case 'vala':
case 'vbnet':
case 'vbscript':
case 'vhdl':
case 'vim':
case 'x86asm':
case 'xml':- off - подсветка синтаксиса отключена,
- auto - автоопределение языка и подсветка синтаксиса,
- остальное - имена поддерживаемых языков, для которых следует подсвечивать синтаксис, их можно узнать здесь: http://highlightjs.readthedocs.org/en/l ... rence.html или по именам файлов скриптов здесь: https://github.com/isagalaev/highlight. ... /languages
Учтите, что для "code=auto" и короткого кода весьма вероятны ошибки автоматического определения языка.
4) В файле language/en/common.php найти
Код: Выделить всё
?>Код: Выделить всё
// HCode mod begin
$lang = array_merge($lang, array(
'HCODE_LINES' => 'Lines',
'HCODE_NUMERATION_ON' => 'Switch ON Numeration',
'HCODE_NUMERATION_OFF' => 'Switch OFF Numeration',
'HCODE_HLJS_LANGUAGE' => 'Language',
'HCODE_HLJS_IDENTIFIED' => 'Identified',
));
// HCode mod endКод: Выделить всё
?>Код: Выделить всё
// HCode mod begin
$lang = array_merge($lang, array(
'HCODE_LINES' => 'Строки',
'HCODE_NUMERATION_ON' => 'Вкл.Нумерацию',
'HCODE_NUMERATION_OFF' => 'Откл.Нумерацию',
'HCODE_HLJS_LANGUAGE' => 'Язык',
'HCODE_HLJS_IDENTIFIED' => 'Распознан',
));
// HCode mod end6.1) В файле styles/prosilver/theme/content.css найти
Код: Выделить всё
dl.codebox code {
/* Also see tweaks.css */
overflow: auto;
display: block;
height: auto;
max-height: 200px;
white-space: normal;
padding-top: 5px;
font: 0.9em Monaco, "Andale Mono","Courier New", Courier, mono;
line-height: 1.3em;
color: #8b8b8b;
margin: 2px 0;
}Код: Выделить всё
dl.codebox code {
padding: 0;
background: inherit;
border: none;
font: inherit;
}
.codebox {
padding: 3px;
border: 1px solid #dcdcdc;
border-radius: 8px;
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
margin: 0.5em 1px 0 25px;
font-size: 1em;
}
.codebox div {
margin-bottom: 3px;
padding-left: 2px;
font-size: 11px;
font-weight: normal;
display: block;
color: #444;
position: relative;
}
.codeboxright {
margin: 0px;
padding: 0px;
position: absolute;
right: 20px;
}
blockquote .codebox {
margin-left: 0;
}
.codebox pre {
background-color: rgba(255, 255, 255, 1.0);
/* Also see tweaks.css */
overflow: auto;
/* Making preformated <pre> text wrap in CSS3, Mozilla, Opera and IE:
http://users.tkk.fi/~tkarvine/pre-wrap-css3-mozilla-opera-ie.html */
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
height: auto;
max-height: 200px;
padding-top: 5px;
font: 0.9em Monaco, "Andale Mono","Courier New", Courier, mono;
line-height: 1.3em;
color: #000;
margin: 2px 0;
-o-tab-size: 4;
-moz-tab-size: 4;
-webkit-tab-size: 4;
tab-size: 4;
}
.codebox code {
padding: 0;
background: inherit;
border: none;
font: inherit;
white-space: inherit;
word-wrap: inherit;
tab-size: inherit;
}
.codeboxlines {
text-align: right;
vertical-align: top;
}
.codeboxlinesdiv {
color: #666;
background-color: #EEE;
}Код: Выделить всё
dl.codebox code {
color: #2E8B57;
}Код: Выделить всё
dl.codebox pre {
color: #2E8B57;
}
div.codebox pre {
color: #2E8B57;
}Код: Выделить всё
/* Accessibility tweaks: Mozilla.org */
.skip_link { display: none; }Код: Выделить всё
/* Making preformated <pre> text wrap in CSS3, Mozilla, Opera and IE:
http://users.tkk.fi/~tkarvine/pre-wrap-css3-mozilla-opera-ie.html */
div.codebox pre {
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
-o-tab-size: 4;
-moz-tab-size: 4;
-webkit-tab-size: 4;
tab-size: 4;
}Код: Выделить всё
<!-- BEGIN code_open --><dl class="codebox"><dt>{L_CODE}: <a href="#" onclick="selectCode(this); return false;">{L_SELECT_ALL_CODE}</a></dt><dd><code><!-- END code_open -->
<!-- BEGIN code_close --></code></dd></dl><!-- END code_close -->Код: Выделить всё
<!-- BEGIN code_open --><div class="codebox"><div>{L_CODE}: <a href="#" onclick="selectCode(this); return false;">{L_SELECT_ALL_CODE}</a></div><pre><code class="{LANGUAGE}"><!-- END code_open -->
<!-- BEGIN code_close --></code></pre></div><!-- END code_close -->6.5) В файле styles/prosilver/template/overall_header.html найти
Код: Выделить всё
</head>Код: Выделить всё
<script type="text/javascript">
// <![CDATA[
var codeoldbrowser = (!('forEach' in Array.prototype) || !document.addEventListener) ? true : false;
if (!codeoldbrowser) {
document.write('<link rel="stylesheet" href="styles\/highlight\/styles\/vs.css" \/>');
document.write('<script type="text\/javascript" src="styles\/highlight\/highlight.pack.js"><\/script>');
}
function expandCode(e) {
var c = e.parentNode.nextSibling;
if (c.style.maxHeight == 'none') {
c.style.maxHeight = '200px';
e.innerHTML = '{L_EXPAND_VIEW}';
}
else {
c.style.maxHeight = 'none';
e.innerHTML = '{L_COLLAPSE_VIEW}';
}
}
function wrapCode(e,set) {
var c = e.parentNode.nextSibling;
if (set) {
c.style.wordWrap = 'normal';
c.style.whiteSpace = 'pre';
e.innerHTML = '{L_COLLAPSE_VIEW}';
}
else {
if (!(c.style.wordWrap == 'normal')){
c.style.wordWrap = 'normal';
c.style.whiteSpace = 'pre';
e.innerHTML = '{L_COLLAPSE_VIEW}';
}
else {
c.style.wordWrap = 'break-word';
c.style.whiteSpace = 'pre-wrap';
e.innerHTML = '{L_EXPAND_VIEW}';
linesCode(e.previousSibling.previousSibling,true);
}
}
}
function linesCode(e,reset) {
var c = e.parentNode.nextSibling.firstChild.firstChild;
if (reset) {
c.rows[0].cells[0].firstChild.style.display = 'none';
e.innerHTML = '{L_HCODE_NUMERATION_ON}';
}
else {
if (!(c.rows[0].cells[0].firstChild.style.display == 'none')) {
c.rows[0].cells[0].firstChild.style.display = 'none';
e.innerHTML = '{L_HCODE_NUMERATION_ON}';
}
else {
wrapCode(e.nextSibling.nextSibling,true);
c.rows[0].cells[0].firstChild.style.display = 'block';
e.innerHTML = '{L_HCODE_NUMERATION_OFF}';
}
}
}
function padlinesCode(number, len) {
var str = '' + (number+1);
for (var i=str.length; i<=len; i++) {
str = '0' + str;
}
return str;
}
function createlinesCode(e) {
String.prototype.replaceAll = function(find, replace_to) {
return this.replace(new RegExp(find, "g"), replace_to);
}
var code = e.innerHTML;
if (code.charAt(code.length - 1) == '\n') code = code.slice(0, -1);
code = code.replaceAll('\r','');
var n = 1;
for (var i=0; i<code.length; i++) {
if (code.charAt(i) == '\n') n++;
}
var len = Math.floor(Math.log(n) / Math.log(10));
if (len < 2) len = 2;
var width = len + 1;
var cl = '<table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td width="' + width + 'xm" class="codeboxlines"><div class="codeboxlinesdiv" style="display: none;">';
for (var i=0; i<n; i++) {
cl += padlinesCode(i,len) + ' \n';
}
cl += '</div></td><td>' + code + '</td></tr></table>';
e.innerHTML = cl;
}
function highlightInit() {
if (!codeoldbrowser) {
var boxes = document.getElementsByTagName('code');
for (i = 0; i < boxes.length; i++) {
switch (boxes[i].className) {
case 'no-highlight': {
break;
}
case '': {
var hl = hljs.highlightAuto(boxes[i].innerHTML);
boxes[i].parentNode.previousSibling.innerHTML += '<span class="codeboxright"> | {L_HCODE_HLJS_IDENTIFIED} {L_HCODE_HLJS_LANGUAGE}: ' + hl.language + '</span>';
break;
}
default: {
boxes[i].parentNode.previousSibling.innerHTML += '<span class="codeboxright"> | {L_HCODE_HLJS_LANGUAGE}: ' + boxes[i].className + '</span>';
break;
}
}
}
hljs.initHighlighting();
for (i = 0; i < boxes.length; i++) {
if (boxes[i].parentNode.scrollHeight > boxes[i].parentNode.offsetHeight + 1) {
boxes[i].parentNode.previousSibling.innerHTML += ' · <a href="#" name="expandCode_' + i + '" onclick="expandCode(this); return false;">{L_EXPAND_VIEW}</a>';
}
boxes[i].parentNode.previousSibling.innerHTML += ' | {L_HCODE_LINES}: <a href="#" name="linesCode_' + i + '" onclick="linesCode(this,false); return false;">{L_HCODE_NUMERATION_ON}</a> · <a href="#" name="wrapCode_' + i + '" onclick="wrapCode(this,false); return false;">{L_EXPAND_VIEW}</a>';
createlinesCode(boxes[i]);
boxes[i].style.width = boxes[i].offsetWidth + 'px';
}
}
}
onload_functions.push('highlightInit()');
// ]]>
</script>Код: Выделить всё
// Timeout to prevent quick_quote()
setTimeout(function() {
// Get ID of code block
var e;
try {
e = a.parentNode.nextSibling.firstChild.firstChild.rows[0].cells[1];
} catch(err) {
e = a.parentNode.parentNode.getElementsByTagName('CODE')[0];
}
// Not IE and IE9+
if (window.getSelection)
{
var s = window.getSelection();
// Safari
if (s.setBaseAndExtent)
{
s.setBaseAndExtent(e, 0, e, e.innerText.length - 1);
}
// Firefox and Opera
else
{
// workaround for bug # 42885
if (window.opera && e.innerHTML.substring(e.innerHTML.length - 4) == '<BR>')
{
e.innerHTML = e.innerHTML + ' ';
}
var r = document.createRange();
r.selectNodeContents(e);
s.removeAllRanges();
s.addRange(r);
}
}
// Some older browsers
else if (document.getSelection)
{
var s = document.getSelection();
var r = document.createRange();
r.selectNodeContents(e);
s.removeAllRanges();
s.addRange(r);
}
// IE
else if (document.selection)
{
var r = document.body.createTextRange();
r.moveToElementText(e);
r.select();
}
}, 0);7.1) В файле styles/subsilver2/theme/stylesheet.css найти
Код: Выделить всё
.codetitle {
margin: 10px 5px 0 5px;
padding: 2px 4px;
border-width: 1px 1px 0 1px;
border-style: solid;
border-color: #A9B8C2;
color: #333333;
background-color: #A9B8C2;
font-family: "Lucida Grande", Verdana, Helvetica, Arial, sans-serif;
font-size: 0.8em;
}
.codecontent {
direction: ltr;
margin: 0 5px 10px 5px;
padding: 5px;
border-color: #A9B8C2;
border-width: 0 1px 1px 1px;
border-style: solid;
font-weight: normal;
color: #006600;
font-size: 0.85em;
font-family: Monaco, 'Courier New', monospace;
background-color: #FAFAFA;
}Код: Выделить всё
.codebox {
direction: ltr;
margin: 10px 5px 0 5px;
padding: 2px 4px;
border-width: 1px 1px 0 1px;
border-style: solid;
border-color: #A9B8C2;
color: #333333;
background-color: #A9B8C2;
font-family: "Lucida Grande", Verdana, Helvetica, Arial, sans-serif;
font-size: 0.8em;
display: block;
}
.codebox div {
margin-bottom: 3px;
padding-left: 2px;
display: block;
color: #444;
position: relative;
}
.codeboxright {
margin: 0px;
padding: 0px;
position: absolute;
right: 20px;
}
.codebox pre {
background-color: rgba(255, 255, 255, 1.0);
/* Also see tweaks.css */
overflow: auto;
/* Making preformated <pre> text wrap in CSS3, Mozilla, Opera and IE:
http://users.tkk.fi/~tkarvine/pre-wrap-css3-mozilla-opera-ie.html */
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
height: auto;
max-height: 200px;
padding-top: 5px;
padding-bottom: 5px;
font-size: 1.2em;
font-family: Monaco, 'Courier New', monospace;
line-height: 1.3em;
color: #000;
margin: 2px 0;
-o-tab-size: 4;
-moz-tab-size: 4;
-webkit-tab-size: 4;
tab-size: 4;
}
.codebox code {
padding: 0;
background: inherit;
border: none;
font: inherit;
white-space: inherit;
word-wrap: inherit;
tab-size: inherit;
}
.codeboxlines {
text-align: right;
vertical-align: top;
}
.codeboxlinesdiv {
color: #666;
background-color: #EEE;
}Код: Выделить всё
<!-- BEGIN code_open -->
<div class="codetitle"><b>{L_CODE}:</b></div><div class="codecontent">
<!-- END code_open -->
<!-- BEGIN code_close -->
</div>
<!-- END code_close -->Код: Выделить всё
<!-- BEGIN code_open -->
<div class="codebox"><div>{L_CODE}: <a href="#" onclick="selectCode(this); return false;">{L_SELECT_ALL_CODE}</a></div><pre><code class="{LANGUAGE}">
<!-- END code_open -->
<!-- BEGIN code_close -->
</code></pre></div>
<!-- END code_close -->Код: Выделить всё
</head>Код: Выделить всё
<script type="text/javascript">
// <![CDATA[
var onload_functions = new Array();
window.onload = function()
{
for (var i = 0; i < onload_functions.length; i++)
{
eval(onload_functions[i]);
}
};
function selectCode(a)
{
// Timeout to prevent quick_quote()
setTimeout(function() {
// Get ID of code block
var e;
try {
e = a.parentNode.nextSibling.firstChild.firstChild.rows[0].cells[1];
} catch(err) {
e = a.parentNode.parentNode.getElementsByTagName('CODE')[0];
}
// Not IE and IE9+
if (window.getSelection)
{
var s = window.getSelection();
// Safari
if (s.setBaseAndExtent)
{
s.setBaseAndExtent(e, 0, e, e.innerText.length - 1);
}
// Firefox and Opera
else
{
// workaround for bug # 42885
if (window.opera && e.innerHTML.substring(e.innerHTML.length - 4) == '<BR>')
{
e.innerHTML = e.innerHTML + ' ';
}
var r = document.createRange();
r.selectNodeContents(e);
s.removeAllRanges();
s.addRange(r);
}
}
// Some older browsers
else if (document.getSelection)
{
var s = document.getSelection();
var r = document.createRange();
r.selectNodeContents(e);
s.removeAllRanges();
s.addRange(r);
}
// IE
else if (document.selection)
{
var r = document.body.createTextRange();
r.moveToElementText(e);
r.select();
}
}, 0);
}
// ]]>
</script>
<script type="text/javascript">
// <![CDATA[
var codeoldbrowser = (!('forEach' in Array.prototype) || !document.addEventListener) ? true : false;
if (!codeoldbrowser) {
document.write('<link rel="stylesheet" href="styles\/highlight\/styles\/vs.css" \/>');
document.write('<script type="text\/javascript" src="styles\/highlight\/highlight.pack.js"><\/script>');
}
function expandCode(e) {
var c = e.parentNode.nextSibling;
if (c.style.maxHeight == 'none') {
c.style.maxHeight = '200px';
e.innerHTML = '{L_EXPAND_VIEW}';
}
else {
c.style.maxHeight = 'none';
e.innerHTML = '{L_COLLAPSE_VIEW}';
}
}
function wrapCode(e,set) {
var c = e.parentNode.nextSibling;
if (set) {
c.style.wordWrap = 'normal';
c.style.whiteSpace = 'pre';
e.innerHTML = '{L_COLLAPSE_VIEW}';
}
else {
if (!(c.style.wordWrap == 'normal')){
c.style.wordWrap = 'normal';
c.style.whiteSpace = 'pre';
e.innerHTML = '{L_COLLAPSE_VIEW}';
}
else {
c.style.wordWrap = 'break-word';
c.style.whiteSpace = 'pre-wrap';
e.innerHTML = '{L_EXPAND_VIEW}';
linesCode(e.previousSibling.previousSibling,true);
}
}
}
function linesCode(e,reset) {
var c = e.parentNode.nextSibling.firstChild.firstChild;
if (reset) {
c.rows[0].cells[0].firstChild.style.display = 'none';
e.innerHTML = '{L_HCODE_NUMERATION_ON}';
}
else {
if (!(c.rows[0].cells[0].firstChild.style.display == 'none')) {
c.rows[0].cells[0].firstChild.style.display = 'none';
e.innerHTML = '{L_HCODE_NUMERATION_ON}';
}
else {
wrapCode(e.nextSibling.nextSibling,true);
c.rows[0].cells[0].firstChild.style.display = 'block';
e.innerHTML = '{L_HCODE_NUMERATION_OFF}';
}
}
}
function padlinesCode(number, len) {
var str = '' + (number+1);
for (var i=str.length; i<=len; i++) {
str = '0' + str;
}
return str;
}
function createlinesCode(e) {
String.prototype.replaceAll = function(find, replace_to) {
return this.replace(new RegExp(find, "g"), replace_to);
}
var code = e.innerHTML;
if (code.charAt(code.length - 1) == '\n') code = code.slice(0, -1);
code = code.replaceAll('\r','');
var n = 1;
for (var i=0; i<code.length; i++) {
if (code.charAt(i) == '\n') n++;
}
var len = Math.floor(Math.log(n) / Math.log(10));
if (len < 2) len = 2;
var width = len + 1;
var cl = '<table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td width="' + width + 'xm" class="codeboxlines"><div class="codeboxlinesdiv" style="display: none;">';
for (var i=0; i<n; i++) {
cl += padlinesCode(i,len) + ' \n';
}
cl += '</div></td><td>' + code + '</td></tr></table>';
e.innerHTML = cl;
}
function highlightInit() {
if (!codeoldbrowser) {
var boxes = document.getElementsByTagName('code');
for (i = 0; i < boxes.length; i++) {
switch (boxes[i].className) {
case 'no-highlight': {
break;
}
case '': {
var hl = hljs.highlightAuto(boxes[i].innerHTML);
boxes[i].parentNode.previousSibling.innerHTML += '<span class="codeboxright"> | {L_HCODE_HLJS_IDENTIFIED} {L_HCODE_HLJS_LANGUAGE}: ' + hl.language + '</span>';
break;
}
default: {
boxes[i].parentNode.previousSibling.innerHTML += '<span class="codeboxright"> | {L_HCODE_HLJS_LANGUAGE}: ' + boxes[i].className + '</span>';
break;
}
}
}
hljs.initHighlighting();
for (i = 0; i < boxes.length; i++) {
if (boxes[i].parentNode.scrollHeight > boxes[i].parentNode.offsetHeight + 1) {
boxes[i].parentNode.previousSibling.innerHTML += ' · <a href="#" name="expandCode_' + i + '" onclick="expandCode(this); return false;">{L_EXPAND_VIEW}</a>';
}
boxes[i].parentNode.previousSibling.innerHTML += ' | {L_HCODE_LINES}: <a href="#" name="linesCode_' + i + '" onclick="linesCode(this,false); return false;">{L_HCODE_NUMERATION_ON}</a> · <a href="#" name="wrapCode_' + i + '" onclick="wrapCode(this,false); return false;">{L_EXPAND_VIEW}</a>';
createlinesCode(boxes[i]);
boxes[i].style.width = boxes[i].offsetWidth + 'px';
}
}
}
onload_functions.push('highlightInit()');
// ]]>
</script>Код: Выделить всё
.code, .codecontent,Код: Выделить всё
.code, .codebox, Код: Выделить всё
.forum {Код: Выделить всё
/* Making preformated <pre> text wrap in CSS3, Mozilla, Opera and IE:
http://users.tkk.fi/~tkarvine/pre-wrap-css3-mozilla-opera-ie.html */
.codebox {
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
-o-tab-size: 4;
-moz-tab-size: 4;
-webkit-tab-size: 4;
tab-size: 4;
}Дополнительно, при необходимости, можно добавить:
- выбор темы оформления подсветки кода в админстративный раздел (Общие->Конфигурация->Функции конференции->Темы Highlight.js)
- включение/отключение автоматического определения языка (Общие->Конфигурация->Функции конференции->Автоматическое определение языка Highlight.js)
- включение/отключение разворачивания строк кода при загрузке страницы (Общие->Конфигурация->Функции конференции->HCode - разворачивать строки)
- включение/отключение нумерации строк кода при загрузке страницы (Общие->Конфигурация->Функции конференции->HCode - нумеровать строки)
Код: Выделить всё
// The following assigns all _common_ variables that may be used at any point in a template.Код: Выделить всё
if (empty($config['hljs_theme']))
{
set_config('hljs_theme', 'vs', false);
}
if (empty($config['hljs_auto']))
{
set_config('hljs_auto', '0', false);
}
if (empty($config['hljs_hcode_wrap']))
{
set_config('hljs_hcode_wrap', '0', false);
}
if (empty($config['hljs_hcode_numerate']))
{
set_config('hljs_hcode_numerate', '0', false);
}Код: Выделить всё
'SITE_DESCRIPTION' => $config['site_desc'],Код: Выделить всё
'HLJS_THEME' => $config['hljs_theme'],
'HCODE_WRAP' => $config['hljs_hcode_wrap'],
'HCODE_NUMERATE' => $config['hljs_hcode_numerate'],Код: Выделить всё
'legend2' => 'ACP_LOAD_SETTINGS',Код: Выделить всё
'hljs_theme' => array('lang' => 'HLJS_THEME_NAME', 'validate' => 'string', 'type' => 'text:40:255', 'explain' => true),
'hljs_auto' => array('lang' => 'HLJS_AUTO', 'validate' => 'bool', 'type' => 'radio:yes_no', 'explain' => true),
'hljs_hcode_wrap' => array('lang' => 'HLJS_HCODE_WRAP', 'validate' => 'bool', 'type' => 'radio:yes_no', 'explain' => true),
'hljs_hcode_numerate' => array('lang' => 'HLJS_HCODE_NUMERATE', 'validate' => 'bool', 'type' => 'radio:yes_no', 'explain' => true),Код: Выделить всё
function bbcode_second_pass_code($type, $code)
{Код: Выделить всё
global $config;Код: Выделить всё
// Autohighlight ON
//if ($type == 'off')
// Autohighlight OFF
if (empty($type) || ($type == 'off'))
{
$type = 'no-highlight';
}
Код: Выделить всё
if ($config['hljs_auto'])
{
// Autohighlight ON
if ($type == 'off')
{
$type = 'no-highlight';
}
}
else
{
// Autohighlight OFF
if (empty($type) || ($type == 'off'))
{
$type = 'no-highlight';
}
}Код: Выделить всё
?>Код: Выделить всё
// Highlight.js Themes settings
$lang = array_merge($lang, array(
'HLJS_THEME_NAME' => 'HCode - Highlight.js Themes',
'HLJS_THEME_NAME_EXPLAIN' => 'To change the theme to one of the included themes you need to specify the theme name here. A theme name is the name of the css file. So for github.css we enter simply: github .',
'HLJS_AUTO' => 'HCode - Highlight.js Automatic language detection',
'HLJS_AUTO_EXPLAIN' => 'Automatic language detection - not good idea for short code fragments. Better use custom definition.',
'HLJS_HCODE_WRAP' => 'HCode - lines wrap',
'HLJS_HCODE_WRAP_EXPLAIN' => 'Wrap code lines after page load.',
'HLJS_HCODE_NUMERATE' => 'HCode - numerate lines',
'HLJS_HCODE_NUMERATE_EXPLAIN' => 'Numerate code lines after page load.',
));Код: Выделить всё
?>Код: Выделить всё
// Highlight.js Themes settings
$lang = array_merge($lang, array(
'HLJS_THEME_NAME' => 'Темы Highlight.js',
'HLJS_THEME_NAME_EXPLAIN' => 'Для изменения темы Вы можете указать здесь её имя. Имя темы - это имя файла css в каталоге styles/highlight/styles. Например, для установки github.css задайте: github',
'HLJS_AUTO' => 'Автоматическое определение языка Highlight.js',
'HLJS_AUTO_EXPLAIN' => 'Автоматическое определение языка - не очень хорошая идея для небольших фрагментов кода. Высока вероятность ошибки.',
'HLJS_HCODE_WRAP' => 'HCode - разворачивать строки',
'HLJS_HCODE_WRAP_EXPLAIN' => 'Разворачивать строки кода при загрузке страницы.',
'HLJS_HCODE_NUMERATE' => 'HCode - нумеровать строки',
'HLJS_HCODE_NUMERATE_EXPLAIN' => 'Нумеровать строки кода при загрузке страницы.',
));Код: Выделить всё
<link rel="stylesheet" href="styles/highlight/styles/vs.css" />Код: Выделить всё
<link rel="stylesheet" href="styles/highlight/styles/{HLJS_THEME}.css" />Код: Выделить всё
hljs.initHighlighting();Код: Выделить всё
var hcode_wrap = {HCODE_WRAP};
var hcode_numerate = {HCODE_NUMERATE};Код: Выделить всё
boxes[i].parentNode.previousSibling.innerHTML += ' | {L_HCODE_LINES}: <a href="#" name="linesCode_' + i + '" onclick="linesCode(this,false); return false;">{L_HCODE_NUMERATION_ON}</a> · <a href="#" name="wrapCode_' + i + '" onclick="wrapCode(this,false); return false;">{L_EXPAND_VIEW}</a>';
createlinesCode(boxes[i]);Код: Выделить всё
boxes[i].parentNode.previousSibling.innerHTML += ' | {L_HCODE_LINES}: <a href="#" name="linesCode_' + i + '" onclick="linesCode(this,false); return false;">' + (hcode_numerate ? '{L_HCODE_NUMERATION_OFF}' : '{L_HCODE_NUMERATION_ON}') + '</a> · <a href="#" name="wrapCode_' + i + '" onclick="wrapCode(this,false); return false;">' + (hcode_wrap ? '{L_COLLAPSE_VIEW}' : '{L_EXPAND_VIEW}') + '</a>';
createlinesCode(boxes[i]);
if (hcode_wrap) wrapCode(boxes[i].parentNode.previousSibling.lastChild.previousSibling,true);
if (hcode_numerate) linesCode(boxes[i].parentNode.previousSibling.lastChild.previousSibling.previousSibling.previousSibling,false);Код: Выделить всё
document.write('<link rel="stylesheet" href="styles\/highlight\/styles\/vs.css" \/>');Код: Выделить всё
document.write('<link rel="stylesheet" href="styles\/highlight\/styles\/{HLJS_THEME}.css" \/>');Код: Выделить всё
hljs.initHighlighting();Код: Выделить всё
var hcode_wrap = {HCODE_WRAP};
var hcode_numerate = {HCODE_NUMERATE};Код: Выделить всё
boxes[i].parentNode.previousSibling.innerHTML += ' | {L_HCODE_LINES}: <a href="#" name="linesCode_' + i + '" onclick="linesCode(this,false); return false;">{L_HCODE_NUMERATION_ON}</a> · <a href="#" name="wrapCode_' + i + '" onclick="wrapCode(this,false); return false;">{L_EXPAND_VIEW}</a>';
createlinesCode(boxes[i]);Код: Выделить всё
boxes[i].parentNode.previousSibling.innerHTML += ' | {L_HCODE_LINES}: <a href="#" name="linesCode_' + i + '" onclick="linesCode(this,false); return false;">' + (hcode_numerate ? '{L_HCODE_NUMERATION_OFF}' : '{L_HCODE_NUMERATION_ON}') + '</a> · <a href="#" name="wrapCode_' + i + '" onclick="wrapCode(this,false); return false;">' + (hcode_wrap ? '{L_COLLAPSE_VIEW}' : '{L_EXPAND_VIEW}') + '</a>';
createlinesCode(boxes[i]);
if (hcode_wrap) wrapCode(boxes[i].parentNode.previousSibling.lastChild.previousSibling,linesCode(this,false); return false;true);
if (hcode_numerate) linesCode(boxes[i].parentNode.previousSibling.lastChild.previousSibling.previousSibling.previousSibling,false);Примечания:
1) Справка по структуре блока кода
Код: Выделить всё
// до выполнения createlinesCode
// <div><div><a>{e}</a></div><pre><code>{code}</code></pre></div>
// | parentNode
// | nextSibling
// | firstChild
createlinesCode(boxes[i]);
// после выполнения createlinesCode
// <div><div><a>{e}</a></div><pre><code><table><tbody><tr><td>{lines}</td><td>{code}</td></tr></tbody></table></code></pre></div>
// | parentNode
// ---------------------| nextSibling
// -----| firstChild
// ------| firstChild
// -------| firstChild
// ------| firstChild
// ----| firstChild
// --------------------| lastChild
// |-------------| rows[0]
// |-------------|---| cells[0] -----| cells[1]
Скачать highlight.js v.7.2 и 8.0 (минимальный набор языков): Спасибо Shredder'у за тестирование и участие в отладке ! Мод появился в результате попытки развития мода CodeEnhancements - расширение для тега code, см. тему на конференции Shredder'а - тынц.
Тема на моей тестовой площадке - тынц, где можно посмотреть, как выглядит переработанный код и проверить работоспособность в разных браузерах. Предупреждаю: для старых браузеров мод отключен. Кое-где код javascript и css не оптимальны. Заинтересованных прошу посмотреть...


