How I added GeSHi to GPORG. Here I will demonstrate using GeSHi (for prettification purposes).
<?php
function sexy_code ($a, $content) {
$attr = shortcode_atts(array( // sets the defaults for each attribute so we don't run into errors if we're missing any
'lang' => 'html', // default language is HTML
'start' => '1' // which line num to start on
), $a);
$content = strip_tags($content); // remove wpautop() formatting from the snippet
$array = explode("\n", $content);
$tab = null;
$t = 0;
$pos = null;
foreach ($array as $i => $line) {
$code = $line;
if (strpos($line, '//') !== false) {
list($code, $comment) = explode('//', $line);
}
if (preg_match("#\{|\($#", $code)) {
$pos = 'after';
$t++;
}
elseif (preg_match("#\}|\)$#", $code)) {
$pos = 'before';
$t--;
}
$tab = ($t > 0 ? implode("", array_fill(0, $t, " ")) : null);
$line = ($pos == 'before' ? $tab : null).$line.( $pos == 'after' ? $tab : null);
$array[$i] = $line;
}
$content = implode("\n", $array);
$content = preg_replace("#( +)(\n)#", "\\2\\1", $content);
$content = str_replace(" }", "}", $content);
$content = preg_replace("#\&([a-z0-9]+);#", "&\\1;", $content);
$content = str_replace('<', '<', $content);
$content = str_replace('>', '>', $content);
//echo secret_output ('test HTML',$content);
$lang = $attr['lang'];
$geshi = new GeSHi($content, $lang);
$geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS); // type of line numbers
$geshi->enable_classes(); // turns on classes so we can prettify thru CSS
if ($attr['start'] != 1) // if you specifically mentioned which line number you want the snippet to start on
$geshi->start_line_numbers_at($attr['start']); // ...set it here
$r = $geshi->parse_code();
$r = str_replace('<ol>', '<ol class="no-custom">', $r);
$r = preg_replace("#^<pre>#", '<pre class="wp-block-code">', $r);
return $r;
}
add_shortcode( 'code', 'sexy_code' ); // shortcodify!
?>
(See the doc on WordPress’s shortcode API if you haven’t already.)
To use in a post…
[code lang="php" start="2"]<?php echo $fun; ?>[/code]
…will get you…
<?php echo $fun; ?>
Leave a Reply