root/codingteam/codingbin/lib/geshi/geshi.php.#.1.2 @ 1

Revision 1, 76.8 kB (checked in by elghinn, 3 years ago)

* initial import

Line 
1<?php
2/*************************************************************************************
3 * geshi.php
4 * ---------
5 * Author: Nigel McNie (oracle.shinoda@gmail.com)
6 * Copyright: (c) 2004 Nigel McNie
7 * Release Version: 1.0.6
8 * CVS Revision Version: $Revision: 1.2 $
9 * Date Started: 2004/05/20
10 * Last Modified: $Date: 2006/04/04 22:20:17 $
11 *
12 * The GeSHi class for Generic Syntax Highlighting. Please refer to the documentation
13 * at http://qbnz.com/highlighter/documentation.php for more information about how to
14 * use this class.
15 *
16 * For changes, release notes, TODOs etc, see the relevant files in the docs/ directory
17 *
18 *************************************************************************************
19 *
20 *     This file is part of GeSHi.
21 *
22 *   GeSHi is free software; you can redistribute it and/or modify
23 *   it under the terms of the GNU General Public License as published by
24 *   the Free Software Foundation; either version 2 of the License, or
25 *   (at your option) any later version.
26 *
27 *   GeSHi is distributed in the hope that it will be useful,
28 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
29 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
30 *   GNU General Public License for more details.
31 *
32 *   You should have received a copy of the GNU General Public License
33 *   along with GeSHi; if not, write to the Free Software
34 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
35 *
36 ************************************************************************************/
37
38
39//
40// GeSHi Constants
41// You should use these constant names in your programs instead of
42// their values - you never know when a value may change in a future
43// version
44//
45
46// For the future (though this may never be realised)
47define('GESHI_OUTPUT_HTML', 0);
48
49// Shouldn't be used by your program
50define('GESHI_COMMENTS', 0);
51
52// Error detection - use these to analyse faults
53define('GESHI_ERROR_NO_INPUT', 1);
54define('GESHI_ERROR_NO_SUCH_LANG', 2);
55define('GESHI_ERROR_FILE_NOT_READABLE', 3);
56// Human error messages - added in 1.0.2
57$_GESHI_ERRORS = array(
58        GESHI_ERROR_NO_INPUT => 'No source code inputted',
59        GESHI_ERROR_NO_SUCH_LANG => 'GeSHi could not find the language {LANGUAGE} (using path {PATH})',
60        GESHI_ERROR_FILE_NOT_READABLE => 'The file specified for load_from_file was not readable'
61);
62
63// Line numbers - use with enable_line_numbers()
64define('GESHI_NO_LINE_NUMBERS', 0);
65define('GESHI_NORMAL_LINE_NUMBERS', 1);
66define('GESHI_FANCY_LINE_NUMBERS', 2);
67
68// Strict mode - shouldn't be used by your scripts
69define('GESHI_NEVER', 0);
70define('GESHI_MAYBE', 1);
71define('GESHI_ALWAYS', 2);
72
73// Container HTML type - use these (added in 1.0.1)
74define('GESHI_HEADER_DIV', 1);
75define('GESHI_HEADER_PRE', 2);
76
77// Capatalisation constants - use these (added in 1.0.1)
78define('GESHI_CAPS_NO_CHANGE', 0);
79define('GESHI_CAPS_UPPER', 1);
80define('GESHI_CAPS_LOWER', 2);
81
82// Link style constants - use these (added in 1.0.2)
83define('GESHI_LINK', 0);
84define('GESHI_HOVER', 1);
85define('GESHI_ACTIVE', 2);
86define('GESHI_VISITED', 3);
87
88// Important string starter/finisher - use these (added in 1.0.2).
89// Note that if you change these, they should be as-is: i.e., don't
90// write them as if they had been run through @htmlentities()
91define('GESHI_START_IMPORTANT', '<BEGIN GeSHi>');
92define('GESHI_END_IMPORTANT', '<END GeSHi>');
93
94// Advanced regexp handling - don't use these (added in 1.0.2)
95define('GESHI_SEARCH', 0);
96define('GESHI_REPLACE', 1);
97define('GESHI_MODIFIERS', 2);
98define('GESHI_BEFORE', 3);
99define('GESHI_AFTER', 4);
100
101// Begin Class GeSHi
102class GeSHi
103{
104        //
105        // Data Fields
106        //
107
108        // Basic fields
109        var $source = '';                     // The source code to highlight
110        var $language = '';                   // The language to use when highlighting
111        var $language_data = array();         // The data for the language used
112        var $language_path = 'geshi/';        // The path to the language files
113        var $error = false;                   // The error message associated with an error
114        var $strict_mode = false;             // Whether highlighting is strict or not
115        var $use_classes = false;             // Whether to use classes
116        var $header_type = GESHI_HEADER_PRE;  // The type of header to use
117        var $lexic_permissions = array();     // Array of permissions for which lexics should be highlighted
118        // Added in 1.0.2 basic fields
119        var $time = 0;                        // The time it took to parse the code
120        var $header_content = '';             // The content of the header block
121        var $footer_content = '';             // The content of the footer block
122        var $header_content_style = '';       // The style of the header block
123        var $footer_content_style = '';       // The style of the footer block
124        var $link_styles = array();           // The styles for hyperlinks in the code
125        var $enable_important_blocks = true;  // Whether important blocks should be recognised or not
126        var $important_styles = 'font-weight: bold; color: red;'; // Styles for important parts of the code
127        var $add_ids = false;                 // Whether css IDs should be added to the code
128        var $highlight_extra_lines = array(); // Lines that should be highlighted extra
129        var $highlight_extra_lines_style = 'color: #cc0; background-color: #ffc;';// Styles of extra-highlighted lines
130        var $line_numbers_start = 1;          // Number at which line numbers should start at
131
132        // Style fields
133        var $overall_style = '';              // The overall style for this code block
134        // The style for the actual code
135        var $code_style = 'font-family: \'Courier New\', Courier, monospace; font-weight: normal;';
136        var $overall_class = '';              // The overall class for this code block
137        var $overall_id = '';                 // The overall id for this code block
138        // Line number styles
139        var $line_style1 = 'font-family: \'Courier New\', Courier, monospace; color: black; font-weight: normal; font-style: normal;';
140        var $line_style2 = 'font-weight: bold;';
141        var $line_numbers = GESHI_NO_LINE_NUMBERS; // Flag for how line numbers are displayed
142        var $line_nth_row = 0;                // The "nth" value for fancy line highlighting
143
144        // Misc
145        var $tab_width = 8;                   // A value for the size of tab stops.
146        var $max_tabs = 20;                   // Maximum number of spaces per tab
147        var $min_tabs = 0;                    // Minimum  "   "    "    "    "
148        var $link_target = '';                // default target for keyword links
149        var $encoding = 'ISO-8859-1';         // The encoding to use for @htmlentities() calls
150
151        // Deprecated/unused
152        var $output_format = GESHI_OUTPUT_HTML;
153
154
155        /**
156         * constructor: GeSHi
157         * ------------------
158         * Creates a new GeSHi object, with source and language
159         */
160        function GeSHi ($source, $language, $path = 'geshi/')
161        {
162                $this->source = $source;
163                // Security, just in case :)
164                $language = preg_replace('#[^a-zA-Z0-9\-\_]#', '', $language);
165                $this->language = strtolower($language);
166                $this->language_path = ( substr($path, strlen($path) - 1, 1) == '/' ) ? $path : $path . '/';
167                $this->load_language();
168        }
169
170
171        //
172        // Error methods
173        //
174
175        /**
176         * method: error
177         * -------------
178         * Returns an error message associated with the last GeSHi operation,
179         * or false if no error has occured
180         */
181        function error()
182        {
183                global $_GESHI_ERRORS;
184                if ( $this->error != 0 )
185                {
186                        $msg = $_GESHI_ERRORS[$this->error];
187                        $debug_tpl_vars = array(
188                                '{LANGUAGE}' => $this->language,
189                                '{PATH}' => $this->language_path
190                        );
191                        foreach ( $debug_tpl_vars as $tpl => $var )
192                        {
193                                $msg = str_replace($tpl, $var, $msg);
194                        }
195                        return "<br /><strong>GeSHi Error:</strong> $msg (code $this->error)<br />";
196                }
197                return false;
198        }
199
200
201        //
202        // Getters
203        //
204
205        /**
206         * get_language_name()
207         * ---------------
208         * Gets a human-readable language name (thanks to Simon Patterson
209         * for the idea :))
210         */
211        function get_language_name()
212        {
213                if ( $this->error == GESHI_ERROR_NO_SUCH_LANG )
214                {
215                        return $this->language_data['LANG_NAME'] . ' (Unknown Language)';
216                }
217                return $this->language_data['LANG_NAME'];
218        }
219
220
221        //
222        // Setters
223        //
224
225        /**
226         * method: set_source
227         * ------------------
228         * Sets the source code for this object
229         */
230        function set_source ( $source )
231        {
232                $this->source = $source;
233        }
234
235
236        /**
237         * method: set_language
238         * --------------------
239         * Sets the language for this object
240         */
241        function set_language ( $language )
242        {
243                $language = preg_replace('#[^a-zA-Z0-9\-_]#', '', $language);
244                $this->language = strtolower($language);
245                // Load the language for parsing
246                $this->load_language();
247        }
248
249
250        /**
251         * method: set_language_path
252         * -------------------------
253         * Sets the path to the directory containing the language files. NOTE
254         * that this path is relative to the directory of the script that included
255         * geshi.php, NOT geshi.php itself.
256         */
257        function set_language_path ( $path )
258        {
259                $this->language_path = ( substr($path, strlen($path) - 1, 1) == '/' ) ? $path : $path . '/';
260        }
261
262
263        /**
264         * method: set_header_type
265         * -----------------------
266         * Sets the type of header to be used. If GESHI_HEADER_DIV is used,
267         * the code is surrounded in a <div>. This means more source code but
268         * more control over tab width and line-wrapping. GESHI_HEADER_PRE
269         * means that a <pre> is used - less source, but less control. Default
270         * is GESHI_HEADER_PRE
271         */
272        function set_header_type ( $type )
273        {
274                $this->header_type = $type;
275        }
276
277
278        /**
279         * method: set_overall_style
280         * -------------------------
281         * Sets the styles for the code that will be outputted
282         * when this object is parsed. The style should be a
283         * string of valid stylesheet declarations
284         */
285        function set_overall_style ( $style, $preserve_defaults = false )
286        {
287                if ( $preserve_defaults )
288                {
289                        $this->overall_style .= $style;
290                }
291                else
292                {
293                        $this->overall_style = $style;
294                }
295        }
296
297
298        /**
299         * method: set_overall_class
300         * -------------------------
301         * Sets the overall classname for this block of code. This
302         * class can then be used in a stylesheet to style this object's
303         * output
304         */
305        function set_overall_class ( $class )
306        {
307                $this->overall_class = $class;
308        }
309
310
311        /**
312         * method: set_overall_id
313         * ----------------------
314         * Sets the overall id for this block of code. This id can then
315         * be used in a stylesheet to style this object's output
316         */
317        function set_overall_id ( $id )
318        {
319                $this->overall_id = $id;
320        }
321
322
323        /**
324         * method: enable_classes
325         * ----------------------
326         * Sets whether CSS classes should be used to highlight the source. Default
327         * is off, calling this method with no arguments will turn it on
328         */
329        function enable_classes ( $flag = true )
330        {
331                $this->use_classes = ( $flag ) ? true : false;
332        }
333
334
335        /**
336         * method: set_code_style
337         * ----------------------
338         * Sets the style for the actual code. This should be a string
339         * containing valid stylesheet declarations. If $preserve_defaults is
340         * true, then styles are merged with the default styles, with the
341         * user defined styles having priority
342         *
343         * NOTE: Use this method to override any style changes you made to
344         * the line numbers if you are using line numbers, else the line of
345         * code will have the same style as the line number! Consult the
346         * GeSHi documentation for more information about this.
347         */
348        function set_code_style ( $style, $preserve_defaults )
349        {
350                if ( $preserve_defaults )
351                {
352                        $this->code_style .= $style;
353                }
354                else
355                {
356                        $this->code_style = $style;
357                }
358        }
359
360
361        /**
362         * method: set_line_style
363         * ----------------------
364         * Sets the styles for the line numbers. This should be a string
365         * containing valid stylesheet declarations. If $preserve_defaults is
366         * true, then styles are merged with the default styles, with the
367         * user defined styles having priority
368         */
369        function set_line_style ( $style1, $style2 = '', $preserve_defaults = false )
370        {
371                if ( is_bool($style2) )
372                {
373                        $preserve_defaults = $style2;
374                        $style2 = '';
375                }
376                if ( $preserve_defaults )
377                {
378                        $this->line_style1 .= $style1;
379                        $this->line_style2 .= $style2;
380                }
381                else
382                {
383                        $this->line_style1 = $style1;
384                        $this->line_style2 = $style2;
385                }
386        }
387
388
389        /**
390         * method: enable_line_numbers
391         * ---------------------------
392         * Sets whether line numbers should be displayed. GESHI_NO_LINE_NUMBERS = not displayed,
393         * GESHI_NORMAL_LINE_NUMBERS = displayed, GESHI_FANCY_LINE_NUMBERS = every nth line a
394         * different class. Default is for no line numbers to be used
395         */
396        function enable_line_numbers ( $flag, $nth_row = 5 )
397        {
398                $this->line_numbers = $flag;
399                $this->line_nth_row = $nth_row;
400        }
401
402
403        /**
404         * method: set_keyword_group_style
405         * -------------------------------
406         * Sets the style for a keyword group. If $preserve_defaults is
407         * true, then styles are merged with the default styles, with the
408         * user defined styles having priority
409         */
410        function set_keyword_group_style ( $key, $style, $preserve_defaults = false )
411        {
412                if ( $preserve_defaults )
413                {
414                        $this->language_data['STYLES']['KEYWORDS'][$key] .= $style;
415                }
416                else
417                {
418                        $this->language_data['STYLES']['KEYWORDS'][$key] = $style;
419                }
420        }
421
422
423        /**
424         * method: set_keyword_group_highlighting
425         * --------------------------------------
426         * Turns highlighting on/off for a keyword group
427         */
428        function set_keyword_group_highlighting ( $key, $flag = true )
429        {
430                $this->lexic_permissions['KEYWORDS'][$key] = ( $flag ) ? true : false;
431        }
432
433
434        /**
435         * method: set_comments_style
436         * --------------------------
437         * Sets the styles for comment groups.  If $preserve_defaults is
438         * true, then styles are merged with the default styles, with the
439         * user defined styles having priority
440         */
441        function set_comments_style ( $key, $style, $preserve_defaults = false )
442        {
443                if ( $preserve_defaults )
444                {
445                        $this->language_data['STYLES']['COMMENTS'][$key] .= $style;
446                }
447                else
448                {
449                        $this->language_data['STYLES']['COMMENTS'][$key] = $style;
450                }
451        }
452
453
454        /**
455         * method: set_comments_highlighting
456         * ---------------------------------
457         * Turns highlighting on/off for comment groups
458         */
459        function set_comments_highlighting ( $key, $flag = true )
460        {
461                $this->lexic_permissions['COMMENTS'][$key] = ( $flag ) ? true : false;
462        }
463
464
465        /**
466         * method: set_escape_characters_style
467         * -----------------------------------
468         * Sets the styles for escaped characters. If $preserve_defaults is
469         * true, then styles are merged with the default styles, with the
470         * user defined styles having priority
471         */
472        function set_escape_characters_style ( $style, $preserve_defaults = false )
473        {
474                if ( $preserve_defaults )
475                {
476                        $this->language_data['STYLES']['ESCAPE_CHAR'][0] .= $style;
477                }
478                else
479                {
480                        $this->language_data['STYLES']['ESCAPE_CHAR'][0] = $style;
481                }
482        }
483
484
485        /**
486         * method: set_escape_characters_highlighting
487         * ------------------------------------------
488         * Turns highlighting on/off for escaped characters
489         */
490        function set_escape_characters_highlighting ( $flag = true )
491        {
492                $this->lexic_permissions['ESCAPE_CHAR'] = ( $flag ) ? true : false;
493        }
494
495
496        /**
497         * method: set_brackets_style
498         * --------------------------
499         * Sets the styles for brackets. If $preserve_defaults is
500         * true, then styles are merged with the default styles, with the
501         * user defined styles having priority
502         *
503         * This method is DEPRECATED: use set_symbols_style instead.
504         * This method will be removed in 1.2.X
505         */
506        function set_brackets_style ( $style, $preserve_defaults = false )
507        {
508                if ( $preserve_defaults )
509                {
510                        $this->language_data['STYLES']['BRACKETS'][0] .= $style;
511                }
512                else
513                {
514                        $this->language_data['STYLES']['BRACKETS'][0] = $style;
515                }
516        }
517
518
519        /**
520         * method: set_brackets_highlighting
521         * ---------------------------------
522         * Turns highlighting on/off for brackets
523         *
524         * This method is DEPRECATED: use set_symbols_highlighting instead.
525         * This method will be remove in 1.2.X
526         */
527        function set_brackets_highlighting ( $flag )
528        {
529                $this->lexic_permissions['BRACKETS'] = ( $flag ) ? true : false;
530        }
531
532
533        /**
534         * method: set_symbols_style
535         * --------------------------
536         * Sets the styles for symbols. If $preserve_defaults is
537         * true, then styles are merged with the default styles, with the
538         * user defined styles having priority
539         */
540        function set_symbols_style ( $style, $preserve_defaults = false )
541        {
542                if ( $preserve_defaults )
543                {
544                        $this->language_data['STYLES']['SYMBOLS'][0] .= $style;
545                }
546                else
547                {
548                        $this->language_data['STYLES']['SYMBOLS'][0] = $style;
549                }
550                // For backward compatibility
551                $this->set_brackets_style ( $style, $preserve_defaults );
552        }
553
554
555        /**
556         * method: set_symbols_highlighting
557         * ---------------------------------
558         * Turns highlighting on/off for symbols
559         */
560        function set_symbols_highlighting ( $flag )
561        {
562                $this->lexic_permissions['SYMBOLS'] = ( $flag ) ? true : false;
563                // For backward compatibility
564                $this->set_brackets_highlighting ( $flag );
565        }
566
567
568        /**
569         * method: set_strings_style
570         * -------------------------
571         * Sets the styles for strings. If $preserve_defaults is
572         * true, then styles are merged with the default styles, with the
573         * user defined styles having priority
574         */
575        function set_strings_style ( $style, $preserve_defaults = false )
576        {
577                if ( $preserve_defaults )
578                {
579                        $this->language_data['STYLES']['STRINGS'][0] .= $style;
580                }
581                else
582                {
583                        $this->language_data['STYLES']['STRINGS'][0] = $style;
584                }
585        }
586
587
588        /**
589         * method: set_strings_highlighting
590         * --------------------------------
591         * Turns highlighting on/off for strings
592         */
593        function set_strings_highlighting ( $flag )
594        {
595                $this->lexic_permissions['STRINGS'] = ( $flag ) ? true : false;
596        }
597
598
599        /**
600         * method: set_numbers_style
601         * -------------------------
602         * Sets the styles for numbers. If $preserve_defaults is
603         * true, then styles are merged with the default styles, with the
604         * user defined styles having priority
605         */
606        function set_numbers_style ( $style, $preserve_defaults = false )
607        {
608                if ( $preserve_defaults )
609                {
610                        $this->language_data['STYLES']['NUMBERS'][0] .= $style;
611                }
612                else
613                {
614                        $this->language_data['STYLES']['NUMBERS'][0] = $style;
615                }
616        }
617
618
619        /**
620         * method: set_numbers_highlighting
621         * --------------------------------
622         * Turns highlighting on/off for numbers
623         */
624        function set_numbers_highlighting ( $flag )
625        {
626                $this->lexic_permissions['NUMBERS'] = ( $flag ) ? true : false;
627        }
628
629
630        /**
631         * method: set_methods_style
632         * -------------------------
633         * Sets the styles for methods. $key is a number that references the
634         * appropriate "object splitter" - see the language file for the language
635         * you are highlighting to get this number. If $preserve_defaults is
636         * true, then styles are merged with the default styles, with the
637         * user defined styles having priority
638         */
639        function set_methods_style ( $key, $style, $preserve_defaults = false )
640        {
641                if ( $preserve_defaults )
642                {
643                        $this->language_data['STYLES']['METHODS'][$key] .= $style;
644                }
645                else
646                {
647                        $this->language_data['STYLES']['METHODS'][$key] = $style;
648                }
649        }
650
651
652        /**
653         * method: set_methods_highlighting
654         * --------------------------------
655         * Turns highlighting on/off for methods
656         */
657        function set_methods_highlighting ( $flag )
658        {
659                $this->lexic_permissions['METHODS'] = ( $flag ) ? true : false;
660        }
661
662
663        /**
664         * method: set_regexps_style
665         * -------------------------
666         * Sets the styles for regexps. If $preserve_defaults is
667         * true, then styles are merged with the default styles, with the
668         * user defined styles having priority
669         */
670        function set_regexps_style ( $key, $style, $preserve_defaults = false )
671        {
672                if ( $preserve_defaults )
673                {
674                        $this->language_data['STYLES']['REGEXPS'][$key] .= $style;
675                }
676                else
677                {
678                        $this->language_data['STYLES']['REGEXPS'][$key] = $style;
679                }
680        }
681
682
683        /**
684         * method: set_regexps_highlighting
685         * --------------------------------
686         * Turns highlighting on/off for regexps
687         */
688        function set_regexps_highlighting ( $key, $flag )
689        {
690                $this->lexic_permissions['REGEXPS'][$key] = ( $flag ) ? true : false;
691        }
692
693
694        /**
695         * method: set_case_sensitivity
696         * ----------------------------
697         * Sets whether a set of keywords are checked for in a case sensitive manner
698         */
699        function set_case_sensitivity ( $key, $case )
700        {
701                $this->language_data['CASE_SENSITIVE'][$key] = ( $case ) ? true : false;
702        }
703
704
705        /**
706         * method: set_case_keywords
707         * -------------------------
708         * Sets the case that keywords should use when found. Use the constants:
709         *   GESHI_CAPS_NO_CHANGE: leave keywords as-is
710         *   GESHI_CAPS_UPPER: convert all keywords to uppercase where found
711         *   GESHI_CAPS_LOWER: convert all keywords to lowercase where found
712         * Method added in 1.0.1
713         */
714        function set_case_keywords ( $case )
715        {
716                $this->language_data['CASE_KEYWORDS'] = $case;
717        }
718
719
720        /**
721         * method: set_tab_width
722         * ---------------------
723         * Sets how many spaces a tab is substituted for
724         * This method will probably be re-engineered later to allow customisability
725         * in the maximum and minimum number of tabs without mutulating data fields.
726         */
727        function set_tab_width ( $width )
728        {
729                if ( $width > $this->max_tabs ) $width = $this->max_tabs;
730                if ( $width < $this->min_tabs ) $width = $this->min_tabs;
731                $this->tab_width = $width;
732        }
733
734
735        /**
736         * method: enable_strict_mode
737         * --------------------------
738         * Enables/disables strict highlighting. Default is off, calling this
739         * method without parameters will turn it on. See documentation
740         * for more details on strict mode and where to use it
741         */
742        function enable_strict_mode ( $mode = true )
743        {
744                $this->strict_mode = ( $mode ) ? true : false;
745                // Turn on strict mode no matter what if language should always
746                // be in strict mode
747                if ( $this->language_data['STRICT_MODE_APPLIES'] == GESHI_ALWAYS )
748                {
749                        $this->strict_mode = true;
750                }
751                // Turn off strict mode no matter what if language should never
752                // be in strict mode
753                elseif ( $this->language_data['STRICT_MODE_APPLIES'] == GESHI_NEVER )
754                {
755                        $this->strict_mode = false;
756                }
757        }
758
759
760        /**
761         * method: disable_highlighting
762         * ----------------------------
763         * Disables all highlighting
764         */
765        function disable_highlighting ()
766        {
767                foreach ( $this->language_data['KEYWORDS'] as $key => $words )
768                {
769                        $this->lexic_permissions['KEYWORDS'][$key] = false;
770                }
771                foreach ( $this->language_data['COMMENT_SINGLE'] as $key => $comment )
772                {
773                        $this->lexic_permissions['COMMENTS'][$key] = false;
774                }
775                // Multiline comments
776                $this->lexic_permissions['COMMENTS']['MULTI'] = false;
777                // Escape characters
778                $this->lexic_permissions['ESCAPE_CHAR'] = false;
779                // Brackets
780                $this->lexic_permissions['BRACKETS'] = false;
781                // Strings
782                $this->lexic_permissions['STRINGS'] = false;
783                // Numbers
784                $this->lexic_permissions['NUMBERS'] = false;
785                // Methods
786                $this->lexic_permissions['METHODS'] = false;
787                // Symbols
788                $this->lexic_permissions['SYMBOLS'] = false;
789                // Script
790                $this->lexic_permissions['SCRIPT'] = false;
791                // Regexps
792                foreach ( $this->language_data['REGEXPS'] as $key => $regexp )
793                {
794                        $this->lexic_permissions['REGEXPS'][$key] = false;
795                }
796                // Context blocks
797                $this->enable_important_blocks = false;
798        }
799
800
801        /**
802         * method: enable_highlighting
803         * ---------------------------
804         * Enables all highlighting
805         */
806        function enable_highlighting ()
807        {
808                foreach ( $this->language_data['KEYWORDS'] as $key => $words )
809                {
810                        $this->lexic_permissions['KEYWORDS'][$key] = true;
811                }
812                foreach ( $this->language_data['COMMENT_SINGLE'] as $key => $comment )
813                {
814                        $this->lexic_permissions['COMMENTS'][$key] = true;
815                }
816                // Multiline comments
817                $this->lexic_permissions['COMMENTS']['MULTI'] = true;
818                // Escape characters
819                $this->lexic_permissions['ESCAPE_CHAR'] = true;
820                // Brackets
821                $this->lexic_permissions['BRACKETS'] = true;
822                // Strings
823                $this->lexic_permissions['STRINGS'] = true;
824                // Numbers
825                $this->lexic_permissions['NUMBERS'] = true;
826                // Methods
827                $this->lexic_permissions['METHODS'] = true;
828                // Symbols
829                $this->lexic_permissions['SYMBOLS'] = true;
830                // Script
831                $this->lexic_permissions['SCRIPT'] = true;
832                // Regexps
833                foreach ( $this->language_data['REGEXPS'] as $key => $regexp )
834                {
835                        $this->lexic_permissions['REGEXPS'][$key] = true;
836                }
837                // Context blocks
838                $this->enable_important_blocks = true;
839        }
840
841
842        /**
843         * method: get_language_name_from_extension
844         * ----------------------------------------
845         * Given a file extension, this method returns either a valid geshi language
846         * name, or the empty string if it couldn't be found
847         */
848        function get_language_name_from_extension ( $extension, $lookup = array() )
849        {
850                if ( !$lookup )
851                {
852                        $lookup = array(
853                                'actionscript' => array('as'),
854                                'ada' => array('a', 'ada', 'adb', 'ads'),
855                                'apache' => array('conf'),
856                                'asm' => array('ash', 'asm'),
857                                'asp' => array('asp'),
858                                'bash' => array('sh'),
859                                'c' => array('c'),
860                                'c_mac' => array('c'),
861                                'caddcl' => array(),
862                                'cadlisp' => array(),
863                                'cpp' => array('cpp'),
864                                'csharp' => array(),
865                                'css' => array('css'),
866                                'delphi' => array('dpk'),
867                                'html4strict' => array('html', 'htm'),
868                                'java' => array('java'),
869                                'javascript' => array('js'),
870                                'lisp' => array('lisp'),
871                                'lua' => array('lua'),
872                                'mpasm' => array(),
873                                'nsis' => array(),
874                                'objc' => array(),
875                                'oobas' => array(),
876                                'oracle8' => array(),
877                                'pascal' => array('pas'),
878                                'perl' => array('pl', 'pm'),
879                                'php' => array('php', 'php5', 'phtml', 'phps'),
880                                'python' => array('py'),
881                                'qbasic' => array('bi'),
882                                'smarty' => array(),
883                                'vb' => array('bas'),
884                                'vbnet' => array(),
885                                'visualfoxpro' => array(),
886                                'xml' => array('xml')
887                        );
888                }
889
890                foreach ( $lookup as $lang => $extensions )
891                {
892                        foreach ( $extensions as $ext )
893                        {
894                                if ( $ext == $extension )
895                                {
896                                        return $lang;
897                                }
898                        }
899                }
900                return '';
901        }
902
903        /**
904         * Method: load_from_file
905         * ----------------------
906         * Given a file name, this method loads its contents in, and attempts
907         * to set the language automatically. An optional lookup table can be
908         * passed for looking up the language name.
909         *
910         * The language table is in the form
911         * <pre>array(
912         *   'lang_name' => array('extension', 'extension', ...),
913         *   'lang_name' ...
914         * );</pre>
915         */
916        function load_from_file ( $file_name, $lookup = array() )
917        {
918                if ( is_readable($file_name) )
919                {
920                        $this->set_source(implode('', file($file_name)));
921                        $this->set_language($this->get_language_name_from_extension(substr(strrchr($file_name, '.'), 1), $lookup));
922                }
923                else
924                {
925                        $this->error = GESHI_ERROR_FILE_NOT_READABLE;
926                }
927        }
928
929        /**
930         * method: add_keyword
931         * -------------------
932         * Adds a keyword to a keyword group for highlighting
933         */
934        function add_keyword( $key, $word )
935        {
936                $this->language_data['KEYWORDS'][$key][] = $word;
937        }
938
939
940        /**
941         * method: remove_keyword
942         * ----------------------
943         * Removes a keyword from a keyword group
944         */
945        function remove_keyword ( $key, $word )
946        {
947                $this->language_data['KEYWORDS'][$key] = array_diff($this->language_data['KEYWORDS'][$key], array($word));
948        }
949
950
951        /**
952         * method: add_keyword_group
953         * -------------------------
954         * Creates a new keyword group
955         */
956        function add_keyword_group ( $key, $styles, $case_sensitive = true, $words = array() )
957        {
958                if ( !is_array($words) )
959                {
960                        $words = array($words);
961                }
962                $this->language_data['KEYWORDS'][$key] = $words;
963                $this->lexic_permissions['KEYWORDS'][$key] = true;
964                $this->language_data['CASE_SENSITIVE'][$key] = $case_sensitive;
965                $this->language_data['STYLES']['KEYWORDS'][$key] = $styles;
966        }
967
968
969        /**
970         * method: remove_keyword_group
971         * ----------------------------
972         * Removes a keyword group
973         */
974        function remove_keyword_group ( $key )
975        {
976                unset($this->language_data['KEYWORDS'][$key]);
977                unset($this->lexic_permissions['KEYWORDS'][$key]);
978                unset($this->language_data['CASE_SENSITIVE'][$key]);
979                unset($this->language_data['STYLES']['KEYWORDS'][$key]);
980        }
981
982
983        /**
984         * method: set_header_content
985         * --------------------------
986         * Sets the content of the header block
987         */
988        function set_header_content ( $content )
989        {
990                $this->header_content = $content;
991        }
992
993
994        /**
995         * method: set_footer_content
996         * --------------------------
997         * Sets the content of the footer block
998         */
999        function set_footer_content ( $content )
1000        {
1001                $this->footer_content = $content;
1002        }
1003
1004
1005        /**
1006         * method: set_header_content_style
1007         * --------------------------------
1008         * Sets the style for the header content
1009         */
1010        function set_header_content_style ( $style )
1011        {
1012                $this->header_content_style = $style;
1013        }
1014
1015
1016        /**
1017         * method: set_footer_content_style
1018         * --------------------------------
1019         * Sets the style for the footer content
1020         */
1021        function set_footer_content_style ( $style )
1022        {
1023                $this->footer_content_style = $style;
1024        }
1025
1026
1027        /**
1028         * method: set_url_for_keyword_group
1029         * ---------------------------------
1030         * Sets the base URL to be used for keywords
1031         */
1032        function set_url_for_keyword_group ( $group, $url )
1033        {
1034                $this->language_data['URLS'][$group] = $url;
1035        }
1036
1037
1038        /**
1039         * method: set_link_styles
1040         * -----------------------
1041         * Sets styles for links in code
1042         */
1043        function set_link_styles ( $type, $styles )
1044        {
1045                $this->link_styles[$type] = $styles;
1046        }
1047
1048
1049        /**
1050        * method: set_link_target
1051        * -----------------------
1052        * Sets the target for links in code
1053        */
1054        function set_link_target ( $target )
1055        {
1056                if ( empty( $target ) )
1057                {
1058                        $this->link_target = '';
1059                }
1060                else
1061                {
1062                        $this->link_target = ' target="' . $target . '" ';
1063                }
1064        }
1065
1066
1067        /**
1068         * method: set_important_styles
1069         * ----------------------------
1070         * Sets styles for important parts of the code
1071         */
1072        function set_important_styles ( $styles )
1073        {
1074                $this->important_styles = $styles;
1075        }
1076
1077
1078        /**
1079         * method: enable_important_blocks
1080         * -------------------------------
1081         * Sets whether context-important blocks are highlighted
1082         */
1083        function enable_important_blocks ( $flag )
1084        {
1085                $this->enable_important_blocks = ( $flag ) ? true : false;
1086        }
1087
1088
1089        /**
1090         * method: enable_ids
1091         * ------------------
1092         * Whether CSS IDs should be added to each line
1093         */
1094        function enable_ids ( $flag = true )
1095        {
1096                $this->add_ids = ( $flag ) ? true : false;
1097        }
1098
1099
1100        /**
1101         * method: highlight_lines_extra
1102         * -----------------------------
1103         * Specifies which lines to highlight extra
1104         */
1105        function highlight_lines_extra ( $lines )
1106        {
1107                if ( is_array($lines) )
1108                {
1109                        foreach ( $lines as $line )
1110                        {
1111                                $this->highlight_extra_lines[intval($line)] = intval($line);
1112                        }
1113                }
1114                else
1115                {
1116                        $this->highlight_extra_lines[intval($lines)] = intval($lines);
1117                }
1118        }
1119
1120
1121        /**
1122         * method: set_highlight_lines_extra_style
1123         * ---------------------------------------
1124         * Sets the style for extra-highlighted lines
1125         */
1126        function set_highlight_lines_extra_style ( $styles )
1127        {
1128                $this->highlight_extra_lines_style = $styles;
1129        }
1130
1131
1132        /**
1133         * method: start_line_numbers_at
1134         * -----------------------------
1135         * Sets what number line numbers should start at. Should
1136         * be a positive integer, and will be converted to one.
1137         */
1138        function start_line_numbers_at ( $number )
1139        {
1140                $this->line_numbers_start = abs(intval($number));
1141        }
1142
1143
1144        /**
1145         * method: set_encoding
1146         * --------------------
1147         * Sets the encoding used for @htmlentities(), for international
1148         * support.
1149         */
1150        function set_encoding ( $encoding )
1151        {
1152                $this->encoding = $encoding;
1153        }
1154
1155
1156        /**
1157         * method: parse_code()
1158         * --------------------
1159         * Returns the code in $this->source, highlighted and surrounded by the
1160         * nessecary HTML. This should only be called ONCE, cos it's SLOW!
1161         * If you want to highlight the same source multiple times, you're better
1162         * off doing a whole lot of str_replaces to replace the <<span>>s
1163         */
1164        function parse_code()
1165        {
1166                // Start the timer
1167                $start_time = microtime();
1168
1169                // Firstly, if there is an error, we won't highlight
1170                // FUTURE: maybe an option to try to force highlighting anyway?
1171                if ( $this->error )
1172                {
1173                        $result = $this->header();
1174                        if ( $this->header_type != GESHI_HEADER_PRE )
1175                        {
1176                                $result .= $this->indent(@htmlentities($this->source, ENT_COMPAT, $this->encoding));
1177                        }
1178                        else
1179                        {
1180                                $result .= @htmlentities($this->source, ENT_COMPAT, $this->encoding);
1181                        }
1182                        // Stop Timing
1183                        $this->set_time($start_time, microtime());
1184                        return $result . $this->footer();
1185                }
1186
1187                // Add spaces for regular expression matching and line numbers
1188                $code = ' ' . $this->source . ' ';
1189                // Replace all newlines to a common form.
1190                $code = str_replace("\r\n", "\n", $code);
1191                $code = str_replace("\r", "\n", $code);
1192
1193                // Initialise various stuff
1194                $length = strlen($code);
1195                $STRING_OPEN = '';
1196                $CLOSE_STRING = false;
1197                $ESCAPE_CHAR_OPEN = false;
1198                $COMMENT_MATCHED = false;
1199                // Turn highlighting on if strict mode doesn't apply to this language
1200                $HIGHLIGHTING_ON = ( !$this->strict_mode ) ? true : '';
1201                // Whether to highlight inside a block of code
1202                $HIGHLIGHT_INSIDE_STRICT = false;
1203                $stuff_to_parse = '';
1204                $result = '';
1205
1206                // "Important" selections are handled like multiline comments
1207                if ( $this->enable_important_blocks )
1208                {
1209                        $this->language_data['COMMENT_MULTI'][GESHI_START_IMPORTANT] = GESHI_END_IMPORTANT;
1210                }
1211
1212
1213                if ( $this->strict_mode )
1214                {
1215                        // Break the source into bits. Each bit will be a portion of the code
1216                        // within script delimiters - for example, HTML between < and >
1217                        $parts = array(0 => array(0 => ''));
1218                        $k = 0;
1219                        for ( $i = 0; $i < $length; $i++ )
1220                        {
1221                                $char = substr($code, $i, 1);
1222                                if ( !$HIGHLIGHTING_ON )
1223                                {
1224                                        foreach ( $this->language_data['SCRIPT_DELIMITERS'] as $key => $delimiters )
1225                                        {
1226                                                foreach ( $delimiters as $open => $close )
1227                                                {
1228                                                        // Get the next little bit for this opening string
1229                                                        $check = substr($code, $i, strlen($open));
1230                                                        // If it matches...
1231                                                        if ( $check == $open )
1232                                                        {
1233                                                                // We start a new block with the highlightable
1234                                                                // code in it
1235                                                                $HIGHLIGHTING_ON = $open;
1236                                                                $i += strlen($open) - 1;
1237                                                                ++$k;
1238                                                                $char = $open;
1239                                                                $parts[$k][0] = $char;
1240
1241                                                                // No point going around again...
1242                                                                break(2);
1243                                                        }
1244                                                }
1245                                        }
1246                                }
1247                                else
1248                                {
1249                                        foreach ( $this->language_data['SCRIPT_DELIMITERS'] as $key => $delimiters )
1250                                        {
1251                                                foreach ( $delimiters as $open => $close )
1252                                                {
1253                                                        if ( $open == $HIGHLIGHTING_ON )
1254                                                        {
1255                                                                // Found the closing tag
1256                                                                break(2);
1257                                                        }
1258                                                }
1259                                        }
1260                                        // We check code from our current position BACKWARDS. This is so
1261                                        // the ending string for highlighting can be included in the block
1262                                        $check = substr($code, $i - strlen($close) + 1, strlen($close));
1263                                        if ( $check == $close )
1264                                        {
1265                                                $HIGHLIGHTING_ON = '';
1266                                                // Add the string to the rest of the string for this part
1267                                                $parts[$k][1] = ( isset($parts[$k][1]) ) ? $parts[$k][1] . $char : $char;
1268                                                ++$k;
1269                                                $parts[$k][0] = '';
1270                                                $char = '';
1271                                        }
1272                                }
1273                                $parts[$k][1] = ( isset($parts[$k][1]) ) ? $parts[$k][1] . $char : $char;
1274                        }
1275                        $HIGHLIGHTING_ON = '';
1276                }
1277                else
1278                {
1279                        // Not strict mode - simply dump the source into
1280                        // the array at index 1 (the first highlightable block)
1281                        $parts = array(
1282                                1 => array(
1283                                        0 => '',
1284                                        1 => $code
1285                                )
1286                        );
1287                }
1288
1289                // Now we go through each part. We know that even-indexed parts are
1290                // code that shouldn't be highlighted, and odd-indexed parts should
1291                // be highlighted
1292                foreach ( $parts as $key => $data )
1293                {
1294                        $part = $data[1];
1295                        // If this block should be highlighted...
1296                        if ( $key % 2 )
1297                        {
1298                                if ( $this->strict_mode )
1299                                {
1300                                        // Find the class key for this block of code
1301                                        foreach ( $this->language_data['SCRIPT_DELIMITERS'] as $script_key => $script_data )
1302                                        {
1303                                                foreach ( $script_data as $open => $close )
1304                                                {
1305                                                        if ( $data[0] == $open )
1306                                                        {
1307                                                                break(2);
1308                                                        }
1309                                                }
1310                                        }
1311
1312                                        if ( $this->language_data['STYLES']['SCRIPT'][$script_key] != '' && $this->lexic_permissions['SCRIPT'] )
1313                                        {
1314                                                // Add a span element around the source to
1315                                                // highlight the overall source block
1316                                                if ( !$this->use_classes && $this->language_data['STYLES']['SCRIPT'][$script_key] != '' )
1317                                                {
1318                                                        $attributes = ' style="' . $this->language_data['STYLES']['SCRIPT'][$script_key] . '"';
1319                                                }
1320                                                else
1321                                                {
1322                                                        $attributes = ' class="sc' . $script_key . '"';
1323                                                }
1324                                                $result .= "<span$attributes>";
1325                                        }
1326                                }
1327
1328                                if ( !$this->strict_mode || $this->language_data['HIGHLIGHT_STRICT_BLOCK'][$script_key] )
1329                                {
1330                                        // Now, highlight the code in this block. This code
1331                                        // is really the engine of GeSHi (along with the method
1332                                        // parse_non_string_part).
1333                                        $length = strlen($part);
1334                                        for ( $i = 0; $i < $length; $i++ )
1335                                        {
1336                                                // Get the next char
1337                                                $char = substr($part, $i, 1);
1338                                                // Is this char the newline and line numbers being used?
1339                                                if ( ($this->line_numbers != GESHI_NO_LINE_NUMBERS || count($this->highlight_extra_lines) > 0) && $char == "\n" )
1340                                                {
1341                                                        // If so, is there a string open? If there is, we should end it before
1342                                                        // the newline and begin it again (so when <li>s are put in the source
1343                                                        // remains XHTML compliant)
1344                                                        // NOTE TO SELF: This opens up possibility of config files specifying
1345                                                        // that languages can/cannot have multiline strings???
1346                                                        if ( $STRING_OPEN )
1347                                                        {
1348                                                                if ( !$this->use_classes )
1349                                                                {
1350                                                                        $attributes = ' style="' . $this->language_data['STYLES']['STRINGS'][0] . '"';
1351                                                                }
1352                                                                else
1353                                                                {
1354                                                                        $attributes = ' class="st0"';
1355                                                                }
1356                                                                $char = '</span>' . $char . "<span$attributes>";
1357                                                        }
1358                                                }
1359                                                // Is this a match of a string delimiter?
1360                                                elseif ( $char == $STRING_OPEN )
1361                                                {
1362                                                        if ( ($this->lexic_permissions['ESCAPE_CHAR'] && $ESCAPE_CHAR_OPEN) || ($this->lexic_permissions['STRINGS'] && !$ESCAPE_CHAR_OPEN) )
1363                                                        {
1364                                                                $char .= '</span>';
1365                                                        }
1366                                                        if ( !$ESCAPE_CHAR_OPEN )
1367                                                        {
1368                                                                $STRING_OPEN = '';
1369                                                                $CLOSE_STRING = true;
1370                                                        }
1371                                                        $ESCAPE_CHAR_OPEN = false;
1372                                                }
1373                                                // Is this the start of a new string?
1374                                                elseif ( in_array( $char, $this->language_data['QUOTEMARKS'] ) && ($STRING_OPEN == '') && $this->lexic_permissions['STRINGS'] )
1375                                                {
1376                                                        $STRING_OPEN = $char;
1377                                                        if ( !$this->use_classes )
1378                                                        {
1379                                                                $attributes = ' style="' . $this->language_data['STYLES']['STRINGS'][0] . '"';
1380                                                        }
1381                                                        else
1382                                                        {
1383                                                                $attributes = ' class="st0"';
1384                                                        }
1385                                                        $char = "<span$attributes>" . $char;
1386
1387                                                        $result .= $this->parse_non_string_part( $stuff_to_parse );
1388                                                        $stuff_to_parse = '';
1389                                                }
1390                                                // Is this an escape char?
1391                                                elseif ( ($char == $this->language_data['ESCAPE_CHAR']) && ($STRING_OPEN != '') )
1392                                                {
1393                                                        if ( !$ESCAPE_CHAR_OPEN )
1394                                                        {
1395                                                                $ESCAPE_CHAR_OPEN = true;
1396                                                                if ( $this->lexic_permissions['ESCAPE_CHAR'] )
1397                                                                {
1398                                                                        if ( !$this->use_classes )
1399                                                                        {
1400                                                                                $attributes = ' style="' . $this->language_data['STYLES']['ESCAPE_CHAR'][0] . '"';
1401                                                                        }
1402                                                                        else
1403                                                                        {
1404                                                                                $attributes = ' class="es0"';
1405                                                                        }
1406                                                                        $char = "<span$attributes>" . $char;
1407                                                                }
1408                                                        }
1409                                                        else
1410                                                        {
1411                                                                $ESCAPE_CHAR_OPEN = false;
1412                                                                if ( $this->lexic_permissions['ESCAPE_CHAR'] )
1413                                                                {
1414                                                                        $char .= '</span>';
1415                                                                }
1416                                                        }
1417                                                }
1418                                                elseif ( $ESCAPE_CHAR_OPEN )
1419                                                {
1420                                                        if ( $this->lexic_permissions['ESCAPE_CHAR'] )
1421                                                        {
1422                                                                $char .= '</span>';
1423                                                        }
1424                                                        $ESCAPE_CHAR_OPEN = false;
1425                                                        $test_str = $char;
1426                                                }
1427                                                elseif ( $STRING_OPEN == '' )
1428                                                {
1429                                                        // Is this a multiline comment?
1430                                                        foreach ( $this->language_data['COMMENT_MULTI'] as $open => $close )
1431                                                        {
1432                                                                $com_len = strlen($open);
1433                                                                $test_str = substr( $part, $i, $com_len );
1434                                                                $test_str_match = $test_str;
1435                                                                if ( $open == $test_str )
1436                                                                {
1437                                                                        $COMMENT_MATCHED = true;
1438                                                                        if ( $this->lexic_permissions['COMMENTS']['MULTI'] || $test_str == GESHI_START_IMPORTANT )
1439                                                                        {
1440                                                                                if ( $test_str != GESHI_START_IMPORTANT )
1441                                                                                {
1442                                                                                        if ( !$this->use_classes )
1443                                                                                        {
1444                                                                                                $attributes = ' style="' . $this->language_data['STYLES']['COMMENTS']['MULTI'] . '"';
1445                                                                                        }
1446                                                                                        else
1447                                                                                        {
1448                                                                                                $attributes = ' class="coMULTI"';
1449                                                                                        }
1450                                                                                        $test_str = "<span$attributes>" . @htmlentities($test_str, ENT_COMPAT, $this->encoding);
1451                                                                                }
1452                                                                                else
1453                                                                                {
1454                                                                                        if ( !$this->use_classes )
1455                                                                                        {
1456                                                                                                $attributes = ' style="' . $this->important_styles . '"';
1457                                                                                        }
1458                                                                                        else
1459                                                                                        {
1460                                                                                                $attributes = ' class="imp"';
1461                                                                                        }
1462                                                                                        // We don't include the start of the comment if it's an
1463                                                                                        // "important" part
1464                                                                                        $test_str = "<span$attributes>";
1465                                                                                }
1466                                                                        }
1467                                                                        else
1468                                                                        {
1469                                                                                $test_str = @htmlentities($test_str, ENT_COMPAT, $this->encoding);
1470                                                                        }
1471
1472                                                                        $close_pos = strpos( $part, $close, $i + strlen($close) );
1473
1474                                                                        if ( $close_pos === false )
1475                                                                        {
1476                                                                                $close_pos = strlen($part);
1477                                                                        }
1478
1479                                                                        // Short-cut through all the multiline code
1480                                                                        $rest_of_comment = @htmlentities(substr($part, $i + $com_len, $close_pos - $i), ENT_COMPAT, $this->encoding);
1481                                                                        if ( ($this->lexic_permissions['COMMENTS']['MULTI'] || $test_str_match == GESHI_START_IMPORTANT) && ($this->line_numbers != GESHI_NO_LINE_NUMBERS || count($this->highlight_extra_lines) > 0) )
1482                                                                        {
1483                                                                                // strreplace to put close span and open span around multiline newlines
1484                                                                                $test_str .= str_replace("\n", "</span>\n<span$attributes>", $rest_of_comment);
1485                                                                        }
1486                                                                        else
1487                                                                        {
1488                                                                                $test_str .= $rest_of_comment;
1489                                                                        }
1490
1491                                                                        if ( $this->lexic_permissions['COMMENTS']['MULTI'] || $test_str_match == GESHI_START_IMPORTANT )
1492                                                                        {
1493                                                                                $test_str .= '</span>';
1494                                                                        }
1495                                                                        $i = $close_pos + $com_len - 1;
1496                                                                        // parse the rest
1497                                                                        $result .= $this->parse_non_string_part( $stuff_to_parse );
1498                                                                        $stuff_to_parse = '';
1499                                                                        break;
1500                                                                }
1501                                                        }
1502                                                        // If we haven't matched a multiline comment, try single-line comments
1503                                                        if ( !$COMMENT_MATCHED )
1504                                                        {
1505                                                                foreach ( $this->language_data['COMMENT_SINGLE'] as $comment_key => $comment_mark )
1506                                                                {
1507                                                                        $com_len = strlen($comment_mark);
1508                                                                        $test_str = substr( $part, $i, $com_len );
1509                                                                        if ( $this->language_data['CASE_SENSITIVE'][GESHI_COMMENTS] )
1510                                                                        {
1511                                                                                $match = ( $comment_mark == $test_str );
1512                                                                        }
1513                                                                        else
1514                                                                        {
1515                                                                                $match = ( strtolower($comment_mark) == strtolower($test_str) );
1516                                                                        }
1517                                                                        if ( $match )
1518                                                                        {
1519                                                                                $COMMENT_MATCHED = true;
1520                                                                                if ( $this->lexic_permissions['COMMENTS'][$comment_key] )
1521                                                                                {
1522                                                                                        if ( !$this->use_classes )
1523                                                                                        {
1524                                                                                                $attributes = ' style="' . $this->language_data['STYLES']['COMMENTS'][$comment_key] . '"';
1525                                                                                        }
1526                                                                                        else
1527                                                                                        {
1528                                                                                                $attributes = ' class="co' . $comment_key . '"';
1529                                                                                        }
1530                                                                                        $test_str = "<span$attributes>" . @htmlentities($this->change_case($test_str), ENT_COMPAT, $this->encoding);
1531                                                                                }
1532                                                                                else
1533                                                                                {
1534                                                                                        $test_str = @htmlentities($test_str, ENT_COMPAT, $this->encoding);
1535                                                                                }
1536                                                                                $close_pos = strpos( $part, "\n", $i );
1537                                                                                if ( $close_pos === false )
1538                                                                                {
1539                                                                                        $close_pos = strlen($part);
1540                                                                                }
1541                                                                                $test_str .= @htmlentities(substr($part, $i + $com_len, $close_pos - $i - $com_len), ENT_COMPAT, $this->encoding);
1542                                                                                if ( $this->lexic_permissions['COMMENTS'][$comment_key] )
1543                                                                                {
1544                                                                                        $test_str .= "</span>";
1545                                                                                }
1546                                                                                $test_str .= "\n";
1547                                                                                $i = $close_pos;
1548                                                                                // parse the rest
1549                                                                                $result .= $this->parse_non_string_part( $stuff_to_parse );
1550                                                                                $stuff_to_parse = '';
1551                                                                                break;
1552                                                                        }
1553                                                                }
1554                                                        }
1555                                                }
1556                                                // Otherwise, convert it to HTML form
1557                                                elseif ( $STRING_OPEN != '' )
1558                                                {
1559                                                        if ( strtolower($this->encoding) == 'utf-8' )
1560                                                        {
1561                                                                //only escape <128 (we don't want to break multibyte chars)
1562                                                                if ( ord($char) < 128 )
1563                                                                {
1564                                                                        $char = htmlentities($char, ENT_COMPAT, $this->encoding);
1565                                                                }
1566                                                        }
1567                                                        else
1568                                                        {
1569                                                                //encode everthing
1570                                                                $char = htmlentities($char, ENT_COMPAT, $this->encoding);
1571                                                        }
1572                                                }
1573                                                // Where are we adding this char?
1574                                                if ( !$COMMENT_MATCHED )
1575                                                {
1576                                                        if ( ($STRING_OPEN == '') && !$CLOSE_STRING )
1577                                                        {
1578                                                                $stuff_to_parse .= $char;
1579                                                        }
1580                                                        else
1581                                                        {
1582                                                                $result .= $char;
1583                                                                $CLOSE_STRING = false;
1584                                                        }
1585                                                }
1586                                                else
1587                                                {
1588                                                        $result .= $test_str;
1589                                                        $COMMENT_MATCHED = false;
1590                                                }
1591                                        }
1592                                        // Parse the last bit
1593                                        $result .= $this->parse_non_string_part( $stuff_to_parse );
1594                                        $stuff_to_parse = '';
1595                                }
1596                                else
1597                                {
1598                                        $result .= @htmlentities($part, ENT_COMPAT, $this->encoding);
1599                                }
1600                                // Close the <span> that surrounds the block
1601                                if ( $this->strict_mode && $this->lexic_permissions['SCRIPT'] )
1602                                {
1603                                        $result .= '</span>';
1604                                }
1605                        }
1606                        // Else not a block to highlight
1607                        else
1608                        {
1609                                $result .= @htmlentities($part, ENT_COMPAT, $this->encoding);
1610                        }
1611                }
1612
1613                // Parse the last stuff (redundant?)
1614                $result .= $this->parse_non_string_part( $stuff_to_parse );
1615
1616                // Lop off the very first and last spaces
1617                $result = substr($result, 1, strlen($result) - 1);
1618
1619                // Are we still in a string?
1620                if ( $STRING_OPEN )
1621                {
1622                        $result .= '</span>';
1623                }
1624
1625                // We're finished: stop timing
1626                $this->set_time($start_time, microtime());
1627
1628                return $this->finalise($result);
1629        }
1630
1631        /**
1632         * method: indent
1633         * --------------
1634         * Swaps out spaces and tabs for HTML indentation. Not needed if
1635         * the code is in a pre block...
1636         */
1637        function indent ( $result )
1638        {
1639            /// Replace tabs with the correct number of spaces
1640            if (false !== strpos($result, "\t")) {
1641                $lines = explode("\n", $result);
1642                foreach ($lines as $key => $line) {
1643                    if (false === strpos($line, "\t")) {
1644                        $lines[$key] = $line;
1645                        continue;
1646                    }//echo 'checking line ' . $key . '<br />';
1647
1648                    $pos = 0;
1649                    $tab_width = $this->tab_width;
1650                    $length = strlen($line);
1651                    $result_line = '';
1652
1653                    //echo '<pre>line: ' . htmlspecialchars($line) . '</pre>';
1654                    $IN_TAG = false;
1655                    for ($i = 0; $i < $length; $i++) {
1656                        $char = substr($line, $i, 1);
1657                        // Simple engine to work out whether we're in a tag.
1658                        // If we are we modify $pos. This is so we ignore HTML
1659                        // in the line and only workout the tab replacement
1660                        // via the actual content of the string
1661                        // This test could be improved to include strings in the
1662                        // html so that < or > would be allowed in user's styles
1663                        // (e.g. quotes: '<' '>'; or similar)
1664                        if ($IN_TAG && '>' == $char) {
1665                            $IN_TAG = false;
1666                            $result_line .= '>';
1667                            ++$pos;
1668                        } elseif (!$IN_TAG && '<' == $char) {
1669                            $IN_TAG = true;
1670                            $result_line .= '<';
1671                            ++$pos;
1672                        } elseif (!$IN_TAG && '&' == $char) {
1673                            //echo "matched &amp; in line... ";
1674                            $substr = substr($line, $i + 3, 4);
1675                            //$substr_5 = substr($line, 5, 1);
1676                            $posi = strpos($substr, ';');
1677                            if (false !== $posi) {
1678                                //echo "found entity at $posi\n";
1679                                $pos += $posi + 3;
1680                            }
1681                            $result_line .= '&';
1682                        } elseif (!$IN_TAG && "\t" == $char) {
1683                            $str = '';
1684                            // OPTIMISE - move $strs out. Make an array:
1685                            // $tabs = array(
1686                            //  1 => '&nbsp;',
1687                            //  2 => '&nbsp; ',
1688                            //  3 => '&nbsp; &nbsp;' etc etc
1689                            // to use instead of building a string every time
1690                            $strs = array(0 => '&nbsp;', 1 => ' ');
1691                            //echo "building (pos=$pos i=$i) (" . ($i - $pos) . ") " . ($tab_width - (($i - $pos) % $tab_width)) . " spaces\n";
1692                            for ($k = 0; $k < ($tab_width - (($i - $pos) % $tab_width)); $k++) $str .= $strs[$k % 2];
1693                            $result_line .= $str;
1694                            //$pos--;
1695                            $pos++;
1696                            //$pos -= $tab_width-1;
1697
1698                            if (false === strpos($line, "\t", $i + 1)) {
1699                                //$lines[$key] = $result_line;
1700                                //echo 'got here';
1701                                $result_line .= substr($line, $i + 1);
1702                                break;
1703                            }
1704                        } elseif ( $IN_TAG ) {
1705                            ++$pos;
1706                            $result_line .= $char;
1707                        } else {
1708                            $result_line .= $char;
1709                            //++$pos;
1710                        }
1711                    }
1712                    $lines[$key] = $result_line;
1713                }
1714                $result = implode("\n", $lines);
1715            }
1716                // Other whitespace
1717                $result = str_replace('  ', '&nbsp; ', $result);
1718                $result = str_replace('  ', ' &nbsp;', $result);
1719                $result = str_replace("\n ", "\n&nbsp;", $result);
1720                //$result = str_replace("\t", $this->get_tab_replacement(), $result);
1721                if ( $this->line_numbers == GESHI_NO_LINE_NUMBERS )
1722                {
1723                        $result = nl2br($result);
1724                }
1725                return $result;
1726        }
1727
1728        /**
1729         * method: change_case
1730         * -------------------
1731         * Changes the case of a keyword for those languages where a change is asked for
1732         */
1733        function change_case ( $instr )
1734        {
1735                if ( $this->language_data['CASE_KEYWORDS'] == GESHI_CAPS_UPPER )
1736                {
1737                        return strtoupper($instr);
1738                }
1739                elseif ( $this->language_data['CASE_KEYWORDS'] == GESHI_CAPS_LOWER )
1740                {
1741                        return strtolower($instr);
1742                }
1743                return $instr;
1744        }
1745
1746
1747        /**
1748         * method: add_url_to_keyword
1749         * --------------------------
1750         * Adds a url to a keyword where needed.
1751         * Added in 1.0.2
1752         */
1753        function add_url_to_keyword ( $keyword, $group, $start_or_end )
1754        {
1755                if ( isset($this->language_data['URLS'][$group]) && $this->language_data['URLS'][$group] != '' && substr($keyword, 0, 5) != '&lt;/' )
1756                {
1757                        // There is a base group for this keyword
1758
1759                        if ( $start_or_end == 'BEGIN' )
1760                        {
1761                                // HTML workaround... not good form (tm) but should work for 1.0.X
1762                                $keyword = ( substr($keyword, 0, 4) == '&lt;' ) ? substr($keyword, 4) : $keyword;
1763                                $keyword = ( substr($keyword, -4) == '&gt;' ) ? substr($keyword, 0, strlen($keyword) - 4) : $keyword;
1764                                if ( $keyword != '' )
1765                                {
1766                                        $keyword = ( $this->language_data['CASE_SENSITIVE'][$group] ) ? $keyword : strtolower($keyword);
1767                                        return '<|UR1|"' . str_replace(array('{FNAME}', '.'), array(@htmlentities($keyword, ENT_COMPAT, $this->encoding), '<DOT>'), $this->language_data['URLS'][$group]) . '">';
1768                                }
1769                                return '';
1770                        }
1771                        else
1772                        {
1773                                return '</a>';
1774                        }
1775                }
1776        }
1777
1778
1779        /**
1780         * method: parse_non_string_part
1781         * -----------------------------
1782         * Takes a string that has no strings or comments in it, and highlights
1783         * stuff like keywords, numbers and methods.
1784         */
1785        function parse_non_string_part ( &$stuff_to_parse )
1786        {
1787                $stuff_to_parse = ' ' . quotemeta(@htmlentities($stuff_to_parse, ENT_COMPAT, $this->encoding));
1788                // These vars will disappear in the future
1789                $func = '$this->change_case';
1790                $func2 = '$this->add_url_to_keyword';
1791
1792
1793                //
1794                // Regular expressions
1795                //
1796                foreach ( $this->language_data['REGEXPS'] as $key => $regexp )
1797                {
1798                        if ( $this->lexic_permissions['REGEXPS'][$key] )
1799                        {
1800                                if ( is_array($regexp) )
1801                                {
1802                                        $stuff_to_parse = preg_replace( "#" . $regexp[GESHI_SEARCH] . "#{$regexp[GESHI_MODIFIERS]}", "{$regexp[GESHI_BEFORE]}<|!REG3XP$key!>{$regexp[GESHI_REPLACE]}|>{$regexp[GESHI_AFTER]}", $stuff_to_parse);
1803                                }
1804                                else
1805                                {
1806                                        $stuff_to_parse = preg_replace( "#(" . $regexp . ")#", "<|!REG3XP$key!>\\1|>", $stuff_to_parse);
1807                                }
1808                        }
1809                }
1810
1811                //
1812                // Highlight numbers. This regexp sucks... anyone with a regexp that WORKS
1813                // here wins a cookie if they send it to me. At the moment there's two doing
1814                // almost exactly the same thing, except the second one prevents a number
1815                // being highlighted twice (eg <span...><span...>5</span></span>)
1816                // Put /NUM!/ in for the styles, which gets replaced at the end.
1817                //
1818                if ( $this->lexic_permissions['NUMBERS'] && preg_match('#[0-9]#', $stuff_to_parse ) )
1819                {
1820                        $stuff_to_parse = preg_replace('#([^a-zA-Z0-9\#])([0-9]+)([^a-zA-Z0-9])#', "\\1<|/NUM!/>\\2|>\\3", $stuff_to_parse);
1821                        $stuff_to_parse = preg_replace('#([^a-zA-Z0-9\#>])([0-9]+)([^a-zA-Z0-9])#', "\\1<|/NUM!/>\\2|>\\3", $stuff_to_parse);
1822                }
1823
1824                // Highlight keywords
1825                // if there is a couple of alpha symbols there *might* be a keyword
1826                if ( preg_match('#[a-zA-Z]{2,}#', $stuff_to_parse) )
1827                {
1828                        foreach ( $this->language_data['KEYWORDS'] as $k => $keywordset )
1829                        {
1830                                if ( $this->lexic_permissions['KEYWORDS'][$k] )
1831                                {
1832                                        foreach ( $keywordset as $keyword )
1833                                        {
1834                                                $keyword = quotemeta($keyword);
1835                                                //
1836                                                // This replacement checks the word is on it's own (except if brackets etc
1837                                                // are next to it), then highlights it. We don't put the color=" for the span
1838                                                // in just yet - otherwise languages with the keywords "color" or "or" have
1839                                                // a fit.
1840                                                //
1841                                                if ( false !== stristr($stuff_to_parse, $keyword ) )
1842                                                {
1843                                                        $stuff_to_parse .= ' ';
1844                                                        // Might make a more unique string for putting the number in soon
1845                                                        // Basically, we don't put the styles in yet because then the styles themselves will
1846                                                        // get highlighted if the language has a CSS keyword in it (like CSS, for example ;))
1847                                                        $styles = "/$k/";
1848                                                        $keyword = quotemeta($keyword);
1849                                                        if ( $this->language_data['CASE_SENSITIVE'][$k] )
1850                                                        {
1851                                                                $stuff_to_parse = preg_replace("#([^a-zA-Z0-9\$_\|\.\#;>])($keyword)([^a-zA-Z0-9_<\|%\-&])#e", "'\\1' . $func2('\\2', '$k', 'BEGIN') . '<|$styles>' . $func('\\2') . '|>' . $func2('\\2', '$k', 'END') . '\\3'", $stuff_to_parse);
1852                                                        }
1853                                                        else
1854                                                        {
1855                                                                // Change the case of the word.
1856                                                                $stuff_to_parse = preg_replace("#([^a-zA-Z0-9\$_\|\.\#;>])($keyword)([^a-zA-Z0-9_<\|%\-&])#ie", "'\\1' . $func2('\\2', '$k', 'BEGIN') . '<|$styles>' . $func('\\2') . '|>' . $func2('\\2', '$k', 'END') . '\\3'", $stuff_to_parse);
1857                                                        }
1858                                                        $stuff_to_parse = substr($stuff_to_parse, 0, strlen($stuff_to_parse) - 1);
1859                                                }
1860                                        }
1861                                }
1862                        }
1863                }
1864
1865                //
1866                // Now that's all done, replace /[number]/ with the correct styles
1867                //
1868                foreach ( $this->language_data['KEYWORDS'] as $k => $kws )
1869                {
1870                        if ( !$this->use_classes )
1871                        {
1872                                $attributes = ' style="' . $this->language_data['STYLES']['KEYWORDS'][$k] . '"';
1873                        }
1874                        else
1875                        {
1876                                $attributes = ' class="kw' . $k . '"';
1877                        }
1878                        $stuff_to_parse = str_replace("/$k/", $attributes, $stuff_to_parse);
1879                }
1880
1881                // Put number styles in
1882                if ( !$this->use_classes && $this->lexic_permissions['NUMBERS'] )
1883                {
1884                        $attributes = ' style="' . $this->language_data['STYLES']['NUMBERS'][0] . '"';
1885                }
1886                else
1887                {
1888                        $attributes = ' class="nu0"';
1889                }
1890                $stuff_to_parse = str_replace('/NUM!/', $attributes, $stuff_to_parse);
1891
1892                //
1893                // Highlight methods and fields in objects
1894                //
1895                if ( $this->lexic_permissions['METHODS'] && $this->language_data['OOLANG'] )
1896                {
1897                        foreach ( $this->language_data['OBJECT_SPLITTERS'] as $key => $splitter )
1898                        {
1899                                if ( false !== stristr($stuff_to_parse, $splitter) )
1900                                {
1901                                        if ( !$this->use_classes )
1902                                        {
1903                                                $attributes = ' style="' . $this->language_data['STYLES']['METHODS'][$key] . '"';
1904                                        }
1905                                        else
1906                                        {
1907                                                $attributes = ' class="me' . $key . '"';
1908                                        }
1909                                        $stuff_to_parse = preg_replace("#(" . quotemeta($this->language_data['OBJECT_SPLITTERS'][$key]) . "[\s]*)([a-zA-Z\*\(][a-zA-Z0-9_\*]*)#", "\\1<|$attributes>\\2|>", $stuff_to_parse);
1910                                }
1911                        }
1912                }
1913
1914                //
1915                // Highlight brackets. Yes, I've tried adding a semi-colon to this list.
1916                // You try it, and see what happens ;)
1917                // TODO: Fix lexic permissions not converting entities if shouldn't
1918                // be highlighting regardless
1919                //
1920                if ( $this->lexic_permissions['BRACKETS'] )
1921                {
1922                        $code_entities_match = array('[', ']', '(', ')', '{', '}');
1923                        if ( !$this->use_classes )
1924                        {
1925                                $code_entities_replace = array(
1926                                        '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#91;|>',
1927                                        '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#93;|>',
1928                                        '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#40;|>',
1929                                        '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#41;|>',
1930                                        '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#123;|>',
1931                                        '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#125;|>',
1932                                );
1933                        }
1934                        else
1935                        {
1936                                $code_entities_replace = array(
1937                                        '<| class="br0">&#91;|>',
1938                                        '<| class="br0">&#93;|>',
1939                                        '<| class="br0">&#40;|>',
1940                                        '<| class="br0">&#41;|>',
1941                                        '<| class="br0">&#123;|>',
1942                                        '<| class="br0">&#125;|>',
1943                                );
1944                        }
1945                        $stuff_to_parse = str_replace( $code_entities_match,  $code_entities_replace, $stuff_to_parse );
1946                }
1947
1948                //
1949                // Add class/style for regexps
1950                //
1951                foreach ( $this->language_data['REGEXPS'] as $key => $regexp )
1952                {
1953                        if ( $this->lexic_permissions['REGEXPS'][$key] )
1954                        {
1955                                if ( !$this->use_classes )
1956                                {
1957                                        $attributes = ' style="' . $this->language_data['STYLES']['REGEXPS'][$key] . '"';
1958                                }
1959                                else
1960                                {
1961                                        $attributes = ' class="re' . $key . '"';
1962                                }
1963                                $stuff_to_parse = str_replace("!REG3XP$key!", "$attributes", $stuff_to_parse);
1964                        }
1965                }
1966
1967                // Replace <DOT> with . for urls
1968                $stuff_to_parse = str_replace('<DOT>', '.', $stuff_to_parse);
1969                // Replace <|UR1| with <a href= for urls also
1970                if ( isset($this->link_styles[GESHI_LINK]) )
1971                {
1972                        if ( $this->use_classes )
1973                        {
1974                                $stuff_to_parse = str_replace('<|UR1|', '<a' . $this->link_target . ' href=', $stuff_to_parse);
1975                        }
1976                        else
1977                        {
1978                                $stuff_to_parse = str_replace('<|UR1|', '<a' . $this->link_target . ' style="' . $this->link_styles[GESHI_LINK] . '" href=', $stuff_to_parse);
1979                        }
1980                }
1981                else
1982                {
1983                        $stuff_to_parse = str_replace('<|UR1|', '<a' . $this->link_target . ' href=', $stuff_to_parse);
1984                }
1985
1986                //
1987                // NOW we add the span thingy ;)
1988                //
1989
1990                $stuff_to_parse = str_replace('<|', '<span', $stuff_to_parse);
1991                $stuff_to_parse = str_replace ( '|>', '</span>', $stuff_to_parse );
1992
1993                return substr(stripslashes($stuff_to_parse), 1);
1994        }
1995
1996        /**
1997         * method: set_time
1998         * ----------------
1999         * Sets the time taken to parse the code
2000         */
2001        function set_time ( $start_time, $end_time )
2002        {
2003                $start = explode(' ', $start_time);
2004                $end = explode(' ', $end_time);
2005                $this->time = $end[0] + $end[1] - $start[0] - $start[1];
2006        }
2007
2008        /**
2009         * method: get_time
2010         * ----------------
2011         * Gets the time taken to parse the code
2012         */
2013        function get_time ()
2014        {
2015                return $this->time;
2016        }
2017
2018        function check_include($file)
2019        {
2020                $ok=false;
2021                $f=@fopen ($file, 'r', true);   
2022                if ($f)
2023                {
2024                        fclose($f);
2025                        $ok=true;
2026                }
2027                return $ok;
2028        }
2029
2030        /**
2031         * method: load_language
2032         * ---------------------
2033         * Gets language information and stores it for later use
2034         */
2035        function load_language ()
2036        {
2037                $file_name = $this->language_path . $this->language . '.php';
2038                if ( !$this->check_include($file_name))
2039                {
2040                        $this->error = GESHI_ERROR_NO_SUCH_LANG;
2041                        return;
2042                }
2043                require($file_name);
2044                // Perhaps some checking might be added here later to check that
2045                // $language data is a valid thing but maybe not
2046                $this->language_data = $language_data;
2047                // Set strict mode if should be set
2048                if ( $this->language_data['STRICT_MODE_APPLIES'] == GESHI_ALWAYS )
2049                {
2050                        $this->strict_mode = true;
2051                }
2052                // Set permissions for all lexics to true
2053                // so they'll be highlighted by default
2054                $this->enable_highlighting();
2055                // Set default class for CSS
2056                $this->overall_class = $this->language;
2057        }
2058
2059        /**
2060         * method: get_tab_replacement
2061         * ---------------------------
2062         * Gets the replacement string for tabs in the source code. Useful for
2063         * HTML highlighting, where tabs don't mean anything to a browser.
2064         */
2065         /*
2066        function get_tab_replacement ()
2067        {
2068                $i = 0;
2069                $result = '';
2070                while ( $i < $this->tab_width )
2071                {
2072                        $i++;
2073                        if ( $i % 2 == 0 )
2074                        {
2075                                $result .= ' ';
2076                        }
2077                        else
2078                        {
2079                                $result .= '&nbsp;';
2080                        }
2081                }
2082                return $result;
2083        }
2084        */
2085
2086        /**
2087         * method: finalise
2088         * ----------------
2089         * Takes the parsed code and various options, and creates the HTML
2090         * surrounding it to make it look nice.
2091         */
2092        function finalise ( $parsed_code )
2093        {
2094                // Remove end parts of important declarations
2095                // This is BUGGY!! My fault for bad code: fix coming in 1.2
2096                if ( $this->enable_important_blocks && (strstr($parsed_code, @htmlentities(GESHI_START_IMPORTANT, ENT_COMPAT, $this->encoding)) === false) )
2097                {
2098                        $parsed_code = str_replace(@htmlentities(GESHI_END_IMPORTANT, ENT_COMPAT, $this->encoding), '', $parsed_code);
2099                }
2100
2101                // Add HTML whitespace stuff if we're using the <div> header
2102                if ( $this->header_type == GESHI_HEADER_DIV )
2103                {
2104                        $parsed_code = $this->indent($parsed_code);
2105                }
2106
2107                // If we're using line numbers, we insert <li>s and appropriate
2108                // markup to style them (otherwise we don't need to do anything)
2109                if ( $this->line_numbers != GESHI_NO_LINE_NUMBERS )
2110                {
2111                        // If we're using the <pre> header, we shouldn't add newlines because
2112                        // the <pre> will line-break them (and the <li>s already do this for us)
2113                        $ls = ( $this->header_type != GESHI_HEADER_PRE ) ? "\n" : '';
2114                        // Get code into lines
2115                        $code = explode("\n", $parsed_code);
2116                        // Set vars to defaults for following loop
2117                        $parsed_code = '';
2118                        $i = 0;
2119                        // Foreach line...
2120                        foreach ( $code as $line )
2121                        {
2122                                $line = ( $line ) ? $line : '&nbsp;';
2123                                // If this is a "special line"...
2124                                if ( $this->line_numbers == GESHI_FANCY_LINE_NUMBERS && $i % $this->line_nth_row == ($this->line_nth_row - 1) )
2125                                {
2126                                        // Set the attributes to style the line
2127                                        if ( $this->use_classes )
2128                                        {
2129                                                $attr = ' class="li2"';
2130                                                $def_attr = ' class="de2"';
2131                                        }
2132                                        else
2133                                        {
2134                                                $attr = ' style="' . $this->line_style2 . '"';
2135                                                // This style "covers up" the special styles set for special lines
2136                                                // so that styles applied to special lines don't apply to the actual
2137                                                // code on that line
2138                                                $def_attr = ' style="' . $this->code_style . '"';
2139                                        }
2140                                        // Span or div?
2141                                        $start = "<div$def_attr>";
2142                                        $end = '</div>';
2143                                }
2144                                else
2145                                {
2146                                        if ( $this->use_classes )
2147                                        {
2148                                                $def_attr = ' class="de1"';
2149                                        }
2150                                        else
2151                                        {
2152                                                $def_attr = ' style="' . $this->code_style . '"';
2153                                        }
2154                                        // Reset everything
2155                                        $attr = '';
2156                                        // Span or div?
2157                                        $start = "<div$def_attr>";
2158                                        $end = '</div>';
2159                                }
2160
2161                                ++$i;
2162                                // Are we supposed to use ids? If so, add them
2163                                if ( $this->add_ids )
2164                                {
2165                                        $attr .= " id=\"{$this->overall_id}-{$i}\"";
2166                                }
2167                                if ( $this->use_classes && in_array($i, $this->highlight_extra_lines) )
2168                                {
2169                                        $attr .= " class=\"ln-xtra\"";
2170                                }
2171                                if ( !$this->use_classes && in_array($i, $this->highlight_extra_lines) )
2172                                {
2173                                        $attr .= " style=\"{$this->highlight_extra_lines_style}\"";
2174                                }
2175
2176                                // Add in the line surrounded by appropriate list HTML
2177                                $parsed_code .= "<li$attr>$start$line$end</li>$ls";
2178                        }
2179                }
2180                else
2181                {
2182                        // No line numbers, but still need to handle highlighting lines extra.
2183                        // Have to use divs so the full width of the code is highlighted
2184                        $code = explode("\n", $parsed_code);
2185                        $parsed_code = '';
2186                        $i = 0;
2187                        foreach ( $code as $line )
2188                        {
2189                                // Make lines have at least one space in them if they're empty
2190                                $line = ( $line ) ? $line : '&nbsp;';
2191                                if ( in_array(++$i, $this->highlight_extra_lines) )
2192                                {
2193                                        if ( $this->use_classes )
2194                                        {
2195                                                //$id = ( $this->overall_id != '' ) ? $this->overall_id . "-$i" : $this->overall_class . "-$i";
2196                                                $parsed_code .= '<div class="ln-xtra">';
2197                                        }
2198                                        else
2199                                        {
2200                                                $parsed_code .= "<div style=\"{$this->highlight_extra_lines_style}\">";
2201                                        }
2202                                        $parsed_code .= $line . "</div>\n";
2203                                }
2204                                else
2205                                {
2206                                        $parsed_code .= $line . "\n";
2207                                }
2208                        }
2209                }
2210
2211                // purge some unnecessary stuff
2212                $parsed_code = preg_replace('#<span[^>]+>(\s*)</span>#', '\\1', $parsed_code);
2213                $parsed_code = preg_replace('#<div[^>]+>(\s*)</div>#', '\\1', $parsed_code);
2214
2215                if ( $this->header_type == GESHI_HEADER_PRE )
2216                {
2217                        // enforce line numbers when using pre
2218                        $parsed_code = str_replace('<li></li>', '<li>&nbsp;</li>', $parsed_code);
2219                }
2220
2221                return $this->header() . chop($parsed_code) . $this->footer();
2222        }
2223
2224
2225        /**
2226         * method: header
2227         * --------------
2228         * Creates the header for the code block (with correct attributes)
2229         */
2230        function header ()
2231        {
2232                // Get attributes needed
2233                $attributes = $this->get_attributes();
2234
2235                /*if ( $this->use_classes )
2236                {*/
2237                        $ol_attributes = '';
2238                /*}
2239                else
2240                {
2241                        //$ol_attributes = ' style="margin: 0;"';
2242                }*/
2243
2244                if ( $this->line_numbers_start != 1 )
2245                {
2246                        $ol_attributes .= ' start="' . $this->line_numbers_start . '"';
2247                }
2248
2249                // Get the header HTML
2250                $header = $this->format_header_content();
2251
2252                // Work out what to return and do it
2253                if ( $this->line_numbers != GESHI_NO_LINE_NUMBERS )
2254                {
2255                        if ( $this->header_type == GESHI_HEADER_PRE )
2256                        {
2257                                return "<pre$attributes>$header<ol$ol_attributes>";
2258                        }
2259                        elseif ( $this->header_type == GESHI_HEADER_DIV )
2260                        {
2261                                return "<div$attributes>$header<ol$ol_attributes>";
2262                        }
2263                }
2264                else
2265                {
2266                        if ( $this->header_type == GESHI_HEADER_PRE )
2267                        {
2268                                return "<pre$attributes>$header";
2269                        }
2270                        elseif ( $this->header_type == GESHI_HEADER_DIV )
2271                        {
2272                                return "<div$attributes>$header";
2273                        }
2274                }
2275        }
2276
2277
2278        /**
2279         * method: format_header_content
2280         * -----------------------------
2281         * Returns the header content, formatted for output
2282         */
2283        function format_header_content ()
2284        {
2285                $header = $this->header_content;
2286                if ( $header )
2287                {
2288                        if ( $this->header_type == GESHI_HEADER_PRE )
2289                        {
2290                                $header = str_replace("\n", '', $header);
2291                        }
2292                        $header = $this->replace_keywords($header);
2293
2294                        if ( $this->use_classes )
2295                        {
2296                                $attr = ' class="head"';
2297                        }
2298                        else
2299                        {
2300                                $attr = " style=\"{$this->header_content_style}\"";
2301                        }
2302                        return "<div$attr>$header</div>";
2303                }
2304        }
2305
2306
2307        /**
2308         * method: footer
2309         * --------------
2310         * Returns the footer for the code block. Ending newline removed in 1.0.2
2311         */
2312        function footer ()
2313        {
2314                $footer_content = $this->format_footer_content();
2315
2316                if ( $this->header_type == GESHI_HEADER_DIV )
2317                {
2318                        if ( $this->line_numbers != GESHI_NO_LINE_NUMBERS )
2319                        {
2320                                return "</ol>$footer_content</div>";
2321                        }
2322                        return "$footer_content</div>";
2323                }
2324                else
2325                {
2326                        if ( $this->line_numbers != GESHI_NO_LINE_NUMBERS )
2327                        {
2328                                return "</ol>$footer_content</pre>";
2329                        }
2330                        return "$footer_content</pre>";
2331                }
2332        }
2333
2334
2335        /**
2336         * method: format_footer_content
2337         * -----------------------------
2338         * Returns the footer content, formatted for output
2339         */
2340        function format_footer_content ()
2341        {
2342                $footer = $this->footer_content;
2343                if ( $footer )
2344                {
2345                        if ( $this->header_type == GESHI_HEADER_PRE )
2346                        {
2347                                $footer = str_replace("\n", '', $footer);;
2348                        }
2349                        $footer = $this->replace_keywords($footer);
2350
2351                        if ( $this->use_classes )
2352                        {
2353                                $attr = ' class="foot"';
2354                        }
2355                        else
2356                        {
2357                                $attr = " style=\"{$this->footer_content_style}\">";
2358                        }
2359                        return "<div$attr>$footer</div>";
2360                }
2361        }
2362
2363
2364        /**
2365         * method: replace_keywords
2366         * ----------------------
2367         * Replaces certain keywords in the header and footer with
2368         * certain configuration values
2369         */
2370        function replace_keywords ( $instr )
2371        {
2372                $keywords = $replacements = array();
2373
2374                $keywords[] = '<TIME>';
2375                $replacements[] = number_format($this->get_time(), 3);
2376
2377                $keywords[] = '<LANGUAGE>';
2378                $replacements[] = $this->language;
2379
2380                $keywords[] = '<VERSION>';
2381                $replacements[] = '1.0.6';
2382
2383                return str_replace($keywords, $replacements, $instr);
2384        }
2385
2386        /**
2387         * method: get_attributes
2388         * ----------------------
2389         * Gets the CSS attributes for this code
2390         */
2391        function get_attributes ()
2392        {
2393                $attributes = '';
2394
2395                if ( $this->overall_class != '' && $this->use_classes )
2396                {
2397                        $attributes .= " class=\"{$this->overall_class}\"";
2398                }
2399                if ( $this->overall_id != '' )
2400                {
2401                        $attributes .= " id=\"{$this->overall_id}\"";
2402                }
2403                if ( $this->overall_style != '' && !$this->use_classes )
2404                {
2405                        $attributes .= ' style="' . $this->overall_style . '"';
2406                }
2407                return $attributes;
2408        }
2409
2410
2411        /**
2412         * method: get_stylesheet
2413         * ----------------------
2414         * Returns a stylesheet for the highlighted code. If $economy mode
2415         * is true, we only return the stylesheet declarations that matter for
2416         * this code block instead of the whole thing
2417         */
2418        function get_stylesheet ( $economy_mode = true )
2419        {
2420                // If there's an error, chances are that the language file
2421                // won't have populated the language data file, so we can't
2422                // risk getting a stylesheet...
2423                if ( $this->error )
2424                {
2425                        return '';
2426                }
2427                // First, work out what the selector should be. If there's an ID,
2428                // that should be used, the same for a class. Otherwise, a selector
2429                // of '' means that these styles will be applied anywhere
2430                $selector = ( $this->overall_id != '' ) ? "#{$this->overall_id} " : '';
2431                $selector = ( $selector == '' && $this->overall_class != '' ) ? ".{$this->overall_class} " : $selector;
2432
2433                // Header of the stylesheet
2434                if ( !$economy_mode )
2435                {
2436                        $stylesheet = "/**\n * GeSHi Dynamically Generated Stylesheet\n * --------------------------------------\n * Dynamically generated stylesheet for {$this->language}\n * CSS class: {$this->overall_class}, CSS id: {$this->overall_id}\n * GeSHi (c) Nigel McNie 2004 (http://qbnz.com/highlighter)\n */\n";
2437                }
2438                else
2439                {
2440                        $stylesheet = '/* GeSHi (c) Nigel McNie 2004 (http://qbnz.com/highlighter) */' . "\n";
2441                }
2442
2443                // Set the <ol> to have no effect at all if there are line numbers
2444                // (<ol>s have margins that should be destroyed so all layout is
2445                // controlled by the set_overall_style method, which works on the
2446                // <pre> or <div> container). Additionally, set default styles for lines
2447                if ( !$economy_mode || $this->line_numbers != GESHI_NO_LINE_NUMBERS )
2448                {
2449                        //$stylesheet .= "$selector, {$selector}ol, {$selector}ol li {margin: 0;}\n";
2450                        $stylesheet .= "$selector.de1, $selector.de2 {{$this->code_style}}\n";
2451                }
2452
2453                // Add overall styles
2454                if ( !$economy_mode || $this->overall_style != '' )
2455                {
2456                        $stylesheet .= "$selector {{$this->overall_style}}\n";
2457                }
2458
2459                // Add styles for links
2460                foreach ( $this->link_styles as $key => $style )
2461                {
2462                        if ( !$economy_mode || $key == GESHI_LINK && $style != '' )
2463                        {
2464                                $stylesheet .= "{$selector}a:link {{$style}}\n";
2465                        }
2466                        if ( !$economy_mode || $key == GESHI_HOVER && $style != '' )
2467                        {
2468                                $stylesheet .= "{$selector}a:hover {{$style}}\n";
2469                        }
2470                        if ( !$economy_mode || $key == GESHI_ACTIVE && $style != '' )
2471                        {
2472                                $stylesheet .= "{$selector}a:active {{$style}}\n";
2473                        }
2474                        if ( !$economy_mode || $key == GESHI_VISITED && $style != '' )
2475                        {
2476                                $stylesheet .= "{$selector}a:visited {{$style}}\n";
2477                        }
2478                }
2479
2480                // Header and footer
2481                if ( !$economy_mode || $this->header_content_style != '' )
2482                {
2483                        $stylesheet .= "$selector.head {{$this->header_content_style}}\n";
2484                }
2485                if ( !$economy_mode || $this->footer_content_style != '' )
2486                {
2487                        $stylesheet .= "$selector.foot {{$this->footer_content_style}}\n";
2488                }
2489
2490                // Styles for important stuff
2491                if ( !$economy_mode || $this->important_styles != '' )
2492                {
2493                        $stylesheet .= "$selector.imp {{$this->important_styles}}\n";
2494                }
2495
2496
2497                // Styles for lines being highlighted extra
2498                if ( !$economy_mode || count($this->highlight_extra_lines) )
2499                {
2500                        /*foreach ( $this->highlight_extra_lines as $line )
2501                        {
2502                                $id = ( $this->overall_id != '' ) ? $this->overall_id . "-$line" : $this->overall_class . "-$line";
2503                                $stylesheet .= "$selector#$id,";
2504                        }*/
2505                        $stylesheet .= "$selector.ln-xtra {{$this->highlight_extra_lines_style}}\n";
2506                }
2507
2508
2509                // Simple line number styles
2510                if ( !$economy_mode || ($this->line_numbers != GESHI_NO_LINE_NUMBERS && $this->line_style1 != '') )
2511                {
2512                        $stylesheet .= "{$selector}li {{$this->line_style1}}\n";
2513                }
2514
2515                // If there is a style set for fancy line numbers, echo it out
2516                if ( !$economy_mode || ($this->line_numbers == GESHI_FANCY_LINE_NUMBERS && $this->line_style2 != '') )
2517                {
2518                        $stylesheet .= "{$selector}li.li2 {{$this->line_style2}}\n";
2519                }
2520
2521
2522                foreach ( $this->language_data['STYLES']['KEYWORDS'] as $group => $styles )
2523                {
2524                        if ( !$economy_mode || !($economy_mode && (!$this->lexic_permissions['KEYWORDS'][$group] || $styles == '')) )
2525                        {
2526                                $stylesheet .= "$selector.kw$group {{$styles}}\n";
2527                        }
2528                }
2529                foreach ( $this->language_data['STYLES']['COMMENTS'] as $group => $styles )
2530                {
2531                        if ( !$economy_mode || !($economy_mode && $styles == '') && !($economy_mode && !$this->lexic_permissions['COMMENTS'][$group]) )
2532                        {
2533                                $stylesheet .= "$selector.co$group {{$styles}}\n";
2534                        }
2535                }
2536                foreach ( $this->language_data['STYLES']['ESCAPE_CHAR'] as $group => $styles )
2537                {
2538                        if ( !$economy_mode || !($economy_mode && $styles == '') && !($economy_mode && !$this->lexic_permissions['ESCAPE_CHAR']) )
2539                        {
2540                                $stylesheet .= "$selector.es$group {{$styles}}\n";
2541                        }
2542                }
2543                foreach ( $this->language_data['STYLES']['SYMBOLS'] as $group => $styles )
2544                {
2545                        if ( !$economy_mode || !($economy_mode && $styles == '') && !($economy_mode && !$this->lexic_permissions['BRACKETS']) )
2546                        {
2547                                $stylesheet .= "$selector.br$group {{$styles}}\n";
2548                        }
2549                }
2550                foreach ( $this->language_data['STYLES']['STRINGS'] as $group => $styles )
2551                {
2552                        if ( !$economy_mode || !($economy_mode && $styles == '') && !($economy_mode && !$this->lexic_permissions['STRINGS']) )
2553                        {
2554                                $stylesheet .= "$selector.st$group {{$styles}}\n";
2555                        }
2556                }
2557                foreach ( $this->language_data['STYLES']['NUMBERS'] as $group => $styles )
2558                {
2559                        if ( !$economy_mode || !($economy_mode && $styles == '') && !($economy_mode && !$this->lexic_permissions['NUMBERS']) )
2560                        {
2561                                $stylesheet .= "$selector.nu$group {{$styles}}\n";
2562                        }
2563                }
2564                foreach ( $this->language_data['STYLES']['METHODS'] as $group => $styles )
2565                {
2566                        if ( !$economy_mode || !($economy_mode && $styles == '') && !($economy_mode && !$this->lexic_permissions['METHODS']) )
2567                        {
2568                                $stylesheet .= "$selector.me$group {{$styles}}\n";
2569                        }
2570                }
2571                foreach ( $this->language_data['STYLES']['SCRIPT'] as $group => $styles )
2572                {
2573                        if ( !$economy_mode || !($economy_mode && $styles == '') /*&& !($economy_mode && !$this->lexic_permissions['SCRIPT'])*/ )
2574                        {
2575                                $stylesheet .= "$selector.sc$group {{$styles}}\n";
2576                        }
2577                }
2578                foreach ( $this->language_data['STYLES']['REGEXPS'] as $group => $styles )
2579                {
2580                        if ( !$economy_mode || !($economy_mode && $styles == '') && !($economy_mode && !$this->lexic_permissions['REGEXPS'][$group]) )
2581                        {
2582                                $stylesheet .= "$selector.re$group {{$styles}}\n";
2583                        }
2584                }
2585
2586                return $stylesheet;
2587        }
2588
2589} // End Class GeSHi
2590
2591
2592if ( !function_exists('geshi_highlight') )
2593{
2594        /**
2595        * function: geshi_highlight
2596        * -------------------------
2597        * Easy way to highlight stuff. Behaves just like highlight_string
2598        */
2599        function geshi_highlight ( $string, $language, $path, $return = false )
2600        {
2601                $geshi = new GeSHi($string, $language, $path);
2602                $geshi->set_header_type(GESHI_HEADER_DIV);
2603                if ( $return )
2604                {
2605                        return str_replace('<div>', '<code>', str_replace('</div>', '</code>', $geshi->parse_code()));
2606                }
2607                echo str_replace('<div>', '<code>', str_replace('</div>', '</code>', $geshi->parse_code()));
2608                if ( $geshi->error() )
2609                {
2610                        return false;
2611                }
2612                return true;
2613        }
2614}
2615
2616?>
Note: See TracBrowser for help on using the browser.