Open main menu

Extension talk:GeSHiCodeTag

The following discussion has been transferred from Meta-Wiki.
Any user names refer to users of that site, who are not necessarily users of MediaWiki.org (even if they share the same username).

For questions/comments/suggestions/etc. please post it here.

Contents

QUESTIONSEdit

Please add:

Q: for questions

A: for answers

GeSHiCodeTag and templatesEdit

Q: GeSHiCodeTag doesn't work well with templates using pure html.

A: To make it work better, turn off the "simple" mode in GeshiCodeTag.php:

 // 1 - enabled, 0 - disabled
 $codeTag["simple"] = 0;                       // ex. <php> echo </php>
 $codeTag["advanced"] = 1;                     // ex. <code php n> echo </php>

It appears that the "simple" mode for the DIV language will interfere with any <div> elements in HTML code.

You can avoid this behaviour by simply changing the name of div.php to something like langdiv.php and also change the Constant in div.php to something like LANGDIV. I am aware that changing this tag the language itself is not "usable" by adding div but only by using langdiv, but as I have a big wiki up and running with an older version it won't be possible to simply disable the simple feature. So changing div to libdiv made my day. Good work, I like your extension and especially the numbering feature...

Auto indentationEdit

Q: The Beautifier syntax highlighting engine supports auto indentation. Can GeSHi do this too?

A: I've looked on the Geshi documentation, and it seems to me that there's no feature for auto indentation. For more features available for GeSHi check out the link.

NOTICE after installationEdit

Q: i've install geshi and get 2 NOTICEs

 Notice: Use of undefined constant div - assumed 'div' in extensions/GeSHICodeTag.php(55) : runtime-created function on line 1
 Notice: Undefined variable: languagesPath in extensions/GeSHICodeTag.php(55) : runtime-created function on line 1

and i cant turn the notice off by

 error_reporting(E_ALL ^ E_NOTICE);

what can i do ?

A: Can you please specify the version of geshi you're using and the version of mediawiki? I'll try to test out and see if there's a fix that I can do. Thanks! --Paul516 22:03, 8 February 2007 (UTC)

A: I had the same problem, I'm using PHP 5.2.1 (I think that was the problem), with MediaWiki 1.9.3 and latest version of Geshi. Was able to fix, in GeshiCodeTag.php replace the entire ExtensionCodeTag function with this:

function ExtensionCodeTag()
{
        global $wgParser, $codeTag, $languages;

        ReadLanguages();

        if($codeTag["advanced"]["mode"])
                $wgParser->setHook('code', 'AdvancedCodeTag');
        $languagesPath = 'extensions/geshi/geshi';
        if($codeTag["simple"])
                foreach($languages as $lang)
                {
                     $wgParser->setHook($lang,
                                   create_function( '$source',
                                        '
                                        global $languagesPath;
                                        $geshi = new GeSHi($source,\'' . $lang . '\', $languagesPath);
                                         return $geshi->parse_code();'
                     ));
                }       
}

Differences: Added global $languagePath; to created function, and added single quotes around the $lang.

--Jonyo 14:51, 3 May 2007 (UTC)


COMMENTSEdit

Q: code cpp-qt n does not work (dumps languages). The same page shows that code cpp-zz works (surprise!).

Q: This plugin and the code on other sites to do syntax highlighting with GeSHi in Mediawiki does not seem to work with older versions of MediaWiki - including the current default install on Ubuntu Dapper: mediawiki v 1.4.14. Can anyone confirm that? When I try, everything seems to work but the text does not get highlighted. If anyone can confirm or deny this, please comment here!

A: I've tried installing a Mediawiki 1.4.14 using GeSHi-1.0.7.12 and GeSHiCodeTag 1.5 it seems that only the simple mode works. There seems to be some slight differences on how the parsing is setup in the older versions. I'll try to see if I can fix it to work in advanced mode as well. --Paul516 06:37, 24 September 2006 (UTC)

A: I just read somewhere that from Mediawiki 1.5 they support giving an argument to a tag. This indeed means that in previous versions only simple mode would work.


Q: I downloaded the code, and it only worked for simple mode. After a while of editing, the problem appeared to be the use of strict mode (which in a previous version was not used by default). Also, the examples at http://www.wikics.org/GeshiCodeTag_Samples suffer from the same problem.

I have removed the strict mode line, and now it works fine. Btw: I use mediawiki 1.6.8 and GeSHi-1.0.7.15.

A: Hmm... if that the case then I'll just disable the strict mode by default. Also instead of removing the line, you can just set it to 0 (false) so you'll still have the feature if you want to enable it later on --Paul516 18:28, 10 November 2006 (UTC)

Q: I just installed GeSHi-1.0.7.16 with mediawiki 1.9.0. When I try to use it, I get error: Undefined index: STRICT_MODE_APPLIES ..... in geshi.php line 1018 I browsed the geshi code, and I just don't understand why this error occurs. There is STRICT_MODE_APPLIES in language file (I'm using php.php), and constants GESHI_MAYBE, etc. are defined. Can somebody help me? Right for now I just disabled check for STRICT_MODE_APPLIES in code.

An easy fix for the "div" problem is just to rename the geshi/div.php file to something not needed for a tag (I used divg.php). I don't know if this will have unintended consequences, but I haven't seen any and it did fix the munging of the message that appears under the edit box and all other places where the "div" tag was in use as far as I can tell. --Woozle 19:32, 10 March 2007 (UTC)

SUGGESTIONSEdit

Q. No biggie but the name and author in the credits are switched. In Special:Version it shows up as Paul Nolasco by GeshiCodeTag. --Icep 23:55, 24 September 2006 (UTC)

A. Thanks for telling me! Fixed :) --Paul516 05:26, 25 September 2006 (UTC)

Q: How would you make a default language so <code> automatically highlights it to a certain language?

Q: I suggest to remove from GeSHi languages catalog language 'div'. At least in MediaWiki 1.12 GeSHiCodeTag highligts contents of some <div> elements. Other solution could be rewrite ReadLanguages() to ignore 'div' language.


Behave properly using multi-lined code in numbered listsEdit

Q: I was having problems putting multi-lined code in numbered lists, the list would start over and the code would get hosed up. Example: Try the following text in a wiki article:

# To fix, open the file example.php.
# Now, find the lines: <code php>$example = 1;
$example['this is just example'] = 2;
echo "Example = $example";</code>
# Replace with the code: <code php>$example = 5;
$example['this is just example'] = 1;
echo "Example = ".print_r($example,1)."<br />";</code>
# Now it should print the correct text.

On mine, it restarts the numbering to 1 whenever there is a newline in the code, and it jacks up the <pre> tags.

A: I came up with a fix, I added a new parameter, "nl2br", and modified the advanced function to allow the parameters after the language to be in any order. Replace the AdvancedCodeTag function with:

function AdvancedCodeTag ($source, $settings){          

        global $languages, $languagesPath, $codeTag;
                
        $language = array_shift($settings);      // [arg1]      
	
        // [arg1]
        if($language == ''){
          $language='text';  // bugfix: to work for existing <code> tags, simply use "text"
        }
        if($language == "list")                                               // list all languages supported
            return "<br>List of supported languages for <b>Geshi " . GESHI_VERSION  . "</b>:<br>"
                   . implode("<br>", $languages);
                
        if($language != "" && !in_array($language, $languages))               // list languages if invalid argument
            return "<br>Invalid language argument, \"<b>" . $language . "</b>\", select one from the list:<br>" 
                   . implode("<br>", $languages);
        
        // set geshi
        $geshi = new GeSHi(trim($source), $language, $languagesPath); 
        $geshi->enable_strict_mode($codeTag["advanced"]["strict"]);        
	
	// [n]

        // Enable line numbers
        if(in_array('n',$settings))                                           // display line numbers
            $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);

	
        /*
          Add more GeSHi features below
          http://qbnz.com/highlighter/geshi-doc.html 
        */

	// [nl2br]
	$return = $geshi->parse_code();
	if (in_array('nl2br',$settings)){                                      // Remove newlines, replace with br
		//change all newlines to BR (manually, since
		//the php function nl2br leaves newlines intact.
		$return = str_replace("\n",'<br />',$return); //remove newlines
	}
	return $return;
}

To see it in action, use the same example as before, but add the parameter nl2br:

# To fix, open the file example.php.
# Now, find the lines: <code php nl2br>$example = 1;
$example['this is just example'] = 2;
echo "Example = $example";</code>
# Replace with the code: <code php nl2br>$example = 5;
$example['this is just example'] = 1;
echo "Example = ".print_r($example,1)."<br />";</code>
# Now it should print the correct text.

Not sure if you want to put the modification as part of the main app or not... I know we are probably going to be using it a lot on our site...

--Jonyo 15:18, 3 May 2007 (UTC)

Thanks for the fix Jonyo. I added the changes as you've suggested to main app. --Paul516 08:44, 9 May 2007 (UTC)

Word wrapEdit

Q: It would be neat to enable the word-wrap feature of GeSHi for the wiki-syntax. This could be done, for example:
<source lang="latex" wrap="True">This is a line of LaTeX, and it can be wrapped in narrow window widths, etc. Other examples are HTML and XML.</source>. ~24.80.179.197 22:59, 6 July 2007 (UTC)

A: I'll take a look on it, and see if this can be implemented. --Paul516 04:22, 24 May 2008 (UTC)

Version in Extension CreditsEdit

  • The version number is useful in the Extension Credits. Also suggest a description.
'version' => '1.65',
'description' => 'Syntax highlighter using [http://qbnz.com/highlighter/ GeSHi]',

A: Thanks for the suggestion! I've added it in the code. --Paul516 04:22, 24 May 2008 (UTC) Servel333 20:29, 27 March 2008 (UTC)

Included in MediaWiki ProtectionEdit

Towards the top of the file, below the credits, you could add the following.

// Ensure file is included as part of MediaWiki. Prevents limited security issues.
if ( !defined('MEDIAWIKI') )
    die( "<h2>This file is part of MediaWiki and is not a valid entry point</h2>\n" );

Servel333 20:29, 27 March 2008 (UTC)

Include support for settings settings in another fileEdit

This code will check for certain variables before setting the default values. This adds an optional variable $GeSHiPath and allows values from $codeTag to be set before this file is included.

This is based on old code for 1.6, but if this section hasn't changed, it's all good.

if ( isset($GeSHiPath) ) {
	$languagesPath = $GeSHiPath . '/geshi';
	include_once($GeSHiPath . '/geshi.php');
} else {
	include_once('GeSHi/geshi.php');
	$languagesPath = "extensions/GeSHi/geshi";

}

// Syntax: <lang> Code </lang>
// Example: <php> Php Code </php>
if ( !isset($codeTag["simple"]) )
	$codeTag["simple"] = false;

// Syntax: <code lang> Code </code>
// Example: <code php> Php Code </code>
if ( !isset($codeTag["advanced"]["mode"]) )
	$codeTag["advanced"]["mode"] = true;

// strict mode - http://qbnz.com/highlighter/geshi-doc.html#using-strict-mode
if ( !isset($codeTag["advanced"]["strict"]) )
	$codeTag["advanced"]["strict"] = true;

Servel333 20:37, 27 March 2008 (UTC)

using full page templatesEdit

Q: i've added the modifications necessary to have full page source code articles, the templates including categorization. unfortunately, the wikitext to categorize the article also gets GeSHied and as a result the article does not get categorized. how can this be fixed? (MW 1.9.3 WAMP, using square brackets for categorizing) - neoNOexSPAMmachina at gmail dot com

highlighting with a templateEdit

Q: Hello, I would like to use semantic forms to create my pages.

As you may know semantic forms wants every bit of the generated page to be in a template.

My (experimental) template is as follows:

<code {{{Language}}}>
 {{{code}}}
 </code>
 {{{Language}}}

but it seems that for some reason the variables don't get parsed and everything I see is similar to the following:

{{{code}}}
php

Note that the code element is interpreted but the language which is a parameter in it is not. it's like the parser gets the <code {{{Language}}}> string and not the correct <code php>. The same happens when interpreting the {{{code}}} The language is correctly interpreted when the variable is called outside the code element.

if I use the short syntax:

<{{{Language}}}>
 {{{code}}}
 </{{{Language}}}>

this is the output I get:

<php> /**
 * Hello World
 * @author Giulio
 */
...

without colors.

Any Idea about why is that and how to solve it?

thank you.

--DonGiulio 20:18, 2 March 2008 (UTC)

I solved it by using the TagParser extension. Thank you for the extension --DonGiulio 11:26, 8 March 2008 (UTC)

disarranged contentEdit

I've installed this extension. and it performs the highlighting in the right way. but when I want to edit any page, all the content which are normally shown top or below the edit box disarrange. like the content of pages: Mediawiki:Newarticletext, Mediawiki:Copyrightwarning & MediaWiki:Edittools
you can see my problem on this link: http://cli.ir/index.php?title=Testpage&action=edit

MediaWiki:	1.12.0rc1
PHP:		5.0.5 (cgi)
MySQL:		4.1.11-Debian_4sarge7-log
GeSHiCodeTag:	1.65 (11/04/2007)
GeSHi:		I've tested both versions: 1.0.7.21 & 1.0.7.20 but none of them works.

sepehrnoush 21:56, 1 April 2008 (UTC)

Hi, I can confirm the disarrangement, too.
Is this fixed already? MW 1.12, peter 212.100.42.217 10:24, 18 July 2008 (UTC)

A: Thanks for the notice. I'll be testing the error and will get back to you ASAP. --Paul516 00:06, 30 July 2008 (UTC)

better default for original <code> tagsEdit

Q: Hi, we are using your cool highlight extension since some days ago here. And we are using only advanced mode. Under it, it seems that right now, if no language is specified, it defaults to 'text'. And this has caused some problems here because we had a bunch of <code>whatever</code> tags along a lot of articles. So we have performed a minimal change to the Extension in order to return the original in case that no language is specified. It's only a matter of changing:

       if($language == '')
         $language='text';

by:

       if($language == '')
       return '<code>' . $source . '</code>';

That way our old code tags are rendered properly and not processed by Geshi. Just wondering if that could become a new setting like: $codeTag["advanced"]["respect_old_codes"] = 0;

Thanks for the great extension, anyway! Ciao :-) Stronk7 17:02, 8 August 2008 (UTC)


This one will keep default code behaviour if the code hasn't a special tag and is inline (no linebreaks)
if($language == & strripos($source,"\n")== 0) {
return '<code>' . $source . '</code>';
}
--153.96.104.2 11:11, 27 April 2009 (UTC)
Hi,
I tried both examples and couldn't make it work. Using MediaWiki 1.16 and Geshi 1.0.8.10. Any idea why? Whenever I type a <code>whatever</code> within a line, I have plain text... I thought about creating a new language.php file within the geshi directory and setting the properties to reproduce the original wiki code formatting, but I know very little of php and I am not sure how to proceed... Thanks for your help!
Nouklea 16:11, 21 September 2011 (UTC)

A: I further modified the AdvancedCodeTag function in order to handle the case where the HTML <code> tag is used, but we don't want GeSHi to handle the text. This specifically rears its head on the Special:Version and Special:Upload pages of MediaWiki 1.20.2, which contain HTML <code> elements mixed in with wiki markup. I modified the function signature to take advantage of additional arguments available for the callback, adding the parser and frame arguments.

function AdvancedCodeTag ($source, array $settings, Parser $parser, PPFrame $frame)

And then, instead of just returning the source text, I run it through the Parser fuction recusiveTagParse first in order to process any of the wiki markup.

return '<code>' . $wgParser->recursiveTagParse($source, $frame) . '</code>';

It is important that the $frame object be passed in to recursiveTagParse. Otherwise, you will receive runtime errors within the Parser.php file when processing <code> elements on Special pages.

Here is the full code for the working AdvancedCodeTag function.

function AdvancedCodeTag ($source, array $settings, Parser $parser, PPFrame $frame)
{
	global $languages, $languagesPath, $codeTag;
	$language = array_shift($settings);      // [arg1]      

	// [arg1]
	if('' == $language)
	{
		return '<code>' . $parser->recursiveTagParse($source, $frame) . '</code>';
	}

	if($language == "list")                                                 // list all languages supported
		return "<br>List of supported languages for <b>Geshi " . GESHI_VERSION  . "</b>:<br>"
			   . implode("<br>", $languages);

	if($language != "" && !in_array($language, $languages))          // list languages if invalid argument
		return "<br>Invalid language argument, \"<b>" . $language . "</b>\", select one from the list:<br>" 
			   . implode("<br>", $languages);

	// set geshi
	$geshi = new GeSHi(trim($source), $language, $languagesPath); 
	$geshi->enable_strict_mode($codeTag["advanced"]["strict"]);        

	// [arg2 or more]
	if(in_array('n',$settings))                                                  // display line numbers
		$geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);

	/*
	   Add more GeSHi features from [ http://qbnz.com/highlighter/geshi-doc.html  ]
	   template:
			  if( in_array( '<PARAMETER NAME>', $settings ) )
			  {
					$geshi-><GESHI FUNCTION CALL>
			  }
	*/

	// removes newlines replaces with <br />
	return str_replace("\n",'<br />', $geshi->parse_code());     
}
Mpolucha 23:30, 20 May 2013 (UTC)

pdf_embedEdit

Conflicts with pdf_embed extension, taking over the syntax and formatting it without <code> tags!

Force LTR align for codeEdit

Q. How can i force the code to show with LTR aliment. i'm using a Hebrew Layout and the output is aligned to the right... witch is so worng for coding :)

A. ???

Syntax not highlighted with MW 1.15.1 and GeSHi 1.0.8.4?Edit

Q: I've followed the instructions exactly from the Wiki page, with MW 1.15.1 and GeSHi 1.0.8.4, and the highlighting does nothing. For reference, see bottom of page at http://apidocs.bonanzle.com/index.php/Get-started-quick. It just keeps the "<php>" unescaped. What are some debugging steps I can take to figure out what's going wrong? It seems that all the right files are being included, given that if I add nonsense code into GeshiCodeTag.php I can get MW to give me errors...

As far as I can tell, GeSHiCodeTag does not work with GeSHi 1.0.8.4 - there is no geshi.php (it's class.geshi.php), the languages are now directories and not files (which GeSHiCodeTag tries to read). It doesn't seem to be a quick fix, at least I did not find one. I suggest, that GeSHi version 1.0.8.4 is removed from the compatibility list. 64.46.7.93 07:42, 12 December 2009 (UTC)

PHP 5.3 compatibility issuesEdit

Q: in PHP 5.3 functions eregi_replace and ereg_match are deprecated. So there should be made some changes to source code. function ReadLanguages could be replaced by

function ReadLanguages()
{       
        global $languages, $languagesPath;
 
        $dirHandle = opendir($languagesPath) 
                        or die("ERROR: Invalid directory path - [$languagesPath], Modify the value of \$languagesPath'");
 
        $pattern = "#^(.*)\.php$#i";
 
        while ($file = readdir($dirHandle))     
        {       
                if( preg_match($pattern, $file) )                            
                        $languages[] = preg_replace($pattern, "\\1", $file); 
        }
        closedir($dirHandle);
}

According to PHP documentation the preg_match() function has some issues with the replacement parameter being ambiguous. The following makes it a little clearer:

function ReadLanguages()
{       
        global $languages, $languagesPath;
 
        $dirHandle = opendir($languagesPath) 
                        or die("ERROR: Invalid directory path - [$languagesPath], Modify the value of \$languagesPath'");
 
        $pattern = "/^(.*)\.php$/i";
 
        while ($file = readdir($dirHandle))     
        {       
                if( preg_match($pattern, $file) )                            
                        $languages[] = preg_replace($pattern, "\${1}", $file); 
        }
        closedir($dirHandle);
}

test on mediawiki 1.17 (SVN)Edit

This fix worked for me in the following setup:

* MediaWiki	1.17alpha (r71201)
* PHP	5.3.2-1ubuntu4.2 (apache2handler)
* MySQL	5.1.41-3ubuntu12.6

--Drunken sapo 13:36, 17 August 2010 (UTC)

tested on media wiki 1.19.9Edit

Worked for me (php 5.4.24) 76.102.26.116 21:48, 31 January 2014 (UTC)

Text size is too smallEdit

Looks like the "font-family:monospace;" style on the pre tag is causing the text to be significantly smaller than the rest on the page - which makes it hard to read. To fix this, I had to add "font-size: 12px;" next to the "font-family:monospace" style in geshi.php

mediawiki 1.19.9 php 5.4.24

76.102.26.116 21:54, 31 January 2014 (UTC)

Return to "GeSHiCodeTag" page.