+}
+
+sub pageterm ($) {
+ my $page=shift;
+
+ # 240 is the number used by omindex to decide when to hash an
+ # overlong term. This does not use a compatible hash method though.
+ if (length $page > 240) {
+ eval q{use Digest::SHA1};
+ if ($@) {
+ debug("search: ".sprintf(gettext("need Digest::SHA1 to index %s"), $page)) if $@;
+ return undef;
+ }
+
+ # Note no colon, therefore it's guaranteed to not overlap
+ # with a page with the same name as the hash..
+ return "U".lc(Digest::SHA1::sha1_hex($page));
+ }
+ else {
+ return "U:".$page;
+ }
+}
+
+my $db;
+sub xapiandb () {
+ if (! defined $db) {
+ eval q{
+ use Search::Xapian;
+ use Search::Xapian::WritableDatabase;
+ };
+ error($@) if $@;
+ $db=Search::Xapian::WritableDatabase->new($config{wikistatedir}."/xapian/default",
+ Search::Xapian::DB_CREATE_OR_OPEN());
+ }
+ return $db;
+}
+
+{
+my $setup=0;
+sub setupfiles () {
+ if (! $setup and (! -e $config{wikistatedir}."/xapian" || $config{rebuild})) {
+ writefile("omega.conf", $config{wikistatedir}."/xapian",
+ "database_dir .\n".
+ "template_dir ./templates\n");
+
+ # Avoid omega interpreting anything in the misctemplate
+ # as an omegascript command.
+ my $misctemplate=IkiWiki::misctemplate(gettext("search"), "\0",
+ searchform => "", # avoid showing the small search form
+ );
+ eval q{use HTML::Entities};
+ error $@ if $@;
+ $misctemplate=encode_entities($misctemplate, '\$');
+
+ my $querytemplate=readfile(IkiWiki::template_file("searchquery.tmpl"));
+ $misctemplate=~s/\0/$querytemplate/;
+
+ writefile("query", $config{wikistatedir}."/xapian/templates",
+ $misctemplate);
+ $setup=1;
+ }
+}
+}