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 if (lc $params{format} eq 'auto') {
27 # first try the more simple format
28 if (is_dsv_data($params{data})) {
29 $params{format} = 'dsv';
32 $params{format} = 'csv';
37 if (lc $params{format} eq 'csv') {
38 @data=split_csv($params{data}, $params{delimiter});
40 elsif (lc $params{format} eq 'dsv') {
41 @data=split_dsv($params{data}, $params{delimiter});
44 return "[[table ".gettext("unknown data format")."]]";
48 if (lc($params{header}) eq "yes") {
52 return "[[table ".gettext("empty data")."]]";
56 push @lines, defined $params{class}
57 ? "<table class=\"".$params{class}.'">'
59 push @lines, "\t<thead>",
60 genrow($params{page}, $params{destpage}, "th", @$header),
61 "\t</thead>" if defined $header;
62 push @lines, "\t<tbody>";
63 push @lines, genrow($params{page}, $params{destpage}, "td", @$_)
65 push @lines, "\t</tbody>" if defined $header;
66 push @lines, '</table>';
67 my $html = join("\n", @lines);
69 if (exists $params{file}) {
71 htmllink($params{page}, $params{destpage}, $params{file},
72 linktext => gettext('Direct data download'));
79 sub is_dsv_data ($) { #{{{
82 my ($line) = split(/\n/, $text);
83 return $line =~ m{.+\|};
86 sub split_csv ($$) { #{{{
87 my @text_lines = split(/\n/, shift);
88 my $delimiter = shift;
90 eval q{use Text::CSV};
92 my $csv = Text::CSV->new({
93 sep_char => defined $delimiter ? $delimiter : ",",
95 }) || error("could not create a Text::CSV object");
99 foreach my $line (@text_lines) {
101 if ($csv->parse($line)) {
102 push(@data, [ $csv->fields() ]);
105 debug(sprintf(gettext('parse fail at line %d: %s'),
106 $l, $csv->error_input()));
113 sub split_dsv ($$) { #{{{
114 my @text_lines = split(/\n/, shift);
115 my $delimiter = shift;
116 $delimiter="|" unless defined $delimiter;
119 foreach my $line (@text_lines) {
120 push @data, [ split(/\Q$delimiter\E/, $line, -1) ];
126 sub genrow ($$$@) { #{{{
128 my $destpage = shift;
133 push @ret, "\t\t<tr>";
134 for (my $x=0; $x < @data; $x++) {
135 my $cell=htmlize($page, $destpage, $data[$x]);
137 while ($x+1 < @data && $data[$x+1] eq '') {
142 push @ret, "\t\t\t<$elt colspan=\"$colspan\">$cell</$elt>"
145 push @ret, "\t\t\t<$elt>$cell</$elt>"
148 push @ret, "\t\t</tr>";
153 sub htmlize ($$$) { #{{{
155 my $destpage = shift;
158 $text=IkiWiki::htmlize($page, pagetype($pagesources{$page}),
159 IkiWiki::preprocess($page, $destpage, $text));
161 # hack to get rid of enclosing junk added by markdown