Add new preprocessor directive syntax¸ using a '!' prefix.
[ikiwiki] / ikiwiki-prefix-directives
1 #!/usr/bin/perl -i
2 undef $/; # process whole files at once
3
4 my $regex = qr{
5         (\\?)           # 1: escape?
6         \[\[(!?)        # directive open; 2: optional prefix
7         ([-\w]+)        # 3: command
8         (               # 4: the parameters (including initial whitespace)
9         \s+
10                 (?:
11                         (?:[-\w]+=)?            # named parameter key?
12                         (?:
13                                 """.*?"""       # triple-quoted value
14                                 |
15                                 "[^"]+"         # single-quoted value
16                                 |
17                                 [^\s\]]+        # unquoted value
18                         )
19                         \s*                     # whitespace or end
20                                                 # of directive
21                 )
22         *)              # 0 or more parameters
23         \]\]            # directive closed
24 }sx;
25
26 sub handle_directive($$$$) {
27         my $escape = shift;
28         my $prefix = shift;
29         my $directive = shift;
30         my $args = shift;
31
32         if (length $escape) {
33                 return "${escape}[[${prefix}${directive}${args}]]"
34         }
35         if ($directive =~ m/^(if|more|table|template|toggleable)$/) {
36                 $args =~ s{$regex}{handle_directive($1, $2, $3, $4)}eg;
37         }
38         return "[[!${directive}${args}]]"
39 }
40
41 while (<>) {
42         s{$regex}{handle_directive($1, $2, $3, $4)}eg;
43         print;
44 }