summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/shortcut.pm
blob: 33d158d3eb6a74a3d02f64e996e66a9a8889724b (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. shortcut => 1,
  36. call => sub { shortcut_expand($params{url}, $params{desc}, @_) });
  37. #translators: This is used to display what shortcuts are defined.
  38. #translators: First parameter is the name of the shortcut, the second
  39. #translators: is an URL.
  40. return sprintf(gettext("shortcut %s points to <i>%s</i>"), $params{name}, $params{url});
  41. }
  42. sub shortcut_expand ($$@) {
  43. my $url=shift;
  44. my $desc=shift;
  45. my %params=@_;
  46. # Get params in original order.
  47. my @params;
  48. while (@_) {
  49. my $key=shift;
  50. my $value=shift;
  51. push @params, $key if ! length $value;
  52. }
  53. # If the shortcuts page changes, all pages that use shortcuts will
  54. # need to be updated.
  55. add_depends($params{destpage}, "shortcuts");
  56. my $text=join(" ", @params);
  57. my $encoded_text=$text;
  58. $encoded_text=~s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
  59. $url=~s{\%([sS])}{
  60. $1 eq 's' ? $encoded_text : $text
  61. }eg;
  62. $text=~s/_/ /g;
  63. if (defined $params{desc}) {
  64. $desc=$params{desc};
  65. }
  66. if (defined $desc) {
  67. $desc=~s/\%s/$text/g;
  68. }
  69. else {
  70. $desc=$text;
  71. }
  72. return "<a href=\"$url\">$desc</a>";
  73. }
  74. 1