summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/link.pm
blob: 2ea6aa19eebbfdb17b0a1859eb79ca511ced8504 (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, IkiWiki::linkpage($linktext)) eq $old) {
  79. $link=IkiWiki::pagetitle($new, 1);
  80. $link=~s/ /_/g;
  81. if ($linktext =~ m/.*\/*?[A-Z]/) {
  82. # preserve leading cap of last component
  83. my @bits=split("/", $link);
  84. $link=join("/", @bits[0..$#bits-1], ucfirst($bits[$#bits]));
  85. }
  86. if (index($linktext, "/") == 0) {
  87. # absolute link
  88. $link="/$link";
  89. }
  90. }
  91. defined $1
  92. ? ( "[[$1|$link".($3 ? "#$3" : "")."]]" )
  93. : ( "[[$link". ($3 ? "#$3" : "")."]]" )
  94. }eg;
  95. return $params{content};
  96. } #}}}
  97. 1