Empire CMS 8.0: Syntax Highlighting for Code Blocks in Post Content (CKEditor)

Unzip the archive linked at the end of this post, then upload the codesnippet folder to: ./eadmin/admin/ecmseditor/infoeditor/plugins/ (if you've renamed the eadmin and admin folders, put it in your renamed folders).

Upload these three files — monokai-sublime.min.css, highlight.min.js, and highlightjs-line-numbers.js — to a suitable folder in your site directory. The front end loads all three, so they don't belong under the admin directory.

Replace ./eadmin/admin/ecmseditor/infoeditor/config.js with the following:

function EcmsEditorDoCKhtml(htmlstr){
    if(htmlstr.indexOf('"')!=-1){return '';}
    if(htmlstr.indexOf("'")!=-1){return '';}
    if(htmlstr.indexOf("/")!=-1){return '';}
    if(htmlstr.indexOf("\\")!=-1){return '';}
    if(htmlstr.indexOf("[")!=-1){return '';}
    if(htmlstr.indexOf("]")!=-1){return '';}
    if(htmlstr.indexOf(":")!=-1){return '';}
    if(htmlstr.indexOf("%")!=-1){return '';}
    if(htmlstr.indexOf("<")!=-1){return '';}
    if(htmlstr.indexOf(">")!=-1){return '';}
    return htmlstr;
}
 
function EcmsEditorGetCs(){
    var js=document.getElementsByTagName("script");
    for(var i=0;i<js.length;i++)
    {
        if(js[i].src.indexOf("ckeditor.js")>=0)
        {
            var arraytemp=new Array();
            arraytemp=js[i].src.split('?');
            return arraytemp;
        }
    }
}
 
var arraycs=new Array();
arraycs=EcmsEditorGetCs();
arraycs[0]=arraycs[0].replace('infoeditor/ckeditor.js','');
arraycs[1]=document.getElementById('doecmseditor_eaddcs').value;
arraycs[1]=EcmsEditorDoCKhtml(arraycs[1]);
 
CKEDITOR.editorConfig = function( config ) {
 
    config.filebrowserImageUploadUrl = '';
    config.filebrowserFlashUploadUrl = arraycs[0];
    config.filebrowserImageBrowseUrl = arraycs[1];
    config.filebrowserFlashBrowseUrl = arraycs[1];
 
    config.enterMode = CKEDITOR.ENTER_BR;
    config.shiftEnterMode = CKEDITOR.ENTER_P;
 
    config.allowedContent = true;
 
    config.font_names='SimSun/SimSun;SimHei/SimHei;FangSong/FangSong_GB2312;KaiTi/KaiTi_GB2312;LiSu/LiSu;YouYuan/YouYuan;Microsoft YaHei/Microsoft YaHei;'+config.font_names;
 
    config.extraPlugins = 'codesnippet,etranfile,etranmedia,etranmore,autoformat,ecleanalltext,einsertbr,einsertpage,einserttime,equotetext';
 
    config.codeSnippet_theme = 'monokai_sublime';
 
    config.toolbar_full = [
        { name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source', '-', 'Preview', 'Print' ] },
        { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
        { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl' ] },
        '/',
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'CopyFormatting', 'RemoveFormat', 'ecleanalltext', 'autoformat' ] },
        { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
        { name: 'insert', items: [ 'Image', 'etranmore', 'Flash', 'etranmedia', 'etranfile', '-', 'Table', 'HorizontalRule', 'SpecialChar', 'equotetext', 'einserttime', 'einsertpage', 'einsertbr', '-', 'CodeSnippet' ] },
        '/',
        { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize' ] },
        { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
        { name: 'tools', items: [ 'ShowBlocks', 'NewPage', 'Templates' ] },
        { name: 'others', items: [ '-' ] },
        { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ], items: [ 'Find', 'Replace', '-', 'SelectAll', 'Maximize' ] }
    ];
 
    config.toolbar_basic = [
        { name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source' ] },
        { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
        { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
        { name: 'insert', items: [ 'Image', 'Table', 'HorizontalRule', 'SpecialChar' ] },
        { name: 'tools', items: [ 'Maximize' ] },
        { name: 'others', items: [ '-' ] },
        '/',
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Strike', '-', 'CopyFormatting', 'RemoveFormat' ] },
        { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote' ] },
        { name: 'styles', items: [ 'Styles', 'Format' ] }
    ];
 
    config.toolbar = 'full';
};

Then open the news content template you're using and add this where it fits:

<!-- Scripts that load the syntax highlighter -->  
<link rel="stylesheet" href="[!--news.url--]css/monokai-sublime.min.css">
<script src="[!--news.url--]js/highlight.min.js"></script>
<script src="[!--news.url--]js/highlightjs-line-numbers.js"></script>
<script>document.addEventListener("DOMContentLoaded",()=>{hljs.highlightAll();hljs.initLineNumbersOnLoad?.({singleLine:!0,startFrom:1});document.querySelectorAll("pre").forEach(p=>{if(p.dataset.wrapped)return;p.dataset.wrapped="1";const w=document.createElement("div");w.className="code-wrapper";const h=document.createElement("div");h.className="code-header";const t=document.createElement("span");t.className="title";const c=p.querySelector("code");let lang="CODE";if(c){const m=c.className.match(/language-(html|xml|css|js|javascript|php|java|python|json|sql|bash|shell|cpp|csharp|go|ruby|swift|kotlin|typescript|apache|coffeescript|cs|diff|http|ini|makefile|markdown|nginx|objectivec|perl|vbscript|xhtml)/i);lang=m?m[1].toUpperCase().replace("JAVASCRIPT","JS").replace("COFFEESCRIPT","CoffeeScript").replace("OBJECTIVEC","Objective-C").replace("VBSCRIPT","VBScript"):lang}t.textContent=lang + ": ";const b=document.createElement("button");b.className="copy-btn";b.textContent="Copy";h.append(t,b);p.parentNode.insertBefore(w,p);w.append(h,p);b.onclick=()=>{const txt=c?.innerText.trim()??"",clip=navigator.clipboard;if(clip&&clip.writeText)clip.writeText(txt).then(()=>{b.textContent="Copied!";b.style.color="#4caf50";setTimeout(()=>{b.textContent="Copy";b.style.color=""},2000)}).catch(()=>fallback(txt,b));else fallback(txt,b)};function fallback(t,b){const ta=document.createElement("textarea");ta.value=t;ta.style.position="fixed";ta.style.opacity="0";document.body.appendChild(ta);ta.focus();ta.select();try{document.execCommand("copy")?(b.textContent="Copied!",b.style.color="#4caf50",setTimeout(()=>{b.textContent="Copy";b.style.color=""},2000)):(alert("Copy failed. Please select the text manually."))}catch(e){alert("Copy failed. Please select the text manually.")}document.body.removeChild(ta)}})});</script>

Clear the cache in both your browser and the Empire admin panel, and the install is done. When editing in the admin panel, it's still worth picking the code language by hand — automatic detection occasionally gets it wrong.

Attachment: Syntax highlighting for ECMS post content

Original thread: http://bbs.phome.net/showthread-42-368142-0.html

Leave a Comment

Comments No Comments

Table of Contents