]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
dd6d3710d03d48592d835f302b02eddce82f52df
[public-inbox.git] / lib / PublicInbox / Search.pm
1 # Copyright (C) 2015-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 # based on notmuch, but with no concept of folders, files or flags
4 #
5 # Read-only search interface for use by the web and NNTP interfaces
6 package PublicInbox::Search;
7 use strict;
8 use parent qw(Exporter);
9 our @EXPORT_OK = qw(retry_reopen int_val get_pct xap_terms);
10 use List::Util qw(max);
11 use POSIX qw(strftime);
12 use Carp ();
13
14 # values for searching, changing the numeric value breaks
15 # compatibility with old indices (so don't change them it)
16 use constant {
17         TS => 0, # Received: in Unix time (IMAP INTERNALDATE, JMAP receivedAt)
18         YYYYMMDD => 1, # Date: header for searching in the WWW UI
19         DT => 2, # Date: YYYYMMDDHHMMSS (IMAP SENT*, JMAP sentAt)
20
21         # added for public-inbox 1.6.0+
22         BYTES => 3, # IMAP RFC822.SIZE
23         UID => 4, # IMAP UID == NNTP article number == Xapian docid
24         THREADID => 5, # RFC 8474, RFC 8621
25
26         # TODO
27         # REPLYCNT => ?, # IMAP ANSWERED
28
29         # SCHEMA_VERSION history
30         # 0 - initial
31         # 1 - subject_path is lower-cased
32         # 2 - subject_path is id_compress in the index, only
33         # 3 - message-ID is compressed if it includes '%' (hack!)
34         # 4 - change "Re: " normalization, avoid circular Reference ghosts
35         # 5 - subject_path drops trailing '.'
36         # 6 - preserve References: order in document data
37         # 7 - remove references and inreplyto terms
38         # 8 - remove redundant/unneeded document data
39         # 9 - disable Message-ID compression (SHA-1)
40         # 10 - optimize doc for NNTP overviews
41         # 11 - merge threads when vivifying ghosts
42         # 12 - change YYYYMMDD value column to numeric
43         # 13 - fix threading for empty References/In-Reply-To
44         #      (commit 83425ef12e4b65cdcecd11ddcb38175d4a91d5a0)
45         # 14 - fix ghost root vivification
46         # 15 - see public-inbox-v2-format(5)
47         #      further bumps likely unnecessary, we'll suggest in-place
48         #      "--reindex" use for further fixes and tweaks:
49         #
50         #      public-inbox v1.5.0 adds (still SCHEMA_VERSION=15):
51         #      * "lid:" and "l:" for List-Id searches
52         #
53         #      v1.6.0 adds BYTES, UID and THREADID values
54         SCHEMA_VERSION => 15,
55 };
56
57 use PublicInbox::Smsg;
58 use PublicInbox::Over;
59 our $QP_FLAGS;
60 our %X = map { $_ => 0 } qw(BoolWeight Database Enquire QueryParser Stem Query);
61 our $Xap; # 'Search::Xapian' or 'Xapian'
62 our $NVRP; # '$Xap::'.('NumberValueRangeProcessor' or 'NumberRangeProcessor')
63
64 # ENQ_DESCENDING and ENQ_ASCENDING weren't in SWIG Xapian.pm prior to 1.4.16,
65 # let's hope the ABI is stable
66 our $ENQ_DESCENDING = 0;
67 our $ENQ_ASCENDING = 1;
68
69 sub load_xapian () {
70         return 1 if defined $Xap;
71         # n.b. PI_XAPIAN is intended for development use only.  We still
72         # favor Search::Xapian since that's what's available in current
73         # Debian stable (10.x) and derived distros.
74         for my $x (($ENV{PI_XAPIAN} // 'Search::Xapian'), 'Xapian') {
75                 eval "require $x";
76                 next if $@;
77
78                 $x->import(qw(:standard));
79                 $Xap = $x;
80
81                 # `version_string' was added in Xapian 1.1
82                 my $xver = eval('v'.eval($x.'::version_string()')) //
83                                 eval('v'.eval($x.'::xapian_version_string()'));
84
85                 # NumberRangeProcessor was added in Xapian 1.3.6,
86                 # NumberValueRangeProcessor was removed for 1.5.0+,
87                 # favor the older /Value/ variant since that's what our
88                 # (currently) preferred Search::Xapian supports
89                 $NVRP = $x.'::'.($x eq 'Xapian' && $xver ge v1.5 ?
90                         'NumberRangeProcessor' : 'NumberValueRangeProcessor');
91                 $X{$_} = $Xap.'::'.$_ for (keys %X);
92
93                 *sortable_serialise = $x.'::sortable_serialise';
94                 *sortable_unserialise = $x.'::sortable_unserialise';
95                 # n.b. FLAG_PURE_NOT is expensive not suitable for a public
96                 # website as it could become a denial-of-service vector
97                 # FLAG_PHRASE also seems to cause performance problems chert
98                 # (and probably earlier Xapian DBs).  glass seems fine...
99                 # TODO: make this an option, maybe?
100                 # or make indexlevel=medium as default
101                 $QP_FLAGS = FLAG_PHRASE() | FLAG_BOOLEAN() | FLAG_LOVEHATE() |
102                                 FLAG_WILDCARD();
103                 return 1;
104         }
105         undef;
106 }
107
108 # This is English-only, everything else is non-standard and may be confused as
109 # a prefix common in patch emails
110 our $LANG = 'english';
111
112 # note: the non-X term prefix allocations are shared with
113 # Xapian omega, see xapian-applications/omega/docs/termprefixes.rst
114 my %bool_pfx_external = (
115         mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
116         lid => 'G', # newsGroup (or similar entity), just inside <>
117         dfpre => 'XDFPRE',
118         dfpost => 'XDFPOST',
119         dfblob => 'XDFPRE XDFPOST',
120 );
121
122 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
123 my %prob_prefix = (
124         # for mairix compatibility
125         s => 'S',
126         m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
127         l => 'XL', # 'lid:' (bool) is exact, 'l:' (prob) can do partial
128         f => 'A',
129         t => 'XTO',
130         tc => 'XTO XCC',
131         c => 'XCC',
132         tcf => 'XTO XCC A',
133         a => 'XTO XCC A',
134         b => $non_quoted_body . ' XQUOT',
135         bs => $non_quoted_body . ' XQUOT S',
136         n => 'XFN',
137
138         q => 'XQUOT',
139         nq => $non_quoted_body,
140         dfn => 'XDFN',
141         dfa => 'XDFA',
142         dfb => 'XDFB',
143         dfhh => 'XDFHH',
144         dfctx => 'XDFCTX',
145
146         # default:
147         '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
148 );
149
150 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
151 # not documenting lid: for now, either, it is probably redundant with l:,
152 # especially since we don't offer boolean searches for To/Cc/From
153 # headers, either
154 our @HELP = (
155         's:' => 'match within Subject  e.g. s:"a quick brown fox"',
156         'd:' => <<EOF,
157 date range as YYYYMMDD  e.g. d:19931002..20101002
158 Open-ended ranges such as d:19931002.. and d:..20101002
159 are also supported
160 EOF
161         'dt:' => <<EOF,
162 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
163 EOF
164         'b:' => 'match within message body, including text attachments',
165         'nq:' => 'match non-quoted text within message body',
166         'q:' => 'match quoted text within message body',
167         'n:' => 'match filename of attachment(s)',
168         't:' => 'match within the To header',
169         'c:' => 'match within the Cc header',
170         'f:' => 'match within the From header',
171         'a:' => 'match within the To, Cc, and From headers',
172         'tc:' => 'match within the To and Cc headers',
173         'l:' => 'match contents of the List-Id header',
174         'bs:' => 'match within the Subject and body',
175         'dfn:' => 'match filename from diff',
176         'dfa:' => 'match diff removed (-) lines',
177         'dfb:' => 'match diff added (+) lines',
178         'dfhh:' => 'match diff hunk header context (usually a function name)',
179         'dfctx:' => 'match diff context lines',
180         'dfpre:' => 'match pre-image git blob ID',
181         'dfpost:' => 'match post-image git blob ID',
182         'dfblob:' => 'match either pre or post-image git blob ID',
183 );
184 chomp @HELP;
185
186 sub xdir ($;$) {
187         my ($self, $rdonly) = @_;
188         if ($rdonly || !defined($self->{shard})) {
189                 $self->{xpfx};
190         } else { # v2 + extindex only:
191                 "$self->{xpfx}/$self->{shard}";
192         }
193 }
194
195 # returns all shards as separate Xapian::Database objects w/o combining
196 sub xdb_shards_flat ($) {
197         my ($self) = @_;
198         my $xpfx = $self->{xpfx};
199         my (@xdb, $slow_phrase);
200         load_xapian();
201         $self->{qp_flags} //= $QP_FLAGS;
202         if ($xpfx =~ m!/xapian[0-9]+\z!) {
203                 @xdb = ($X{Database}->new($xpfx));
204                 $self->{qp_flags} |= FLAG_PHRASE() if !-f "$xpfx/iamchert";
205         } else {
206                 opendir(my $dh, $xpfx) or return (); # not initialized yet
207                 # We need numeric sorting so shard[0] is first for reading
208                 # Xapian metadata, if needed
209                 my $last = max(grep(/\A[0-9]+\z/, readdir($dh))) // return ();
210                 for (0..$last) {
211                         my $shard_dir = "$self->{xpfx}/$_";
212                         push @xdb, $X{Database}->new($shard_dir);
213                         $slow_phrase ||= -f "$shard_dir/iamchert";
214                 }
215                 $self->{qp_flags} |= FLAG_PHRASE() if !$slow_phrase;
216         }
217         @xdb;
218 }
219
220 # v2 Xapian docids don't conflict, so they're identical to
221 # NNTP article numbers and IMAP UIDs.
222 # https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
223 sub mdocid {
224         my ($nshard, $mitem) = @_;
225         my $docid = $mitem->get_docid;
226         int(($docid - 1) / $nshard) + 1;
227 }
228
229 sub mset_to_artnums {
230         my ($self, $mset) = @_;
231         my $nshard = $self->{nshard};
232         [ map { mdocid($nshard, $_) } $mset->items ];
233 }
234
235 sub xdb ($) {
236         my ($self) = @_;
237         $self->{xdb} // do {
238                 my @xdb = $self->xdb_shards_flat or return;
239                 $self->{nshard} = scalar(@xdb);
240                 my $xdb = shift @xdb;
241                 $xdb->add_database($_) for @xdb;
242                 $self->{xdb} = $xdb;
243         };
244 }
245
246 # returns true if a future rescan is desired
247 sub cleanup_shards {
248         my ($self) = @_;
249         return unless exists($self->{xdb});
250         my $xpfx = $self->{xpfx};
251         return reopen($self) if $xpfx =~ m!/xapian[0-9]+\z!; # true
252         opendir(my $dh, $xpfx) or return warn("$xpfx gone: $!\n"); # true
253         my $nr = grep(/\A[0-9]+\z/, readdir($dh)) or
254                 return warn("$xpfx has no shards\n"); # true
255         return reopen($self) if $nr == ($self->{nshard} // -1);
256         delete @$self{qw(xdb qp)};
257         undef;
258 }
259
260 sub new {
261         my ($class, $ibx) = @_;
262         ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
263         my $xap = $ibx->version > 1 ? 'xap' : 'public-inbox/xapian';
264         my $xpfx = "$ibx->{inboxdir}/$xap".SCHEMA_VERSION;
265         my $self = bless { xpfx => $xpfx }, $class;
266         $self->{altid} = $ibx->{altid} if defined($ibx->{altid});
267         $self;
268 }
269
270 sub reopen {
271         my ($self) = @_;
272         if (my $xdb = $self->{xdb}) {
273                 $xdb->reopen;
274         }
275         $self; # make chaining easier
276 }
277
278 # Convert git "approxidate" ranges to something usable with our
279 # Xapian indices.  At the moment, Xapian only offers a C++-only API
280 # and neither the SWIG nor XS bindings allow us to use custom code
281 # to parse dates (and libgit2 doesn't expose git__date_parse, either,
282 # so we're running git-rev-parse(1)).
283 # This replaces things we need to send to $git->date_parse with
284 # "\0".$strftime_format.['+'|$idx]."\0" placeholders
285 sub date_parse_prepare {
286         my ($to_parse, $pfx, $range) = @_;
287         # are we inside a parenthesized statement?
288         my $end = $range =~ s/([\)\s]*)\z// ? $1 : '';
289         my @r = split(/\.\./, $range, 2);
290
291         # expand "d:20101002" => "d:20101002..20101003" and like
292         # n.b. git doesn't do YYYYMMDD w/o '-', it needs YYYY-MM-DD
293         # We upgrade "d:" to "dt:" to iff using approxidate
294         if ($pfx eq 'd') {
295                 my $fmt = "\0%Y%m%d";
296                 if (!defined($r[1])) {
297                         if ($r[0] =~ /\A([0-9]{4})([0-9]{2})([0-9]{2})\z/) {
298                                 push @$to_parse, "$1-$2-$3";
299                                 # we could've handled as-is, but we need
300                                 # to parse anyways for "d+" below
301                         } else {
302                                 push @$to_parse, $r[0];
303                                 if ($r[0] !~ /\A[0-9]{4}-[0-9]{2}-[0-9]{2}\z/) {
304                                         $pfx = 'dt';
305                                         $fmt = "\0%Y%m%d%H%M%S";
306                                 }
307                         }
308                         $r[0] = "$fmt+$#$to_parse\0";
309                         $r[1] = "$fmt+\0";
310                 } else {
311                         for my $x (@r) {
312                                 next if $x eq '' || $x =~ /\A[0-9]{8}\z/;
313                                 push @$to_parse, $x;
314                                 if ($x !~ /\A[0-9]{4}-[0-9]{2}-[0-9]{2}\z/) {
315                                         $pfx = 'dt';
316                                 }
317                                 $x = "$fmt$#$to_parse\0";
318                         }
319                         if ($pfx eq 'dt') {
320                                 for (@r) {
321                                         s/\0%Y%m%d/\0%Y%m%d%H%M%S/;
322                                         s/\A([0-9]{8})\z/${1}000000/;
323                                 }
324                         }
325                 }
326         } elsif ($pfx eq 'dt') {
327                 if (!defined($r[1])) { # git needs gaps and not /\d{14}/
328                         if ($r[0] =~ /\A([0-9]{4})([0-9]{2})([0-9]{2})
329                                         ([0-9]{2})([0-9]{2})([0-9]{2})\z/x) {
330                                 push @$to_parse, "$1-$2-$3 $4:$5:$6";
331                         } else {
332                                 push @$to_parse, $r[0];
333                         }
334                         $r[0] = "\0%Y%m%d%H%M%S$#$to_parse\0";
335                         $r[1] = "\0%Y%m%d%H%M%S+\0";
336                 } else {
337                         for my $x (@r) {
338                                 next if $x eq '' || $x =~ /\A[0-9]{14}\z/;
339                                 push @$to_parse, $x;
340                                 $x = "\0%Y%m%d%H%M%S$#$to_parse\0";
341                         }
342                 }
343         } else { # "rt", let git interpret "YYYY", deal with Y10K later :P
344                 for my $x (@r) {
345                         next if $x eq '' || $x =~ /\A[0-9]{5,}\z/;
346                         push @$to_parse, $x;
347                         $x = "\0%s$#$to_parse\0";
348                 }
349                 $r[1] //= "\0%s+\0"; # add 1 day
350         }
351         "$pfx:".join('..', @r).$end;
352 }
353
354 sub date_parse_finalize {
355         my ($git, $to_parse) = @_;
356         # git-rev-parse can handle any number of args up to system
357         # limits (around (4096*32) bytes on Linux).
358         my @r = $git->date_parse(@$to_parse);
359         # n.b. git respects TZ, times stored in SQLite/Xapian are always UTC,
360         # and gmtime doesn't seem to do the right thing when TZ!=UTC
361         my ($i, $t);
362         $_[2] =~ s/\0(%[%YmdHMSs]+)([0-9\+]+)\0/
363                 $t = $2 eq '+' ? ($r[$i]+86400) : $r[$i=$2+0];
364                 $1 eq '%s' ? $t : strftime($1, gmtime($t))/sge;
365 }
366
367 # n.b. argv never has NUL, though we'll need to filter it out
368 # if this $argv isn't from a command execution
369 sub query_argv_to_string {
370         my (undef, $git, $argv) = @_;
371         my $to_parse;
372         my $tmp = join(' ', map {;
373                 if (s!\b(d|rt|dt):(\S+)\z!date_parse_prepare(
374                                                 $to_parse //= [], $1, $2)!sge) {
375                         $_;
376                 } elsif (/\s/) {
377                         s/(.*?)\b(\w+:)// ? qq{$1$2"$_"} : qq{"$_"};
378                 } else {
379                         $_
380                 }
381         } @$argv);
382         date_parse_finalize($git, $to_parse, $tmp) if $to_parse;
383         $tmp
384 }
385
386 # this is for the WWW "q=" query parameter and "lei q --stdin"
387 # it can't do d:"5 days ago", but it will do d:5.days.ago
388 sub query_approxidate {
389         my (undef, $git) = @_; # $_[2] = $query_string (modified in-place)
390         my $DQ = qq<"\x{201c}\x{201d}>; # Xapian can use curly quotes
391         $_[2] =~ tr/\x00/ /; # Xapian doesn't do NUL, we use it as a placeholder
392         my ($terms, $phrase, $to_parse);
393         $_[2] =~ s{([^$DQ]*)([$DQ][^$DQ]*[$DQ])?}{
394                 ($terms, $phrase) = ($1, $2);
395                 $terms =~ s!\b(d|rt|dt):(\S+)!
396                         date_parse_prepare($to_parse //= [], $1, $2)!sge;
397                 $terms.($phrase // '');
398                 }sge;
399         date_parse_finalize($git, $to_parse, $_[2]) if $to_parse;
400 }
401
402 # read-only
403 sub mset {
404         my ($self, $query_string, $opts) = @_;
405         $opts ||= {};
406         my $qp = $self->{qp} //= $self->qparse_new;
407         my $query = $qp->parse_query($query_string, $self->{qp_flags});
408         _do_enquire($self, $query, $opts);
409 }
410
411 sub retry_reopen {
412         my ($self, $cb, @arg) = @_;
413         for my $i (1..10) {
414                 if (wantarray) {
415                         my @ret;
416                         eval { @ret = $cb->($self, @arg) };
417                         return @ret unless $@;
418                 } else {
419                         my $ret;
420                         eval { $ret = $cb->($self, @arg) };
421                         return $ret unless $@;
422                 }
423                 # Exception: The revision being read has been discarded -
424                 # you should call Xapian::Database::reopen()
425                 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
426                         reopen($self);
427                 } else {
428                         # let caller decide how to spew, because ExtMsg queries
429                         # get wonky and trigger:
430                         # "something terrible happened at .../Xapian/Enquire.pm"
431                         Carp::croak($@);
432                 }
433         }
434         Carp::croak("Too many Xapian database modifications in progress\n");
435 }
436
437 sub _do_enquire {
438         my ($self, $query, $opts) = @_;
439         retry_reopen($self, \&_enquire_once, $query, $opts);
440 }
441
442 # returns true if all docs have the THREADID value
443 sub has_threadid ($) {
444         my ($self) = @_;
445         (xdb($self)->get_metadata('has_threadid') // '') eq '1';
446 }
447
448 sub _enquire_once { # retry_reopen callback
449         my ($self, $query, $opts) = @_;
450         my $xdb = xdb($self);
451         if (defined(my $eidx_key = $opts->{eidx_key})) {
452                 $query = $X{Query}->new(OP_FILTER(), $query, 'O'.$eidx_key);
453         }
454         if (defined(my $uid_range = $opts->{uid_range})) {
455                 my $range = $X{Query}->new(OP_VALUE_RANGE(), UID,
456                                         sortable_serialise($uid_range->[0]),
457                                         sortable_serialise($uid_range->[1]));
458                 $query = $X{Query}->new(OP_FILTER(), $query, $range);
459         }
460         my $enquire = $X{Enquire}->new($xdb);
461         $enquire->set_query($query);
462         $opts ||= {};
463         my $rel = $opts->{relevance} // 0;
464         if ($rel == -2) { # ORDER BY docid/UID (highest first)
465                 $enquire->set_weighting_scheme($X{BoolWeight}->new);
466                 $enquire->set_docid_order($ENQ_DESCENDING);
467         } elsif ($rel == -1) { # ORDER BY docid/UID (lowest first)
468                 $enquire->set_weighting_scheme($X{BoolWeight}->new);
469                 $enquire->set_docid_order($ENQ_ASCENDING);
470         } elsif ($rel == 0) {
471                 $enquire->set_sort_by_value_then_relevance(TS, !$opts->{asc});
472         } else { # rel > 0
473                 $enquire->set_sort_by_relevance_then_value(TS, !$opts->{asc});
474         }
475
476         # `mairix -t / --threads' or JMAP collapseThreads
477         if ($opts->{threads} && has_threadid($self)) {
478                 $enquire->set_collapse_key(THREADID);
479         }
480         $enquire->get_mset($opts->{offset} || 0, $opts->{limit} || 50);
481 }
482
483 sub mset_to_smsg {
484         my ($self, $ibx, $mset) = @_;
485         my $nshard = $self->{nshard};
486         my $i = 0;
487         my %order = map { mdocid($nshard, $_) => ++$i } $mset->items;
488         my @msgs = sort {
489                 $order{$a->{num}} <=> $order{$b->{num}}
490         } @{$ibx->over->get_all(keys %order)};
491         wantarray ? ($mset->get_matches_estimated, \@msgs) : \@msgs;
492 }
493
494 # read-write
495 sub stemmer { $X{Stem}->new($LANG) }
496
497 # read-only
498 sub qparse_new {
499         my ($self) = @_;
500
501         my $xdb = xdb($self);
502         my $qp = $X{QueryParser}->new;
503         $qp->set_default_op(OP_AND());
504         $qp->set_database($xdb);
505         $qp->set_stemmer(stemmer($self));
506         $qp->set_stemming_strategy(STEM_SOME());
507         my $cb = $qp->can('set_max_wildcard_expansion') //
508                 $qp->can('set_max_expansion'); # Xapian 1.5.0+
509         $cb->($qp, 100);
510         $cb = $qp->can('add_valuerangeprocessor') //
511                 $qp->can('add_rangeprocessor'); # Xapian 1.5.0+
512         $cb->($qp, $NVRP->new(YYYYMMDD, 'd:'));
513         $cb->($qp, $NVRP->new(DT, 'dt:'));
514
515         # for IMAP, undocumented for WWW and may be split off go away
516         $cb->($qp, $NVRP->new(BYTES, 'z:'));
517         $cb->($qp, $NVRP->new(TS, 'rt:'));
518         $cb->($qp, $NVRP->new(UID, 'uid:'));
519
520         while (my ($name, $prefix) = each %bool_pfx_external) {
521                 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
522         }
523
524         # we do not actually create AltId objects,
525         # just parse the spec to avoid the extra DB handles for now.
526         if (my $altid = $self->{altid}) {
527                 my $user_pfx = $self->{-user_pfx} = [];
528                 for (@$altid) {
529                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
530                         # note: Xapian supports multibyte UTF-8, /^[0-9]+$/,
531                         # and '_' with prefixes matching \w+
532                         /\Aserial:(\w+):/ or next;
533                         my $pfx = $1;
534                         push @$user_pfx, "$pfx:", <<EOF;
535 alternate serial number  e.g. $pfx:12345 (boolean)
536 EOF
537                         # gmane => XGMANE
538                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
539                 }
540                 chomp @$user_pfx;
541         }
542
543         while (my ($name, $prefix) = each %prob_prefix) {
544                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
545         }
546         $qp;
547 }
548
549 sub help {
550         my ($self) = @_;
551         $self->{qp} //= $self->qparse_new; # parse altids
552         my @ret = @HELP;
553         if (my $user_pfx = $self->{-user_pfx}) {
554                 push @ret, @$user_pfx;
555         }
556         \@ret;
557 }
558
559 sub int_val ($$) {
560         my ($doc, $col) = @_;
561         my $val = $doc->get_value($col) or return; # undefined is '' in Xapian
562         sortable_unserialise($val) + 0; # PV => IV conversion
563 }
564
565 sub get_pct ($) { # mset item
566         # Capped at "99%" since "100%" takes an extra column in the
567         # thread skeleton view.  <xapian/mset.h> says the value isn't
568         # very meaningful, anyways.
569         my $n = $_[0]->get_percent;
570         $n > 99 ? 99 : $n;
571 }
572
573 sub xap_terms ($$;@) {
574         my ($pfx, $xdb_or_doc, @docid) = @_; # @docid may be empty ()
575         my %ret;
576         my $end = $xdb_or_doc->termlist_end(@docid);
577         my $cur = $xdb_or_doc->termlist_begin(@docid);
578         for (; $cur != $end; $cur++) {
579                 $cur->skip_to($pfx);
580                 last if $cur == $end;
581                 my $tn = $cur->get_termname;
582                 $ret{substr($tn, length($pfx))} = undef if !index($tn, $pfx);
583         }
584         wantarray ? sort(keys(%ret)) : \%ret;
585 }
586
587 1;