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';
34 $params{format} = 'csv';
39 if (lc $params{format} eq 'csv') {
40 @data=split_csv($params{data}, $params{delimiter});
42 elsif (lc $params{format} eq 'dsv') {
43 @data=split_dsv($params{data}, $params{delimiter});
46 return "[[table ".gettext("unknown data format")."]]";
50 if (lc($params{header}) eq "yes") {
54 return "[[table ".gettext("empty data")."]]";
58 push @lines, defined $params{class}
59 ? "<table class=\"".$params{class}.'">'
61 push @lines, "\t<thead>","\t\t<tr>",
64 htmlize($params{page}, $params{destpage}, $_).
67 "\t\t</tr>", "\t</thead>" if defined $header;
68 push @lines, "\t<tbody>";
69 foreach my $record (@data) {
70 push @lines, "\t\t<tr>",
73 htmlize($params{page}, $params{destpage}, $_).
78 push @lines, "\t</tbody>" if defined $header;
79 push @lines, '</table>';
80 my $html = join("\n", @lines);
82 if (exists $params{file}) {
84 htmllink($params{page}, $params{destpage}, $params{file},
85 linktext => gettext('Direct data download'));
92 sub is_dsv_data ($) { #{{{
95 my ($line) = split(/\n/, $text);
96 return $line =~ m{.+\|};
99 sub split_csv ($$) { #{{{
100 my @text_lines = split(/\n/, shift);
101 my $delimiter = shift;
103 eval q{use Text::CSV};
105 my $csv = Text::CSV->new({
106 sep_char => defined $delimiter ? $delimiter : ",",
108 }) || error("could not create a Text::CSV object");
112 foreach my $line (@text_lines) {
114 if ($csv->parse($line)) {
115 push(@data, [ $csv->fields() ]);
118 debug(sprintf(gettext('parse fail at line %d: %s'),
119 $l, $csv->error_input()));
126 sub split_dsv ($$) { #{{{
127 my @text_lines = split(/\n/, shift);
128 my $delimiter = shift;
129 $delimiter="|" unless defined $delimiter;
132 foreach my $line (@text_lines) {
133 push @data, [ split(/\Q$delimiter\E/, $line) ];
139 sub htmlize ($$$){ #{{{
141 my $destpage = shift;
144 $text=IkiWiki::htmlize($page, pagetype($pagesources{$page}),
145 IkiWiki::preprocess($page, $destpage, $text));
147 # hack to get rid of enclosing junk added by markdown