SynTag, Version 0.2d (alt)

Hinweis: dies ist nicht die neueste Version!

Zurück zur Übersicht

Datei: syntag/syntag.php

<?php

/*
    "SynTag" - Flocke's Syntax Highlighter

    A PHP class to create syntax highlighted HTML from sourcecode. See the
    base file "syntag.php" resp. the included file README.txt for information
    on how to use it.

    This file: syntag.php (base class definition + main include file)

    Version 0.2b - always find the latest version at
    http://flocke.vssd.de/prog/code/php/syntag/

    Copyright (C) 2005 Volker Siebert <flocke@vssd.de>
    All rights reserved.

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

define('SYNTAG_CONTEXT_SWITCH_BEGIN', '<span style="background-color:#FFEBCC;">');
define('SYNTAG_CONTEXT_SWITCH_END',   '</span>');

$SYNTAG = array();
$SYNTAG_FILES = array();
$SYNTAG_MAP = array();

class SynTag {

    /**
     * Load the language syntax definition.
     */
    function LoadLibrary($file)
    {
        global $SYNTAG_FILES;

        if (empty($file))
            return false;

        if (isset($SYNTAG_FILES[$file]))
            return $SYNTAG_FILES[$file];

        $SYNTAG_FILES[$file] = true;
        require_once($file);
        return true;
    }

    /**
     * Registers the given language(s) with their libraries and
     * matching filenames.
     */
    function RegisterLanguage($lang, $lib = '', $filematch = '')
    {
        global $SYNTAG_MAP;

        $SYNTAG_MAP[$filematch] = array(
            'f' => $lib,
            'l' => $lang,
        );
    }

    function RegisterLanguages($defs)
    {
        global $SYNTAG_MAP;

        reset($defs);
        while (list(, $value) = each($defs))
            $SYNTAG_MAP[$value['m']] = array(
                'f' => $value['f'],
                'l' => $value['l']
            );
    }

    /**
     * Load the language syntax definition.
     */
    function LoadLanguage($lang)
    {
        global $SYNTAG, $SYNTAG_MAP;

        if (empty($lang))
            return false;

        if (isset($SYNTAG[$lang]))
            return true;

        reset($SYNTAG_MAP);
        while (list($key, $value) = each($SYNTAG_MAP))
            if ($value['l'] == $lang)
            {
                SynTag::LoadLibrary($value['f']);
                return isset($SYNTAG[$lang]);
            }

        return false;
    }

    /**
     * Gets a reference to the language syntax definition. Loads the
     * definition for the language if that has not been done yet.
     */
    function &GetLanguage($lang)
    {
        global $SYNTAG;

        if (!SynTag::LoadLanguage($lang))
            $res = null;
        else
            $res =& $SYNTAG[$lang];

        return $res;
    }

    /**
     * Finds the appropriate language for the given filename
     */
    function FindLanguageForFile($file)
    {
        global $SYNTAG_MAP;

        $language = '';
        $library = '';

        reset($SYNTAG_MAP);
        while (list($key, $value) = each($SYNTAG_MAP))
            if (eregi($key, $file))
            {
                $language = $value['l'];
                $library = $value['f'];
            }

        SynTag::LoadLibrary($library);
        return $language;
    }

    /**
     * Return the item with name $name from the language $language.
     */
    function &GetItem($lang, $name)
    {
        $syn =& SynTag::GetLanguage($lang);
        return $syn['items'][$name];
    }

    /**
     * Adds the syntax for the language $lang, defined by the parameter $def.
     * If $lang is '*', then instead all elements from the array $def are
     * added recursively. If $def is null, the language is removed.
     *    This function also fixes up all required fields with default values.
     */
    function AddLanguage($lang, $def)
    {
        global $SYNTAG;

        if ($lang == '*')
        {
            reset($def);
            while (list($key, ) = each($def))
                SynTag::AddLanguage($key, $def[$key]);
            return;
        }

        if (is_null($def))
        {
            unset($SYNTAG[$lang]);
            return;
        }

        if (isset($SYNTAG[$lang]))
            return;

        $SYNTAG[$lang] =& $def;

        if (!empty($SYNTAG[$lang]['done']))
            return;

        if (!isset($SYNTAG[$lang]['flags']))
            $SYNTAG[$lang]['flags'] = '';

        if (!isset($SYNTAG[$lang]['tabs']))
            $SYNTAG[$lang]['tabs'] = 4;

        if (!isset($SYNTAG[$lang]['format']))
            $SYNTAG[$lang]['format'] = array();

        $format =& $SYNTAG[$lang]['format'];
        if (!isset($format['<']))
        {
            $add = '';
            if (isset($format['c']))
                $add .= ' class="' . $format['c'] . '"';
            if (isset($format['s']))
                $add .= ' style="' . $format['s'] . '"';
            if ($add)
            {
                $format['<'] = '<span' . $add . '>';
                $format['>'] = '</span>';
            }
        }

        if (!isset($format['<'])) $format['<'] = '';
        if (!isset($format['>'])) $format['>'] = '';

        if (!isset($SYNTAG[$lang]['items']))
            $SYNTAG[$lang]['items'] = array();

        $matches = array();

        $items =& $SYNTAG[$lang]['items'];
        reset($items);
        while (list($index, ) = each($items))
        {
            $item =& $items[$index];

            if (is_string($item))
            {
                $splat = explode('/', $item);
                $items[$index] =& SynTag::GetItem($splat[0], $splat[1]);
                $item =& $items[$index];
            }

            if (!isset($item['(']) && isset($item['k']))
            {
                $item['('] = "[[:<:]](" . str_replace('.', '\\.', join('|', $item['k'])) . ")[[:>:]]";
                $item[')'] = "";
            }

            if (!isset($item['(']) || $item['('] === '')
            {
                unset($items[$index]);
                continue;
            }

            if (!isset($item[')'])) $item[')'] = '';
            if (!isset($item['i'])) $item['i'] = '';
            if (!isset($item['o'])) $item['o'] = '';
            if (!isset($item['<'])) $item['<'] = '';
            if (!isset($item['>'])) $item['>'] = '';

            if (substr($item['('], 0, 10) == '[[:sign:]]')
            {
                if (!isset($item['c']))
                {
                    $match = '[-+]?' . substr($item['('], 10);
                    if (substr($match, -7, 7) == '[[:>:]]')
                        $match = substr($match, 0, -7);

                    $item['c'] = "^(" . $match . ")$";
                }

                $matches['([-+]|[[:<:]])' . substr($item['('], 10)] = true;
            }
            else
            {
                if (!isset($item['c']))
                {
                    $match = $item['('];
                    if (substr($match, 0, 7) == '[[:<:]]')
                        $match = substr($match, 7);
                    if (substr($match, -7, 7) == '[[:>:]]')
                        $match = substr($match, 0, -7);
                    if (substr($match, 0, 1) == '^')
                        $match = substr($match, 1);
                    if (substr($match, -1, 1) == '$' && substr($match, -2, 2) != '\\$')
                        $match = substr($match, 0, -1);
                    if (substr($match, 0, 1) == '(' && substr($match, -1, 1) == ')')
                        $match = substr($match, 1, -1);

                    $item['c'] = "^(" . $match . ")$";
                }

                $matches[$item['(']] = true;
            }
        }

        $SYNTAG[$lang]['match'] = join('|', array_keys($matches));
        $SYNTAG[$lang]['done'] = true;
    }

    function AddLanguages($defs)
    {
        reset($defs);
        while (list($key, ) = each($defs))
            SynTag::AddLanguage($key, $defs[$key]);
        return;
    }

    /**
     * Defines a new language as extension of the given old language.
     * An example for this is PHP which extends HTML.
     */
    function ExtendLanguage($oldlang, $lang, $def)
    {
        global $SYNTAG;

        $old =& SynTag::GetLanguage($oldlang);
        if (empty($old))
        {
            SynTag::AddLanguage($lang, $def);
            return;
        }

        if (!isset($def['flags']))
            $def['flags'] = $old['flags'];
        else
            $def['flags'] .= $old['flags'];

        if (!isset($def['tabs']))
            $def['tabs'] = $old['tabs'];

        if (!isset($def['items']))
            $def['items'] = array();

        reset($old['items']);
        while (list($key, $value) = each($old['items']))
            if (!isset($def['items'][$key]))
                $def['items'][$key] = $value;

        SynTag::AddLanguage($lang, $def);
    }

    /**
     * Changes all tabs in the given flat string to spaces, using the argument
     * $tabwidth as the tabulator width (normally 8 or 4). Note that it also
     * removes trailing whitespace and reduces CR/LF to simple LF.
     */
    function &TabsToSpaces(&$flat, $tabwidth)
    {
        if (strpos($flat, "\t") === false || $tabwidth < 1)
            return str_replace("\r\n", "\n", rtrim($flat));

        $lines = split("\r?\n", $flat);
        $res = '';

        $spaces = array();
        for ($k = 0; $k < $tabwidth; $k++)
            $spaces[$k] = str_pad('', $tabwidth - $k);

        $c = count($lines);
        $s = "";
        for ($k = 0; $k < $c; $k++)
        {
            $line =& $lines[$k];
            if (strpos($line, "\t") !== false)
            {
                $parts = explode("\t", $line);

                $c2 = count($parts);
                $line = $parts[0];
                for ($k2 = 1; $k2 < $c2; $k2++)
                    $line .= $spaces[strlen($line) % $tabwidth] . $parts[$k2];
            }

            $res .= $s . $line;
            $s = "\n";
        }

        return $res;
    }

    /**
     * Highlight the given block $text for the given language $language.
     * Context switches are supported (e.g. html->php / html->js).
     */
    function &_doHighlight($text, $language)    // OPT[5]
    {
        global $SYNTAG;

        if (!isset($SYNTAG[$language]))
            return htmlspecialchars($text);

        $syn =& $SYNTAG[$language]; // OPT[4]

        $mch = $syn['match'];
        if (empty($mch))
            return $syn['format']['<'] . htmlspecialchars($text) . $syn['format']['>'];

        $res = $syn['format']['<'];
        $ncs = strchr($syn['flags'], 'i') !== false;

        while ($text != '')
        {
            if ($ncs)
                $splat = spliti($mch, $text, 2);
            else
                $splat = split($mch, $text, 2);

            if (count($splat) < 2)
            {
                $res .= htmlspecialchars($text);
                break;
            }

            $res .= htmlspecialchars($splat[0]);

            $sl0 = strlen($splat[0]);
            $start = substr($text, $sl0, strlen($text) - $sl0 - strlen($splat[1]));
            $text = $splat[1];      // OPT[1]

            $item = -1;
            reset($syn['items']);
            while (list($key, $val) = each($syn['items']))
                if ($ncs ? eregi($val['c'], $start) : ereg($val['c'], $start))
                {
                    $item = $key;
                    break;
                }

            if ($item < 0)
            {
                // Internal error!
                $res .= htmlspecialchars($start);
                continue;
            }

            $val = $syn['items'][$item];
            $outer = $val['o'];

            if (empty($val[')']))
            {
                if (empty($SYNTAG[$outer]['match']))    // OPT[6]
                    $res .= $SYNTAG[$outer]['format']['<'] . htmlspecialchars($start) . $SYNTAG[$outer]['format']['>'];
                else
                    $res .= SynTag::_doHighlight($start, $outer);
            }
            else
            {
                if ($ncs)
                    $splat = spliti($val[')'], $text, 2);
                else
                    $splat = split($val[')'], $text, 2);

                if (count($splat) < 2)
                {
                    $splat[0] = $text;
                    $splat[1] = '';
                }

                $sl0 = strlen($splat[0]);
                $stop = substr($text, $sl0, strlen($text) - $sl0 - strlen($splat[1]));
                $text = $splat[1];      // OPT[1]

                if ($val['i'])
                    $res .= SynTag::_doHighlight($start, $outer)
                          . $val['<']
                          . SynTag::_doHighlight($splat[0], $val['i'])
                          . $val['>']
                          . SynTag::_doHighlight($stop, $outer);
                elseif (empty($SYNTAG[$outer]['match']))    // OPT[7]
                    $res .= $val['<'] . $SYNTAG[$outer]['format']['<']
                          . htmlspecialchars($start . $splat[0] . $stop)
                          . $SYNTAG[$outer]['format']['>'] . $val['>'];
                else
                    $res .= $val['<']
                          . SynTag::_doHighlight($start . $splat[0] . $stop, $outer)
                          . $val['>'];
            }
        }

        $res .= $syn['format']['>'];

        return $res;
    }

    /**
     * Highlight the given block $text with the given filename $file.
     */
    function &Highlight(&$text, $file)
    {
        global $SYNTAG;

        $language = SynTag::FindLanguageForFile($file);

        if (empty($language) || !isset($SYNTAG[$language]))
            return htmlspecialchars(SynTag::TabsToSpaces($text, 4));

        return SynTag::_doHighlight(SynTag::TabsToSpaces($text, $SYNTAG[$language]['tabs']), $language);
    }

    /**
     * Highlight the given block $text for the given language $language.
     * Context switches are supported (e.g. html->php / html->js).
     */
    function &HighlightLanguage($text, $language)
    {
        global $SYNTAG;

        SynTag::LoadLanguage($language);

        if (empty($language) || !isset($SYNTAG[$language]))
            return htmlspecialchars(SynTag::TabsToSpaces($text, 4));

        return SynTag::_doHighlight(SynTag::TabsToSpaces($text, $SYNTAG[$language]['tabs']), $language);
    }

    /**
     * Fix the formatted text for the case that it is not put into
     * pre-tags - replace spaces by &nbsp; and linefeeds by br-tags.
     */
    function &FixFormat(&$flat, $xhtml = true)
    {
        if ($xhtml)
            return str_replace(array("\n", "  "), array("<br/>\n", "&nbsp; "), $flat);
        else
            return str_replace(array("\n", "  "), array("<br>\n", "&nbsp; "), $flat);
    }

};

// Initialization
SynTag::AddLanguages(array(
    'all.other.files' => array(
        'file'  => '.*',
    ),

    'plain.text' => array(
        'file'  => '\.(txt)$',
        'tabs'  => 8,
    ),

    // Einfache Formate, keine inneren Gruppen oder Schlüsselworte
    '#none'     => array( 'format' => array( '<' => '', '>' => '' ) ),
    '#comment'  => array( 'format' => array( 's' => 'color:#090;' ) ),
    '#directive'=> array( 'format' => array( 's' => 'color:#099;' ) ),
    '#string'   => array( 'format' => array( 's' => 'color:#33f;' ) ),
    '#number'   => array( 'format' => array( 's' => 'color:#f06;' ) ),
    '#data'     => array( 'format' => array( 's' => 'color:#093;' ) ),
    '#keyword'  => array( 'format' => array( '<' => '<b>', '>' => '</b>' ) ),
    '#name'     => array( 'format' => array( 's' => 'color:#90c;' ) ),
    '#fatname'  => array( 'format' => array( 's' => 'color:#009; font-weight:bold;' ) ),
    '#label'    => array( 'format' => array( 's' => 'color:#c00;' ) ),
    '#variable' => array( 'format' => array( '<' => '', '>' => '' ) ),
    '#entity'   => array( 'format' => array( 's' => 'color:#090; font-weight:bold;' ) ),
));

SynTag::RegisterLanguages(array(
    array('m' => '.*',                  'f' => '',                  'l' => 'all.other.files'),
    array('m' => '\.(txt)$',            'f' => '',                  'l' => 'plain.text'),
    array('m' => '\.(asm)$',            'f' => 'syntag.asm.php',    'l' => 'assembler'),
    array('m' => '\.(c|h)$',            'f' => 'syntag.c.php',      'l' => 'c'),
    array('m' => '\.(cpp|hpp)$',        'f' => 'syntag.c.php',      'l' => 'cpp'),
    array('m' => '\.(css)$',            'f' => 'syntag.css.php',    'l' => 'stylesheet'),
    array('m' => '\.(html?)$',          'f' => 'syntag.html.php',   'l' => 'html'),
    array('m' => '\.(js)$',             'f' => 'syntag.js.php',     'l' => 'javascript'),
    array('m' => '\.(dfm)$',            'f' => 'syntag.pas.php',    'l' => 'delphi.form'),
    array('m' => '\.(pas|inc|dpr)$',    'f' => 'syntag.pas.php',    'l' => 'pascal'),
    array('m' => '\.(php[3-5]?)$',      'f' => 'syntag.php.php',    'l' => 'php'),
));

/*
    Optimizing trials:

    OPT[1]  Changing the assignment from "$text = $splat[1]" to a reference
            "$text =& $splat[1]" made the code ~63% slower.
            -> Removed.

    OPT[2]  Using constants as array indexes made the code ~5% slower, changing
            them to numerical values increased by ~5% again, useless.
            -> Removed.

    OPT[3]  Changed later to OPT[6] and OPT[7].

    OPT[4]  Using a reference at "$syn =& $SYNTAG[$language]" is ~1,8% faster.
            -> Kept.

    OPT[5]  Removing the reference on the return value of HighlightLanguage
            made the code ~1,6% slower.
            -> Removed.

    OPT[6]  Checking for format-only elements to avoid recursion made the
            code ~11,5 faster.
            -> Kept.

    OPT[7]  Doing the same for elements with begin/end resulted in no
            significant speed-up but reduced recursion significantly.
            -> Kept.

    OPT[8]  In syntax definitions, items with begin/end like "//"->"\n" are
            about 10% faster than writing it as a single element like
            "//[^\n]*\n".
*/

?>
Flocke's Garage
Valid HTML 4.01 Transitional Valid CSS!
(C) 2005-2018 Volker Siebert.
Creative Commons-LizenzvertragDer gesamte Inhalt dieser Webseite steht unter einer Creative Commons-Lizenz (sofern nicht anders angegeben).