1 package IkiWiki::Plugin::table;
2 # by Victor Moral <victor@taquiones.net>
9 hook(type => "preprocess", id => "table", call => \&preprocess);
12 sub preprocess (@) { #{{{
19 if (exists $params{file}) {
20 if (! $pagesources{$params{file}}) {
21 return "[[table ".gettext("cannot find file")."]]";
23 $params{data} = readfile(srcfile($params{file}));
26 $params{data} = IkiWiki::linkify($params{page},
27 $params{destpage}, $params{data});
30 if (lc $params{format} eq 'auto') {
31 # first try the more simple format
32 if (is_dsv_data($params{data})) {
33 $params{format} = 'dsv';
36 $params{format} = 'csv';
41 if (lc $params{format} eq 'csv') {
42 @data=split_csv($params{data}, $params{delimiter});
44 elsif (lc $params{format} eq 'dsv') {
45 @data=split_dsv($params{data}, $params{delimiter});
48 return "[[table ".gettext("unknown data format")."]]";
52 if (lc($params{header}) eq "yes") {
56 return "[[table ".gettext("empty data")."]]";
60 push @lines, defined $params{class}
61 ? "<table class=\"".$params{class}.'">'
63 push @lines, "\t<thead>",
64 genrow($params{page}, $params{destpage}, "th", @$header),
65 "\t</thead>" if defined $header;
66 push @lines, "\t<tbody>";
67 push @lines, genrow($params{page}, $params{destpage}, "td", @$_)
69 push @lines, "\t</tbody>" if defined $header;
70 push @lines, '</table>';
71 my $html = join("\n", @lines);
73 if (exists $params{file}) {
75 htmllink($params{page}, $params{destpage}, $params{file},
76 linktext => gettext('Direct data download'));
83 sub is_dsv_data ($) { #{{{
86 my ($line) = split(/\n/, $text);
87 return $line =~ m{.+\|};
90 sub split_csv ($$) { #{{{
91 my @text_lines = split(/\n/, shift);
92 my $delimiter = shift;
94 eval q{use Text::CSV};
96 my $csv = Text::CSV->new({
97 sep_char => defined $delimiter ? $delimiter : ",",
99 allow_loose_quotes => 1,
100 }) || error("could not create a Text::CSV object");
104 foreach my $line (@text_lines) {
106 if ($csv->parse($line)) {
107 push(@data, [ $csv->fields() ]);
110 debug(sprintf(gettext('parse fail at line %d: %s'),
111 $l, $csv->error_input()));
118 sub split_dsv ($$) { #{{{
119 my @text_lines = split(/\n/, shift);
120 my $delimiter = shift;
121 $delimiter="|" unless defined $delimiter;
124 foreach my $line (@text_lines) {
125 push @data, [ split(/\Q$delimiter\E/, $line, -1) ];
131 sub genrow ($$$@) { #{{{
133 my $destpage = shift;
138 push @ret, "\t\t<tr>";
139 for (my $x=0; $x < @data; $x++) {
140 my $cell=htmlize($page, $destpage, $data[$x]);
142 while ($x+1 < @data && $data[$x+1] eq '') {
147 push @ret, "\t\t\t<$elt colspan=\"$colspan\">$cell</$elt>"
150 push @ret, "\t\t\t<$elt>$cell</$elt>"
153 push @ret, "\t\t</tr>";
158 sub htmlize ($$$) { #{{{
160 my $destpage = shift;
163 $text=IkiWiki::htmlize($page, pagetype($pagesources{$page}),
164 IkiWiki::preprocess($page, $destpage, $text));
166 # hack to get rid of enclosing junk added by markdown