aboutsummaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/shortcut.pm
blob: 98df143ab27e34506217f770d40c03e554dcd386 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/usr/bin/perl
package IkiWiki::Plugin::shortcut;

use warnings;
use strict;
use IkiWiki 3.00;

sub import {
	hook(type => "getsetup", id => "shortcut", call => \&getsetup);
	hook(type => "checkconfig", id => "shortcut", call => \&checkconfig);
	hook(type => "preprocess", id => "shortcut", call => \&preprocess_shortcut);
}

sub getsetup () {
	return
		plugin => {
			safe => 1,
			rebuild => undef,
			section => "widget",
		},
}

sub checkconfig () {
	if (defined $config{srcdir} && length $config{srcdir}) {
		# Preprocess the shortcuts page to get all the available shortcuts
		# defined before other pages are rendered.
		my $srcfile=srcfile("shortcuts.".$config{default_pageext}, 1);
		if (! defined $srcfile) {
			$srcfile=srcfile("shortcuts.mdwn", 1);
		}
		if (! defined $srcfile) {
			print STDERR sprintf(gettext("shortcut plugin will not work without %s"),
				"shortcuts.".$config{default_pageext})."\n";
		}
		else {
			IkiWiki::preprocess("shortcuts", "shortcuts", readfile($srcfile));
		}
	}
}

sub preprocess_shortcut (@) {
	my %params=@_;

	if (! defined $params{name} || ! defined $params{url}) {
		error gettext("missing name or url parameter");
	}

	hook(type => "preprocess", no_override => 1, id => $params{name},
		shortcut => 1,
		call => sub { shortcut_expand($params{url}, $params{desc}, @_) });

	#translators: This is used to display what shortcuts are defined.
	#translators: First parameter is the name of the shortcut, the second
	#translators: is an URL.
	return sprintf(gettext("shortcut %s points to <i>%s</i>"), $params{name}, $params{url});
}

sub shortcut_expand ($$@) {
	my $url=shift;
	my $desc=shift;
	my %params=@_;

	# Get params in original order.
	my @params;
	while (@_) {
		my $key=shift;
		my $value=shift;
		push @params, $key if ! length $value;
	}

	# If the shortcuts page changes, all pages that use shortcuts will
	# need to be updated.
	add_depends($params{destpage}, "shortcuts");

	my $text=join(" ", @params);
	
	$url=~s{\%([sSW])}{
		if ($1 eq 's') {
			my $t=$text;
			$t=~s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
			$t;
		}
		elsif ($1 eq 'S') {
			$text;
		}
		elsif ($1 eq 'W') {
			my $t=Encode::encode_utf8($text);
			$t=~s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
			$t;
		}
	}eg;

	$text=~s/_/ /g;
	if (defined $params{desc}) {
		$desc=$params{desc};
	}
	if (defined $desc) {
		$desc=~s/\%s/$text/g;
	}
	else {
		$desc=$text;
	}

	return "<a href=\"$url\">$desc</a>";
}

1