summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/shortcut.pm
blob: 77131edb07ac588a7108f5659e686ce1954a45d7 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki::Plugin::shortcut;
  3. use warnings;
  4. use strict;
  5. use IkiWiki 2.00;
  6. sub import { #{{{
  7. hook(type => "getsetup", id => "shortcut", call => \&getsetup);
  8. hook(type => "checkconfig", id => "shortcut", call => \&checkconfig);
  9. hook(type => "preprocess", id => "shortcut", call => \&preprocess_shortcut);
  10. } #}}}
  11. sub getsetup () { #{{{
  12. return
  13. plugin => {
  14. safe => 1,
  15. rebuild => undef,
  16. },
  17. } #}}}
  18. sub checkconfig () { #{{{
  19. if (defined $config{srcdir}) {
  20. # Preprocess the shortcuts page to get all the available shortcuts
  21. # defined before other pages are rendered.
  22. my $srcfile=srcfile("shortcuts.mdwn", 1);
  23. if (! defined $srcfile) {
  24. error(gettext("shortcut plugin will not work without a shortcuts.mdwn"));
  25. }
  26. IkiWiki::preprocess("shortcuts", "shortcuts", readfile($srcfile));
  27. }
  28. } # }}}
  29. sub preprocess_shortcut (@) { #{{{
  30. my %params=@_;
  31. if (! defined $params{name} || ! defined $params{url}) {
  32. error gettext("missing name or url parameter");
  33. }
  34. hook(type => "preprocess", no_override => 1, id => $params{name},
  35. call => sub { shortcut_expand($params{url}, $params{desc}, @_) });
  36. #translators: This is used to display what shortcuts are defined.
  37. #translators: First parameter is the name of the shortcut, the second
  38. #translators: is an URL.
  39. return sprintf(gettext("shortcut %s points to <i>%s</i>"), $params{name}, $params{url});
  40. } # }}}
  41. sub shortcut_expand ($$@) { #{{{
  42. my $url=shift;
  43. my $desc=shift;
  44. my %params=@_;
  45. # Get params in original order.
  46. my @params;
  47. while (@_) {
  48. my $key=shift;
  49. my $value=shift;
  50. push @params, $key if ! length $value;
  51. }
  52. # If the shortcuts page changes, all pages that use shortcuts will
  53. # need to be updated.
  54. add_depends($params{destpage}, "shortcuts");
  55. my $text=join(" ", @params);
  56. my $encoded_text=$text;
  57. $encoded_text=~s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
  58. $url=~s{\%([sS])}{
  59. $1 eq 's' ? $encoded_text : $text
  60. }eg;
  61. $text=~s/_/ /g;
  62. if (defined $params{desc}) {
  63. $desc=$params{desc};
  64. }
  65. if (defined $desc) {
  66. $desc=~s/\%s/$text/g;
  67. }
  68. else {
  69. $desc=$text;
  70. }
  71. return "<a href=\"$url\">$desc</a>";
  72. } #}}}
  73. 1