1 package IkiWiki::Plugin::table;
2 # by Victor Moral <victor@taquiones.net>
8 use IkiWiki::Plugin::mdwn;
11 hook(type => "preprocess", id => "table", call => \&preprocess);
14 sub preprocess (@) { #{{{
21 if (exists $params{file}) {
22 if (! $pagesources{$params{file}}) {
23 return "[[table ".gettext("cannot find file")."]]";
25 $params{data} = readfile(srcfile($params{file}));
28 if (lc $params{format} eq 'auto') {
29 # first try the more simple format
30 if (is_dsv_data($params{data})) {
31 $params{format} = 'dsv';
32 $params{sep_char}->{dsv} = '|';
35 $params{format} = 'csv';
36 $params{sep_char}->{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>","\t\t<tr>",
66 htmlize($params{page}, $params{destpage}, $_).
69 "\t\t</tr>", "\t</thead>" if defined $header;
70 push @lines, "\t<tbody>";
71 foreach my $record (@data) {
72 push @lines, "\t\t<tr>",
75 htmlize($params{page}, $params{destpage}, $_).
80 push @lines, "\t</tbody>" if defined $header;
81 push @lines, '</table>';
82 my $html = join("\n", @lines);
84 if (exists $params{file}) {
86 htmllink($params{page}, $params{destpage}, $params{file},
87 linktext => gettext('Direct data download'));
94 sub is_dsv_data ($) { #{{{
97 my ($line) = split(/\n/, $text);
98 return $line =~ m{.+\|};
101 sub split_csv ($$) { #{{{
102 my @text_lines = split(/\n/, shift);
103 my $delimiter = shift;
105 eval q{use Text::CSV};
107 my $csv = Text::CSV->new({
108 sep_char => defined $delimiter ? $delimiter : ",",
110 }) || error("could not create a Text::CSV object");
114 foreach my $line (@text_lines) {
116 if ($csv->parse($line)) {
117 push(@data, [ $csv->fields() ]);
120 debug(sprintf(gettext('parse fail at line %d: %s'),
121 $l, $csv->error_input()));
128 sub split_dsv ($$) { #{{{
129 my @text_lines = split(/\n/, shift);
130 my $delimiter = shift;
131 $delimiter="|" unless defined $delimiter;
134 foreach my $line (@text_lines) {
135 push @data, [ split(/\Q$delimiter\E/, $line) ];
141 sub htmlize ($$$){ #{{{
143 my $destpage = shift;
146 $text=IkiWiki::htmlize($page, pagetype($pagesources{$page}),
147 IkiWiki::preprocess($page, $destpage, $text));
149 # hack to get rid of enclosing junk added by markdown