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