Friday 3 July 2009

Finest code syntax highlighter

Quotation from the Code Syntax Highlighter, the homepage of the project, allowing to embed colorizing of text and fully written on Javascript.
SyntaxHighlighter is a fully functional self-contained code syntax highlighter developed in JavaScript.
It is really true! It is very useful, very flexible and easy to customize. The main idea is to use so-named brushes to colorize codes within <pre /> tags (it is defined by default and customizable too!). Colorizing is simple. You have to link scripts and styles to your pages and add brush via class attribute (like this class="brush:js" for colorizing of Javascript codes).
I decided to use it in my blog and found that it works fine. Unfortunately there is no brushes for cmd/bat scripts and i have implemented this embedding to the blog's layout the code from below.
SyntaxHighlighter.brushes.Cmd = function()
{
    var commands = 'ASSOC AT ATTRIB BREAK BCDEDIT CACLS CD CHCP CHDIR CHKDSK CHKNTFS CLS CMD COLOR COMP COMPACT CONVERT '
                 + 'COPY DATE DEL DIR DISKCOMP DISKCOPY DISKPART DOSKEY DRIVERQUERY ECHO ERASE FC FIND FINDSTR FORMAT '
                 + 'FSUTIL FTYPE GPRESULT GRAFTABL HELP ICACLS LABEL MD MKDIR MKLINK MODE MORE MOVE OPENFILES PATH PAUSE '
                 + 'POPD PRINT PROMPT PUSHD RD RECOVER REN RENAME REPLACE RMDIR ROBOCOPY SC SCHTASKS SHIFT SHUTDOWN SORT '
                 + 'START SUBST SYSTEMINFO TASKLIST TASKKILL TIME TITLE TREE TYPE VER VERIFY VOL XCOPY WMIC';

    var keywords = 'CALL CON DEFINED DO ELSE ENABLEDELAYEDEXPANSION ENABLEEXTENSIONS EXIST EXIT ENDLOCAL FOR GOTO IF IN '
                 + 'NOT NUL REM SET SETLOCAL';

    var variables = 'ALLUSERSPROFILE APPDATA CommonProgramFiles CommonProgramFiles(x86) CommonProgramW6432 COMPUTERNAME '
                  + 'ComSpec HOMEDRIVE HOMEPATH LOCALAPPDATA LOGONSERVER NUMBER_OF_PROCESSORS OS Path PATHEXT '
                  + 'PROCESSOR_ARCHITECTURE PROCESSOR_IDENTIFIER PROCESSOR_LEVEL PROCESSOR_REVISION ProgramData '
                  + 'ProgramFiles ProgramFiles(x86) ProgramW6432 PROMPT PUBLIC SESSIONNAME SystemDrive SystemRoot TEMP '
                  + 'TMP USERDNSDOMAIN USERDOMAIN USERDOMAIN_ROAMINGPROFILE USERNAME USERPROFILE windir';

    this.regexList = [
        //
        // REM Comments
        //
        {
            regex: /(^::|rem).*$/gmi,
            css: 'comments'
        },

        //
        // "Strings"
        // 'Strings'
        // `Strings`
        // ECHO String
        //
        {
            regex: SyntaxHighlighter.regexLib.doubleQuotedString,
            css: 'string' 
        },
        {
            regex: SyntaxHighlighter.regexLib.singleQuotedString,
            css: 'string' 
        },
        {
            regex: /`(?:\.|(\\\`)|[^\``\n])*`/g,
            css: 'string' 
        },
        {
            regex: /echo.*$/gmi,
            css: 'string'
        },

        //
        // :Labels
        //
        {
            regex: /^:.+$/gmi,
            css: 'color3' 
        },

        //
        // %Variables%
        // !Variables!
        //
        {
            regex: /(%|!)\w+\1/gmi,
            css: 'variable'
        },

        //
        // %%a variable Refs
        // %1 variable Refs
        //
        {
            regex: /%\*|%%?~?[fdpnxsatz]*[0-9a-z]\b/gmi,
            css: 'variable' 
        },

        //
        // keywords
        //
        {
            regex: new RegExp(this.getKeywords(commands), 'gmi'),
            css: 'keyword'
        },

        //
        // keywords
        //
        {
            regex: new RegExp(this.getKeywords(keywords), 'gmi'),
            css: 'keyword' 
        }
    ];
};

SyntaxHighlighter.brushes.Cmd.prototype = new SyntaxHighlighter.Highlighter();
SyntaxHighlighter.brushes.Cmd.aliases = ['bat', 'cmd', 'batch'];

8 comments:

  1. I love those good old Batch files! They can be life savers for those little repetitive tasks we find ourselves doing so often.

    Hope you don't mind that I added your script to my overview of SyntaxHighlighter brushes here: http://www.undermyhat.org/blog/2009/09/list-of-brushes-syntaxhighligher/, of course with the proper credits. Please let me know if this is ok, otherwise I'll remove it instantly.

    ReplyDelete
  2. Hi Abel,

    Many thanks for publishing of these little pieces for the large work like the SyntaxHighlighter.

    ReplyDelete
  3. Добрый день!

    Не объясните ли "на пальцах" как правильно запихнуть это в SyntaxHighlighter?

    ReplyDelete
  4. Как добавить SyntaxHighlighter читайте на сайте автора. Как добавить ЭТОТ код - смотрите в исходники этого сайта.

    ReplyDelete
  5. Hello:

    Thanks for the brush. I wish they would install this as a default. I wrote some instructions for installing your brush. See http://sysadmin-e.com/notes-syntaxhighlighter.

    ReplyDelete
  6. Hope, this brush is useful for your blog and it's readers.

    ReplyDelete
  7. Thanks for the script. Got it installed and it works for the better part.
    Its coming up with inconsistent results when using the :: as comments however REM works fine. bizzare and i couldnt work it out.

    Your help appreciated.

    ReplyDelete
    Replies
    1. Hi Ivan,

      Could you be so kind as to explain where is the problem? This script takes in account comments starting both with REM and ::.

      Delete