2 package IkiWiki::Plugin::link;
10 my $email_regexp = qr/^.+@.+$/;
11 my $url_regexp = qr/^(?:[^:]+:\/\/|mailto:).*/i;
14 hook(type => "getsetup", id => "link", call => \&getsetup);
15 hook(type => "checkconfig", id => "link", call => \&checkconfig);
16 hook(type => "linkify", id => "link", call => \&linkify);
17 hook(type => "scan", id => "link", call => \&scan);
18 hook(type => "renamepage", id => "link", call => \&renamepage);
31 if ($config{prefix_directives}) {
33 \[\[(?=[^!]) # beginning of link
35 ([^\]\|]+) # 1: link text
39 ([^\n\r\]#]+) # 2: page to link to
41 \# # '#', beginning of anchor
42 ([^\s\]]+) # 3: anchor text
50 \[\[ # beginning of link
52 ([^\]\|\n\s]+) # 1: link text
56 ([^\s\]#]+) # 2: page to link to
58 \# # '#', beginning of anchor
59 ([^\s\]]+) # 3: anchor text
67 sub is_externallink ($$;$) {
72 if (defined $anchor) {
76 if ($url =~ /$email_regexp/) {
77 # url looks like an email address, so we assume it
78 # is supposed to be an external link if there is no
79 # page with that name.
80 return (! (bestlink($page, linkpage($url))))
82 return ($url =~ /$url_regexp/)
85 sub externallink ($$;$) {
88 my $pagetitle = shift;
90 if (defined $anchor) {
97 # use only the email address as title for mailto: urls
98 if ($pagetitle =~ /^mailto:.*/) {
99 $pagetitle =~ s/^mailto:([^?]+).*/$1/;
103 if ($url !~ /$url_regexp/) {
104 # handle email addresses (without mailto:)
105 $url = "mailto:" . $url;
108 return "<a href=\"$url\">$pagetitle</a>";
113 my $page=$params{page};
114 my $destpage=$params{destpage};
116 $params{content} =~ s{(\\?)$link_regexp}{
119 ? "[[$2|$3".(defined $4 ? "#$4" : "")."]]"
120 : is_externallink($page, $3, $4)
121 ? externallink($3, $4, $2)
122 : htmllink($page, $destpage, linkpage($3),
123 anchor => $4, linktext => pagetitle($2)))
125 ? "[[$3".(defined $4 ? "#$4" : "")."]]"
126 : is_externallink($page, $3, $4)
127 ? externallink($3, $4)
128 : htmllink($page, $destpage, linkpage($3),
132 return $params{content};
137 my $page=$params{page};
138 my $content=$params{content};
140 while ($content =~ /(?<!\\)$link_regexp/g) {
141 if (! is_externallink($page, $2, $3)) {
142 add_link($page, linkpage($2));
149 my $page=$params{page};
150 my $old=$params{oldpage};
151 my $new=$params{newpage};
153 $params{content} =~ s{(?<!\\)$link_regexp}{
154 if (! is_externallink($page, $2, $3)) {
157 if (bestlink($page, linkpage($linktext)) eq $old) {
158 $link=pagetitle($new, 1);
160 if ($linktext =~ m/.*\/*?[A-Z]/) {
161 # preserve leading cap of last component
162 my @bits=split("/", $link);
163 $link=join("/", @bits[0..$#bits-1], ucfirst($bits[$#bits]));
165 if (index($linktext, "/") == 0) {
171 ? ( "[[$1|$link".($3 ? "#$3" : "")."]]" )
172 : ( "[[$link". ($3 ? "#$3" : "")."]]" )
176 return $params{content};