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>","\t\t<tr>",
63 htmlize($params{page}, $params{destpage}, $_).
66 "\t\t</tr>", "\t</thead>" if defined $header;
67 push @lines, "\t<tbody>";
68 foreach my $record (@data) {
69 push @lines, "\t\t<tr>",
72 htmlize($params{page}, $params{destpage}, $_).
77 push @lines, "\t</tbody>" if defined $header;
78 push @lines, '</table>';
79 my $html = join("\n", @lines);
81 if (exists $params{file}) {
83 htmllink($params{page}, $params{destpage}, $params{file},
84 linktext => gettext('Direct data download'));
91 sub is_dsv_data ($) { #{{{
94 my ($line) = split(/\n/, $text);
95 return $line =~ m{.+\|};
98 sub split_csv ($$) { #{{{
99 my @text_lines = split(/\n/, shift);
100 my $delimiter = shift;
102 eval q{use Text::CSV};
104 my $csv = Text::CSV->new({
105 sep_char => defined $delimiter ? $delimiter : ",",
107 }) || error("could not create a Text::CSV object");
111 foreach my $line (@text_lines) {
113 if ($csv->parse($line)) {
114 push(@data, [ $csv->fields() ]);
117 debug(sprintf(gettext('parse fail at line %d: %s'),
118 $l, $csv->error_input()));
125 sub split_dsv ($$) { #{{{
126 my @text_lines = split(/\n/, shift);
127 my $delimiter = shift;
128 $delimiter="|" unless defined $delimiter;
131 foreach my $line (@text_lines) {
132 push @data, [ split(/\Q$delimiter\E/, $line) ];
138 sub htmlize ($$$) { #{{{
140 my $destpage = shift;
143 $text=IkiWiki::htmlize($page, pagetype($pagesources{$page}),
144 IkiWiki::preprocess($page, $destpage, $text));
146 # hack to get rid of enclosing junk added by markdown