1 package IkiWiki::Plugin::table;
2 # by Victor Moral <victor@taquiones.net>
10 hook(type => "preprocess", id => "table", call => \&preprocess);
13 sub preprocess (@) { #{{{
20 if (exists $params{file}) {
21 if (! $pagesources{$params{file}}) {
22 return "[[table ".gettext("cannot find file")."]]";
24 $params{data} = readfile(srcfile($params{file}));
27 if (lc $params{format} eq 'auto') {
28 # first try the more simple format
29 if (is_dsv_data($params{data})) {
30 $params{format} = 'dsv';
33 $params{format} = 'csv';
38 if (lc $params{format} eq 'csv') {
39 @data=split_csv($params{data}, $params{delimiter});
41 elsif (lc $params{format} eq 'dsv') {
42 @data=split_dsv($params{data}, $params{delimiter});
45 return "[[table ".gettext("unknown data format")."]]";
49 if (lc($params{header}) eq "yes") {
53 return "[[table ".gettext("empty data")."]]";
57 push @lines, defined $params{class}
58 ? "<table class=\"".$params{class}.'">'
60 push @lines, "\t<thead>",
61 genrow($params{page}, $params{destpage}, "th", @$header),
62 "\t</thead>" if defined $header;
63 push @lines, "\t<tbody>";
64 push @lines, genrow($params{page}, $params{destpage}, "td", @$_)
66 push @lines, "\t</tbody>" if defined $header;
67 push @lines, '</table>';
68 my $html = join("\n", @lines);
70 if (exists $params{file}) {
72 htmllink($params{page}, $params{destpage}, $params{file},
73 linktext => gettext('Direct data download'));
80 sub is_dsv_data ($) { #{{{
83 my ($line) = split(/\n/, $text);
84 return $line =~ m{.+\|};
87 sub split_csv ($$) { #{{{
88 my @text_lines = split(/\n/, shift);
89 my $delimiter = shift;
91 eval q{use Text::CSV};
93 my $csv = Text::CSV->new({
94 sep_char => defined $delimiter ? $delimiter : ",",
96 }) || error("could not create a Text::CSV object");
100 foreach my $line (@text_lines) {
102 if ($csv->parse($line)) {
103 push(@data, [ $csv->fields() ]);
106 debug(sprintf(gettext('parse fail at line %d: %s'),
107 $l, $csv->error_input()));
114 sub split_dsv ($$) { #{{{
115 my @text_lines = split(/\n/, shift);
116 my $delimiter = shift;
117 $delimiter="|" unless defined $delimiter;
120 foreach my $line (@text_lines) {
121 push @data, [ split(/\Q$delimiter\E/, $line, -1) ];
127 sub genrow ($$$@) { #{{{
129 my $destpage = shift;
134 push @ret, "\t\t<tr>";
135 for (my $x=0; $x < @data; $x++) {
136 my $cell=htmlize($page, $destpage, $data[$x]);
138 while ($x+1 < @data && $data[$x+1] eq '') {
143 push @ret, "\t\t\t<$elt colspan=\"$colspan\">$cell</$elt>"
146 push @ret, "\t\t\t<$elt>$cell</$elt>"
149 push @ret, "\t\t</tr>";
154 sub htmlize ($$$) { #{{{
156 my $destpage = shift;
159 $text=IkiWiki::htmlize($page, pagetype($pagesources{$page}),
160 IkiWiki::preprocess($page, $destpage, $text));
162 # hack to get rid of enclosing junk added by markdown