3 * GeSHi - Generic Syntax Highlighter
5 * The GeSHi class for Generic Syntax Highlighting. Please refer to the
6 * documentation at http://qbnz.com/highlighter/documentation.php for more
7 * information about how to use this class.
9 * For changes, release notes, TODOs etc, see the relevant files in the docs/
12 * This file is part of GeSHi.
14 * GeSHi is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 2 of the License, or
17 * (at your option) any later version.
19 * GeSHi is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with GeSHi; if not, write to the Free Software
26 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30 * @author Nigel McNie <nigel@geshi.org>
31 * @copyright (C) 2004 - 2007 Nigel McNie
32 * @license http://gnu.org/copyleft/gpl.html GNU GPL
38 // You should use these constant names in your programs instead of
39 // their values - you never know when a value may change in a future
43 /** The version of this GeSHi file */
44 define('GESHI_VERSION', '1.0.7.19');
46 // Define the root directory for the GeSHi code tree
47 if (!defined('GESHI_ROOT')) {
48 /** The root directory for GeSHi */
49 define('GESHI_ROOT', dirname(__FILE__
) . DIRECTORY_SEPARATOR
);
51 /** The language file directory for GeSHi
53 define('GESHI_LANG_ROOT', GESHI_ROOT
. 'geshi' . DIRECTORY_SEPARATOR
);
56 // Line numbers - use with enable_line_numbers()
57 /** Use no line numbers when building the result */
58 define('GESHI_NO_LINE_NUMBERS', 0);
59 /** Use normal line numbers when building the result */
60 define('GESHI_NORMAL_LINE_NUMBERS', 1);
61 /** Use fancy line numbers when building the result */
62 define('GESHI_FANCY_LINE_NUMBERS', 2);
64 // Container HTML type
65 /** Use nothing to surround the source */
66 define('GESHI_HEADER_NONE', 0);
67 /** Use a "div" to surround the source */
68 define('GESHI_HEADER_DIV', 1);
69 /** Use a "pre" to surround the source */
70 define('GESHI_HEADER_PRE', 2);
72 // Capatalisation constants
73 /** Lowercase keywords found */
74 define('GESHI_CAPS_NO_CHANGE', 0);
75 /** Uppercase keywords found */
76 define('GESHI_CAPS_UPPER', 1);
77 /** Leave keywords found as the case that they are */
78 define('GESHI_CAPS_LOWER', 2);
80 // Link style constants
81 /** Links in the source in the :link state */
82 define('GESHI_LINK', 0);
83 /** Links in the source in the :hover state */
84 define('GESHI_HOVER', 1);
85 /** Links in the source in the :active state */
86 define('GESHI_ACTIVE', 2);
87 /** Links in the source in the :visited state */
88 define('GESHI_VISITED', 3);
90 // Important string starter/finisher
91 // Note that if you change these, they should be as-is: i.e., don't
92 // write them as if they had been run through htmlentities()
93 /** The starter for important parts of the source */
94 define('GESHI_START_IMPORTANT', '<BEGIN GeSHi>');
95 /** The ender for important parts of the source */
96 define('GESHI_END_IMPORTANT', '<END GeSHi>');
101 // When strict mode applies for a language
102 /** Strict mode never applies (this is the most common) */
103 define('GESHI_NEVER', 0);
104 /** Strict mode *might* apply, and can be enabled or
105 disabled by {@link GeSHi::enable_strict_mode()} */
106 define('GESHI_MAYBE', 1);
107 /** Strict mode always applies */
108 define('GESHI_ALWAYS', 2);
110 // Advanced regexp handling constants, used in language files
111 /** The key of the regex array defining what to search for */
112 define('GESHI_SEARCH', 0);
113 /** The key of the regex array defining what bracket group in a
114 matched search to use as a replacement */
115 define('GESHI_REPLACE', 1);
116 /** The key of the regex array defining any modifiers to the regular expression */
117 define('GESHI_MODIFIERS', 2);
118 /** The key of the regex array defining what bracket group in a
119 matched search to put before the replacement */
120 define('GESHI_BEFORE', 3);
121 /** The key of the regex array defining what bracket group in a
122 matched search to put after the replacement */
123 define('GESHI_AFTER', 4);
124 /** The key of the regex array defining a custom keyword to use
125 for this regexp's html tag class */
126 define('GESHI_CLASS', 5);
128 /** Used in language files to mark comments */
129 define('GESHI_COMMENTS', 0);
131 // Error detection - use these to analyse faults
132 /** No sourcecode to highlight was specified
135 define('GESHI_ERROR_NO_INPUT', 1);
136 /** The language specified does not exist */
137 define('GESHI_ERROR_NO_SUCH_LANG', 2);
138 /** GeSHi could not open a file for reading (generally a language file) */
139 define('GESHI_ERROR_FILE_NOT_READABLE', 3);
140 /** The header type passed to {@link GeSHi::set_header_type()} was invalid */
141 define('GESHI_ERROR_INVALID_HEADER_TYPE', 4);
142 /** The line number type passed to {@link GeSHi::enable_line_numbers()} was invalid */
143 define('GESHI_ERROR_INVALID_LINE_NUMBER_TYPE', 5);
150 * Please refer to the documentation for GeSHi 1.0.X that is available
151 * at http://qbnz.com/highlighter/documentation.php for more information
152 * about how to use this class.
155 * @author Nigel McNie <nigel@geshi.org>
156 * @copyright (C) 2004 - 2007 Nigel McNie
163 * The source code to highlight
169 * The language to use when highlighting
175 * The data for the language used
178 var $language_data = array();
181 * The path to the language files
184 var $language_path = GESHI_LANG_ROOT
;
187 * The error message associated with an error
189 * @todo check err reporting works
194 * Possible error messages
197 var $error_messages = array(
198 GESHI_ERROR_NO_SUCH_LANG
=> 'GeSHi could not find the language {LANGUAGE} (using path {PATH})',
199 GESHI_ERROR_FILE_NOT_READABLE
=> 'The file specified for load_from_file was not readable',
200 GESHI_ERROR_INVALID_HEADER_TYPE
=> 'The header type specified is invalid',
201 GESHI_ERROR_INVALID_LINE_NUMBER_TYPE
=> 'The line number type specified is invalid'
205 * Whether highlighting is strict or not
208 var $strict_mode = false
;
211 * Whether to use CSS classes in output
214 var $use_classes = false
;
217 * The type of header to use. Can be one of the following
220 * - GESHI_HEADER_PRE: Source is outputted in a "pre" HTML element.
221 * - GESHI_HEADER_DIV: Source is outputted in a "div" HTML element.
222 * - GESHI_HEADER_NONE: No header is outputted.
226 var $header_type = GESHI_HEADER_PRE
;
229 * Array of permissions for which lexics should be highlighted
232 var $lexic_permissions = array(
233 'KEYWORDS' => array(),
234 'COMMENTS' => array('MULTI' => true
),
235 'REGEXPS' => array(),
236 'ESCAPE_CHAR' => true
,
246 * The time it took to parse the code
252 * The content of the header block
255 var $header_content = '';
258 * The content of the footer block
261 var $footer_content = '';
264 * The style of the header block
267 var $header_content_style = '';
270 * The style of the footer block
273 var $footer_content_style = '';
276 * The styles for hyperlinks in the code
279 var $link_styles = array();
282 * Whether important blocks should be recognised or not
285 * @todo REMOVE THIS FUNCTIONALITY!
287 var $enable_important_blocks = false
;
290 * Styles for important parts of the code
293 * @todo As above - rethink the whole idea of important blocks as it is buggy and
294 * will be hard to implement in 1.2
296 var $important_styles = 'font-weight: bold; color: red;'; // Styles for important parts of the code
299 * Whether CSS IDs should be added to the code
302 var $add_ids = false
;
305 * Lines that should be highlighted extra
308 var $highlight_extra_lines = array();
311 * Styles of extra-highlighted lines
314 var $highlight_extra_lines_style = 'color: #cc0; background-color: #ffc;';
317 * Number at which line numbers should start at
320 var $line_numbers_start = 1;
323 * The overall style for this code block
326 var $overall_style = '';
329 * The style for the actual code
332 var $code_style = 'font-family: \'Courier New\', Courier, monospace; font-weight: normal;';
335 * The overall class for this code block
338 var $overall_class = '';
341 * The overall ID for this code block
344 var $overall_id = '';
350 var $line_style1 = 'font-family: \'Courier New\', Courier, monospace; color: black; font-weight: normal; font-style: normal;';
353 * Line number styles for fancy lines
356 var $line_style2 = 'font-weight: bold;';
359 * Flag for how line nubmers are displayed
362 var $line_numbers = GESHI_NO_LINE_NUMBERS
;
365 * The "nth" value for fancy line highlighting
368 var $line_nth_row = 0;
371 * The size of tab stops
377 * Default target for keyword links
380 var $link_target = '';
383 * The encoding to use for entity encoding
384 * NOTE: no longer used
387 var $encoding = 'ISO-8859-1';
390 * Should keywords be linked?
393 var $keyword_links = true
;
398 * Creates a new GeSHi object, with source and language
400 * @param string The source code to highlight
401 * @param string The language to highlight the source with
402 * @param string The path to the language file directory. <b>This
403 * is deprecated!</b> I've backported the auto path
404 * detection from the 1.1.X dev branch, so now it
405 * should be automatically set correctly. If you have
406 * renamed the language directory however, you will
407 * still need to set the path using this parameter or
408 * {@link GeSHi::set_language_path()}
411 function GeSHi($source, $language, $path = '') {
412 $this->set_source($source);
413 $this->set_language_path($path);
414 $this->set_language($language);
418 * Returns an error message associated with the last GeSHi operation,
419 * or false if no error has occured
421 * @return string|false An error message if there has been an error, else false
426 $msg = $this->error_messages
[$this->error
];
427 $debug_tpl_vars = array(
428 '{LANGUAGE}' => $this->language
,
429 '{PATH}' => $this->language_path
431 foreach ($debug_tpl_vars as $tpl => $var) {
432 $msg = str_replace($tpl, $var, $msg);
434 return "<br /><strong>GeSHi Error:</strong> $msg (code $this->error)<br />";
440 * Gets a human-readable language name (thanks to Simon Patterson
443 * @return string The name for the current language
446 function get_language_name() {
447 if (GESHI_ERROR_NO_SUCH_LANG
== $this->error
) {
448 return $this->language_data
['LANG_NAME'] . ' (Unknown Language)';
450 return $this->language_data
['LANG_NAME'];
454 * Sets the source code for this object
456 * @param string The source code to highlight
459 function set_source($source) {
460 $this->source
= $source;
461 $this->highlight_extra_lines
= array();
465 * Sets the language for this object
467 * @param string The name of the language to use
470 function set_language($language) {
471 $this->error
= false
;
472 $this->strict_mode
= GESHI_NEVER
;
474 $language = preg_replace('#[^a-zA-Z0-9\-_]#', '', $language);
475 $this->language
= strtolower($language);
477 $file_name = $this->language_path
. $this->language
. '.php';
478 if (!is_readable($file_name)) {
479 $this->error
= GESHI_ERROR_NO_SUCH_LANG
;
482 // Load the language for parsing
483 $this->load_language($file_name);
487 * Sets the path to the directory containing the language files. Note
488 * that this path is relative to the directory of the script that included
489 * geshi.php, NOT geshi.php itself.
491 * @param string The path to the language directory
493 * @deprecated The path to the language files should now be automatically
494 * detected, so this method should no longer be needed. The
495 * 1.1.X branch handles manual setting of the path differently
496 * so this method will disappear in 1.2.0.
498 function set_language_path($path) {
500 $this->language_path
= ('/' == substr($path, strlen($path) - 1, 1)) ?
$path : $path . '/';
501 $this->set_language($this->language
); // otherwise set_language_path has no effect
506 * Sets the type of header to be used.
508 * If GESHI_HEADER_DIV is used, the code is surrounded in a "div".This
509 * means more source code but more control over tab width and line-wrapping.
510 * GESHI_HEADER_PRE means that a "pre" is used - less source, but less
511 * control. Default is GESHI_HEADER_PRE.
513 * From 1.0.7.2, you can use GESHI_HEADER_NONE to specify that no header code
514 * should be outputted.
516 * @param int The type of header to be used
519 function set_header_type($type) {
520 if (GESHI_HEADER_DIV
!= $type && GESHI_HEADER_PRE
!= $type && GESHI_HEADER_NONE
!= $type) {
521 $this->error
= GESHI_ERROR_INVALID_HEADER_TYPE
;
524 $this->header_type
= $type;
525 // Set a default overall style if the header is a <div>
526 if (GESHI_HEADER_DIV
== $type && !$this->overall_style
) {
527 $this->overall_style
= 'font-family: monospace;';
532 * Sets the styles for the code that will be outputted
533 * when this object is parsed. The style should be a
534 * string of valid stylesheet declarations
536 * @param string The overall style for the outputted code block
537 * @param boolean Whether to merge the styles with the current styles or not
540 function set_overall_style($style, $preserve_defaults = false
) {
541 if (!$preserve_defaults) {
542 $this->overall_style
= $style;
545 $this->overall_style
.= $style;
550 * Sets the overall classname for this block of code. This
551 * class can then be used in a stylesheet to style this object's
554 * @param string The class name to use for this block of code
557 function set_overall_class($class) {
558 $this->overall_class
= $class;
562 * Sets the overall id for this block of code. This id can then
563 * be used in a stylesheet to style this object's output
565 * @param string The ID to use for this block of code
568 function set_overall_id($id) {
569 $this->overall_id
= $id;
573 * Sets whether CSS classes should be used to highlight the source. Default
574 * is off, calling this method with no arguments will turn it on
576 * @param boolean Whether to turn classes on or not
579 function enable_classes($flag = true
) {
580 $this->use_classes
= ($flag) ? true
: false
;
584 * Sets the style for the actual code. This should be a string
585 * containing valid stylesheet declarations. If $preserve_defaults is
586 * true, then styles are merged with the default styles, with the
587 * user defined styles having priority
589 * Note: Use this method to override any style changes you made to
590 * the line numbers if you are using line numbers, else the line of
591 * code will have the same style as the line number! Consult the
592 * GeSHi documentation for more information about this.
594 * @param string The style to use for actual code
595 * @param boolean Whether to merge the current styles with the new styles
597 function set_code_style($style, $preserve_defaults = false
) {
598 if (!$preserve_defaults) {
599 $this->code_style
= $style;
602 $this->code_style
.= $style;
607 * Sets the styles for the line numbers.
609 * @param string The style for the line numbers that are "normal"
610 * @param string|boolean If a string, this is the style of the line
611 * numbers that are "fancy", otherwise if boolean then this
612 * defines whether the normal styles should be merged with the
613 * new normal styles or not
614 * @param boolean If set, is the flag for whether to merge the "fancy"
615 * styles with the current styles or not
618 function set_line_style($style1, $style2 = '', $preserve_defaults = false
) {
619 if (is_bool($style2)) {
620 $preserve_defaults = $style2;
623 if (!$preserve_defaults) {
624 $this->line_style1
= $style1;
625 $this->line_style2
= $style2;
628 $this->line_style1
.= $style1;
629 $this->line_style2
.= $style2;
634 * Sets whether line numbers should be displayed.
636 * Valid values for the first parameter are:
638 * - GESHI_NO_LINE_NUMBERS: Line numbers will not be displayed
639 * - GESHI_NORMAL_LINE_NUMBERS: Line numbers will be displayed
640 * - GESHI_FANCY_LINE_NUMBERS: Fancy line numbers will be displayed
642 * For fancy line numbers, the second parameter is used to signal which lines
643 * are to be fancy. For example, if the value of this parameter is 5 then every
644 * 5th line will be fancy.
646 * @param int How line numbers should be displayed
647 * @param int Defines which lines are fancy
650 function enable_line_numbers($flag, $nth_row = 5) {
651 if (GESHI_NO_LINE_NUMBERS
!= $flag && GESHI_NORMAL_LINE_NUMBERS
!= $flag
652 && GESHI_FANCY_LINE_NUMBERS
!= $flag) {
653 $this->error
= GESHI_ERROR_INVALID_LINE_NUMBER_TYPE
;
655 $this->line_numbers
= $flag;
656 $this->line_nth_row
= $nth_row;
660 * Sets the style for a keyword group. If $preserve_defaults is
661 * true, then styles are merged with the default styles, with the
662 * user defined styles having priority
664 * @param int The key of the keyword group to change the styles of
665 * @param string The style to make the keywords
666 * @param boolean Whether to merge the new styles with the old or just
670 function set_keyword_group_style($key, $style, $preserve_defaults = false
) {
671 if (!$preserve_defaults) {
672 $this->language_data
['STYLES']['KEYWORDS'][$key] = $style;
675 $this->language_data
['STYLES']['KEYWORDS'][$key] .= $style;
680 * Turns highlighting on/off for a keyword group
682 * @param int The key of the keyword group to turn on or off
683 * @param boolean Whether to turn highlighting for that group on or off
686 function set_keyword_group_highlighting($key, $flag = true
) {
687 $this->lexic_permissions
['KEYWORDS'][$key] = ($flag) ? true
: false
;
691 * Sets the styles for comment groups. If $preserve_defaults is
692 * true, then styles are merged with the default styles, with the
693 * user defined styles having priority
695 * @param int The key of the comment group to change the styles of
696 * @param string The style to make the comments
697 * @param boolean Whether to merge the new styles with the old or just
701 function set_comments_style($key, $style, $preserve_defaults = false
) {
702 if (!$preserve_defaults) {
703 $this->language_data
['STYLES']['COMMENTS'][$key] = $style;
706 $this->language_data
['STYLES']['COMMENTS'][$key] .= $style;
711 * Turns highlighting on/off for comment groups
713 * @param int The key of the comment group to turn on or off
714 * @param boolean Whether to turn highlighting for that group on or off
717 function set_comments_highlighting($key, $flag = true
) {
718 $this->lexic_permissions
['COMMENTS'][$key] = ($flag) ? true
: false
;
722 * Sets the styles for escaped characters. If $preserve_defaults is
723 * true, then styles are merged with the default styles, with the
724 * user defined styles having priority
726 * @param string The style to make the escape characters
727 * @param boolean Whether to merge the new styles with the old or just
731 function set_escape_characters_style($style, $preserve_defaults = false
) {
732 if (!$preserve_defaults) {
733 $this->language_data
['STYLES']['ESCAPE_CHAR'][0] = $style;
736 $this->language_data
['STYLES']['ESCAPE_CHAR'][0] .= $style;
741 * Turns highlighting on/off for escaped characters
743 * @param boolean Whether to turn highlighting for escape characters on or off
746 function set_escape_characters_highlighting($flag = true
) {
747 $this->lexic_permissions
['ESCAPE_CHAR'] = ($flag) ? true
: false
;
751 * Sets the styles for brackets. If $preserve_defaults is
752 * true, then styles are merged with the default styles, with the
753 * user defined styles having priority
755 * This method is DEPRECATED: use set_symbols_style instead.
756 * This method will be removed in 1.2.X
758 * @param string The style to make the brackets
759 * @param boolean Whether to merge the new styles with the old or just
762 * @deprecated In favour of set_symbols_style
764 function set_brackets_style($style, $preserve_defaults = false
) {
765 if (!$preserve_defaults) {
766 $this->language_data
['STYLES']['BRACKETS'][0] = $style;
769 $this->language_data
['STYLES']['BRACKETS'][0] .= $style;
774 * Turns highlighting on/off for brackets
776 * This method is DEPRECATED: use set_symbols_highlighting instead.
777 * This method will be remove in 1.2.X
779 * @param boolean Whether to turn highlighting for brackets on or off
781 * @deprecated In favour of set_symbols_highlighting
783 function set_brackets_highlighting($flag) {
784 $this->lexic_permissions
['BRACKETS'] = ($flag) ? true
: false
;
788 * Sets the styles for symbols. If $preserve_defaults is
789 * true, then styles are merged with the default styles, with the
790 * user defined styles having priority
792 * @param string The style to make the symbols
793 * @param boolean Whether to merge the new styles with the old or just
797 function set_symbols_style($style, $preserve_defaults = false
) {
798 if (!$preserve_defaults) {
799 $this->language_data
['STYLES']['SYMBOLS'][0] = $style;
802 $this->language_data
['STYLES']['SYMBOLS'][0] .= $style;
804 // For backward compatibility
805 $this->set_brackets_style ($style, $preserve_defaults);
809 * Turns highlighting on/off for symbols
811 * @param boolean Whether to turn highlighting for symbols on or off
814 function set_symbols_highlighting($flag) {
815 $this->lexic_permissions
['SYMBOLS'] = ($flag) ? true
: false
;
816 // For backward compatibility
817 $this->set_brackets_highlighting ($flag);
821 * Sets the styles for strings. If $preserve_defaults is
822 * true, then styles are merged with the default styles, with the
823 * user defined styles having priority
825 * @param string The style to make the escape characters
826 * @param boolean Whether to merge the new styles with the old or just
830 function set_strings_style($style, $preserve_defaults = false
) {
831 if (!$preserve_defaults) {
832 $this->language_data
['STYLES']['STRINGS'][0] = $style;
835 $this->language_data
['STYLES']['STRINGS'][0] .= $style;
840 * Turns highlighting on/off for strings
842 * @param boolean Whether to turn highlighting for strings on or off
845 function set_strings_highlighting($flag) {
846 $this->lexic_permissions
['STRINGS'] = ($flag) ? true
: false
;
850 * Sets the styles for numbers. If $preserve_defaults is
851 * true, then styles are merged with the default styles, with the
852 * user defined styles having priority
854 * @param string The style to make the numbers
855 * @param boolean Whether to merge the new styles with the old or just
859 function set_numbers_style($style, $preserve_defaults = false
) {
860 if (!$preserve_defaults) {
861 $this->language_data
['STYLES']['NUMBERS'][0] = $style;
864 $this->language_data
['STYLES']['NUMBERS'][0] .= $style;
869 * Turns highlighting on/off for numbers
871 * @param boolean Whether to turn highlighting for numbers on or off
874 function set_numbers_highlighting($flag) {
875 $this->lexic_permissions
['NUMBERS'] = ($flag) ? true
: false
;
879 * Sets the styles for methods. $key is a number that references the
880 * appropriate "object splitter" - see the language file for the language
881 * you are highlighting to get this number. If $preserve_defaults is
882 * true, then styles are merged with the default styles, with the
883 * user defined styles having priority
885 * @param int The key of the object splitter to change the styles of
886 * @param string The style to make the methods
887 * @param boolean Whether to merge the new styles with the old or just
891 function set_methods_style($key, $style, $preserve_defaults = false
) {
892 if (!$preserve_defaults) {
893 $this->language_data
['STYLES']['METHODS'][$key] = $style;
896 $this->language_data
['STYLES']['METHODS'][$key] .= $style;
901 * Turns highlighting on/off for methods
903 * @param boolean Whether to turn highlighting for methods on or off
906 function set_methods_highlighting($flag) {
907 $this->lexic_permissions
['METHODS'] = ($flag) ? true
: false
;
911 * Sets the styles for regexps. If $preserve_defaults is
912 * true, then styles are merged with the default styles, with the
913 * user defined styles having priority
915 * @param string The style to make the regular expression matches
916 * @param boolean Whether to merge the new styles with the old or just
920 function set_regexps_style($key, $style, $preserve_defaults = false
) {
921 if (!$preserve_defaults) {
922 $this->language_data
['STYLES']['REGEXPS'][$key] = $style;
925 $this->language_data
['STYLES']['REGEXPS'][$key] .= $style;
930 * Turns highlighting on/off for regexps
932 * @param int The key of the regular expression group to turn on or off
933 * @param boolean Whether to turn highlighting for the regular expression group on or off
936 function set_regexps_highlighting($key, $flag) {
937 $this->lexic_permissions
['REGEXPS'][$key] = ($flag) ? true
: false
;
941 * Sets whether a set of keywords are checked for in a case sensitive manner
943 * @param int The key of the keyword group to change the case sensitivity of
944 * @param boolean Whether to check in a case sensitive manner or not
947 function set_case_sensitivity($key, $case) {
948 $this->language_data
['CASE_SENSITIVE'][$key] = ($case) ? true
: false
;
952 * Sets the case that keywords should use when found. Use the constants:
954 * - GESHI_CAPS_NO_CHANGE: leave keywords as-is
955 * - GESHI_CAPS_UPPER: convert all keywords to uppercase where found
956 * - GESHI_CAPS_LOWER: convert all keywords to lowercase where found
958 * @param int A constant specifying what to do with matched keywords
960 * @todo Error check the passed value
962 function set_case_keywords($case) {
963 $this->language_data
['CASE_KEYWORDS'] = $case;
967 * Sets how many spaces a tab is substituted for
969 * Widths below zero are ignored
971 * @param int The tab width
974 function set_tab_width($width) {
975 $this->tab_width
= intval($width);
979 * Enables/disables strict highlighting. Default is off, calling this
980 * method without parameters will turn it on. See documentation
981 * for more details on strict mode and where to use it.
983 * @param boolean Whether to enable strict mode or not
986 function enable_strict_mode($mode = true
) {
987 if (GESHI_MAYBE
== $this->language_data
['STRICT_MODE_APPLIES']) {
988 $this->strict_mode
= ($mode) ? true
: false
;
993 * Disables all highlighting
996 * @todo Rewrite with an array traversal
998 function disable_highlighting() {
999 foreach ($this->lexic_permissions
as $key => $value) {
1000 if (is_array($value)) {
1001 foreach ($value as $k => $v) {
1002 $this->lexic_permissions
[$key][$k] = false
;
1006 $this->lexic_permissions
[$key] = false
;
1010 $this->enable_important_blocks
= false
;
1014 * Enables all highlighting
1017 * @todo Rewrite with array traversal
1019 function enable_highlighting() {
1020 foreach ($this->lexic_permissions
as $key => $value) {
1021 if (is_array($value)) {
1022 foreach ($value as $k => $v) {
1023 $this->lexic_permissions
[$key][$k] = true
;
1027 $this->lexic_permissions
[$key] = true
;
1031 $this->enable_important_blocks
= true
;
1035 * Given a file extension, this method returns either a valid geshi language
1036 * name, or the empty string if it couldn't be found
1038 * @param string The extension to get a language name for
1039 * @param array A lookup array to use instead of the default
1041 * @todo Re-think about how this method works (maybe make it private and/or make it
1042 * a extension->lang lookup?)
1045 function get_language_name_from_extension( $extension, $lookup = array() ) {
1048 'actionscript' => array('as'),
1049 'ada' => array('a', 'ada', 'adb', 'ads'),
1050 'apache' => array('conf'),
1051 'asm' => array('ash', 'asm'),
1052 'asp' => array('asp'),
1053 'bash' => array('sh'),
1054 'c' => array('c', 'h'),
1055 'c_mac' => array('c', 'h'),
1056 'caddcl' => array(),
1057 'cadlisp' => array(),
1058 'cdfg' => array('cdfg'),
1059 'cpp' => array('cpp', 'h', 'hpp'),
1060 'csharp' => array(),
1061 'css' => array('css'),
1062 'delphi' => array('dpk', 'dpr'),
1063 'html4strict' => array('html', 'htm'),
1064 'java' => array('java'),
1065 'javascript' => array('js'),
1066 'lisp' => array('lisp'),
1067 'lua' => array('lua'),
1072 'oracle8' => array(),
1073 'pascal' => array('pas'),
1074 'perl' => array('pl', 'pm'),
1075 'php' => array('php', 'php5', 'phtml', 'phps'),
1076 'python' => array('py'),
1077 'qbasic' => array('bi'),
1078 'sas' => array('sas'),
1079 'smarty' => array(),
1080 'vb' => array('bas'),
1082 'visualfoxpro' => array(),
1083 'xml' => array('xml')
1087 foreach ($lookup as $lang => $extensions) {
1088 foreach ($extensions as $ext) {
1089 if ($ext == $extension) {
1098 * Given a file name, this method loads its contents in, and attempts
1099 * to set the language automatically. An optional lookup table can be
1100 * passed for looking up the language name. If not specified a default
1103 * The language table is in the form
1105 * 'lang_name' => array('extension', 'extension', ...),
1109 * @todo Complete rethink of this and above method
1112 function load_from_file($file_name, $lookup = array()) {
1113 if (is_readable($file_name)) {
1114 $this->set_source(implode('', file($file_name)));
1115 $this->set_language($this->get_language_name_from_extension(substr(strrchr($file_name, '.'), 1), $lookup));
1118 $this->error
= GESHI_ERROR_FILE_NOT_READABLE
;
1123 * Adds a keyword to a keyword group for highlighting
1125 * @param int The key of the keyword group to add the keyword to
1126 * @param string The word to add to the keyword group
1129 function add_keyword($key, $word) {
1130 $this->language_data
['KEYWORDS'][$key][] = $word;
1134 * Removes a keyword from a keyword group
1136 * @param int The key of the keyword group to remove the keyword from
1137 * @param string The word to remove from the keyword group
1140 function remove_keyword($key, $word) {
1141 $this->language_data
['KEYWORDS'][$key] =
1142 array_diff($this->language_data
['KEYWORDS'][$key], array($word));
1146 * Creates a new keyword group
1148 * @param int The key of the keyword group to create
1149 * @param string The styles for the keyword group
1150 * @param boolean Whether the keyword group is case sensitive ornot
1151 * @param array The words to use for the keyword group
1154 function add_keyword_group($key, $styles, $case_sensitive = true
, $words = array()) {
1155 $words = (array) $words;
1156 $this->language_data
['KEYWORDS'][$key] = $words;
1157 $this->lexic_permissions
['KEYWORDS'][$key] = true
;
1158 $this->language_data
['CASE_SENSITIVE'][$key] = $case_sensitive;
1159 $this->language_data
['STYLES']['KEYWORDS'][$key] = $styles;
1163 * Removes a keyword group
1165 * @param int The key of the keyword group to remove
1168 function remove_keyword_group ($key) {
1169 unset($this->language_data
['KEYWORDS'][$key]);
1170 unset($this->lexic_permissions
['KEYWORDS'][$key]);
1171 unset($this->language_data
['CASE_SENSITIVE'][$key]);
1172 unset($this->language_data
['STYLES']['KEYWORDS'][$key]);
1176 * Sets the content of the header block
1178 * @param string The content of the header block
1181 function set_header_content($content) {
1182 $this->header_content
= $content;
1186 * Sets the content of the footer block
1188 * @param string The content of the footer block
1191 function set_footer_content($content) {
1192 $this->footer_content
= $content;
1196 * Sets the style for the header content
1198 * @param string The style for the header content
1201 function set_header_content_style($style) {
1202 $this->header_content_style
= $style;
1206 * Sets the style for the footer content
1208 * @param string The style for the footer content
1211 function set_footer_content_style($style) {
1212 $this->footer_content_style
= $style;
1216 * Sets the base URL to be used for keywords
1218 * @param int The key of the keyword group to set the URL for
1219 * @param string The URL to set for the group. If {FNAME} is in
1220 * the url somewhere, it is replaced by the keyword
1221 * that the URL is being made for
1224 function set_url_for_keyword_group($group, $url) {
1225 $this->language_data
['URLS'][$group] = $url;
1229 * Sets styles for links in code
1231 * @param int A constant that specifies what state the style is being
1232 * set for - e.g. :hover or :visited
1233 * @param string The styles to use for that state
1236 function set_link_styles($type, $styles) {
1237 $this->link_styles
[$type] = $styles;
1241 * Sets the target for links in code
1243 * @param string The target for links in the code, e.g. _blank
1246 function set_link_target($target) {
1248 $this->link_target
= '';
1251 $this->link_target
= ' target="' . $target . '" ';
1256 * Sets styles for important parts of the code
1258 * @param string The styles to use on important parts of the code
1261 function set_important_styles($styles) {
1262 $this->important_styles
= $styles;
1266 * Sets whether context-important blocks are highlighted
1268 * @todo REMOVE THIS SHIZ FROM GESHI!
1271 function enable_important_blocks($flag) {
1272 $this->enable_important_blocks
= ( $flag ) ? true
: false
;
1276 * Whether CSS IDs should be added to each line
1278 * @param boolean If true, IDs will be added to each line.
1281 function enable_ids($flag = true
) {
1282 $this->add_ids
= ($flag) ? true
: false
;
1286 * Specifies which lines to highlight extra
1288 * @param mixed An array of line numbers to highlight, or just a line
1289 * number on its own.
1291 * @todo Some data replication here that could be cut down on
1293 function highlight_lines_extra($lines) {
1294 if (is_array($lines)) {
1295 foreach ($lines as $line) {
1296 $this->highlight_extra_lines
[intval($line)] = intval($line);
1300 $this->highlight_extra_lines
[intval($lines)] = intval($lines);
1305 * Sets the style for extra-highlighted lines
1307 * @param string The style for extra-highlighted lines
1310 function set_highlight_lines_extra_style($styles) {
1311 $this->highlight_extra_lines_style
= $styles;
1315 * Sets what number line numbers should start at. Should
1316 * be a positive integer, and will be converted to one.
1318 * <b>Warning:</b> Using this method will add the "start"
1319 * attribute to the <ol> that is used for line numbering.
1320 * This is <b>not</b> valid XHTML strict, so if that's what you
1321 * care about then don't use this method. Firefox is getting
1322 * support for the CSS method of doing this in 1.1 and Opera
1323 * has support for the CSS method, but (of course) IE doesn't
1324 * so it's not worth doing it the CSS way yet.
1326 * @param int The number to start line numbers at
1329 function start_line_numbers_at($number) {
1330 $this->line_numbers_start
= abs(intval($number));
1334 * Sets the encoding used for htmlspecialchars(), for international
1337 * NOTE: This is not needed for now because htmlspecialchars() is not
1338 * being used (it has a security hole in PHP4 that has not been patched).
1339 * Maybe in a future version it may make a return for speed reasons, but
1342 * @param string The encoding to use for the source
1345 function set_encoding($encoding) {
1347 $this->encoding
= $encoding;
1352 * Turns linking of keywords on or off.
1354 * @param boolean If true, links will be added to keywords
1356 function enable_keyword_links($enable = true
) {
1357 $this->keyword_links
= ($enable) ? true
: false
;
1361 * Returns the code in $this->source, highlighted and surrounded by the
1364 * This should only be called ONCE, cos it's SLOW! If you want to highlight
1365 * the same source multiple times, you're better off doing a whole lot of
1366 * str_replaces to replace the <span>s
1370 function parse_code () {
1372 $start_time = microtime();
1374 // Firstly, if there is an error, we won't highlight
1376 $result = GeSHi
::hsc($this->source
);
1377 // Timing is irrelevant
1378 $this->set_time($start_time, $start_time);
1379 return $this->finalise($result);
1382 // Replace all newlines to a common form.
1383 $code = str_replace("\r\n", "\n", $this->source
);
1384 $code = str_replace("\r", "\n", $code);
1385 // Add spaces for regular expression matching and line numbers
1386 $code = "\n" . $code . "\n";
1388 // Initialise various stuff
1389 $length = strlen($code);
1391 $CLOSE_STRING = false
;
1392 $ESCAPE_CHAR_OPEN = false
;
1393 $COMMENT_MATCHED = false
;
1394 // Turn highlighting on if strict mode doesn't apply to this language
1395 $HIGHLIGHTING_ON = ( !$this->strict_mode
) ? true
: '';
1396 // Whether to highlight inside a block of code
1397 $HIGHLIGHT_INSIDE_STRICT = false
;
1398 $HARDQUOTE_OPEN = false
;
1400 $stuff_to_parse = '';
1403 // "Important" selections are handled like multiline comments
1404 // @todo GET RID OF THIS SHIZ
1405 if ($this->enable_important_blocks
) {
1406 $this->language_data
['COMMENT_MULTI'][GESHI_START_IMPORTANT
] = GESHI_END_IMPORTANT
;
1409 if ($this->strict_mode
) {
1410 // Break the source into bits. Each bit will be a portion of the code
1411 // within script delimiters - for example, HTML between < and >
1412 $parts = array(0 => array(0 => ''));
1414 for ($i = 0; $i < $length; $i++
) {
1415 $char = substr($code, $i, 1);
1416 if (!$HIGHLIGHTING_ON) {
1417 foreach ($this->language_data
['SCRIPT_DELIMITERS'] as $key => $delimiters) {
1418 foreach ($delimiters as $open => $close) {
1419 // Get the next little bit for this opening string
1420 $check = substr($code, $i, strlen($open));
1422 if ($check == $open) {
1423 // We start a new block with the highlightable
1425 $HIGHLIGHTING_ON = $open;
1426 $i +
= strlen($open) - 1;
1428 $parts[++
$k][0] = $char;
1430 // No point going around again...
1437 foreach ($this->language_data
['SCRIPT_DELIMITERS'] as $key => $delimiters) {
1438 foreach ($delimiters as $open => $close) {
1439 if ($open == $HIGHLIGHTING_ON) {
1440 // Found the closing tag
1445 // We check code from our current position BACKWARDS. This is so
1446 // the ending string for highlighting can be included in the block
1447 $check = substr($code, $i - strlen($close) +
1, strlen($close));
1448 if ($check == $close) {
1449 $HIGHLIGHTING_ON = '';
1450 // Add the string to the rest of the string for this part
1451 $parts[$k][1] = ( isset($parts[$k][1]) ) ?
$parts[$k][1] . $char : $char;
1452 $parts[++
$k][0] = '';
1456 $parts[$k][1] = ( isset($parts[$k][1]) ) ?
$parts[$k][1] . $char : $char;
1458 $HIGHLIGHTING_ON = '';
1461 // Not strict mode - simply dump the source into
1462 // the array at index 1 (the first highlightable block)
1471 // Now we go through each part. We know that even-indexed parts are
1472 // code that shouldn't be highlighted, and odd-indexed parts should
1474 foreach ($parts as $key => $data) {
1476 // If this block should be highlighted...
1478 if ($this->strict_mode
) {
1479 // Find the class key for this block of code
1480 foreach ($this->language_data
['SCRIPT_DELIMITERS'] as $script_key => $script_data) {
1481 foreach ($script_data as $open => $close) {
1482 if ($data[0] == $open) {
1488 if ($this->language_data
['STYLES']['SCRIPT'][$script_key] != '' &&
1489 $this->lexic_permissions
['SCRIPT']) {
1490 // Add a span element around the source to
1491 // highlight the overall source block
1492 if (!$this->use_classes
&&
1493 $this->language_data
['STYLES']['SCRIPT'][$script_key] != '') {
1494 $attributes = ' style="' . $this->language_data
['STYLES']['SCRIPT'][$script_key] . '"';
1497 $attributes = ' class="sc' . $script_key . '"';
1499 $result .= "<span$attributes>";
1500 $STRICTATTRS = $attributes;
1504 if (!$this->strict_mode ||
$this->language_data
['HIGHLIGHT_STRICT_BLOCK'][$script_key]) {
1505 // Now, highlight the code in this block. This code
1506 // is really the engine of GeSHi (along with the method
1507 // parse_non_string_part).
1508 $length = strlen($part);
1509 for ($i = 0; $i < $length; $i++
) {
1510 // Get the next char
1511 $char = substr($part, $i, 1);
1512 $hq = isset($this->language_data
['HARDQUOTE']) ?
$this->language_data
['HARDQUOTE'][0] : false
;
1513 // Is this char the newline and line numbers being used?
1514 if (($this->line_numbers
!= GESHI_NO_LINE_NUMBERS
1515 ||
count($this->highlight_extra_lines
) > 0)
1517 // If so, is there a string open? If there is, we should end it before
1518 // the newline and begin it again (so when <li>s are put in the source
1519 // remains XHTML compliant)
1520 // note to self: This opens up possibility of config files specifying
1521 // that languages can/cannot have multiline strings???
1523 if (!$this->use_classes
) {
1524 $attributes = ' style="' . $this->language_data
['STYLES']['STRINGS'][0] . '"';
1527 $attributes = ' class="st0"';
1529 $char = '</span>' . $char . "<span$attributes>";
1532 else if ($char == $STRING_OPEN) {
1533 // A match of a string delimiter
1534 if (($this->lexic_permissions
['ESCAPE_CHAR'] && $ESCAPE_CHAR_OPEN) ||
1535 ($this->lexic_permissions
['STRINGS'] && !$ESCAPE_CHAR_OPEN)) {
1536 $char = GeSHi
::hsc($char) . '</span>';
1539 if ($HARDQUOTE_OPEN) {
1540 if ($ESCAPE_CHAR_OPEN) {
1544 foreach ($this->language_data
['HARDESCAPE'] as $hardesc) {
1545 if (substr($part, $i, strlen($hardesc)) == $hardesc) {
1553 if (!$ESCAPE_CHAR_OPEN) {
1555 $CLOSE_STRING = true
;
1558 $HARDQUOTE_OPEN = false
;
1560 $ESCAPE_CHAR_OPEN = false
;
1562 else if (in_array($char, $this->language_data
['QUOTEMARKS']) &&
1563 ($STRING_OPEN == '') && $this->lexic_permissions
['STRINGS']) {
1564 // The start of a new string
1565 $STRING_OPEN = $char;
1566 if (!$this->use_classes
) {
1567 $attributes = ' style="' . $this->language_data
['STYLES']['STRINGS'][0] . '"';
1570 $attributes = ' class="st0"';
1572 $char = "<span$attributes>" . GeSHi
::hsc($char);
1574 $result .= $this->parse_non_string_part( $stuff_to_parse );
1575 $stuff_to_parse = '';
1577 else if ($hq && substr($part, $i, strlen($hq)) == $hq &&
1578 ($STRING_OPEN == '') && $this->lexic_permissions
['STRINGS']) {
1579 // The start of a hard quoted string
1580 $STRING_OPEN = $this->language_data
['HARDQUOTE'][1];
1581 if (!$this->use_classes
) {
1582 $attributes = ' style="' . $this->language_data
['STYLES']['STRINGS'][0] . '"';
1585 $attributes = ' class="st0"';
1587 $char = "<span$attributes>" . $hq;
1588 $i +
= strlen($hq) - 1;
1589 $HARDQUOTE_OPEN = true
;
1590 $result .= $this->parse_non_string_part($stuff_to_parse);
1591 $stuff_to_parse = '';
1593 else if ($char == $this->language_data
['ESCAPE_CHAR'] && $STRING_OPEN != '') {
1594 // An escape character
1595 if (!$ESCAPE_CHAR_OPEN) {
1596 $ESCAPE_CHAR_OPEN = !$HARDQUOTE_OPEN; // true unless $HARDQUOTE_OPEN
1597 if ($HARDQUOTE_OPEN) {
1598 foreach ($this->language_data
['HARDESCAPE'] as $hard) {
1599 if (substr($part, $i, strlen($hard)) == $hard) {
1600 $ESCAPE_CHAR_OPEN = true
;
1605 if ($ESCAPE_CHAR_OPEN && $this->lexic_permissions
['ESCAPE_CHAR']) {
1606 if (!$this->use_classes
) {
1607 $attributes = ' style="' . $this->language_data
['STYLES']['ESCAPE_CHAR'][0] . '"';
1610 $attributes = ' class="es0"';
1612 $char = "<span$attributes>" . $char;
1613 if (substr($code, $i +
1, 1) == "\n") {
1614 // escaping a newline, what's the point in putting the span around
1615 // the newline? It only causes hassles when inserting line numbers
1617 $ESCAPE_CHAR_OPEN = false
;
1622 $ESCAPE_CHAR_OPEN = false
;
1623 if ($this->lexic_permissions
['ESCAPE_CHAR']) {
1628 else if ($ESCAPE_CHAR_OPEN) {
1629 if ($this->lexic_permissions
['ESCAPE_CHAR']) {
1632 $ESCAPE_CHAR_OPEN = false
;
1635 else if ($STRING_OPEN == '') {
1636 // Is this a multiline comment?
1637 foreach ($this->language_data
['COMMENT_MULTI'] as $open => $close) {
1638 $com_len = strlen($open);
1639 $test_str = substr( $part, $i, $com_len );
1640 $test_str_match = $test_str;
1641 if ($open == $test_str) {
1642 $COMMENT_MATCHED = true
;
1643 //@todo If remove important do remove here
1644 if ($this->lexic_permissions
['COMMENTS']['MULTI'] ||
1645 $test_str == GESHI_START_IMPORTANT
) {
1646 if ($test_str != GESHI_START_IMPORTANT
) {
1647 if (!$this->use_classes
) {
1648 $attributes = ' style="' . $this->language_data
['STYLES']['COMMENTS']['MULTI'] . '"';
1651 $attributes = ' class="coMULTI"';
1653 $test_str = "<span$attributes>" . GeSHi
::hsc($test_str);
1656 if (!$this->use_classes
) {
1657 $attributes = ' style="' . $this->important_styles
. '"';
1660 $attributes = ' class="imp"';
1662 // We don't include the start of the comment if it's an
1664 $test_str = "<span$attributes>";
1668 $test_str = GeSHi
::hsc($test_str);
1671 $close_pos = strpos( $part, $close, $i +
strlen($close) );
1674 if ($close_pos === false
) {
1675 $close_pos = strlen($part);
1679 $close_pos -= ($com_len - strlen($close));
1682 // Short-cut through all the multiline code
1683 $rest_of_comment = GeSHi
::hsc(substr($part, $i +
$com_len, $close_pos - $i));
1684 if (($this->lexic_permissions
['COMMENTS']['MULTI'] ||
1685 $test_str_match == GESHI_START_IMPORTANT
) &&
1686 ($this->line_numbers
!= GESHI_NO_LINE_NUMBERS ||
1687 count($this->highlight_extra_lines
) > 0)) {
1688 // strreplace to put close span and open span around multiline newlines
1689 $test_str .= str_replace("\n", "</span>\n<span$attributes>", $rest_of_comment);
1692 $test_str .= $rest_of_comment;
1695 if ($this->lexic_permissions
['COMMENTS']['MULTI'] ||
1696 $test_str_match == GESHI_START_IMPORTANT
) {
1697 $test_str .= '</span>';
1702 $i = $close_pos +
$com_len - 1;
1704 $result .= $this->parse_non_string_part($stuff_to_parse);
1705 $stuff_to_parse = '';
1709 // If we haven't matched a multiline comment, try single-line comments
1710 if (!$COMMENT_MATCHED) {
1711 foreach ($this->language_data
['COMMENT_SINGLE'] as $comment_key => $comment_mark) {
1712 $com_len = strlen($comment_mark);
1713 $test_str = substr($part, $i, $com_len);
1714 if ($this->language_data
['CASE_SENSITIVE'][GESHI_COMMENTS
]) {
1715 $match = ($comment_mark == $test_str);
1718 $match = (strtolower($comment_mark) == strtolower($test_str));
1721 $COMMENT_MATCHED = true
;
1722 if ($this->lexic_permissions
['COMMENTS'][$comment_key]) {
1723 if (!$this->use_classes
) {
1724 $attributes = ' style="' . $this->language_data
['STYLES']['COMMENTS'][$comment_key] . '"';
1727 $attributes = ' class="co' . $comment_key . '"';
1729 $test_str = "<span$attributes>" . GeSHi
::hsc($this->change_case($test_str));
1732 $test_str = GeSHi
::hsc($test_str);
1734 $close_pos = strpos($part, "\n", $i);
1736 if ($close_pos === false
) {
1737 $close_pos = strlen($part);
1740 $test_str .= GeSHi
::hsc(substr($part, $i +
$com_len, $close_pos - $i - $com_len));
1741 if ($this->lexic_permissions
['COMMENTS'][$comment_key]) {
1742 $test_str .= "</span>";
1744 // Take into account that the comment might be the last in the source
1750 $result .= $this->parse_non_string_part($stuff_to_parse);
1751 $stuff_to_parse = '';
1757 else if ($STRING_OPEN != '') {
1758 // Otherwise, convert it to HTML form
1759 if (strtolower($this->encoding
) == 'utf-8') {
1760 //only escape <128 (we don't want to break multibyte chars)
1761 if (ord($char) < 128) {
1762 $char = GeSHi
::hsc($char);
1767 $char = GeSHi
::hsc($char);
1770 // Where are we adding this char?
1771 if (!$COMMENT_MATCHED) {
1772 if (($STRING_OPEN == '') && !$CLOSE_STRING) {
1773 $stuff_to_parse .= $char;
1777 $CLOSE_STRING = false
;
1781 $result .= $test_str;
1782 $COMMENT_MATCHED = false
;
1785 // Parse the last bit
1786 $result .= $this->parse_non_string_part($stuff_to_parse);
1787 $stuff_to_parse = '';
1790 if ($STRICTATTRS != '') {
1791 $part = str_replace("\n", "</span>\n<span$STRICTATTRS>", GeSHi
::hsc($part));
1796 // Close the <span> that surrounds the block
1797 if ($this->strict_mode
&& $this->language_data
['STYLES']['SCRIPT'][$script_key] != '' &&
1798 $this->lexic_permissions
['SCRIPT']) {
1799 $result .= '</span>';
1803 // Else not a block to highlight
1804 $result .= GeSHi
::hsc($part);
1808 // Parse the last stuff (redundant?)
1809 $result .= $this->parse_non_string_part($stuff_to_parse);
1811 // Lop off the very first and last spaces
1812 $result = substr($result, 1, -1);
1814 // Are we still in a string?
1816 $result .= '</span>';
1819 // We're finished: stop timing
1820 $this->set_time($start_time, microtime());
1822 return $this->finalise($result);
1826 * Swaps out spaces and tabs for HTML indentation. Not needed if
1827 * the code is in a pre block...
1829 * @param string The source to indent
1830 * @return string The source with HTML indenting applied
1834 function indent($result) {
1835 /// Replace tabs with the correct number of spaces
1836 if (false
!== strpos($result, "\t")) {
1837 $lines = explode("\n", $result);
1838 foreach ($lines as $key => $line) {
1839 if (false
=== strpos($line, "\t")) {
1840 $lines[$key] = $line;
1845 $tab_width = $this->tab_width
;
1846 $length = strlen($line);
1850 for ($i = 0; $i < $length; $i++
) {
1851 $char = substr($line, $i, 1);
1852 // Simple engine to work out whether we're in a tag.
1853 // If we are we modify $pos. This is so we ignore HTML
1854 // in the line and only workout the tab replacement
1855 // via the actual content of the string
1856 // This test could be improved to include strings in the
1857 // html so that < or > would be allowed in user's styles
1858 // (e.g. quotes: '<' '>'; or similar)
1859 if ($IN_TAG && '>' == $char) {
1861 $result_line .= '>';
1864 else if (!$IN_TAG && '<' == $char) {
1866 $result_line .= '<';
1869 else if (!$IN_TAG && '&' == $char) {
1870 $substr = substr($line, $i +
3, 4);
1871 //$substr_5 = substr($line, 5, 1);
1872 $posi = strpos($substr, ';');
1873 if (false
!== $posi) {
1876 $result_line .= '&';
1878 else if (!$IN_TAG && "\t" == $char) {
1880 // OPTIMISE - move $strs out. Make an array:
1884 // 3 => ' ' etc etc
1885 // to use instead of building a string every time
1886 $strs = array(0 => ' ', 1 => ' ');
1887 for ($k = 0; $k < ($tab_width - (($i - $pos) %
$tab_width)); $k++
) $str .= $strs[$k %
2];
1888 $result_line .= $str;
1891 if (false
=== strpos($line, "\t", $i +
1)) {
1892 $result_line .= substr($line, $i +
1);
1898 $result_line .= $char;
1901 $result_line .= $char;
1905 $lines[$key] = $result_line;
1907 $result = implode("\n", $lines);
1910 $result = str_replace(' ', ' ', $result);
1911 $result = str_replace(' ', ' ', $result);
1912 $result = str_replace("\n ", "\n ", $result);
1914 if ($this->line_numbers
== GESHI_NO_LINE_NUMBERS
) {
1915 $result = nl2br($result);
1921 * Changes the case of a keyword for those languages where a change is asked for
1923 * @param string The keyword to change the case of
1924 * @return string The keyword with its case changed
1928 function change_case($instr) {
1929 if ($this->language_data
['CASE_KEYWORDS'] == GESHI_CAPS_UPPER
) {
1930 return strtoupper($instr);
1932 else if ($this->language_data
['CASE_KEYWORDS'] == GESHI_CAPS_LOWER
) {
1933 return strtolower($instr);
1939 * Adds a url to a keyword where needed.
1941 * @param string The keyword to add the URL HTML to
1942 * @param int What group the keyword is from
1943 * @param boolean Whether to get the HTML for the start or end
1944 * @return The HTML for either the start or end of the HTML <a> tag
1947 * @todo Get rid of ender
1949 function add_url_to_keyword($keyword, $group, $start_or_end) {
1950 if (!$this->keyword_links
) {
1951 // Keyword links have been disabled
1955 if (isset($this->language_data
['URLS'][$group]) &&
1956 $this->language_data
['URLS'][$group] != '' &&
1957 substr($keyword, 0, 5) != '</') {
1958 // There is a base group for this keyword
1959 if ($start_or_end == 'BEGIN') {
1960 // HTML workaround... not good form (tm) but should work for 1.0.X
1961 if ($keyword != '') {
1962 // Old system: strtolower
1963 //$keyword = ( $this->language_data['CASE_SENSITIVE'][$group] ) ? $keyword : strtolower($keyword);
1964 // New system: get keyword from language file to get correct case
1965 foreach ($this->language_data
['KEYWORDS'][$group] as $word) {
1966 if (strtolower($word) == strtolower($keyword)) {
1970 $word = ( substr($word, 0, 4) == '<' ) ?
substr($word, 4) : $word;
1971 $word = ( substr($word, -4) == '>' ) ?
substr($word, 0, strlen($word) - 4) : $word;
1972 if (!$word) return '';
1976 array('{FNAME}', '.'),
1977 array(GeSHi
::hsc($word), '<DOT>'),
1978 $this->language_data
['URLS'][$group]
1982 // HTML fix. Again, dirty hackage...
1984 else if (!($this->language
== 'html4strict' && ('>' == $keyword ||
'<' == $keyword))) {
1991 * Takes a string that has no strings or comments in it, and highlights
1992 * stuff like keywords, numbers and methods.
1994 * @param string The string to parse for keyword, numbers etc.
1997 * @todo BUGGY! Why? Why not build string and return?
1999 function parse_non_string_part(&$stuff_to_parse) {
2000 $stuff_to_parse = ' ' . GeSHi
::hsc($stuff_to_parse);
2001 $stuff_to_parse_pregquote = preg_quote($stuff_to_parse, '/');
2002 $func = '$this->change_case';
2003 $func2 = '$this->add_url_to_keyword';
2006 // Regular expressions
2008 foreach ($this->language_data
['REGEXPS'] as $key => $regexp) {
2009 if ($this->lexic_permissions
['REGEXPS'][$key]) {
2010 if (is_array($regexp)) {
2011 $stuff_to_parse = preg_replace(
2013 str_replace('/', '\/', $regexp[GESHI_SEARCH
]) .
2014 "/{$regexp[GESHI_MODIFIERS]}",
2015 "{$regexp[GESHI_BEFORE]}<|!REG3XP$key!>{$regexp[GESHI_REPLACE]}|>{$regexp[GESHI_AFTER]}",
2020 $stuff_to_parse = preg_replace( "/(" . str_replace('/', '\/', $regexp) . ")/", "<|!REG3XP$key!>\\1|>", $stuff_to_parse);
2026 // Highlight numbers. This regexp sucks... anyone with a regexp that WORKS
2027 // here wins a cookie if they send it to me. At the moment there's two doing
2028 // almost exactly the same thing, except the second one prevents a number
2029 // being highlighted twice (eg <span...><span...>5</span></span>)
2030 // Put /NUM!/ in for the styles, which gets replaced at the end.
2032 // NEW ONE: Brice Bernard
2034 if ($this->lexic_permissions
['NUMBERS'] && preg_match('#[0-9]#', $stuff_to_parse )) {
2035 $stuff_to_parse = preg_replace('/([-+]?\\b(?:[0-9]*\\.)?[0-9]+\\b)/', '<|/NUM!/>\\1|>', $stuff_to_parse);
2038 // Highlight keywords
2039 // if there is a couple of alpha symbols there *might* be a keyword
2040 if (preg_match('#[a-zA-Z]{2,}#', $stuff_to_parse)) {
2041 foreach ($this->language_data
['KEYWORDS'] as $k => $keywordset) {
2042 if ($this->lexic_permissions
['KEYWORDS'][$k]) {
2043 foreach ($keywordset as $keyword) {
2044 $keyword = preg_quote($keyword, '/');
2046 // This replacement checks the word is on it's own (except if brackets etc
2047 // are next to it), then highlights it. We don't put the color=" for the span
2048 // in just yet - otherwise languages with the keywords "color" or "or" have
2051 if (false
!== stristr($stuff_to_parse_pregquote, $keyword )) {
2052 $stuff_to_parse .= ' ';
2053 // Might make a more unique string for putting the number in soon
2054 // Basically, we don't put the styles in yet because then the styles themselves will
2055 // get highlighted if the language has a CSS keyword in it (like CSS, for example ;))
2057 if ($this->language_data
['CASE_SENSITIVE'][$k]) {
2058 $stuff_to_parse = preg_replace(
2059 "/([^a-zA-Z0-9\$_\|\#;>|^])($keyword)(?=[^a-zA-Z0-9_<\|%\-&])/e",
2060 "'\\1' . $func2('\\2', '$k', 'BEGIN') . '<|$styles>' . $func('\\2') . '|>' . $func2('\\2', '$k', 'END')",
2065 // Change the case of the word.
2066 // hackage again... must... release... 1.2...
2067 if ('smarty' == $this->language
) { $hackage = '\/'; } else { $hackage = ''; }
2068 $stuff_to_parse = preg_replace(
2069 "/([^a-zA-Z0-9\$_\|\#;>$hackage|^])($keyword)(?=[^a-zA-Z0-9_<\|%\-&])/ie",
2070 "'\\1' . $func2('\\2', '$k', 'BEGIN') . '<|$styles>' . $func('\\2') . '|>' . $func2('\\2', '$k', 'END')",
2074 $stuff_to_parse = substr($stuff_to_parse, 0, strlen($stuff_to_parse) - 1);
2082 // Now that's all done, replace /[number]/ with the correct styles
2084 foreach ($this->language_data
['KEYWORDS'] as $k => $kws) {
2085 if (!$this->use_classes
) {
2086 $attributes = ' style="' . $this->language_data
['STYLES']['KEYWORDS'][$k] . '"';
2089 $attributes = ' class="kw' . $k . '"';
2091 $stuff_to_parse = str_replace("/$k/", $attributes, $stuff_to_parse);
2094 // Put number styles in
2095 if (!$this->use_classes
&& $this->lexic_permissions
['NUMBERS']) {
2096 $attributes = ' style="' . $this->language_data
['STYLES']['NUMBERS'][0] . '"';
2099 $attributes = ' class="nu0"';
2101 $stuff_to_parse = str_replace('/NUM!/', $attributes, $stuff_to_parse);
2104 // Highlight methods and fields in objects
2106 if ($this->lexic_permissions
['METHODS'] && $this->language_data
['OOLANG']) {
2107 foreach ($this->language_data
['OBJECT_SPLITTERS'] as $key => $splitter) {
2108 if (false
!== stristr($stuff_to_parse, $splitter)) {
2109 if (!$this->use_classes
) {
2110 $attributes = ' style="' . $this->language_data
['STYLES']['METHODS'][$key] . '"';
2113 $attributes = ' class="me' . $key . '"';
2115 $stuff_to_parse = preg_replace("/(" . preg_quote($this->language_data
['OBJECT_SPLITTERS'][$key], 1) . "[\s]*)([a-zA-Z\*\(][a-zA-Z0-9_\*]*)/", "\\1<|$attributes>\\2|>", $stuff_to_parse);
2121 // Highlight brackets. Yes, I've tried adding a semi-colon to this list.
2122 // You try it, and see what happens ;)
2123 // TODO: Fix lexic permissions not converting entities if shouldn't
2124 // be highlighting regardless
2126 if ($this->lexic_permissions
['BRACKETS']) {
2127 $code_entities_match = array('[', ']', '(', ')', '{', '}');
2128 if (!$this->use_classes
) {
2129 $code_entities_replace = array(
2130 '<| style="' . $this->language_data
['STYLES']['BRACKETS'][0] . '">[|>',
2131 '<| style="' . $this->language_data
['STYLES']['BRACKETS'][0] . '">]|>',
2132 '<| style="' . $this->language_data
['STYLES']['BRACKETS'][0] . '">(|>',
2133 '<| style="' . $this->language_data
['STYLES']['BRACKETS'][0] . '">)|>',
2134 '<| style="' . $this->language_data
['STYLES']['BRACKETS'][0] . '">{|>',
2135 '<| style="' . $this->language_data
['STYLES']['BRACKETS'][0] . '">}|>',
2139 $code_entities_replace = array(
2140 '<| class="br0">[|>',
2141 '<| class="br0">]|>',
2142 '<| class="br0">(|>',
2143 '<| class="br0">)|>',
2144 '<| class="br0">{|>',
2145 '<| class="br0">}|>',
2148 $stuff_to_parse = str_replace( $code_entities_match, $code_entities_replace, $stuff_to_parse );
2152 // Add class/style for regexps
2154 foreach ($this->language_data
['REGEXPS'] as $key => $regexp) {
2155 if ($this->lexic_permissions
['REGEXPS'][$key]) {
2156 if (!$this->use_classes
) {
2157 $attributes = ' style="' . $this->language_data
['STYLES']['REGEXPS'][$key] . '"';
2160 if(is_array($this->language_data
['REGEXPS'][$key]) &&
2161 array_key_exists(GESHI_CLASS
, $this->language_data
['REGEXPS'][$key])) {
2162 $attributes = ' class="'
2163 . $this->language_data
['REGEXPS'][$key][GESHI_CLASS
] . '"';
2166 $attributes = ' class="re' . $key . '"';
2169 $stuff_to_parse = str_replace("!REG3XP$key!", "$attributes", $stuff_to_parse);
2173 // Replace <DOT> with . for urls
2174 $stuff_to_parse = str_replace('<DOT>', '.', $stuff_to_parse);
2175 // Replace <|UR1| with <a href= for urls also
2176 if (isset($this->link_styles
[GESHI_LINK
])) {
2177 if ($this->use_classes
) {
2178 $stuff_to_parse = str_replace('<|UR1|', '<a' . $this->link_target
. ' href=', $stuff_to_parse);
2181 $stuff_to_parse = str_replace('<|UR1|', '<a' . $this->link_target
. ' style="' . $this->link_styles
[GESHI_LINK
] . '" href=', $stuff_to_parse);
2185 $stuff_to_parse = str_replace('<|UR1|', '<a' . $this->link_target
. ' href=', $stuff_to_parse);
2189 // NOW we add the span thingy ;)
2192 $stuff_to_parse = str_replace('<|', '<span', $stuff_to_parse);
2193 $stuff_to_parse = str_replace ( '|>', '</span>', $stuff_to_parse );
2195 return substr($stuff_to_parse, 1);
2199 * Sets the time taken to parse the code
2201 * @param microtime The time when parsing started
2202 * @param microtime The time when parsing ended
2206 function set_time($start_time, $end_time) {
2207 $start = explode(' ', $start_time);
2208 $end = explode(' ', $end_time);
2209 $this->time
= $end[0] +
$end[1] - $start[0] - $start[1];
2213 * Gets the time taken to parse the code
2215 * @return double The time taken to parse the code
2218 function get_time() {
2223 * Gets language information and stores it for later use
2226 * @todo Needs to load keys for lexic permissions for keywords, regexps etc
2228 function load_language($file_name) {
2229 $this->enable_highlighting();
2230 $language_data = array();
2232 // Perhaps some checking might be added here later to check that
2233 // $language data is a valid thing but maybe not
2234 $this->language_data
= $language_data;
2235 // Set strict mode if should be set
2236 if ($this->language_data
['STRICT_MODE_APPLIES'] == GESHI_ALWAYS
) {
2237 $this->strict_mode
= true
;
2239 // Set permissions for all lexics to true
2240 // so they'll be highlighted by default
2241 foreach ($this->language_data
['KEYWORDS'] as $key => $words) {
2242 $this->lexic_permissions
['KEYWORDS'][$key] = true
;
2244 foreach ($this->language_data
['COMMENT_SINGLE'] as $key => $comment) {
2245 $this->lexic_permissions
['COMMENTS'][$key] = true
;
2247 foreach ($this->language_data
['REGEXPS'] as $key => $regexp) {
2248 $this->lexic_permissions
['REGEXPS'][$key] = true
;
2250 // Set default class for CSS
2251 $this->overall_class
= $this->language
;
2255 * Takes the parsed code and various options, and creates the HTML
2256 * surrounding it to make it look nice.
2258 * @param string The code already parsed
2259 * @return string The code nicely finalised
2263 function finalise($parsed_code) {
2264 // Remove end parts of important declarations
2265 // This is BUGGY!! My fault for bad code: fix coming in 1.2
2266 // @todo Remove this crap
2267 if ($this->enable_important_blocks
&&
2268 (strstr($parsed_code, GeSHi
::hsc(GESHI_START_IMPORTANT
)) === false
)) {
2269 $parsed_code = str_replace(GeSHi
::hsc(GESHI_END_IMPORTANT
), '', $parsed_code);
2272 // Add HTML whitespace stuff if we're using the <div> header
2273 if ($this->header_type
!= GESHI_HEADER_PRE
) {
2274 $parsed_code = $this->indent($parsed_code);
2277 // purge some unnecessary stuff
2278 $parsed_code = preg_replace('#<span[^>]+>(\s*)</span>#', '\\1', $parsed_code);
2279 $parsed_code = preg_replace('#<div[^>]+>(\s*)</div>#', '\\1', $parsed_code);
2281 // If we are using IDs for line numbers, there needs to be an overall
2282 // ID set to prevent collisions.
2283 if ($this->add_ids
&& !$this->overall_id
) {
2284 $this->overall_id
= 'geshi-' . substr(md5(microtime()), 0, 4);
2287 // If we're using line numbers, we insert <li>s and appropriate
2288 // markup to style them (otherwise we don't need to do anything)
2289 if ($this->line_numbers
!= GESHI_NO_LINE_NUMBERS
) {
2290 // If we're using the <pre> header, we shouldn't add newlines because
2291 // the <pre> will line-break them (and the <li>s already do this for us)
2292 $ls = ($this->header_type
!= GESHI_HEADER_PRE
) ?
"\n" : '';
2293 // Get code into lines
2294 $code = explode("\n", $parsed_code);
2295 // Set vars to defaults for following loop
2301 foreach ($code as $line) {
2302 // Make lines have at least one space in them if they're empty
2303 // BenBE: Checking emptiness using trim instead of relying on blanks
2304 if ('' == trim($line)) {
2307 // If this is a "special line"...
2308 if ($this->line_numbers
== GESHI_FANCY_LINE_NUMBERS
&&
2309 $i %
$this->line_nth_row
== ($this->line_nth_row
- 1)) {
2310 // Set the attributes to style the line
2311 if ($this->use_classes
) {
2312 //$attr = ' class="li2"';
2313 $attrs['class'][] = 'li2';
2314 $def_attr = ' class="de2"';
2317 //$attr = ' style="' . $this->line_style2 . '"';
2318 $attrs['style'][] = $this->line_style2
;
2319 // This style "covers up" the special styles set for special lines
2320 // so that styles applied to special lines don't apply to the actual
2321 // code on that line
2322 $def_attr = ' style="' . $this->code_style
. '"';
2325 $start = "<div$def_attr>";
2329 if ($this->use_classes
) {
2330 //$attr = ' class="li1"';
2331 $attrs['class'][] = 'li1';
2332 $def_attr = ' class="de1"';
2335 //$attr = ' style="' . $this->line_style1 . '"';
2336 $attrs['style'][] = $this->line_style1
;
2337 $def_attr = ' style="' . $this->code_style
. '"';
2339 $start = "<div$def_attr>";
2344 // Are we supposed to use ids? If so, add them
2345 if ($this->add_ids
) {
2346 $attrs['id'][] = "$this->overall_id-$i";
2348 if ($this->use_classes
&& in_array($i, $this->highlight_extra_lines
)) {
2349 $attrs['class'][] = 'ln-xtra';
2351 if (!$this->use_classes
&& in_array($i, $this->highlight_extra_lines
)) {
2352 $attrs['style'][] = $this->highlight_extra_lines_style
;
2355 // Add in the line surrounded by appropriate list HTML
2357 foreach ($attrs as $key => $attr) {
2358 $attr_string .= $key . '="' . implode(' ', $attr) . '" ';
2360 $attr_string = substr($attr_string, 0, -1);
2361 $parsed_code .= "<li$attr_string>$start$line$end</li>$ls";
2366 // No line numbers, but still need to handle highlighting lines extra.
2367 // Have to use divs so the full width of the code is highlighted
2368 $code = explode("\n", $parsed_code);
2371 foreach ($code as $line) {
2372 // Make lines have at least one space in them if they're empty
2373 // BenBE: Checking emptiness using trim instead of relying on blanks
2374 if ('' == trim($line)) {
2377 if (in_array(++
$i, $this->highlight_extra_lines
)) {
2378 if ($this->use_classes
) {
2379 $parsed_code .= '<div class="ln-xtra">';
2382 $parsed_code .= "<div style=\"{$this->highlight_extra_lines_style}\">";
2384 // Remove \n because it stuffs up <pre> header
2385 $parsed_code .= $line . "</div>";
2388 $parsed_code .= $line . "\n";
2393 if ($this->header_type
== GESHI_HEADER_PRE
) {
2394 // enforce line numbers when using pre
2395 $parsed_code = str_replace('<li></li>', '<li> </li>', $parsed_code);
2398 return $this->header() . chop($parsed_code) . $this->footer();
2402 * Creates the header for the code block (with correct attributes)
2404 * @return string The header for the code block
2409 // Get attributes needed
2410 $attributes = $this->get_attributes();
2412 $ol_attributes = '';
2414 if ($this->line_numbers_start
!= 1) {
2415 $ol_attributes .= ' start="' . $this->line_numbers_start
. '"';
2418 // Get the header HTML
2419 $header = $this->format_header_content();
2421 if (GESHI_HEADER_NONE
== $this->header_type
) {
2422 if ($this->line_numbers
!= GESHI_NO_LINE_NUMBERS
) {
2423 return "$header<ol$ol_attributes>";
2428 // Work out what to return and do it
2429 if ($this->line_numbers
!= GESHI_NO_LINE_NUMBERS
) {
2430 if ($this->header_type
== GESHI_HEADER_PRE
) {
2431 return "<pre$attributes>$header<ol$ol_attributes>";
2433 else if ($this->header_type
== GESHI_HEADER_DIV
) {
2434 return "<div$attributes>$header<ol$ol_attributes>";
2438 if ($this->header_type
== GESHI_HEADER_PRE
) {
2439 return "<pre$attributes>$header";
2441 else if ($this->header_type
== GESHI_HEADER_DIV
) {
2442 return "<div$attributes>$header";
2448 * Returns the header content, formatted for output
2450 * @return string The header content, formatted for output
2454 function format_header_content() {
2455 $header = $this->header_content
;
2457 if ($this->header_type
== GESHI_HEADER_PRE
) {
2458 $header = str_replace("\n", '', $header);
2460 $header = $this->replace_keywords($header);
2462 if ($this->use_classes
) {
2463 $attr = ' class="head"';
2466 $attr = " style=\"{$this->header_content_style}\"";
2468 return "<div$attr>$header</div>";
2473 * Returns the footer for the code block.
2475 * @return string The footer for the code block
2480 $footer_content = $this->format_footer_content();
2482 if (GESHI_HEADER_NONE
== $this->header_type
) {
2483 return ($this->line_numbers
!= GESHI_NO_LINE_NUMBERS
) ?
'</ol>' . $footer_content
2487 if ($this->header_type
== GESHI_HEADER_DIV
) {
2488 if ($this->line_numbers
!= GESHI_NO_LINE_NUMBERS
) {
2489 return "</ol>$footer_content</div>";
2491 return "$footer_content</div>";
2494 if ($this->line_numbers
!= GESHI_NO_LINE_NUMBERS
) {
2495 return "</ol>$footer_content</pre>";
2497 return "$footer_content</pre>";
2502 * Returns the footer content, formatted for output
2504 * @return string The footer content, formatted for output
2508 function format_footer_content() {
2509 $footer = $this->footer_content
;
2511 if ($this->header_type
== GESHI_HEADER_PRE
) {
2512 $footer = str_replace("\n", '', $footer);;
2514 $footer = $this->replace_keywords($footer);
2516 if ($this->use_classes
) {
2517 $attr = ' class="foot"';
2520 $attr = " style=\"{$this->footer_content_style}\"";
2522 return "<div$attr>$footer</div>";
2527 * Replaces certain keywords in the header and footer with
2528 * certain configuration values
2530 * @param string The header or footer content to do replacement on
2531 * @return string The header or footer with replaced keywords
2535 function replace_keywords($instr) {
2536 $keywords = $replacements = array();
2538 $keywords[] = '<TIME>';
2539 $keywords[] = '{TIME}';
2540 $replacements[] = $replacements[] = number_format($this->get_time(), 3);
2542 $keywords[] = '<LANGUAGE>';
2543 $keywords[] = '{LANGUAGE}';
2544 $replacements[] = $replacements[] = $this->language
;
2546 $keywords[] = '<VERSION>';
2547 $keywords[] = '{VERSION}';
2548 $replacements[] = $replacements[] = GESHI_VERSION
;
2550 return str_replace($keywords, $replacements, $instr);
2554 * Gets the CSS attributes for this code
2556 * @return The CSS attributes for this code
2559 * @todo Document behaviour change - class is outputted regardless of whether we're using classes or not.
2562 function get_attributes() {
2565 if ($this->overall_class
!= '') {
2566 $attributes .= " class=\"{$this->overall_class}\"";
2568 if ($this->overall_id
!= '') {
2569 $attributes .= " id=\"{$this->overall_id}\"";
2571 if ($this->overall_style
!= '') {
2572 $attributes .= ' style="' . $this->overall_style
. '"';
2578 * Secure replacement for PHP built-in function htmlspecialchars().
2580 * See ticket #427 (http://wush.net/trac/wikka/ticket/427) for the rationale
2581 * for this replacement function.
2583 * The INTERFACE for this function is almost the same as that for
2584 * htmlspecialchars(), with the same default for quote style; however, there
2585 * is no 'charset' parameter. The reason for this is as follows:
2588 * "The third argument charset defines character set used in conversion."
2590 * I suspect PHP's htmlspecialchars() is working at the byte-value level and
2591 * thus _needs_ to know (or asssume) a character set because the special
2592 * characters to be replaced could exist at different code points in
2593 * different character sets. (If indeed htmlspecialchars() works at
2594 * byte-value level that goes some way towards explaining why the
2595 * vulnerability would exist in this function, too, and not only in
2596 * htmlentities() which certainly is working at byte-value level.)
2598 * This replacement function however works at character level and should
2599 * therefore be "immune" to character set differences - so no charset
2600 * parameter is needed or provided. If a third parameter is passed, it will
2601 * be silently ignored.
2603 * In the OUTPUT there is a minor difference in that we use ''' instead
2604 * of PHP's ''' for a single quote: this provides compatibility with
2605 * get_html_translation_table(HTML_SPECIALCHARS, ENT_QUOTES)
2606 * (see comment by mikiwoz at yahoo dot co dot uk on
2607 * http://php.net/htmlspecialchars); it also matches the entity definition
2609 * (http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_Special_characters).
2610 * Like PHP we use a numeric character reference instead of ''' for the
2611 * single quote. For the other special characters we use the named entity
2612 * references, as PHP is doing.
2614 * @author {@link http://wikkawiki.org/JavaWoman Marjolein Katsma}
2616 * @license http://www.gnu.org/copyleft/lgpl.html
2617 * GNU Lesser General Public License
2618 * @copyright Copyright 2007, {@link http://wikkawiki.org/CreditsPage
2619 * Wikka Development Team}
2622 * @param string $string string to be converted
2623 * @param integer $quote_style
2624 * - ENT_COMPAT: escapes &, <, > and double quote (default)
2625 * - ENT_NOQUOTES: escapes only &, < and >
2626 * - ENT_QUOTES: escapes &, <, >, double and single quotes
2627 * @return string converted string
2629 function hsc($string, $quote_style=ENT_COMPAT
) {
2631 $aTransSpecchar = array(
2636 ); // ENT_COMPAT set
2638 if (ENT_NOQUOTES
== $quote_style) // don't convert double quotes
2640 unset($aTransSpecchar['"']);
2642 elseif (ENT_QUOTES
== $quote_style) // convert single quotes as well
2644 $aTransSpecchar["'"] = '''; // (apos) htmlspecialchars() uses '''
2647 // return translated string
2648 return strtr($string,$aTransSpecchar);
2652 * Returns a stylesheet for the highlighted code. If $economy mode
2653 * is true, we only return the stylesheet declarations that matter for
2654 * this code block instead of the whole thing
2656 * @param boolean Whether to use economy mode or not
2657 * @return string A stylesheet built on the data for the current language
2660 function get_stylesheet($economy_mode = true
) {
2661 // If there's an error, chances are that the language file
2662 // won't have populated the language data file, so we can't
2663 // risk getting a stylesheet...
2667 // First, work out what the selector should be. If there's an ID,
2668 // that should be used, the same for a class. Otherwise, a selector
2669 // of '' means that these styles will be applied anywhere
2670 $selector = ($this->overall_id
!= '') ?
"#{$this->overall_id} " : '';
2671 $selector = ($selector == '' && $this->overall_class
!= '') ?
".{$this->overall_class} " : $selector;
2673 // Header of the stylesheet
2674 if (!$economy_mode) {
2675 $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) 2004 - 2007 Nigel McNie (http://qbnz.com/highlighter)\n */\n";
2677 $stylesheet = '/* GeSHi (C) 2004 - 2007 Nigel McNie (http://qbnz.com/highlighter) */' . "\n";
2680 // Set the <ol> to have no effect at all if there are line numbers
2681 // (<ol>s have margins that should be destroyed so all layout is
2682 // controlled by the set_overall_style method, which works on the
2683 // <pre> or <div> container). Additionally, set default styles for lines
2684 if (!$economy_mode ||
$this->line_numbers
!= GESHI_NO_LINE_NUMBERS
) {
2685 //$stylesheet .= "$selector, {$selector}ol, {$selector}ol li {margin: 0;}\n";
2686 $stylesheet .= "$selector.de1, $selector.de2 {{$this->code_style}}\n";
2689 // Add overall styles
2690 if (!$economy_mode ||
$this->overall_style
!= '') {
2691 $stylesheet .= "$selector {{$this->overall_style}}\n";
2694 // Add styles for links
2695 foreach ($this->link_styles
as $key => $style) {
2696 if (!$economy_mode ||
$key == GESHI_LINK
&& $style != '') {
2697 $stylesheet .= "{$selector}a:link {{$style}}\n";
2699 if (!$economy_mode ||
$key == GESHI_HOVER
&& $style != '') {
2700 $stylesheet .= "{$selector}a:hover {{$style}}\n";
2702 if (!$economy_mode ||
$key == GESHI_ACTIVE
&& $style != '') {
2703 $stylesheet .= "{$selector}a:active {{$style}}\n";
2705 if (!$economy_mode ||
$key == GESHI_VISITED
&& $style != '') {
2706 $stylesheet .= "{$selector}a:visited {{$style}}\n";
2710 // Header and footer
2711 if (!$economy_mode ||
$this->header_content_style
!= '') {
2712 $stylesheet .= "$selector.head {{$this->header_content_style}}\n";
2714 if (!$economy_mode ||
$this->footer_content_style
!= '') {
2715 $stylesheet .= "$selector.foot {{$this->footer_content_style}}\n";
2718 // Styles for important stuff
2719 if (!$economy_mode ||
$this->important_styles
!= '') {
2720 $stylesheet .= "$selector.imp {{$this->important_styles}}\n";
2723 // Styles for lines being highlighted extra
2724 if (!$economy_mode ||
count($this->highlight_extra_lines
)) {
2725 $stylesheet .= "$selector.ln-xtra {{$this->highlight_extra_lines_style}}\n";
2728 // Simple line number styles
2729 if (!$economy_mode ||
($this->line_numbers
!= GESHI_NO_LINE_NUMBERS
&& $this->line_style1
!= '')) {
2730 $stylesheet .= "{$selector}li {{$this->line_style1}}\n";
2733 // If there is a style set for fancy line numbers, echo it out
2734 if (!$economy_mode ||
($this->line_numbers
== GESHI_FANCY_LINE_NUMBERS
&& $this->line_style2
!= '')) {
2735 $stylesheet .= "{$selector}li.li2 {{$this->line_style2}}\n";
2738 foreach ($this->language_data
['STYLES']['KEYWORDS'] as $group => $styles) {
2739 if (!$economy_mode ||
!($economy_mode && (!$this->lexic_permissions
['KEYWORDS'][$group] ||
$styles == ''))) {
2740 $stylesheet .= "$selector.kw$group {{$styles}}\n";
2743 foreach ($this->language_data
['STYLES']['COMMENTS'] as $group => $styles) {
2744 if (!$economy_mode ||
!($economy_mode && $styles == '') &&
2745 !($economy_mode && !$this->lexic_permissions
['COMMENTS'][$group])) {
2746 $stylesheet .= "$selector.co$group {{$styles}}\n";
2749 foreach ($this->language_data
['STYLES']['ESCAPE_CHAR'] as $group => $styles) {
2750 if (!$economy_mode ||
!($economy_mode && $styles == '') && !($economy_mode &&
2751 !$this->lexic_permissions
['ESCAPE_CHAR'])) {
2752 $stylesheet .= "$selector.es$group {{$styles}}\n";
2755 foreach ($this->language_data
['STYLES']['SYMBOLS'] as $group => $styles) {
2756 if (!$economy_mode ||
!($economy_mode && $styles == '') && !($economy_mode &&
2757 !$this->lexic_permissions
['BRACKETS'])) {
2758 $stylesheet .= "$selector.br$group {{$styles}}\n";
2761 foreach ($this->language_data
['STYLES']['STRINGS'] as $group => $styles) {
2762 if (!$economy_mode ||
!($economy_mode && $styles == '') && !($economy_mode &&
2763 !$this->lexic_permissions
['STRINGS'])) {
2764 $stylesheet .= "$selector.st$group {{$styles}}\n";
2767 foreach ($this->language_data
['STYLES']['NUMBERS'] as $group => $styles) {
2768 if (!$economy_mode ||
!($economy_mode && $styles == '') && !($economy_mode &&
2769 !$this->lexic_permissions
['NUMBERS'])) {
2770 $stylesheet .= "$selector.nu$group {{$styles}}\n";
2773 foreach ($this->language_data
['STYLES']['METHODS'] as $group => $styles) {
2774 if (!$economy_mode ||
!($economy_mode && $styles == '') && !($economy_mode &&
2775 !$this->lexic_permissions
['METHODS'])) {
2776 $stylesheet .= "$selector.me$group {{$styles}}\n";
2779 foreach ($this->language_data
['STYLES']['SCRIPT'] as $group => $styles) {
2780 if (!$economy_mode ||
!($economy_mode && $styles == '')) {
2781 $stylesheet .= "$selector.sc$group {{$styles}}\n";
2784 foreach ($this->language_data
['STYLES']['REGEXPS'] as $group => $styles) {
2785 if (!$economy_mode ||
!($economy_mode && $styles == '') && !($economy_mode &&
2786 !$this->lexic_permissions
['REGEXPS'][$group])) {
2787 if (is_array($this->language_data
['REGEXPS'][$group]) &&
2788 array_key_exists(GESHI_CLASS
,
2789 $this->language_data
['REGEXPS'][$group])) {
2790 $stylesheet .= "$selector.";
2791 $stylesheet .= $this->language_data
['REGEXPS'][$group][GESHI_CLASS
];
2792 $stylesheet .= " {{$styles}}\n";
2795 $stylesheet .= "$selector.re$group {{$styles}}\n";
2803 } // End Class GeSHi
2806 if (!function_exists('geshi_highlight')) {
2808 * Easy way to highlight stuff. Behaves just like highlight_string
2810 * @param string The code to highlight
2811 * @param string The language to highlight the code in
2812 * @param string The path to the language files. You can leave this blank if you need
2813 * as from version 1.0.7 the path should be automatically detected
2814 * @param boolean Whether to return the result or to echo
2815 * @return string The code highlighted (if $return is true)
2818 function geshi_highlight($string, $language, $path = null
, $return = false
) {
2819 $geshi = new GeSHi($string, $language, $path);
2820 $geshi->set_header_type(GESHI_HEADER_NONE
);
2822 return '<code>' . $geshi->parse_code() . '</code>';
2824 echo '<code>' . $geshi->parse_code() . '</code>';
2825 if ($geshi->error()) {