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