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 $params{data} = IkiWiki::linkify($params{page},
28 $params{destpage}, $params{data});
31 if (lc $params{format} eq 'auto') {
32 # first try the more simple format
33 if (is_dsv_data($params{data})) {
34 $params{format} = 'dsv';
37 $params{format} = 'csv';
42 if (lc $params{format} eq 'csv') {
43 @data=split_csv($params{data}, $params{delimiter});
45 elsif (lc $params{format} eq 'dsv') {
46 @data=split_dsv($params{data}, $params{delimiter});
49 return "[[table ".gettext("unknown data format")."]]";
53 if (lc($params{header}) eq "yes") {
57 return "[[table ".gettext("empty data")."]]";
61 push @lines, defined $params{class}
62 ? "<table class=\"".$params{class}.'">'
64 push @lines, "\t<thead>",
65 genrow($params{page}, $params{destpage}, "th", @$header),
66 "\t</thead>" if defined $header;
67 push @lines, "\t<tbody>";
68 push @lines, genrow($params{page}, $params{destpage}, "td", @$_)
70 push @lines, "\t</tbody>" if defined $header;
71 push @lines, '</table>';
72 my $html = join("\n", @lines);
74 if (exists $params{file}) {
76 htmllink($params{page}, $params{destpage}, $params{file},
77 linktext => gettext('Direct data download'));
84 sub is_dsv_data ($) { #{{{
87 my ($line) = split(/\n/, $text);
88 return $line =~ m{.+\|};
91 sub split_csv ($$) { #{{{
92 my @text_lines = split(/\n/, shift);
93 my $delimiter = shift;
95 eval q{use Text::CSV};
97 my $csv = Text::CSV->new({
98 sep_char => defined $delimiter ? $delimiter : ",",
100 allow_loose_quotes => 1,
101 }) || error("could not create a Text::CSV object");
105 foreach my $line (@text_lines) {
107 if ($csv->parse($line)) {
108 push(@data, [ map { decode_utf8 $_ } $csv->fields() ]);
111 debug(sprintf(gettext('parse fail at line %d: %s'),
112 $l, $csv->error_input()));
119 sub split_dsv ($$) { #{{{
120 my @text_lines = split(/\n/, shift);
121 my $delimiter = shift;
122 $delimiter="|" unless defined $delimiter;
125 foreach my $line (@text_lines) {
126 push @data, [ split(/\Q$delimiter\E/, $line, -1) ];
132 sub genrow ($$$@) { #{{{
134 my $destpage = shift;
139 push @ret, "\t\t<tr>";
140 for (my $x=0; $x < @data; $x++) {
141 my $cell=htmlize($page, $destpage, $data[$x]);
143 while ($x+1 < @data && $data[$x+1] eq '') {
148 push @ret, "\t\t\t<$elt colspan=\"$colspan\">$cell</$elt>"
151 push @ret, "\t\t\t<$elt>$cell</$elt>"
154 push @ret, "\t\t</tr>";
159 sub htmlize ($$$) { #{{{
161 my $destpage = shift;
164 $text=IkiWiki::htmlize($page, pagetype($pagesources{$page}),
165 IkiWiki::preprocess($page, $destpage, $text));
167 # hack to get rid of enclosing junk added by markdown