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 (@) { #{{{
25 if (exists $params{delimiter}) {
26 $params{sep_char}->{$params{format}} = $params{delimiter};
28 if (exists $params{file}) {
29 if (! $pagesources{$params{file}}) {
30 return "[[table ".gettext("cannot find file")."]]";
32 $params{data} = readfile(srcfile($params{file}));
35 if (lc $params{format} eq 'auto') {
36 # first try the more simple format
37 if (is_dsv_data($params{data})) {
38 $params{format} = 'dsv';
39 $params{sep_char}->{dsv} = '|';
42 $params{format} = 'csv';
43 $params{sep_char}->{csv} = ',';
48 if (lc $params{format} eq 'csv') {
49 @data=read_csv(\%params);
51 elsif (lc $params{format} eq 'dsv') {
52 @data=read_dsv(\%params);
55 return "[[table ".gettext("unknown data format")."]]";
59 if (lc($params{header}) eq "yes") {
63 return "[[table ".gettext("empty data")."]]";
66 my $html = tidy_up(open_table(\%params, $header),
67 build_rows(\%params, @data),
68 close_table(\%params, $header));
70 if (exists $params{file}) {
72 htmllink($params{page}, $params{destpage}, $params{file},
73 linktext => gettext('Direct data download'));
80 sub tidy_up (@) { #{{{
83 foreach my $text (@_) {
84 my $indentation = $text =~ m{thead>|tbody>} ? 0 :
86 $text =~ m{td>|th>} ? 8 :
88 $html .= (' ' x $indentation)."$text\n";
94 sub is_dsv_data ($) { #{{{
97 my ($line) = split(/\n/, $text);
98 return $line =~ m{.+\|};
101 sub read_csv ($) { #{{{
103 my @text_lines = split(/\n/, $params->{data});
105 eval q{use Text::CSV};
107 my $csv = Text::CSV->new({
108 sep_char => $params->{sep_char}->{csv},
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 read_dsv ($) { #{{{
130 my @text_lines = split(/\n/, $params->{data});
133 my $splitter = qr{\Q$params->{sep_char}->{dsv}\E};
134 foreach my $line (@text_lines) {
135 push @data, [ split($splitter, $line) ];
141 sub open_table ($$) { #{{{
146 push @items, defined $params->{class}
147 ? "<table class=\"".$params->{class}.'">'
149 push @items, '<thead>','<tr>',
150 (map { "<th>".htmlize($params, $_)."</th>" } @$header),
151 '</tr>','</thead>' if defined $header;
152 push @items, '<tbody>';
157 sub build_rows ($@) { #{{{
161 foreach my $record (@_) {
163 (map { "<td>".htmlize($params, $_)."</td>" } @$record),
169 sub close_table ($$) { #{{{
174 push @items, '</tbody>' if defined $header;
175 push @items, '</table>';
183 $text=IkiWiki::preprocess($params->{page},
184 $params->{destpage}, $text);
185 $text=IkiWiki::htmlize($params->{page},
186 pagetype($pagesources{$params->{page}}), $text);
188 # hack to get rid of enclosing junk added by markdown