summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/link.pm
blob: 515a62bced96396a906dd6c84e2c5ec0335c0200 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki::Plugin::link;
  3. use warnings;
  4. use strict;
  5. use IkiWiki 2.00;
  6. my $link_regexp;
  7. sub import { #{{{
  8. hook(type => "checkconfig", id => "link", call => \&checkconfig);
  9. hook(type => "linkify", id => "link", call => \&linkify);
  10. hook(type => "scan", id => "link", call => \&scan);
  11. hook(type => "renamepage", id => "link", call => \&renamepage);
  12. } # }}}
  13. sub checkconfig () { #{{{
  14. if ($config{prefix_directives}) {
  15. $link_regexp = qr{
  16. \[\[(?=[^!]) # beginning of link
  17. (?:
  18. ([^\]\|]+) # 1: link text
  19. \| # followed by '|'
  20. )? # optional
  21. ([^\n\r\]#]+) # 2: page to link to
  22. (?:
  23. \# # '#', beginning of anchor
  24. ([^\s\]]+) # 3: anchor text
  25. )? # optional
  26. \]\] # end of link
  27. }x;
  28. }
  29. else {
  30. $link_regexp = qr{
  31. \[\[ # beginning of link
  32. (?:
  33. ([^\]\|\n\s]+) # 1: link text
  34. \| # followed by '|'
  35. )? # optional
  36. ([^\s\]#]+) # 2: page to link to
  37. (?:
  38. \# # '#', beginning of anchor
  39. ([^\s\]]+) # 3: anchor text
  40. )? # optional
  41. \]\] # end of link
  42. }x,
  43. }
  44. } #}}}
  45. sub linkify (@) { #{{{
  46. my %params=@_;
  47. my $page=$params{page};
  48. my $destpage=$params{destpage};
  49. $params{content} =~ s{(\\?)$link_regexp}{
  50. defined $2
  51. ? ( $1
  52. ? "[[$2|$3".($4 ? "#$4" : "")."]]"
  53. : htmllink($page, $destpage, IkiWiki::linkpage($3),
  54. anchor => $4, linktext => IkiWiki::pagetitle($2)))
  55. : ( $1
  56. ? "[[$3".($4 ? "#$4" : "")."]]"
  57. : htmllink($page, $destpage, IkiWiki::linkpage($3),
  58. anchor => $4))
  59. }eg;
  60. return $params{content};
  61. } #}}}
  62. sub scan (@) { #{{{
  63. my %params=@_;
  64. my $page=$params{page};
  65. my $content=$params{content};
  66. while ($content =~ /(?<!\\)$link_regexp/g) {
  67. push @{$links{$page}}, IkiWiki::linkpage($2);
  68. }
  69. } # }}}
  70. sub renamepage (@) { #{{{
  71. my %params=@_;
  72. my $page=$params{page};
  73. my $old=$params{oldpage};
  74. my $new=$params{newpage};
  75. $params{content} =~ s{(?<!\\)$link_regexp}{
  76. my $linktext=$2;
  77. my $link=$linktext;
  78. if (bestlink($page, $2) eq $old) {
  79. $link=$new;
  80. if ($linktext =~ m/.*\/*?[A-Z]/) {
  81. # preserve leading cap of last component
  82. my @bits=split("/", $link);
  83. $link=join("/", @bits[0..$#bits-1], ucfirst($bits[$#bits]));
  84. }
  85. if (index($linktext, "/") == 0) {
  86. # absolute link
  87. $link="/$link";
  88. }
  89. }
  90. defined $1
  91. ? ( "[[$1|$link".($3 ? "#$3" : "")."]]" )
  92. : ( "[[$link". ($3 ? "#$3" : "")."]]" )
  93. }eg;
  94. return $params{content};
  95. } #}}}
  96. 1