/** * * Renders a token into text matching the requested format. * * @access public * * @param array $options The "options" portion of the token (second * element). * * @return string The text rendered from the token options. * */ function token($options) { $text = $options['text']; $attr = $options['attr']; $type = strtolower($attr['type']); $css = $this->formatConf(' class="%s"', 'css'); $css_code = $this->formatConf(' class="%s"', 'css_code'); $css_php = $this->formatConf(' class="%s"', 'css_php'); $css_html = $this->formatConf(' class="%s"', 'css_html'); $geshi_class = path::file("plugins") . "geshi/geshi.php"; if ($type != "" && file_exists(path::file("plugins") . "geshi/geshi.php") && is_readable(path::file("plugins") . "geshi/geshi.php")) { require_once path::file("plugins") . "geshi/geshi.php"; $geshi = new GeSHi(trim($text), $type, path::file("plugins") . "geshi/geshi/"); $geshi->set_encoding("utf-8"); $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS, 1); $geshi->set_header_type(GESHI_HEADER_DIV); $geshi->enable_classes(); $geshi->set_overall_class('geshi_code'); $text = $geshi->parse_code(); $style = $geshi->get_stylesheet(); global $page_handler; $style = "<style type='text/css'>\n{$style}\n</style>"; $page_handler->add_header_data($style); } else { //generic code example: //convert tabs to four spaces, //convert entities. $text = trim(htmlentities($text)); $text = str_replace("\t", " ", $text); $text = str_replace(" ", " ", $text); $text = "<code{$css_code}>{$text}</code>"; } return "\n{$text}\n\n"; }
function code_callback($matches) { $index = (int) $matches[1]; $lang = $this->saved_code[$index]['lang']; $code = $this->saved_code[$index]['code']; // for prevent memory leaks unset($this->saved_code[$index]); // translate some language names so that simpler names can be used ${$lang} = strtr($lang, array('html' => 'html4strict', 'php' => 'php-brief')); // if we get HTML for example, it's already encoded $geshi = new GeSHi(htmlspecialchars_decode(trim($code, " \t\n\r\v�"), ENT_QUOTES), $lang); $geshi->enable_classes(); $geshi->set_overall_class('code'); return $geshi->parse_code(); }
private function highlight(&$text, $lang = 'php', $lines = false) { $geshi = new GeSHi(trim($text, "\r\n"), $lang); $geshi->enable_classes(); $geshi->set_header_type(GESHI_HEADER_PRE); $geshi->set_overall_class("code"); $geshi->set_encoding("utf-8"); // [[mw:user:Brianegge]] suggestion $geshi->set_overall_style('background: #EEEEEE; border: padding: 0.2em'); if ($lines == true or $lines == 1 or $lines == '1') { $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS); } else { $geshi->enable_line_numbers(GESHI_NO_LINE_NUMBERS); } return "<style>" . $geshi->get_stylesheet() . "</style>" . $geshi->parse_code(); }
/** * filter * * @param string $text * @return string */ public function filter($text) { return preg_replace_callback(self::$regex, function ($matches) { if (isset($matches[1]) && isset($matches[2])) { //we have a #lang attribute in our <code /> $language = trim($matches[1], "#\n"); $code = html_entity_decode(trim($matches[2], "\n")); $geshi = new \GeSHi($code, $language); $geshi->set_header_type(GESHI_HEADER_PRE_VALID); $geshi->set_overall_class('highlighted'); $geshi->enable_classes(); return $geshi->parse_code(); } return $matches[0]; //for some reason this went wrong }, $text); }
public function codeHighlight($source, $lang) { Zend_Loader::loadFile("geshi.php", array(config::getFilename("geshi/"), "/usr/share/php-geshi"), true); if ($lang == "cpp") { $lang = "C++"; } if ($lang == "gcj") { $lang = "Java"; } if (!class_exists("GeSHi")) { return "<!-- GeSHi disabled --> <pre>" . htmlspecialchars($source) . "</pre>"; } $geshi = new GeSHi($source, $lang); $geshi->set_header_type(GESHI_HEADER_PRE_TABLE); $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS); $geshi->set_overall_class("geshi"); $code = $geshi->parse_code(); return $code; }
function highlight($code, $lang, $path) { if (empty($lang)) { $lang = 'c'; } $geshi = new GeSHi($code, $lang); $geshi->enable_classes(); $geshi->set_overall_class('highlight'); $geshi->set_header_type(GESHI_HEADER_NONE); /* Now this feature works, maybe activate it? */ /* $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS, 1); */ $result = $geshi->parse_code(); /* This thing fixes styles when line numbers are disabled */ $result = '<div class="highlight ' . $lang . '">' . $result . '</div>'; if ($geshi->error()) { $result = $code; } return $result; }
function onParseContentBlock($page, $name, $text, $shortcut) { $output = NULL; if (!empty($name) && !$shortcut) { list($language, $lineNumber, $class, $id) = $this->getHighlightInfo($name); if (!empty($language)) { $geshi = new GeSHi(trim($text), $language); $geshi->set_language_path($this->yellow->config->get("pluginDir") . "/highlight/"); $geshi->set_header_type(GESHI_HEADER_PRE_TABLE); $geshi->set_overall_class($class); $geshi->set_overall_id($id); $geshi->enable_line_numbers($lineNumber ? GESHI_NORMAL_LINE_NUMBERS : GESHI_NO_LINE_NUMBERS); $geshi->start_line_numbers_at($lineNumber); $geshi->enable_classes(true); $geshi->enable_keyword_links(false); $output = $geshi->parse_code(); $output = preg_replace("#<pre(.*?)>(.+?)</pre>#s", "<pre\$1><code>\$2</code></pre>", $output); } } return $output; }
/** * Initialise a GeSHi object to format some code, performing * common setup for all our uses of it * * @param string $text * @param string $lang * @return GeSHi */ public static function prepare($text, $lang) { global $wgSyntaxHighlightKeywordLinks; self::initialise(); $geshi = new GeSHi($text, $lang); if ($geshi->error() == GESHI_ERROR_NO_SUCH_LANG) { return null; } $geshi->set_encoding('UTF-8'); $geshi->enable_classes(); $geshi->set_overall_class("source-{$lang}"); $geshi->enable_keyword_links($wgSyntaxHighlightKeywordLinks); // If the source code is over 100 kB, disable higlighting of symbols. // If over 200 kB, disable highlighting of strings too. $bytes = strlen($text); if ($bytes > 102400) { $geshi->set_symbols_highlighting(false); if ($bytes > 204800) { $geshi->set_strings_highlighting(false); } } /** * GeSHi comes by default with a font-family set to monospace, which * causes the font-size to be smaller than one would expect. * We append a CSS hack to the default GeSHi styles: specifying 'monospace' * twice "resets" the browser font-size specified for monospace. * * The hack is documented in MediaWiki core under * docs/uidesign/monospace.html and in bug 33496. */ // Preserve default since we don't want to override the other style // properties set by geshi (padding, font-size, vertical-align etc.) $geshi->set_code_style('font-family: monospace, monospace;', true); // No need to preserve default (which is just "font-family: monospace;") // outputting both is unnecessary $geshi->set_overall_style('font-family: monospace, monospace;', false); return $geshi; }
$geshi->set_tab_width(2); //$geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS); //$geshi->set_line_style('background: #fcfcfc;', true); Yii::app()->clientScript->registerCss('highlightcode2', $geshi->get_stylesheet()); echo $geshi->parse_code(); ?> <p> </p> <p>Now we modify our function:<br> </p> <?php $source = "\nvar counter = 0;\nvar reset_comment = false;\nvar comment_id = 0;\nvar subject_id = 0;\n\nfunction getLiveInfo(){\n\t\$.getJSON('http://samesub.com/api/v1/live/getall?callback=?',\n\t\t{subject_id:subject_id, coment_id:comment_id},\n\t\tfunction(data) {\n\t\t\t//If everything is ok(response_code == 200), let's print some LIVE information\n\t\t\tif(data.response_code == 200){\n\t\t\t\tcounter = data.time_remaining;\n\t\t\t\tif(data.new_sub != 0 || data.new_comment != 0 ){\n\t\t\t\t\tif(data.new_sub != 0) {\n\t\t\t\t\t\t//Every time there is a nuew sub, comments must be cleared\n\t\t\t\t\t\treset_comment=true;\n\t\t\t\t\t\tcomment_id = 0;\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t//Display subject\n\t\t\t\t\t\tsubject_id = data.subject_id;\n\t\t\t\t\t\t\$('#title').html(data.title);\n\t\t\t\t\t\t\$('#time_remaining').html(data.time_remaining + ' seconds.');\n\t\t\t\t\t}\n\t\t\t\t\tif(data.new_comment != 0){\n\t\t\t\t\t\tcomment_id = data.comment_id;\n\t\t\t\t\t\tshow_comments(data.comments);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\t//Otherwise alert data.response_message\t\t\t\t\n\t\t\t\talert(data.response_message);\n\t\t\t}\n\t\t}\n\t);\n\tvar aa = setTimeout('getLiveInfo()',8000);\n}\n\nfunction show_comments(comments){\n\tif(reset_comment == true) {\n\t\t\$('#comments_box').html('');//Clear all previous comments\n\t}\n\tfor(var i in comments) {\n\t\t\$('#comments_box').prepend(comments[i]['comment_text']+ '<br />');\n\t}\n}\n\nvar myInterval = setInterval(\n\tfunction(){\n\t\tcounter = counter - 1;\n\t\t\$('#time_remaining').html(counter + ' seconds.');\n\t}\n,1000);\n"; $language = 'Javascript'; $geshi = new GeSHi($source, $language); $geshi->enable_classes(); $geshi->set_overall_class('myjs_no_lines'); $geshi->set_header_type(GESHI_HEADER_DIV); $geshi->set_overall_style("padding:1px 15px 1px 15px;border:1px solid #999999;background: #fcfcfc;font: normal normal 1em/1.2em monospace;"); $geshi->set_tab_width(2); //$geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS); //$geshi->set_line_style('background: #fcfcfc;', true); Yii::app()->clientScript->registerCss('highlightcode2', $geshi->get_stylesheet()); echo $geshi->parse_code(); ?> <p> </p> <p>As you can see there are several changes: </p> <ol> <li>We have declared few global variables.</li> <li>We have splitted our function in three main parts: the <b>getLiveInfo</b> function itself, the <b>show_comments</b> function, and the interval function.</li>
/** * Callback for code text * * Uses GeSHi to highlight language syntax * * @author Andreas Gohr <*****@*****.**> */ function code($text, $language = NULL) { global $conf; if (is_null($language)) { $this->preformatted($text); } else { //strip leading blank line $text = preg_replace('/^\\s*?\\n/', '', $text); // Handle with Geshi here require_once DOKU_INC . 'inc/geshi.php'; $geshi = new GeSHi($text, strtolower($language), DOKU_INC . 'inc/geshi'); $geshi->set_encoding('utf-8'); $geshi->enable_classes(); $geshi->set_header_type(GESHI_HEADER_PRE); $geshi->set_overall_class("code {$language}"); $geshi->set_link_target($conf['target']['extern']); $text = $geshi->parse_code(); $this->doc .= $text; } }
function ch_highlight_code($matches) { global $ch_options; // undo nl and p formatting $plancode = $matches[2]; $plancode = $this->entodec($plancode); $geshi = new GeSHi($plancode, strtolower($matches[1])); $geshi->set_encoding('utf-8'); $geshi->set_header_type(GESHI_HEADER_DIV); $geshi->enable_classes(true); $language = $geshi->get_language_name(); if ($language == 'PHP') { $geshi->add_keyword(2, 'protected'); $geshi->add_keyword(2, 'private'); $geshi->add_keyword(2, 'abstract'); $geshi->add_keyword(2, 'static'); $geshi->add_keyword(2, 'final'); $geshi->add_keyword(2, 'implements'); } elseif ($language == 'Bash') { $geshi->add_keyword(2, 'convert'); $geshi->add_keyword(2, 'git'); } elseif ($language == 'Vim Script') { $geshi->add_keyword(1, 'endfunction'); } if (ch_go('ch_b_linenumber')) { $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS); } $geshi->enable_strict_mode(ch_go('ch_b_strict_mode')); $geshi->set_tab_width(ch_go('ch_in_tab_width')); $geshi->set_overall_class('dean_ch'); $overall_style = ''; if (!ch_go("ch_b_wrap_text")) { $overall_style .= 'white-space: nowrap;'; } else { $overall_style .= 'white-space: wrap;'; } if ($overall_style != '') { $geshi->set_overall_style($overall_style, false); } return $geshi->parse_code(); }
/** * Initialise a GeSHi object to format some code, performing * common setup for all our uses of it * * @param string $text * @param string $lang * @return GeSHi */ public static function prepare($text, $lang) { global $wgTitle, $wgOut; self::initialise(); $geshi = new GeSHi($text, $lang); if ($geshi->error() == GESHI_ERROR_NO_SUCH_LANG) { return null; } $geshi->set_encoding('UTF-8'); $geshi->enable_classes(); $geshi->set_overall_class("source-{$lang}"); $geshi->enable_keyword_links(false); // Wikia change start if ($wgTitle instanceof Title && EditPageLayoutHelper::isCodeSyntaxHighlightingEnabled($wgTitle)) { $theme = 'solarized-light'; if (SassUtil::isThemeDark()) { $theme = 'solarized-dark'; } $geshi->set_language_path(GESHI_ROOT . $theme . DIRECTORY_SEPARATOR); $geshi->set_overall_id('theme-' . $theme); $wgOut->addStyle(AssetsManager::getInstance()->getSassCommonURL('extensions/SyntaxHighlight_GeSHi/styles/solarized.scss')); } // Wikia change end return $geshi; }
/** * Wrapper for GeSHi Code Highlighter, provides caching of its output * Modified to calculate cache from URL so we don't have to re-download time and again * * @author Christopher Smith <*****@*****.**> * @author Esther Brunner <*****@*****.**> */ function _cached_geshi($url, $refresh) { global $conf; $cache = getCacheName($url, '.code'); $mtime = @filemtime($cache); // 0 if it doesn't exist if ($mtime != 0 && !$_REQUEST['purge'] && $mtime > time() - $refresh && $mtime > filemtime(DOKU_INC . 'inc/geshi.php')) { $hi_code = io_readFile($cache, false); if ($conf['allowdebug']) { $hi_code .= "\n<!-- cachefile {$cache} used -->\n"; } } else { require_once DOKU_INC . 'inc/geshi.php'; // get the source code language first $search = array('/^htm/', '/^js$/'); $replace = array('html4strict', 'javascript'); $lang = preg_replace($search, $replace, substr(strrchr($url, '.'), 1)); // download external file $http = new DokuHTTPClient(); $http->timeout = 25; //max. 25 sec $code = $http->get($url); $geshi = new GeSHi($code, strtolower($lang), DOKU_INC . 'inc/geshi'); $geshi->set_encoding('utf-8'); $geshi->enable_classes(); $geshi->set_header_type(GESHI_HEADER_PRE); $geshi->set_overall_class("code {$language}"); $geshi->set_link_target($conf['target']['extern']); $hi_code = $geshi->parse_code(); io_saveFile($cache, $hi_code); if ($conf['allowdebug']) { $hi_code .= "\n<!-- no cachefile used, but created -->\n"; } } return $hi_code; }
| license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Jakub Vrana <*****@*****.**> | +----------------------------------------------------------------------+ */ if ($_SERVER["argc"] < 3) { exit("Purpose: Syntax highlight PHP examples in XSLT generated manual.\r\n" . 'Usage: highlight.php [ "xml" | "php" ] [ filename.ext | dir | wildcard ] ...' . "\r\n"); } set_time_limit(5 * 60); // can run long, but not more than 5 minutes ini_set("error_reporting", E_ALL); // kill the E_STRICT warnings in GeSHi under PHP 5 require dirname(__FILE__) . '/geshi/geshi.php'; $geshi = new GeSHi('', 'php', dirname(__FILE__) . '/geshi/geshi'); $geshi->set_tab_width(4); $geshi->set_overall_class('phpcode'); $geshi->set_overall_style('font-size: 85%', true); $geshi->set_symbols_highlighting(false); $geshi->set_strings_style('color: green', true); $geshi->set_keyword_group_style(1, 'color: #d09010; font-weight: bold', true); $geshi->set_numbers_style('color: #aa0000; font-weight: bold', true); $geshi->set_methods_style('color: black; font-style: italic', true); $geshi->set_regexps_style(0, 'color: #004090', true); // use this to get updated stylesheet info if changed via abovementioned API // file_put_contents('style.css', $geshi->get_stylesheet()); function callback_html_number_entities_decode($matches) { return chr($matches[1]); } function callback_highlight_php($matches) {
/** * Initialise a GeSHi object to format some code, performing * common setup for all our uses of it * * @note Used only until MW 1.20 * * @param string $text * @param string $lang * @return GeSHi */ public static function prepare( $text, $lang ) { global $wgSyntaxHighlightKeywordLinks; self::initialise(); $geshi = new GeSHi( $text, $lang ); if( $geshi->error() == GESHI_ERROR_NO_SUCH_LANG ) { return null; } $geshi->set_encoding( 'UTF-8' ); $geshi->enable_classes(); $geshi->set_overall_class( "source-$lang" ); $geshi->enable_keyword_links( $wgSyntaxHighlightKeywordLinks ); // If the source code is over 100 kB, disable higlighting of symbols. // If over 200 kB, disable highlighting of strings too. $bytes = strlen( $text ); if ( $bytes > 102400 ) { $geshi->set_symbols_highlighting( false ); if ( $bytes > 204800 ) { $geshi->set_strings_highlighting( false ); } } return $geshi; }
function cut_string($string, $length = 1024) { if (strlen($string) > $length) { return substr($string, 0, $length); } return $string; } if ($isCodePosted) { //if code posted... include_once '../../site/geshi/geshi.php'; $code = cut_string($_POST['code']); $geshi = new GeSHi($code, 'cpp'); $geshi->enable_classes(); $geshi->set_header_type(GESHI_HEADER_PRE_TABLE); $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS); $geshi->set_overall_class('geshicode'); echo "<h3>Input</h3>\n"; echo $geshi->parse_code(); echo "<h3>Output</h3>\n"; $output = get_democlient_output($code); $results = parse_democlient_output($output); if (!empty($results)) { echo "<table id=\"resultsTable\">\n"; echo "<thead>\n"; echo " <tr><th class=\"center\" filter-type=\"ddl\">Line</th><th class=\"center\" filter-type=\"ddl\">Severity</th><th>Message</th></tr>\n"; echo "</thead>\n"; echo "<tbody>\n"; foreach ($results as $result) { //for each result... echo " <tr><td class=\"center\">" . htmlspecialchars($result['line']) . "</td><td class=\"center\">" . htmlspecialchars($result['severity']) . "</td><td>" . htmlspecialchars($result['msg']) . "</td></tr>\n"; }
/** * Function called by the pre_typography extension hook before the text will be parsed by EE * @param string $str text that will be parsed * @param object $typo Typography object * @param array $prefs Preferences sent to $TYPE->parse_type * @return string text where the code has been stripped and code positions marked with an MD5-ID * @access public * @global $EXT Extension-Object to support multiple calls to the same extension hook * @global $OUT could be used to display errors - it isn't at the moment * @todo Display error using $OUT */ function pre_typography($str, $typo, $prefs) { // we don't need the DB, nor IN, nor DSP // should probably use OUT to display user_error messages global $EXT, $OUT; // here we're doing the actual work if ($EXT->last_call !== FALSE) { // A different extension has run before us $str = $EXT->last_call; } $cache_dir = dirname(__FILE__) . '/' . $this->settings['cache_dir']; $rllen = strlen($this->rlimit); $pos = array(); preg_match_all($this->llimit, $str, $matches, PREG_OFFSET_CAPTURE); foreach ($matches[0] as $key => $match) { $pos[$match[1]] = array(); $pos[$match[1]]['match'] = $match[0]; // lang (called type internally for historical reasons) if (!empty($matches[1][$key][0])) { // strip slashes for filesystem security and quotes because the value might be quoted $pos[$match[1]]['type'] = str_replace(array('/', '"', "'"), '', substr($matches[1][$key][0], 5)); } else { $pos[$match[1]]['type'] = NULL; } // strict if (!empty($matches[2][$key][0])) { switch (str_replace(array('"', "'"), '', strtolower(substr($matches[2][$key][0], 7)))) { case 'true': case '1': $pos[$match[1]]['strict'] = TRUE; break; case 'false': case '0': $pos[$match[1]]['strict'] = FALSE; break; default: $pos[$match[1]]['strict'] = NULL; break; } } else { $pos[$match[1]]['strict'] = NULL; } // line $pos[$match[1]]['line'] = !empty($matches[3][$key][0]) ? str_replace(array('"', "'"), '', substr($matches[3][$key][0], 5)) : NULL; // start $pos[$match[1]]['start'] = !empty($matches[4][$key][0]) ? str_replace(array('"', "'"), '', substr($matches[4][$key][0], 6)) : NULL; // keyword_links if (!empty($matches[5][$key][0])) { switch (str_replace(array("'", '"'), '', strtolower(substr($matches[5][$key][0], 14)))) { case 'true': case '1': $pos[$match[1]]['keyword_links'] = TRUE; break; case 'false': case '0': $pos[$match[1]]['keyword_links'] = FALSE; break; default: $pos[$match[1]]['keyword_links'] = NULL; break; } } else { $pos[$match[1]]['keyword_links'] = NULL; } // overall_class $pos[$match[1]]['overall_class'] = !empty($matches[6][$key][0]) ? str_replace(array("'", '"'), '', substr($matches[6][$key][0], 14)) : NULL; // overall_id $pos[$match[1]]['overall_id'] = !empty($matches[7][$key][0]) ? str_replace(array("'", '"'), '', substr($matches[7][$key][0], 11)) : NULL; } // clean variables used in the loop unset($matches, $key, $match); // krsort the array so we can use substr stuff and won't mess future replacements krsort($pos); // Check for the cache dir if (file_exists($cache_dir) && is_dir($cache_dir)) { $cache_dir = realpath($cache_dir) . '/'; if (!is_writable($cache_dir)) { // try to chmod it @chmod($cache_dir, 0777); if (!is_writable($cache_dir)) { // still not writable? display a warning print '<b>Warning</b>: Your <i>' . $this->name . '</i> cache directory <b>' . $cache_dir . '</b> is not writable! This will cause severe performance problems, so I suggest you chmod that dir.'; } } } else { if (!mkdir($cache_dir, 0777)) { print '<b>Warning</b>: Your <i>' . $this->name . '</i> cache directory <b>' . $cache_dir . '</b> could not be created! This will cause severe performance problems, so I suggest you create and chmod that dir.'; } else { // create an index.html so the contents will not be listed. @touch($cache_dir . 'index.html'); } } if (mt_rand(0, 10) == 10) { // on every 10th visit do the garbage collection $cur = time(); $d = dir($cache_dir); while (($f = $d->read()) !== FALSE) { if ($f != 'index.html' && $f[0] != '.') { if ($cur - filemtime($cache_dir . $f) > $this->settings['cache_cutoff']) { // File is older than cutoff, delete it. @unlink($cache_dir . $f); } } } } // loop through the code snippets $i = 0; foreach ($pos as $code_pos => $match) { $error = FALSE; if (($code_end_pos = strpos($str, $this->rlimit, (int) $code_pos + strlen($match['match']))) !== FALSE) { // we have a matching end tag. // make sure cache is regenerated when changing options, too! $md5 = md5(($not_geshified = substr($str, $code_pos + strlen($match['match']), $code_end_pos - $code_pos - strlen($match['match']))) . print_r($match, TRUE) . print_r($this->settings, TRUE)); // check whether we already have this in a cache file if (is_file($cache_dir . $md5) && is_readable($cache_dir . $md5)) { if (is_callable('file_get_contents')) { $geshified = file_get_contents($cache_dir . $md5); // this is for the garbage collection touch($cache_dir . $md5); } else { // screw PHP4! $f = fopen($cache_dir . $md5, 'r'); $geshified = fread($f, filesize($cache_dir . $md5)); fclose($f); touch($cache_dir . $md5); } } else { // no cache so do the GeSHi thing if ($this->settings['geshi_version'] == '1.1') { // use GeSHi 1.1 include_once dirname(__FILE__) . '/geshi-1.1/class.geshi.php'; // highlight code according to type setting, default to setting $geshi = new GeSHi($not_geshified, $match['type'] !== NULL ? $match['type'] : $this->settings['default_type']); $str_error = $geshi->error(); if (empty($str_error)) { // neither line numbers, nor strict mode is supported in GeSHi 1.1 yet. // in fact it does pretty much nothing // there used to be a rather large block of code here, testing wether methods were callable and call them if // that's the case. // parse the code $geshified = $geshi->parseCode(); } else { $error = TRUE; } } else { // use GeSHi 1.0 include_once dirname(__FILE__) . '/geshi-1.0/geshi.php'; // highlight code according to type setting, default to php $geshi = new GeSHi($not_geshified, $match['type'] !== NULL ? $match['type'] : $this->settings['default_type']); $str_error = $geshi->error(); if (empty($str_error)) { // enable line numbers $number_style = !empty($match['line']) ? $match['line'] : $this->settings['default_line']; switch (strtolower(preg_replace('/\\d+/', '', $number_style))) { case 'normal': $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS); break; case 'fancy': $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS, (int) preg_replace('/[^\\d]*/', '', $number_style)); break; case 'none': $geshi->enable_line_numbers(GESHI_NO_LINE_NUMBERS); break; } // set first line number if ($match['start']) { $geshi->start_line_numbers_at($match['start']); } // set strict mode if ($match['strict']) { $geshi->enable_strict_mode(TRUE); } // enable or disable keyword links $geshi->enable_keyword_links((bool) ($match['keyword_links'] !== NULL) ? $match['keyword_links'] : $this->settings['keyword_links']); // set overall class name if ($match['overall_class'] != NULL) { $geshi->set_overall_class($match['overall_class']); } // set overall id if ($match['overall_id'] != NULL) { $geshi->set_overall_id($match['overall_id']); } // set header type switch ($this->settings['geshi_header_type']) { case 'div': $geshi->set_header_type(GESHI_HEADER_DIV); break; case 'pre': $geshi->set_header_type(GESHI_HEADER_PRE); break; case 'pre-valid': $geshi->set_header_type(GESHI_HEADER_PRE_VALID); break; case 'pre-table': $geshi->set_header_type(GESHI_HEADER_PRE_TABLE); break; case 'none': $geshi->set_header_type(GESHI_HEADER_NONE); break; } // set encoding (for legacy reasons afaik) $geshi->set_encoding($this->settings['geshi_encoding']); // parse the source code $geshified = $geshi->parse_code(); } else { $error = TRUE; } } if (!file_exists($cache_dir . $md5) && is_writable($cache_dir) || file_exists($cache_dir . $md5) && is_writable($cache_dir . $md5)) { if (!$error) { // we can write to the cache file if (is_callable('file_put_contents')) { file_put_contents($cache_dir . $md5, $geshified); @chmod($cache_dir . $md5, 0777); } else { // when will you guys finally drop PHP4 support? $f = fopen($cache_dir . $md5, 'w'); fwrite($f, $geshified); fclose($f); @chmod($cache_dir . $md5, 0777); } } } else { // We could ignore that, but for performance reasons better warn the user. print '<b>Warning</b>: Your <i>' . $this->name . '</i> cache directory <b>' . $cache_dir . '</b> is not writable! This will cause severe performance problems, so I suggest you chmod that dir.'; } } // save replacement to cache and mark location with an identifier for later replacement if (!isset($_SESSION['cache']['ext.geshify'])) { $_SESSION['cache']['ext.geshify'] = array(); } if (!$error) { $_SESSION['cache']['ext.geshify'][$md5] = $geshified; $str = substr($str, 0, $code_pos) . $md5 . substr($str, $code_end_pos + $rllen); } } // unset used variables, so we don't get messed up unset($code_pos, $code_end_pos, $md5, $geshified, $not_geshified, $geshi, $match, $ident, $error); } return $str; }
function plugin_geshi_highlight_code($source, $options) { if (!class_exists('GeSHi')) { require PLUGIN_GESHI_LIB_DIR . 'geshi.php'; } $geshi = new GeSHi($source, $options['language']); $geshi->set_encoding(CONTENT_CHARSET); if (PLUGIN_GESHI_USE_CSS) { $geshi->enable_classes(); } if ($options['number']) { $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS); $geshi->start_line_numbers_at($options['start']); $geshi->set_overall_class('geshi number ' . $options['language']); plugin_geshi_read_setting($geshi, 'default'); plugin_geshi_read_setting($geshi, $options['language']); $html = $geshi->parse_code(); if ($geshi->header_type == GESHI_HEADER_PRE) { $before = array('<ol', '/ol>', '</div', '> ', ' '); $after = array('<code><object><ol style="margin-top: 0; margin-bottom: 0;"', '/ol></object></code>', "\n</div", '> ', ' '); $html = str_replace($before, $after, $html); } } else { $geshi->set_overall_class('geshi ' . $options['language']); plugin_geshi_read_setting($geshi, 'default'); plugin_geshi_read_setting($geshi, $options['language']); $html = $geshi->parse_code(); $html = str_replace("\n ", "\n", $html); } return $html; }
function plugin_geshi_highlight_code($source, $options) { if (class_exists('GeSHi') === false) { require PLUGIN_GESHI_LIB_DIR . 'geshi.php'; } $geshi = new GeSHi($source, $options['language']); $geshi->set_encoding(CONTENT_CHARSET); if (PLUGIN_GESHI_USE_CSS) { $geshi->enable_classes(); } $class = 'geshi'; if (version_compare(GESHI_VERSION, '1.0.8', '<')) { $class .= ' ' . $options['language']; } if ($options['number']) { $class .= ' number'; } $geshi->set_overall_class($class); if ($options['number']) { $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS); $geshi->start_line_numbers_at($options['start']); plugin_geshi_read_setting($geshi, 'default'); plugin_geshi_read_setting($geshi, $options['language']); switch ($geshi->header_type) { case GESHI_HEADER_PRE: $before = array('<ol', '/ol>', '</div', '> ', ' '); $after = array('<code><object><ol style="margin-top: 0; margin-bottom: 0;"', '/ol></object></code>', "\n</div", '> ', ' '); break; case GESHI_HEADER_PRE_TABLE: $before = array(" \n"); $after = array("\n"); if (PLUGIN_GESHI_USE_CSS) { $before[] = '"><td class="'; $after[] = '"><td class="de1 '; } else { $before[] = '"><td'; $after[] = '"><td style="' . $geshi->code_style . '"'; } break; } } else { plugin_geshi_read_setting($geshi, 'default'); plugin_geshi_read_setting($geshi, $options['language']); $before = array(" \n"); $after = array("\n"); } $html = $geshi->parse_code(); if (isset($before) && isset($after)) { $html = str_replace($before, $after, $html); } return $html; }
/** * Initialise a GeSHi object to format some code, performing * common setup for all our uses of it * * @param string $text * @param string $lang * @return GeSHi */ private static function prepare($text, $lang) { self::initialise(); $geshi = new GeSHi($text, $lang); if ($geshi->error() == GESHI_ERROR_NO_SUCH_LANG) { return null; } $geshi->set_encoding('UTF-8'); $geshi->enable_classes(); $geshi->set_overall_class("source-{$lang}"); $geshi->enable_keyword_links(false); return $geshi; }
function fox_code($atts, $thing) { global $file_base_path, $thisfile, $fox_code_prefs; if (isset($fox_code_prefs)) { foreach (array('fileid', 'filename', 'language', 'lines', 'startline', 'overallclass', 'tabs', 'css', 'keywordslinks', 'encoding', 'fromline', 'toline') as $value) { ${$value} = $fox_code_prefs[$value]; } } else { extract(lAtts(array('fileid' => '', 'filename' => '', 'language' => 'php', 'lines' => '1', 'startline' => '1', 'overallclass' => '', 'tabs' => '2', 'css' => '0', 'keywordslinks' => '0', 'encoding' => 'UTF-8', 'fromline' => '', 'toline' => ''), $atts)); } if (!$thisfile) { if ($fileid) { $thisfile = fileDownloadFetchInfo('id = ' . intval($fileid)); } else { if ($filename) { $thisfile = fileDownloadFetchInfo("filename = '" . $filename . "'"); } else { $local_notfile = false; } } } if (!empty($thisfile)) { $filename = $thisfile['filename']; $fileid = $thisfile['id']; if (!empty($fromline) || !empty($toline)) { $handle = fopen($file_base_path . '/' . $filename, "r"); $fromline = !empty($fromline) ? intval($fromline) : intval(1); $toline = !empty($toline) ? intval($toline) : intval(-1); $currentLine = 0; $code = ""; while (!feof($handle)) { $currentLine++; if ($currentLine >= $fromline && ($toline < 0 || $currentLine <= $toline)) { $code .= fgets($handle); } else { fgets($handle); } } fclose($handle); $startline = $fromline; } else { $code = file_get_contents($file_base_path . '/' . $filename); } } else { if (strlen($fox_code_prefs['code']) > 0) { $code = $fox_code_prefs['code']; } else { $code = $thing; } } if (!$overallclass) { $overallclass = $language; } require_once 'geshi.php'; $geshi = new GeSHi(trim($code, "\r\n"), $language); if ((bool) $css) { $geshi->enable_classes(); $geshi->set_overall_class($overallclass); } $geshi->start_line_numbers_at($startline); $geshi->set_header_type(GESHI_HEADER_DIV); $geshi->set_encoding($encoding); $geshi->set_tab_width(intval($tabs)); $geshi->enable_keyword_links((bool) $keywordslinks); $geshi->enable_line_numbers((bool) $lines); if (!isset($local_notfile)) { $thisfile = NULL; } return $geshi->parse_code(); }
static function texyBlockHandler($invocation, $blocktype, $content, $lang, $modifier) { if ($blocktype !== 'block/code') { return $invocation->proceed(); } $texy = $invocation->getTexy(); if ($lang == 'html') { $lang = 'html4strict'; } elseif ($lang == 'yaml') { $lang = 'python'; } $content = Texy::outdent($content); $geshi = new GeSHi($content, $lang); // GeSHi could not find the language if ($geshi->error) { return $invocation->proceed(); } // do syntax-highlighting $geshi->set_encoding('UTF-8'); $geshi->set_header_type(GESHI_HEADER_PRE); $geshi->enable_classes(); $geshi->enable_keyword_links(false); $geshi->set_overall_style(''); $geshi->set_overall_class('code'); // save generated stylesheet $content = $geshi->parse_code(); // check buggy GESHI, it sometimes produce not UTF-8 valid code :-(( $content = iconv('UTF-8', 'UTF-8//IGNORE', $content); // protect output is in HTML $content = $texy->protect($content, Texy::CONTENT_BLOCK); $el = TexyHtml::el(); $el->setText($content); return $el; }
/** * Apply syntax highlighting * * @param String $language Code language * @param String $code Code to format * @param bool $enable_classes Enable the CSS class * @param string $style CSS class to apply * * @return mixed */ static function highlightCode($language, $code, $enable_classes = true, $style = "max-height: 100%; white-space:pre-wrap;") { if (!class_exists("GeSHi", false)) { CAppUI::requireLibraryFile("geshi/geshi"); } $geshi = new GeSHi($code, $language); $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS); $geshi->set_overall_style($style); $geshi->set_overall_class("geshi"); if ($enable_classes) { $geshi->enable_classes(); } return $geshi->parse_code(); }
/** * Wrapper for GeSHi Code Highlighter, provides caching of its output * * @author Christopher Smith <*****@*****.**> */ function p_xhtml_cached_geshi($code, $language) { $cache = getCacheName($language . $code, ".code"); if (@file_exists($cache) && !$_REQUEST['purge'] && filemtime($cache) > filemtime(DOKU_INC . 'inc/geshi.php')) { $highlighted_code = io_readFile($cache, false); @touch($cache); } else { require_once DOKU_INC . 'inc/geshi.php'; $geshi = new GeSHi($code, strtolower($language), DOKU_INC . 'inc/geshi'); $geshi->set_encoding('utf-8'); $geshi->enable_classes(); $geshi->set_header_type(GESHI_HEADER_PRE); $geshi->set_overall_class("code {$language}"); $geshi->set_link_target($conf['target']['extern']); $highlighted_code = $geshi->parse_code(); io_saveFile($cache, $highlighted_code); } return $highlighted_code; }
function geshicallback($matches) { $pathtogeshi = $this->get_config('pathtogeshi') . '/geshi'; $geshilang = strtolower($matches[1]); $showln = $this->get_config('showlinenumbers') == TRUE ? TRUE : FALSE; if (strlen($matches[2]) == 4 and substr($matches[2], 0, 3) == 'ln=') { $showln = strtolower(substr($matches[2], -1)) == 'y' ? TRUE : FALSE; } $geshi = new GeSHi($matches[3], $geshilang, $pathtogeshi); $geshi->set_header_type(GESHI_HEADER_DIV); if ($showln) { $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS); } // Have to get rid of newlines. // Left align per suggestion from Norbert Mocsnik $geshi->set_overall_style('text-align: left'); $geshi->set_overall_class('geshi'); return str_replace("\n", '', $geshi->parse_code()); }