How I added GeSHi to GPORG. Here I will demonstrate using GeSHi (for prettification purposes).

  1. function sexy_code ($a, $content) {
  2. $attr = shortcode_atts(array( // sets the defaults for each attribute so we don't run into errors if we're missing any
  3. 'lang' => 'html', // default language is HTML
  4. 'start' => '1' // which line num to start on
  5. ), $a);
  6.  
  7. $content = strip_tags($content); // remove wpautop() formatting from the snippet
  8.  
  9. $array = explode("\n", $content);
  10. $tab = null;
  11. $t = 0;
  12. $pos = null;
  13.  
  14. foreach ($array as $i => $line) {
  15. $code = $line;
  16. if (strpos($line, '//') !== false) {
  17. list($code, $comment) = explode('//', $line);
  18. }
  19. if (preg_match("#\{|\($#", $code)) {
  20. $pos = 'after';
  21. $t++;
  22. }
  23. elseif (preg_match("#\}|\)$#", $code)) {
  24. $pos = 'before';
  25. $t--;
  26. }
  27. $tab = ($t > 0 ? implode("", array_fill(0, $t, " ")) : null);
  28. $line = ($pos == 'before' ? $tab : null).$line.( $pos == 'after' ? $tab : null);
  29. $array[$i] = $line;
  30. }
  31. $content = implode("\n", $array);
  32. $content = preg_replace("#( +)(\n)#", "\\2\\1", $content);
  33. $content = str_replace("}", "}", $content);
  34.  
  35. $content = preg_replace("#\&([a-z0-9]+);#", "&\\1;", $content);
  36. $content = str_replace('<', '', $content);
  37.  
  38. //echo secret_output ('test HTML',$content);
  39.  
  40. $lang = $attr['lang'];
  41. $geshi = new GeSHi($content, $lang);
  42. $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS); // type of line numbers
  43. $geshi->enable_classes(); // turns on classes so we can prettify thru CSS
  44. if ($attr['start'] != 1) // if you specifically mentioned which line number you want the snippet to start on
  45. $geshi->start_line_numbers_at($attr['start']); // ...set it here
  46.  
  47. $r = $geshi->parse_code();
  48.  
  49. $r = str_replace('', '', $r);
  50. $r = preg_replace("#^#", '', $r);
  51.  
  52. return $r;
  53. }
  54. add_shortcode( 'code', 'sexy_code' ); // shortcodify!
  55.  

(See the doc on WordPress's shortcode API if you haven't already.)

To use in a post...

[code lang="php" start="2"]echo $fun;[/code]

...will get you...

  1. echo $fun;