Extension talk:SimpleTable/Archive

From mediawiki.org
Latest comment: 4 years ago by Vicarage in topic Collapsing tables
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).

Allow Wiki Text in Dataset[edit]

I have modified the script to allow wiki text within the dataset and properly handle the parse reference so it does not conflict with other extensions.

--- (Smcnaught) 20:12, 28 July 2006 (UTC) - I am also available on irc.chekmate.org #MediaWikiReply

Thanks for your contribution -- that's a big improvement (wish I'd thought of it!). As you'll see, I've moved your version to the main page, and also uploaded an improved version, which also includes your change. Cheers, JohanTheGhost 15:31, 12 April 2007 (UTC)Reply

Quoted strings containing separator literals[edit]

I haven't tested this extension yet - though I've wanted one like it for a long time. Does it deal well with quoted strings that contain delimiters? For example:

<tab class=wikitable sep=comma>
"field, 1" , "field, 2"
"field 3" , "field 4"
</tab>

Along the same lines, if it does handle quoted strings containing separator literals, does it support quote escaping, or would the user just have to put in &quot;. --Jimbojw 16:05, 12 April 2007 (UTC)Reply

No, it doesn't handle quoted delimiters yet; with the most recent enhancement, the idea is that you can pick a non-clashing delimiter.
Having said that, being able to handle quoted delimiters in the style exported by Excel (eg.) would be useful -- I'll look into it. JohanTheGhost 16:45, 19 April 2007 (UTC)Reply
OK, the Excel CSV format encloses any values which contain commas in double quotes; double quotes are escaped by doubling them. So, UK, "average" becomes "UK, ""average""". This is pretty repugnant from a parsing point of view... I think the simplest thing is to use tab-separated data, and convert tabs to spaces in your data. JohanTheGhost 17:38, 19 April 2007 (UTC)Reply
This is a biggie. I realize that escaping delimiters is a pain to parse, but there is a LOT of CSV-producing software out there that do not give you control over what delimiter you use. We primarily use Apple Numbers for spreadsheets, which has no options for CSV output -- it's as you said, comma delimiters with quoted fields that contain commas and double quotes for embedded. This means (as one HUGE example) that you can't have a field that looks like "$1,000" and export it to SimpleTable. I may take a shot at munging this... might try a google for PHP-based CSV parsers... — Bytesmiths 17:45, 23 October 2009 (UTC)Reply

column/row headings[edit]

Since most tables usually have column headings (sometimes also row headings), it's be nice if there was an option for this.
A simple parameter in the TAB tag (heading=column and/or heading=row) could tell the parser to format the first row/column accordingly.
I'll look into it myself when I get around to it, though that might take a few weeks.
-- FND 18:44, 12 April 2007 (UTC)Reply

Move to MediaWiki.org[edit]

Why is this at Meta - doesn't it belong at MediaWiki.org? -- FND 18:44, 12 April 2007 (UTC)Reply

Dude, read the box on the article page! JohanTheGhost 16:41, 19 April 2007 (UTC)#Reply
Sorry; I guess I meant why you didn't create it there in the first place, but that's probably because things were different when this page was first started... -- FND 17:38, 19 April 2007 (UTC)Reply
That's right; TabbedData appeared in May 06, the "new extensions on MW.org" notice appeared in August. JohanTheGhost 20:02, 19 April 2007 (UTC)Reply

name misleading[edit]

As mentioned on MediaWiki-l, the current name of this extension makes it a bit hard to immediately grasp its purpose. The term "tabbed" is reminiscent of things like "tabbed browsing", which might be misleading.
"Tabular Data" has been suggested as an alternative, though something like "CSV-Data Tables" might be a more telling name.
-- FND 09:52, 13 April 2007 (UTC)Reply

Agreed -- moving it would be a hassle, though. Maybe one day -- maybe after it gets moved to MW.org. JohanTheGhost 16:47, 19 April 2007 (UTC)Reply
So, now that I've made Sayuri move the page, let's talk business... How about something like xSV Data Tables ("xSV" because "CSV" would be too limiting)? It doesn't sound very fancy, but at least it reflects the purpose!? -- FND 14:29, 26 June 2007 (UTC)Reply
Hmmm... I really prefer "TabularData", or "SimpleTable". JohanTheGhost 15:13, 26 June 2007 (UTC)Reply
"SimpleTable" sounds nice - though "TabularData" might be a more telling name... -- FND 16:05, 26 June 2007 (UTC)Reply
"SimpleTable" it is -- I like simple... ;-) JohanTheGhost 20:21, 26 June 2007 (UTC)Reply
Great! :) -- FND 13:40, 28 June 2007 (UTC)Reply

modification: column headings[edit]

I've changed and added a few lines of code to allow column headings using the "HEAD" parameter.
Unfortunately, I do not know how to make TortoiseSVN create a patch from two local files, so I'll have to post the full code.
(Disclaimer: I'm not an experienced coder, and don't know very much about PHP - so the quality of my changes might be questionable... )
-- FND 12:53, 19 April 2007 (UTC)Reply

Nice job! I've moved it into the main version, and added "head=top" and "head=left". I've deleted your posted version from here to make the page easier to navigate, but it is still available in the history. JohanTheGhost 17:25, 19 April 2007 (UTC)Reply
Looks good - I can't test it here, but I'll update as soon as I'm in the office again!
Just one question: Why don't you use SWITCH/CASE instead of IF ... ELSE?
-- FND 18:16, 19 April 2007 (UTC)Reply
With only two cases, it makes the code more compact, and it's not any slower. JohanTheGhost 19:58, 19 April 2007 (UTC)Reply
Well, I guess it's a matter of personal preference...
I just tested it, and it works like a charm! (A nice addition would be to be able to specify both TOP and LEFT as headings, but I guess that's rarely needed.)
-- FND 08:23, 25 April 2007 (UTC)Reply
Done, as of version 1,2 -- "head=topleft". JohanTheGhost 20:22, 26 June 2007 (UTC)Reply
Good job! (I almost overlooked the update though; the revision history should have a timestamp too.) -- FND 13:40, 28 June 2007 (UTC)Reply

No borders in SimpleTable v1.2[edit]

I am using Mediawiki 1.10 on a Apache/2.2.3 (Ubuntu) PHP/5.2.1 Server. I installed SimpleTable v1.2.Everithing is ok except the tables have no borders I tried all kinds of separations and I still get the same result.Can you please help? If you need any additional info, please post here so I can provide you with what you need

Yes, same problem here. no borders, "no pretty format". How to do this? --Nyks 17:22, 31 August 2007 (UTC)Reply
The table doesn't have borders by default. If you want borders, you have to add the relevant markup to the <tab> tag; for example
<tab border=1>
. . .
If your wiki has the "wikitable" CSS class defined, then this should work:
<tab class=wikitable>
That wasn't very clear in the main page; I've now clarified it. Sorry for the confusion. JohanTheGhost 21:02, 18 September 2007 (UTC)Reply
Thanks for the info. btw, perhaps a small border would be nice as default for this extension :) --Nyks 02:29, 19 September 2007 (UTC)Reply

Table Captions and row/cell classes.[edit]

I love this extension!

I like to use SimpleTables with the sortable class to make my tables sort. It would be great to be able to assign a class to arbitrary rows to use the sortbottom and unsortable classes.

Thanks.

Please add sep=semicolon (;)[edit]

It often seems to be necessary to have the semicolon (;) as an additional separator. This is often used in Germany, because we use the comma as the decimal separator (instead of the point). Adding the following line to the $separators array provides this feature:

    'semicolon' => '/;/',

I'd like to see this in the next official version of this great extension. --Rrosenfeld 12:50, 15 October 2007 (UTC)Reply

Me too! When writing/editing by hand using the semicolon is the easiest one. Using tab it can't be entered by hand (cursor jumps to next inputfield), space and comma is often used in text and bar is used in [[Link|Wiki-Links]]. I'm using your extension in our company intranet-mediawiki and i'm using semicolon as default-sep. --84.57.26.228 07:31, 9 January 2008 (UTC) aka. de:User:FolkeReply
Me too too: another vote for semicolon as standard --Samdutton 14:02, 21 January 2008 (UTC)Reply

Introducing SimpleTable into Wikipedia[edit]

Is there a plan to introduce this extension into wikipedia? If not, I want to propose introducing this extension. Please teach me if there are any problems. J8takagi 15:09, 8 April 2008 (UTC)Reply

Nevermind - I'm dumb. --LNick 13:35, 16 May 2008 (UTC)Reply

SimpleTable with Style[edit]

I have created some enhancements that allow you to add style to each line. The style is 100% optional and shouldn't make it any more difficult to use SimpleTable unless you are interested in the style functionality. If you don't include the word "style" in the head field the output is normal and the table still works as its supposed to. top and left are still supported in the head field as well. If you add the word style to the head field the first column in each row is treated as the style for the column. This allows you to color the text or the background, change the style of the border on a single row, justify the text of that row, etc... I also added functionality to allow the use of a title for the table. Once again this is 100% optional. I plan on making more enhancements like the ability to optionally specify a color for every other row. Right now I am calling my extension ESTable (Enhanced Simple Table) and it can coexist with the original SimpleTable extension in a wiki (it uses the hook estable instead of tab) but if you are interested in these enhancements I would be glad to become a contributor to your extension. --Rudieia 16:29, 14 November 2008 (UTC)Reply

Cell editing does work[edit]

Just use the bar as you do in regular wikis.

colspan="2" | Field 1, Field 3, Field 4

This made the first column have a colspan of 2.

How do you manually add a tab[edit]

typing \t did not work.

Is it known that indentation of a list is broken by this table ?[edit]

I found that a list indentation is broken by this table in my Wiki (ver 1.13.3). Say I have a list, and one item is a table. After the list I have a new Level 2 headline. The headline appears indented, which is incorrect. Using the standard wiki table worked. --62.134.44.197 08:04, 13 February 2009 (UTC)Reply

Displacement bug in version 1.2 & 1.2a[edit]

Comparison screenshot

All elements after a table generated by the extension are vertically displaced by six pixels. This is caused by an additional paragraph in the HTML code, generated by the WikiText Parser.

HTML code via normal table syntax HTML code via SimpleTable syntax
<table class="wikitable"><tr>
<th> Head 1
</th><th> Head 2
</th><th> Head 3
</th></tr>
<tr>
<td> Field 4
</td><td> Field 5
</td><td> Field 6
</td></tr>
<tr>
<td> Field 7
</td><td> Field 8
</td><td> Field 9
</td></tr></table>
<table class="wikitable"><tr>
<th> Head 1
</th><th> Head 2
</th><th> Head 3
</th></tr>
<tr>
<td> Field 4
</td><td> Field 5
</td><td> Field 6
</td></tr>
<tr>
<td> Field 7
</td><td> Field 8
</td><td> Field 9
</td></tr></table>
<p><!-- 
NewPP limit report
Preprocessor node count: 5/1000000
Post-expand include size: 0/2097152 bytes
Template argument size: 0/2097152 bytes
Expensive parser function count: 0/100
-->
</p>

To fix this bug, you have to disable the output of the limit report in the ParserOptions. To achieve this, simply change the parser call in line 113 to the following new code:

Old New
        $ret = $parser->parse($wikiTable,
                              $parser->mTitle,
                              $parser->mOptions,
                              false,
                              false);
        $popts = $parser->mOptions;
        $popts->enableLimitReport(false);
        $ret = $parser->parse($wikiTable,
                              $parser->mTitle,
                              $popts,
                              false,
                              false);

Basically, the "enableLimitReport" function of the ParserOptions is called with "false", which will disable the output of the limit report. After this, the output is exactly the same as generated via the normal table syntax. --WikiMichi 02:27, 22 November 2009 (UTC)Reply

This bug is still present in 1.2a. --79.245.181.137 20:50, 30 July 2011 (UTC)Reply

SimpleTable & PHP 5.3[edit]

Since the handling of call by reference / -value method parameters is different since PHP 5.3, SimpleTable will not work, because the hookTab method is expecting the third parameter as reference. But the Wiki-Parser is passing itself as value, not as reference. In my mediawiki instance, this will prevent SimpleTable from working. No tables are generated.

Solution: Get the newest revision of version 1.2 (I fixed it there already) or remove the & in line 82 (i.e. &$parser --> $parser). --80.129.148.209 09:56, 11 May 2010 (UTC)Reply

Modified version[edit]

VitaliyFilippov 15:39, 11 April 2011 (UTC)Reply

We use modified version which allows wiki-code in dataset (own implementation) and allows to specify column CSS styles. Russian description. Here is the code:

<?php

/**
 * Tabbed Data extension.
 * (c) Vitaliy Filippov 2011
 * http://wiki.4intra.net/SimpleTable
 *
 * This extension implements a simple method to display tabular data, with a
 * far simpler markup than the standard Wiki table markup.  The goal is to
 * allow tabular data to be very easily pasted in from an external source,
 * such as a spreadsheet.  The disadvantage is that it doesn't allow for any
 * fancy formatting; for example, there is no way (as yet) to set row and cell
 * parameters, including row and cell spanning.  However, it makes a very
 * simple way to include tabular data in a Wiki.
 *
 * All you need to do is prepare your data in rows, with fields separated
 * by tab characters.  Excel's "Save as" -> "Text (Tab delimited)" function
 * saves data in this format.  Place the data inside <tab>...</tab> tags,
 * and set any table parameters inside the opening <tab> tag; eg.:
 *
 * <tab class=wikitable sep=tab>
 *   field1\tfield2\t...
 *   field1\tfield2\t...
 * </tab>
 *
 * Additional parameters allowed in the tag are:
 *   sep    Specify a different separator; can be one of:
 *          'tab', 'bar', 'space', 'spaces', 'comma', 'semicolon'
 *   head   Specify a heading; "head=top" makes the first row a heading,
 *          "head=left" makes the first column a heading, "head=topleft"
 *          does both.
 *   colN   Specify CSS style for each cell of _COLUMN_ number N.
 *          First column has N=1 (not N=0).
 *
 * Based @ the original SimpleTable
 *   http://www.mediawiki.org/wiki/Extension:SimpleTable
 *   (c) Johan the Ghost
 * Thanks for contributions to:
 *   Smcnaught
 *   Frederik Dohr
 */

$wgExtensionFunctions[] = 'wfSimpleTable';
$wgExtensionCredits['parserhook'][] = array(
    'name'        => 'SimpleTable',
    'author'      => 'Vitaliy Filippov',
    'url'         => 'http://wiki.4intra.net/SimpleTable',
    'description' => 'Convert tab-separated or similar data into a Wiki table',
);

/*
 * Setup SimpleTable extension.
 * Sets a parser hook for <tab></tab>.
 */
function wfSimpleTable()
{
    new SimpleTable();
}

class SimpleTable
{
    /*
     * The permitted separators.  An array of separator style name
     * and preg pattern to match it.
     */
    private $separators = array(
        'space'     => '/ /',
        'spaces'    => '/\s+/',
        'tab'       => '/\t/',
        'comma'     => '/,/',
        'semicolon' => '/;/',
        'bar'       => '/\|/',
    );

    /*
     * Construct the extension and install it as a parser hook.
     */
    public function __construct() {
        global $wgParser;
        $wgParser->setHook('tab', array(&$this, 'hookTab'));
    }

    /*
     * The hook function. Handles <tab></tab>.
     * Receives the table content and <tab> parameters.
     */
    public function hookTab($tableText, $argv, $parser)
    {
        // The default field separator.
        $sep = 'tab';

        // Default value for using table headings.
        $head = NULL;

        // Styles for individual columns
        $colstyle = array();

        // Build the table parameters string from the tag parameters.
        // The 'sep' and 'head' parameters are special, and are handled
        // here, not passed to the table.
        $params = '';
        foreach ($argv as $key => $value)
        {
            if ($key == 'sep')
                $sep = $value;
            elseif ($key == 'head')
                $head = $value;
            elseif (preg_match('/^col([1-9]\d*)$/s', $key, $m))
                $colstyle[$m[1]-1] = $value;
            else
                $params .= ' ' . $key . '="' . htmlspecialchars($value) . '"';
        }

        if (!array_key_exists($sep, $this->separators))
            return "Invalid separator: $sep";

        // Parse and convert the table body:

        // Parse preserving line-feeds
        $uniq = $parser->insertStripItem("\x01");
        $tableText = str_replace(array("\r\n", "\n\r", "\n", "\r"), array($uniq, $uniq, $uniq, ''), $tableText);
        $html = $parser->parse($tableText, $parser->mTitle, $parser->mOptions, false, false)->getText();
        $html = str_replace(array("\r\n", "\n\r", "\n", "\r"), array(' ', ' ', ' ', ' '), $html);
        $html = explode("\x01", trim($html, "\x01 \t\n\r"));

        // Build HTML <table> content
        $table = '';
        $headtop = strpos($head, 'top') !== false;
        $headleft = strpos($head, 'left') !== false;
        foreach ($html as $i => $line)
        {
            $line = preg_replace('/<!--.*?-->/', '', $line);
            if (trim($line))
            {
                $line = preg_split($this->separators[$sep], $line);
                foreach ($line as $j => &$c)
                {
                    $e = $headtop && !$i || $headleft && !$j ? 'th' : 'td';
                    $c = "<$e".($colstyle[$j] ? " style=\"".htmlspecialchars($colstyle[$j])."\"" : '').">$c</$e>";
                }
                $table .= "<tr>" . implode('', $line) . "</tr>\n";
            }
        }
        $html = "<table$params>$table</table>";

        return $html;
    }

}

Colored Head[edit]

How to make only the table head with colored background? (like style="background:#f0f0f0") --87.123.180.109 13:30, 13 October 2011 (UTC)Reply

I use:
{{#vardefine:background|bgcolor=Orange|}}

To define colours and then e.g.

| {{#var:background}}Test      ||

to use them. That requires using variables, but you can just use

bgcolor=Orange

--Robinson Weijman 13:01, 4 November 2011 (UTC)Reply

Change parse() to recursiveTagParse()[edit]

I noticed a problem when using SimpleTable on a page with <ref> tag and the Cite extension installed. It thew the error "Cite error: <ref> tags exist, but no <references/> tag was found." It looks like the call to "$parse->parse()" is the source of the problem. Since we're already in a tag hook, we're already inside a parse() so the function should not be called recursively. The method recursiveTagParse() should be used instead. The simplest fix would be to change the lines

       $ret = $parser->parse($wikiTable,
                             $parser->mTitle,
                             $parser->mOptions,
                             false,
                             false);
       $HTML = trim( str_replace("</table>\n\n", "</table>", $ret->getText()) ); # remove superfluous newlines

to

       $ret = $parser->recursiveTagParse($wikiTable);
       $HTML = trim( str_replace("</table>\n\n", "</table>", $ret) ); # remove superfluous newlines

This should work with version 1.8 and up according to the tag extension guide. Versions 1.16alpha and above should update the method definition

       public function hookTab($tableText, $argv, $parser, $frame)

and

       $ret = $parser->recursiveTagParse($wikiTable, $frame);
       $HTML = trim( str_replace("</table>\n\n", "</table>", $ret) ); # remove superfluous newlines

This would also fix the displacement bug above (i think). - 25 January 2012

Thank you, I had the same problem. Now it works.--Wasserkäfer (talk) 20:19, 24 June 2013 (UTC)Reply

Support for Mediawiki 1.23?[edit]

Please update this extension.

It prevents images from displaying in Mediawiki 1.23alpha.

Also please put it in GIT https://gerrit.wikimedia.org/r/mediawiki/extensions/SimpleTable.git

Buggy Interaction between Mediawiki indentation and SimpleTable Extension[edit]

The following markup results in head11 and head00 being indented out to start at the table indentation, rather than being aligned with head0 and head1.

=head0=
==head1==
:::<tab class=wikitable sep=comma head=top>
Head 1,Head 2,Head 3
Field 4,Field 5,Field 6
Field 7,Field 8,Field 9
</tab>
==head11==
=head00=

Adding a SimpleTable button to the editor[edit]

UPDATED FOR MEDIAWIKI 1.29.2
Add this to the top of SimpleTable12a.php:

$wgResourceModules['ext.SimpleTable'] = array('localBasePath' => __DIR__, 'scripts' => 'SimpleTable.js');   
$wgHooks['EditPage::showEditForm:initial'][] = 'SyntaxHighlight_addModule';
function SyntaxHighlight_addModule(EditPage $editPage, OutputPage $output)
{$output->addModules('ext.SimpleTable');}

And create a new file called 'SimpleTable.js' in the same directory as the PHP file:

// Icon from https://en.wikipedia.org/wiki/User:MarkS/Extra_edit_buttons
// https://www.mediawiki.org/wiki/Manual_talk:Custom_edit_buttons#Getting_a_bit_complicated,_doesn't_it?

if ( ['edit', 'submit'].indexOf( mw.config.get( 'wgAction' ) ) !== -1 ) {
    mw.loader.using( 'mediawiki.action.edit', function () {
        $( function ( $ ) {
            if ( mw.toolbar ) {
                mw.toolbar.addButton( {
        imageFile: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABcAAAAWCAIAAACkFJBSAAAAB3RJTUUH1gMHEyYhQxOZqAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAARnQU1BAACxjwv8YQUAAAE3SURBVHjaY/z//z8DZSCnZiILkLrxgiKD7j59DzLl91+KT
        speedTip: 'SimpleTable',
        tagOpen: "<tab class='wikitable sortable' sep=tab head=top width=600>\n",
        tagClose: "\n</tab>",
        sampleText: 'style="text-align:left"|Header1	style="text-align:left"|Header2\nFieldA	FieldB',
        imageId: 'button-simpletable'
            });
            }
        } );
    } );
}

Bug, cannot handle | as a delimiter if it occurs to provide alternate text in a link[edit]

Compare

<tab border=1 head=top sep=bar>
Header1 | Header2
[[Field 1|Smile]] | Field 2
Field 3 | Field 4
</tab>

<tab border=1 head=top sep=semicolon>
Header1 ; Header2
[[Field 1|Smile]] ; Field 2
Field 3 ; Field 4
</tab>

The latter renders correctly, but in the former the | in the link is treated as a column delimiter. It should be ignored as valid link syntax. Notmadewelcome (talk) 08:14, 2 February 2019 (UTC)Reply

My workaround was to add a new separator barbar, using "||", a one line change. Notmadewelcome (talk) 22:50, 2 February 2019 (UTC)Reply

Collapsing tables[edit]

Anyone who wants to make the tables collapsible but does not want to add the required lines to every table can edit SimpleTable.php as follows

        // here, not passed to the table.
        $params = 'data-expandtext="+" data-collapsetext="-"';
        $collapse = '';
        foreach ($argv as $key => $val) {
            if ($key == 'sep')
                $sep = $val;
            else if ($key == 'head')
                $head = $val;
            else if ($key == 'applycssborderstyle')
                $applycssborderstyle = $val;
            else if ($key == 'collapse')
                $collapse= 'mw-collapsed';
            else
                $params .= ' ' . $key . '="' . $val . '"';
        }
        $params .= ' ' . 'class="wikitable mw-collapsible ' . $collapse . '"';

I tried hard to get these options added as a template <tab {{collapsed}}> but to no avail. Vicarage (talk) 13:57, 25 November 2019 (UTC)Reply