sup

A curses threads-with-tags style email client

sup.git

git clone https://supmua.dev/git/sup/
commit 5e1890d982e7cad75beee1c98787ba3fff6376af
parent aaa384af6ec7054f5e16086b1e54b8f3740723a6
Author: Rich Lane <rlane@club.cc.cmu.edu>
Date:   Sun, 28 Feb 2010 12:34:52 -0800

remove ferret and index choice code

Diffstat:
M bin/sup | 34 +---------------------------------
M bin/sup-add | 3 +--
D bin/sup-convert-ferret-index | 84 -------------------------------------------------------------------------------
M bin/sup-dump | 5 +----
M bin/sup-sync | 3 +--
M bin/sup-sync-back | 3 +--
M bin/sup-tweak-labels | 3 +--
M lib/sup.rb | 2 --
D lib/sup/ferret_index.rb | 476 -------------------------------------------------------------------------------
M lib/sup/index.rb | 607 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
M lib/sup/message.rb | 2 +-
M lib/sup/modes/console-mode.rb | 3 +--
M lib/sup/modes/search-results-mode.rb | 2 +-
D lib/sup/xapian_index.rb | 618 -------------------------------------------------------------------------------
M sup-files.rb | 2 +-
15 files changed, 571 insertions(+), 1276 deletions(-)
diff --git a/bin/sup b/bin/sup
@@ -39,7 +39,6 @@ EOS
   opt :search, "Search for this query upon startup", :type => String
   opt :compose, "Compose message to this recipient upon startup", :type => String
   opt :subject, "When composing, use this subject", :type => String, :short => "j"
-  opt :index, "Use this index type ('auto' for autodetect)", :default => "auto"
 end
 
 Trollop::die :subject, "requires --compose" if $opts[:subject] && !$opts[:compose]
@@ -144,36 +143,9 @@ def stop_cursing
 end
 module_function :start_cursing, :stop_cursing
 
-Index.init $opts[:index]
+Index.init
 Index.lock_interactively or exit
 
-if Index.is_a_deprecated_ferret_index?
-  FERRET_DEPRECATION_WARNING_FN = File.join BASE_DIR, "you-have-been-warned-about-ferret-deprecation"
-  unless File.exist? FERRET_DEPRECATION_WARNING_FN
-    $stderr.puts <<EOS
-Warning! Your 30-day trial period for using Sup is almost over!
-
-To purchase the full version of Sup, please see http://sup.rubyforge.org/.
-
-Just kidding. BUT! You are using an old Ferret index. The Ferret backend is
-deprecated and support will be removed in the next version of Sup.
-
-You should convert to Xapian before that happens.
-
-The conversion process may take several hours. It is safe and interruptable.
-You can start it at any point by typing:
-
-  sup-convert-ferret-index
-
-Press enter to continue and be on your way. You won't see this message
-again, just a brief reminder at shutdown.
-EOS
-
-    $stdin.gets
-    FileUtils.touch FERRET_DEPRECATION_WARNING_FN
-  end
-end
-
 begin
   Redwood::start
   Index.load
@@ -432,8 +404,4 @@ EOS
   end
 end
 
-if Index.is_a_deprecated_ferret_index?
-  puts "Reminder: to update your Ferret index to Xapian, run sup-convert-ferret-index."
-end
-
 end
diff --git a/bin/sup-add b/bin/sup-add
@@ -40,7 +40,6 @@ EOS
   opt :labels, "A comma-separated set of labels to apply to all messages from this source", :type => String
   opt :force_new, "Create a new account for this source, even if one already exists."
   opt :force_account, "Reuse previously defined account user@hostname.", :type => String
-  opt :index, "Use this index type ('auto' for autodetect)", :default => "auto"
 end
 
 Trollop::die "require one or more sources" if ARGV.empty?
@@ -86,7 +85,7 @@ end
 
 $terminal.wrap_at = :auto
 Redwood::start
-index = Redwood::Index.init $opts[:index]
+index = Redwood::Index.init
 index.load
 
 index.lock_interactively or exit
diff --git a/bin/sup-convert-ferret-index b/bin/sup-convert-ferret-index
@@ -1,84 +0,0 @@
-#!/usr/bin/env ruby
-
-require 'rubygems'
-require 'trollop'
-require "sup"; Redwood::check_library_version_against "git"
-
-STATE_BACKUP_FN = "/tmp/sup-state.txt"
-SOURCE_BACKUP_FN = "sources.yaml-before-xapian-upgrade"
-BIN_DIR = File.dirname __FILE__
-
-$opts = Trollop::options do
-  version "sup-convert-ferret-index (sup #{Redwood::VERSION})"
-  banner <<EOS
-Convert an Sup Ferret index to a Xapian index.
-
-This will be a very slow process, but it will be lossless.
-
-If you interrupt it, nothing bad will happen. However, you will have to
-restart it from scratch.
-
-Usage:
-  sup-convert-ferret-index
-
-Options:
-EOS
-  opt :verbose, "Be verbose", :short => "-v"
-  opt :dry_run, "Don't actually do anything, just print out what would happen.", :short => "-n"
-  opt :force, "Force overwrite of an old Xapian index"
-  opt :version, "Show version information", :short => :none
-end
-
-def build_cmd cmd
-  (ENV["RUBY_INVOCATION"] ? ENV["RUBY_INVOCATION"] + " " : "") + File.join(BIN_DIR, cmd)
-end
-
-def run cmd
-  puts cmd
-  unless $opts[:dry_run]
-    startt = Time.now
-    system cmd or abort
-    printf "(completed in %.1fs)\n", (Time.now - startt)
-  end
-  puts
-end
-
-begin
-  require 'xapian'
-rescue LoadError
-  Trollop::die "you don't have the xapian gem installed, so this script won't do much for you--`gem install xapian` (or xapian-full) first"
-end
-
-Redwood::start
-index = Redwood::Index.init
-Trollop::die "you appear to already have a Xapian index--delete #{File.join(Redwood::BASE_DIR, "xapian")} or use --force if you really want to do this" unless Redwood::Index.is_a_deprecated_ferret_index? || $opts[:force]
-
-puts "## Step one: back up all message state to #{STATE_BACKUP_FN}"
-run "#{build_cmd 'sup-dump'} --index ferret > #{STATE_BACKUP_FN}"
-puts "## message state saved to #{STATE_BACKUP_FN}"
-
-source_backup_fn = File.join Redwood::BASE_DIR, SOURCE_BACKUP_FN
-puts "## Step two: back up sources.yaml file to #{source_backup_fn}"
-run "cp #{Redwood::SOURCE_FN} #{source_backup_fn}"
-
-puts "## Step three: build the Xapian index"
-run "#{build_cmd 'sup-sync'} --all --all-sources --index xapian --restore #{STATE_BACKUP_FN} #{$opts[:verbose] ? '--verbose' : ''}"
-puts "## xapian index successfully built!"
-
-puts <<EOS
-
-Congratulations, your index has been upgraded to the Xapian backend.
-From now on, running sup should detect this index automatically.
-
-If you want to revert to the Ferret index:
-1. overwrite #{Redwood::SOURCE_FN} with #{source_backup_fn}
-2. use sup --index ferret, OR delete your #{Redwood::BASE_DIR}/xapian directory"
-Note that the Ferret index will not be supported as of the next Sup release, so
-you probably shouldn't do this.
-
-If you are happy with Xapian and want to reclaim precious hard drive space:
-1. rm #{source_backup_fn}
-2. rm -r #{Redwood::BASE_DIR}/ferret
-
-Happy supping!
-EOS
diff --git a/bin/sup-dump b/bin/sup-dump
@@ -16,13 +16,10 @@ the index format. This happened, for example, at Ferret version 0.11.
 Usage:
   sup-dump > <filename>
   sup-dump | bzip2 > <filename> # even better
-
-Options:
 EOS
-  opt :index, "Use this index type ('auto' for autodetect)", :default => "auto"
 end
 
-index = Redwood::Index.init $opts[:index]
+index = Redwood::Index.init
 Redwood::SourceManager.init
 index.load
 
diff --git a/bin/sup-sync b/bin/sup-sync
@@ -76,7 +76,6 @@ text <<EOS
 
 Other options:
 EOS
-  opt :index, "Use this index type ('auto' for autodetect)", :default => "auto"
   opt :verbose, "Print message ids as they're processed."
   opt :optimize, "As the final operation, optimize the index."
   opt :all_sources, "Scan over all sources.", :short => :none
@@ -96,7 +95,7 @@ target = [:new, :changed, :all, :restored].find { |x| opts[x] } || :new
 op = [:asis, :restore, :discard].find { |x| opts[x] } || :asis
 
 Redwood::start
-index = Redwood::Index.init opts[:index]
+index = Redwood::Index.init
 
 restored_state = if opts[:restore]
   dump = {}
diff --git a/bin/sup-sync-back b/bin/sup-sync-back
@@ -47,7 +47,6 @@ EOS
   opt :with_dotlockfile, "Specific dotlockfile location (mbox files only).", :default => "/usr/bin/dotlockfile", :short => :none
   opt :dont_use_dotlockfile, "Don't use dotlockfile to lock mbox files. Dangerous if other processes modify them concurrently.", :default => false, :short => :none
 
-  opt :index, "Use this index type ('auto' for autodetect)", :default => "auto"
   opt :verbose, "Print message ids as they're processed."
   opt :dry_run, "Don't actually modify the index. Probably only useful with --verbose.", :short => "-n"
   opt :version, "Show version information", :short => :none
@@ -66,7 +65,7 @@ EOS
 end
 
 Redwood::start
-index = Redwood::Index.init opts[:index]
+index = Redwood::Index.init
 index.lock_interactively or exit
 
 deleted_fp, spam_fp = nil
diff --git a/bin/sup-tweak-labels b/bin/sup-tweak-labels
@@ -46,7 +46,6 @@ EOS
 
 Other options:
 EOS
-  opt :index, "Use this index type ('auto' for autodetect)", :default => "auto"
   opt :verbose, "Print message ids as they're processed."
   opt :very_verbose, "Print message names and subjects as they're processed."
   opt :all_sources, "Scan over all sources.", :short => :none
@@ -61,7 +60,7 @@ remove_labels = opts[:remove].to_set_of_symbols ","
 Trollop::die "nothing to do: no labels to add or remove" if add_labels.empty? && remove_labels.empty?
 
 Redwood::start
-index = Redwood::Index.init opts[:index]
+index = Redwood::Index.init
 index.lock_interactively or exit
 begin
   index.load
diff --git a/lib/sup.rb b/lib/sup.rb
@@ -55,8 +55,6 @@ module Redwood
   YAML_DOMAIN = "masanjin.net"
   YAML_DATE = "2006-10-01"
 
-  DEFAULT_NEW_INDEX_TYPE = 'xapian'
-
   ## record exceptions thrown in threads nicely
   @exceptions = []
   @exception_mutex = Mutex.new
diff --git a/lib/sup/ferret_index.rb b/lib/sup/ferret_index.rb
@@ -1,476 +0,0 @@
-require 'ferret'
-
-module Redwood
-
-class FerretIndex < BaseIndex
-
-  HookManager.register "custom-search", <<EOS
-Executes before a string search is applied to the index,
-returning a new search string.
-Variables:
-  subs: The string being searched.
-EOS
-
-  def is_a_deprecated_ferret_index?; true end
-
-  def initialize dir=BASE_DIR
-    super
-
-    @index_mutex = Monitor.new
-    wsa = Ferret::Analysis::WhiteSpaceAnalyzer.new false
-    sa = Ferret::Analysis::StandardAnalyzer.new [], true
-    @analyzer = Ferret::Analysis::PerFieldAnalyzer.new wsa
-    @analyzer[:body] = sa
-    @analyzer[:subject] = sa
-    @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer, :or_default => false
-  end
-
-  def load_index dir=File.join(@dir, "ferret")
-    if File.exists? dir
-      debug "loading index..."
-      @index_mutex.synchronize do
-        @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer, :id_field => 'message_id')
-        debug "loaded index of #{@index.size} messages"
-      end
-    else
-      debug "creating index..."
-      @index_mutex.synchronize do
-        field_infos = Ferret::Index::FieldInfos.new :store => :yes
-        field_infos.add_field :message_id, :index => :untokenized
-        field_infos.add_field :source_id
-        field_infos.add_field :source_info
-        field_infos.add_field :date, :index => :untokenized
-        field_infos.add_field :body
-        field_infos.add_field :label
-        field_infos.add_field :attachments
-        field_infos.add_field :subject
-        field_infos.add_field :from
-        field_infos.add_field :to
-        field_infos.add_field :refs
-        field_infos.add_field :snippet, :index => :no, :term_vector => :no
-        field_infos.create_index dir
-        @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer, :id_field => 'message_id')
-      end
-    end
-  end
-
-  def add_message m; sync_message m end
-  def update_message m; sync_message m end
-  def update_message_state m; sync_message m end
-
-  def sync_message m, opts={}
-    entry = @index[m.id]
-
-    raise "no source info for message #{m.id}" unless m.source && m.source_info
-
-    source_id = if m.source.is_a? Integer
-      m.source
-    else
-      m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
-    end
-
-    snippet = if m.snippet_contains_encrypted_content? && $config[:discard_snippets_from_encrypted_messages]
-      ""
-    else
-      m.snippet
-    end
-
-    ## write the new document to the index. if the entry already exists in the
-    ## index, reuse it (which avoids having to reload the entry from the source,
-    ## which can be quite expensive for e.g. large threads of IMAP actions.)
-    ##
-    ## exception: if the index entry belongs to an earlier version of the
-    ## message, use everything from the new message instead, but union the
-    ## flags. this allows messages sent to mailing lists to have their header
-    ## updated and to have flags set properly.
-    ##
-    ## minor hack: messages in sources with lower ids have priority over
-    ## messages in sources with higher ids. so messages in the inbox will
-    ## override everyone, and messages in the sent box will be overridden
-    ## by everyone else.
-    ##
-    ## written in this manner to support previous versions of the index which
-    ## did not keep around the entry body. upgrading is thus seamless.
-    entry ||= {}
-    labels = m.labels # override because this is the new state, unless...
-
-    ## if we are a later version of a message, ignore what's in the index,
-    ## but merge in the labels.
-    if entry[:source_id] && entry[:source_info] && entry[:label] &&
-      ((entry[:source_id].to_i > source_id) || (entry[:source_info].to_i < m.source_info))
-      labels += entry[:label].to_set_of_symbols
-      #debug "found updated version of message #{m.id}: #{m.subj}"
-      #debug "previous version was at #{entry[:source_id].inspect}:#{entry[:source_info].inspect}, this version at #{source_id.inspect}:#{m.source_info.inspect}"
-      #debug "merged labels are #{labels.inspect} (index #{entry[:label].inspect}, message #{m.labels.inspect})"
-      entry = {}
-    end
-
-    ## if force_overwite is true, ignore what's in the index. this is used
-    ## primarily by sup-sync to force index updates.
-    entry = {} if opts[:force_overwrite]
-
-    d = {
-      :message_id => m.id,
-      :source_id => source_id,
-      :source_info => m.source_info,
-      :date => (entry[:date] || m.date.to_indexable_s),
-      :body => (entry[:body] || m.indexable_content),
-      :snippet => snippet, # always override
-      :label => labels.to_a.join(" "),
-      :attachments => (entry[:attachments] || m.attachments.uniq.join(" ")),
-
-      ## always override :from and :to.
-      ## older versions of Sup would often store the wrong thing in the index
-      ## (because they were canonicalizing email addresses, resulting in the
-      ## wrong name associated with each.) the correct address is read from
-      ## the original header when these messages are opened in thread-view-mode,
-      ## so this allows people to forcibly update the address in the index by
-      ## marking those threads for saving.
-      :from => (m.from ? m.from.indexable_content : ""),
-      :to => (m.to + m.cc + m.bcc).map { |x| x.indexable_content }.join(" "),
-
-      ## always overwrite :refs.
-      ## these might have changed due to manual thread joining.
-      :refs => (m.refs + m.replytos).uniq.join(" "),
-
-      :subject => (entry[:subject] || wrap_subj(Message.normalize_subj(m.subj))),
-    }
-
-    @index_mutex.synchronize do
-      @index.delete m.id
-      @index.add_document d
-    end
-  end
-  private :sync_message
-
-  def save_index fn=File.join(@dir, "ferret")
-    # don't have to do anything, apparently
-  end
-
-  def contains_id? id
-    @index_mutex.synchronize { @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0 }
-  end
-
-  def size
-    @index_mutex.synchronize { @index.size }
-  end
-
-  EACH_BY_DATE_NUM = 100
-  def each_id_by_date query={}
-    return if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
-    ferret_query = build_ferret_query query
-    offset = 0
-    while true
-      limit = (query[:limit])? [EACH_BY_DATE_NUM, query[:limit] - offset].min : EACH_BY_DATE_NUM
-      results = @index_mutex.synchronize { @index.search ferret_query, :sort => "date DESC", :limit => limit, :offset => offset }
-      debug "got #{results.total_hits} results for query (offset #{offset}) #{ferret_query.inspect}"
-      results.hits.each do |hit|
-        yield @index_mutex.synchronize { @index[hit.doc][:message_id] }, lambda { build_message hit.doc }
-      end
-      break if query[:limit] and offset >= query[:limit] - limit
-      break if offset >= results.total_hits - limit
-      offset += limit
-    end
-  end
-
-  def num_results_for query={}
-    return 0 if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
-    ferret_query = build_ferret_query query
-    @index_mutex.synchronize { @index.search(ferret_query, :limit => 1).total_hits }
-  end
-
-  SAME_SUBJECT_DATE_LIMIT = 7
-  MAX_CLAUSES = 1000
-  def each_message_in_thread_for m, opts={}
-    #debug "Building thread for #{m.id}: #{m.subj}"
-    messages = {}
-    searched = {}
-    num_queries = 0
-
-    pending = [m.id]
-    if $config[:thread_by_subject] # do subject queries
-      date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
-      date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
-
-      q = Ferret::Search::BooleanQuery.new true
-      sq = Ferret::Search::PhraseQuery.new(:subject)
-      wrap_subj(Message.normalize_subj(m.subj)).split.each do |t|
-        sq.add_term t
-      end
-      q.add_query sq, :must
-      q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
-
-      q = build_ferret_query :qobj => q
-
-      p1 = @index_mutex.synchronize { @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] } }
-      debug "found #{p1.size} results for subject query #{q}"
-
-      p2 = @index_mutex.synchronize { @index.search(q.to_s, :limit => :all).hits.map { |hit| @index[hit.doc][:message_id] } }
-      debug "found #{p2.size} results in string form"
-
-      pending = (pending + p1 + p2).uniq
-    end
-
-    until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
-      q = Ferret::Search::BooleanQuery.new true
-      # this disappeared in newer ferrets... wtf.
-      # q.max_clause_count = 2048
-
-      lim = [MAX_CLAUSES / 2, pending.length].min
-      pending[0 ... lim].each do |id|
-        searched[id] = true
-        q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
-        q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
-      end
-      pending = pending[lim .. -1]
-
-      q = build_ferret_query :qobj => q
-
-      num_queries += 1
-      killed = false
-      @index_mutex.synchronize do
-        @index.search_each(q, :limit => :all) do |docid, score|
-          break if opts[:limit] && messages.size >= opts[:limit]
-          if @index[docid][:label].split(/\s+/).include?("killed") && opts[:skip_killed]
-            killed = true
-            break
-          end
-          mid = @index[docid][:message_id]
-          unless messages.member?(mid)
-            #debug "got #{mid} as a child of #{id}"
-            messages[mid] ||= lambda { build_message docid }
-            refs = @index[docid][:refs].split
-            pending += refs.select { |id| !searched[id] }
-          end
-        end
-      end
-    end
-
-    if killed
-      #debug "thread for #{m.id} is killed, ignoring"
-      false
-    else
-      #debug "ran #{num_queries} queries to build thread of #{messages.size} messages for #{m.id}: #{m.subj}" if num_queries > 0
-      messages.each { |mid, builder| yield mid, builder }
-      true
-    end
-  end
-
-  ## builds a message object from a ferret result
-  def build_message docid
-    @index_mutex.synchronize do
-      doc = @index[docid] or return
-
-      source = SourceManager[doc[:source_id].to_i]
-      raise "invalid source #{doc[:source_id]}" unless source
-
-      #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
-
-      fake_header = {
-        "date" => Time.at(doc[:date].to_i),
-        "subject" => unwrap_subj(doc[:subject]),
-        "from" => doc[:from],
-        "to" => doc[:to].split.join(", "), # reformat
-        "message-id" => doc[:message_id],
-        "references" => doc[:refs].split.map { |x| "<#{x}>" }.join(" "),
-      }
-
-      m = Message.new :source => source, :source_info => doc[:source_info].to_i,
-                  :labels => doc[:label].to_set_of_symbols,
-                  :snippet => doc[:snippet]
-      m.parse_header fake_header
-      m
-    end
-  end
-
-  def delete id
-    @index_mutex.synchronize { @index.delete id }
-  end
-
-  def load_contacts emails, h={}
-    q = Ferret::Search::BooleanQuery.new true
-    emails.each do |e|
-      qq = Ferret::Search::BooleanQuery.new true
-      qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
-      qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
-      q.add_query qq
-    end
-    q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
-
-    debug "contact search: #{q}"
-    contacts = {}
-    num = h[:num] || 20
-    @index_mutex.synchronize do
-      @index.search_each q, :sort => "date DESC", :limit => :all do |docid, score|
-        break if contacts.size >= num
-        #debug "got message #{docid} to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
-        f = @index[docid][:from]
-        t = @index[docid][:to]
-
-        if AccountManager.is_account_email? f
-          t.split(" ").each { |e| contacts[Person.from_address(e)] = true }
-        else
-          contacts[Person.from_address(f)] = true
-        end
-      end
-    end
-
-    contacts.keys.compact
-  end
-
-  def each_id query={}
-    ferret_query = build_ferret_query query
-    results = @index_mutex.synchronize { @index.search ferret_query, :limit => (query[:limit] || :all) }
-    results.hits.map { |hit| yield @index[hit.doc][:message_id] }
-  end
-
-  def optimize
-    @index_mutex.synchronize { @index.optimize }
-  end
-
-  def source_for_id id
-    entry = @index[id]
-    return unless entry
-    entry[:source_id].to_i
-  end
-
-  class ParseError < StandardError; end
-
-  ## parse a query string from the user. returns a query object
-  ## that can be passed to any index method with a 'query'
-  ## argument, as well as build_ferret_query.
-  ##
-  ## raises a ParseError if something went wrong.
-  def parse_query s
-    query = {}
-
-    subs = HookManager.run("custom-search", :subs => s) || s
-    subs = subs.gsub(/\b(to|from):(\S+)\b/) do
-      field, name = $1, $2
-      if(p = ContactManager.contact_for(name))
-        [field, p.email]
-      elsif name == "me"
-        [field, "(" + AccountManager.user_emails.join("||") + ")"]
-      else
-        [field, name]
-      end.join(":")
-    end
-
-    ## if we see a label:deleted or a label:spam term anywhere in the query
-    ## string, we set the extra load_spam or load_deleted options to true.
-    ## bizarre? well, because the query allows arbitrary parenthesized boolean
-    ## expressions, without fully parsing the query, we can't tell whether
-    ## the user is explicitly directing us to search spam messages or not.
-    ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
-    ## search spam messages or not?
-    ##
-    ## so, we rely on the fact that turning these extra options ON turns OFF
-    ## the adding of "-label:deleted" or "-label:spam" terms at the very
-    ## final stage of query processing. if the user wants to search spam
-    ## messages, not adding that is the right thing; if he doesn't want to
-    ## search spam messages, then not adding it won't have any effect.
-    query[:load_spam] = true if subs =~ /\blabel:spam\b/
-    query[:load_deleted] = true if subs =~ /\blabel:deleted\b/
-
-    ## gmail style "is" operator
-    subs = subs.gsub(/\b(is|has):(\S+)\b/) do
-      field, label = $1, $2
-      case label
-      when "read"
-        "-label:unread"
-      when "spam"
-        query[:load_spam] = true
-        "label:spam"
-      when "deleted"
-        query[:load_deleted] = true
-        "label:deleted"
-      else
-        "label:#{$2}"
-      end
-    end
-
-    ## gmail style attachments "filename" and "filetype" searches
-    subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
-      field, name = $1, ($3 || $4)
-      case field
-      when "filename"
-        debug "filename: translated #{field}:#{name} to attachments:(#{name.downcase})"
-        "attachments:(#{name.downcase})"
-      when "filetype"
-        debug "filetype: translated #{field}:#{name} to attachments:(*.#{name.downcase})"
-        "attachments:(*.#{name.downcase})"
-      end
-    end
-
-    if $have_chronic
-      subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
-        field, datestr = $1, ($3 || $4)
-        realdate = Chronic.parse datestr, :guess => false, :context => :past
-        if realdate
-          case field
-          when "after"
-            debug "chronic: translated #{field}:#{datestr} to #{realdate.end}"
-            "date:(>= #{sprintf "%012d", realdate.end.to_i})"
-          when "before"
-            debug "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
-            "date:(<= #{sprintf "%012d", realdate.begin.to_i})"
-          else
-            debug "chronic: translated #{field}:#{datestr} to #{realdate}"
-            "date:(<= #{sprintf "%012d", realdate.end.to_i}) date:(>= #{sprintf "%012d", realdate.begin.to_i})"
-          end
-        else
-          raise ParseError, "can't understand date #{datestr.inspect}"
-        end
-      end
-    end
-
-    ## limit:42 restrict the search to 42 results
-    subs = subs.gsub(/\blimit:(\S+)\b/) do
-      lim = $1
-      if lim =~ /^\d+$/
-        query[:limit] = lim.to_i
-        ''
-      else
-        raise ParseError, "non-numeric limit #{lim.inspect}"
-      end
-    end
-
-    begin
-      query[:qobj] = @qparser.parse(subs)
-      query[:text] = s
-      query
-    rescue Ferret::QueryParser::QueryParseException => e
-      raise ParseError, e.message
-    end
-  end
-
-private
-
-  def build_ferret_query query
-    q = Ferret::Search::BooleanQuery.new
-    q.add_query Ferret::Search::MatchAllQuery.new, :must
-    q.add_query query[:qobj], :must if query[:qobj]
-    labels = ([query[:label]] + (query[:labels] || [])).compact
-    labels.each { |t| q.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
-    if query[:participants]
-      q2 = Ferret::Search::BooleanQuery.new
-      query[:participants].each do |p|
-        q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
-        q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
-      end
-      q.add_query q2, :must
-    end
-
-    q.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless query[:load_spam] || labels.include?(:spam)
-    q.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless query[:load_deleted] || labels.include?(:deleted)
-    q.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not if query[:skip_killed]
-
-    q.add_query Ferret::Search::TermQuery.new("source_id", query[:source_id]), :must if query[:source_id]
-    q
-  end
-
-  def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
-  def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
-end
-
-end
diff --git a/lib/sup/index.rb b/lib/sup/index.rb
@@ -1,5 +1,7 @@
-## Index interface, subclassed by Ferret indexer.
+ENV["XAPIAN_FLUSH_THRESHOLD"] = "1000"
 
+require 'xapian'
+require 'set'
 require 'fileutils'
 
 begin
@@ -12,9 +14,28 @@ end
 
 module Redwood
 
-class BaseIndex
+# This index implementation uses Xapian for searching and storage. It
+# tends to be slightly faster than Ferret for indexing and significantly faster
+# for searching due to precomputing thread membership.
+class Index
   include InteractiveLock
 
+  STEM_LANGUAGE = "english"
+  INDEX_VERSION = '2'
+
+  ## dates are converted to integers for xapian, and are used for document ids,
+  ## so we must ensure they're reasonably valid. this typically only affect
+  ## spam.
+  MIN_DATE = Time.at 0
+  MAX_DATE = Time.at(2**31-1)
+
+  HookManager.register "custom-search", <<EOS
+Executes before a string search is applied to the index,
+returning a new search string.
+Variables:
+  subs: The string being searched.
+EOS
+
   class LockError < StandardError
     def initialize h
       @h = h
@@ -23,8 +44,6 @@ class BaseIndex
     def method_missing m; @h[m.to_s] end
   end
 
-  def is_a_deprecated_ferret_index?; false end
-
   include Singleton
 
   def initialize dir=BASE_DIR
@@ -32,6 +51,7 @@ class BaseIndex
     @lock = Lockfile.new lockfile, :retries => 0, :max_age => nil
     @sync_worker = nil
     @sync_queue = Queue.new
+    @index_mutex = Monitor.new
   end
 
   def lockfile; File.join @dir, "lock" end
@@ -79,25 +99,43 @@ class BaseIndex
   end
 
   def load_index
-    unimplemented
+    path = File.join(@dir, 'xapian')
+    if File.exists? path
+      @xapian = Xapian::WritableDatabase.new(path, Xapian::DB_OPEN)
+      db_version = @xapian.get_metadata 'version'
+      db_version = '0' if db_version.empty?
+      if db_version == '1'
+        info "Upgrading index format 1 to 2"
+        @xapian.set_metadata 'version', INDEX_VERSION
+      elsif db_version != INDEX_VERSION
+        fail "This Sup version expects a v#{INDEX_VERSION} index, but you have an existing v#{db_version} index. Please downgrade to your previous version and dump your labels before upgrading to this version (then run sup-sync --restore)."
+      end
+    else
+      @xapian = Xapian::WritableDatabase.new(path, Xapian::DB_CREATE)
+      @xapian.set_metadata 'version', INDEX_VERSION
+    end
+    @enquire = Xapian::Enquire.new @xapian
+    @enquire.weighting_scheme = Xapian::BoolWeight.new
+    @enquire.docid_order = Xapian::Enquire::ASCENDING
   end
 
-  def add_message m; unimplemented end
-  def update_message m; unimplemented end
-  def update_message_state m; unimplemented end
+  def add_message m; sync_message m, true end
+  def update_message m; sync_message m, true end
+  def update_message_state m; sync_message m, false end
 
-  def save_index fn
-    unimplemented
+  def save_index
+    info "Flushing Xapian updates to disk. This may take a while..."
+    @xapian.flush
   end
 
   def contains_id? id
-    unimplemented
+    synchronize { find_docid(id) && true }
   end
 
   def contains? m; contains_id? m.id end
 
   def size
-    unimplemented
+    synchronize { @xapian.doccount }
   end
 
   def empty?; size == 0 end
@@ -107,12 +145,14 @@ class BaseIndex
   ## You should probably not call this on a block that doesn't break
   ## rather quickly because the results can be very large.
   def each_id_by_date query={}
-    unimplemented
+    each_id(query) { |id| yield id, lambda { build_message id } }
   end
 
   ## Return the number of matches for query in the index
   def num_results_for query={}
-    unimplemented
+    xapian_query = build_xapian_query query
+    matchset = run_query xapian_query, 0, 0, 100
+    matchset.matches_estimated
   end
 
   ## yield all messages in the thread containing 'm' by repeatedly
@@ -124,28 +164,82 @@ class BaseIndex
   ## true, stops loading any thread if a message with a :killed flag
   ## is found.
   def each_message_in_thread_for m, opts={}
-    unimplemented
+    # TODO thread by subject
+    return unless doc = find_doc(m.id)
+    queue = doc.value(THREAD_VALUENO).split(',')
+    msgids = [m.id]
+    seen_threads = Set.new
+    seen_messages = Set.new [m.id]
+    while not queue.empty?
+      thread_id = queue.pop
+      next if seen_threads.member? thread_id
+      return false if opts[:skip_killed] && thread_killed?(thread_id)
+      seen_threads << thread_id
+      docs = term_docids(mkterm(:thread, thread_id)).map { |x| @xapian.document x }
+      docs.each do |doc|
+        msgid = doc.value MSGID_VALUENO
+        next if seen_messages.member? msgid
+        msgids << msgid
+        seen_messages << msgid
+        queue.concat doc.value(THREAD_VALUENO).split(',')
+      end
+    end
+    msgids.each { |id| yield id, lambda { build_message id } }
+    true
   end
 
   ## Load message with the given message-id from the index
   def build_message id
-    unimplemented
+    entry = synchronize { get_entry id }
+    return unless entry
+
+    source = SourceManager[entry[:source_id]]
+    raise "invalid source #{entry[:source_id]}" unless source
+
+    m = Message.new :source => source, :source_info => entry[:source_info],
+                    :labels => entry[:labels], :snippet => entry[:snippet]
+
+    mk_person = lambda { |x| Person.new(*x.reverse!) }
+    entry[:from] = mk_person[entry[:from]]
+    entry[:to].map!(&mk_person)
+    entry[:cc].map!(&mk_person)
+    entry[:bcc].map!(&mk_person)
+
+    m.load_from_index! entry
+    m
   end
 
   ## Delete message with the given message-id from the index
   def delete id
-    unimplemented
+    synchronize { @xapian.delete_document mkterm(:msgid, id) }
   end
 
   ## Given an array of email addresses, return an array of Person objects that
   ## have sent mail to or received mail from any of the given addresses.
   def load_contacts email_addresses, h={}
-    unimplemented
+    contacts = Set.new
+    num = opts[:num] || 20
+    each_id_by_date :participants => emails do |id,b|
+      break if contacts.size >= num
+      m = b.call
+      ([m.from]+m.to+m.cc+m.bcc).compact.each { |p| contacts << [p.name, p.email] }
+    end
+    contacts.to_a.compact.map { |n,e| Person.new n, e }[0...num]
   end
 
   ## Yield each message-id matching query
+  EACH_ID_PAGE = 100
   def each_id query={}
-    unimplemented
+    offset = 0
+    page = EACH_ID_PAGE
+
+    xapian_query = build_xapian_query query
+    while true
+      ids = run_query_ids xapian_query, offset, (offset+page)
+      ids.each { |id| yield id }
+      break if ids.size < page
+      offset += page
+    end
   end
 
   ## Yield each message matching query
@@ -155,15 +249,15 @@ class BaseIndex
     end
   end
 
-  ## Implementation-specific optimization step
+  ## xapian-compact takes too long, so this is a no-op
+  ## until we think of something better
   def optimize
-    unimplemented
   end
 
   ## Return the id source of the source the message with the given message-id
   ## was synced from
   def source_for_id id
-    unimplemented
+    synchronize { get_entry(id)[:source_id] }
   end
 
   class ParseError < StandardError; end
@@ -174,7 +268,130 @@ class BaseIndex
   ##
   ## raises a ParseError if something went wrong.
   def parse_query s
-    unimplemented
+    query = {}
+
+    subs = HookManager.run("custom-search", :subs => s) || s
+    begin
+      subs = SearchManager.expand subs
+    rescue SearchManager::ExpansionError => e
+      raise ParseError, e.message
+    end
+    subs = subs.gsub(/\b(to|from):(\S+)\b/) do
+      field, value = $1, $2
+      email_field, name_field = %w(email name).map { |x| "#{field}_#{x}" }
+      if(p = ContactManager.contact_for(value))
+        "#{email_field}:#{p.email}"
+      elsif value == "me"
+        '(' + AccountManager.user_emails.map { |e| "#{email_field}:#{e}" }.join(' OR ') + ')'
+      else
+        "(#{email_field}:#{value} OR #{name_field}:#{value})"
+      end
+    end
+
+    ## if we see a label:deleted or a label:spam term anywhere in the query
+    ## string, we set the extra load_spam or load_deleted options to true.
+    ## bizarre? well, because the query allows arbitrary parenthesized boolean
+    ## expressions, without fully parsing the query, we can't tell whether
+    ## the user is explicitly directing us to search spam messages or not.
+    ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
+    ## search spam messages or not?
+    ##
+    ## so, we rely on the fact that turning these extra options ON turns OFF
+    ## the adding of "-label:deleted" or "-label:spam" terms at the very
+    ## final stage of query processing. if the user wants to search spam
+    ## messages, not adding that is the right thing; if he doesn't want to
+    ## search spam messages, then not adding it won't have any effect.
+    query[:load_spam] = true if subs =~ /\blabel:spam\b/
+    query[:load_deleted] = true if subs =~ /\blabel:deleted\b/
+
+    ## gmail style "is" operator
+    subs = subs.gsub(/\b(is|has):(\S+)\b/) do
+      field, label = $1, $2
+      case label
+      when "read"
+        "-label:unread"
+      when "spam"
+        query[:load_spam] = true
+        "label:spam"
+      when "deleted"
+        query[:load_deleted] = true
+        "label:deleted"
+      else
+        "label:#{$2}"
+      end
+    end
+
+    ## gmail style attachments "filename" and "filetype" searches
+    subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
+      field, name = $1, ($3 || $4)
+      case field
+      when "filename"
+        debug "filename: translated #{field}:#{name} to attachment:\"#{name.downcase}\""
+        "attachment:\"#{name.downcase}\""
+      when "filetype"
+        debug "filetype: translated #{field}:#{name} to attachment_extension:#{name.downcase}"
+        "attachment_extension:#{name.downcase}"
+      end
+    end
+
+    if $have_chronic
+      lastdate = 2<<32 - 1
+      firstdate = 0
+      subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
+        field, datestr = $1, ($3 || $4)
+        realdate = Chronic.parse datestr, :guess => false, :context => :past
+        if realdate
+          case field
+          when "after"
+            debug "chronic: translated #{field}:#{datestr} to #{realdate.end}"
+            "date:#{realdate.end.to_i}..#{lastdate}"
+          when "before"
+            debug "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
+            "date:#{firstdate}..#{realdate.end.to_i}"
+          else
+            debug "chronic: translated #{field}:#{datestr} to #{realdate}"
+            "date:#{realdate.begin.to_i}..#{realdate.end.to_i}"
+          end
+        else
+          raise ParseError, "can't understand date #{datestr.inspect}"
+        end
+      end
+    end
+
+    ## limit:42 restrict the search to 42 results
+    subs = subs.gsub(/\blimit:(\S+)\b/) do
+      lim = $1
+      if lim =~ /^\d+$/
+        query[:limit] = lim.to_i
+        ''
+      else
+        raise ParseError, "non-numeric limit #{lim.inspect}"
+      end
+    end
+
+    debug "translated query: #{subs.inspect}"
+
+    qp = Xapian::QueryParser.new
+    qp.database = @xapian
+    qp.stemmer = Xapian::Stem.new(STEM_LANGUAGE)
+    qp.stemming_strategy = Xapian::QueryParser::STEM_SOME
+    qp.default_op = Xapian::Query::OP_AND
+    qp.add_valuerangeprocessor(Xapian::NumberValueRangeProcessor.new(DATE_VALUENO, 'date:', true))
+    NORMAL_PREFIX.each { |k,vs| vs.each { |v| qp.add_prefix k, v } }
+    BOOLEAN_PREFIX.each { |k,vs| vs.each { |v| qp.add_boolean_prefix k, v } }
+
+    begin
+      xapian_query = qp.parse_query(subs, Xapian::QueryParser::FLAG_PHRASE|Xapian::QueryParser::FLAG_BOOLEAN|Xapian::QueryParser::FLAG_LOVEHATE|Xapian::QueryParser::FLAG_WILDCARD)
+    rescue RuntimeError => e
+      raise ParseError, "xapian query parser error: #{e}"
+    end
+
+    debug "parsed xapian query: #{xapian_query.description}"
+
+    raise ParseError if xapian_query.nil? or xapian_query.empty?
+    query[:qobj] = xapian_query
+    query[:text] = s
+    query
   end
 
   def save_thread t
@@ -207,34 +424,332 @@ class BaseIndex
       sleep 0.03
     end
   end
-end
 
-## just to make the backtraces even more insane, here we engage in yet more
-## method_missing metaprogramming so that Index.init(index_type_name) will
-## magically make Index act like the correct Index class.
-class Index
-  def self.init type=nil
-    ## determine the index type from the many possible ways of setting it
-    type = (type == "auto" ? nil : type) ||
-      ENV['SUP_INDEX'] ||
-      $config[:index] ||
-      (File.exist?(File.join(BASE_DIR, "xapian")) && "xapian") || ## PRIORITIZE THIS
-      (File.exist?(File.join(BASE_DIR, "ferret")) && "ferret") || ## deprioritize this
-      DEFAULT_NEW_INDEX_TYPE
+  private
+
+  # Stemmed
+  NORMAL_PREFIX = {
+    'subject' => 'S',
+    'body' => 'B',
+    'from_name' => 'FN',
+    'to_name' => 'TN',
+    'name' => %w(FN TN),
+    'attachment' => 'A',
+    'email_text' => 'E',
+    '' => %w(S B FN TN A E),
+  }
+
+  # Unstemmed
+  BOOLEAN_PREFIX = {
+    'type' => 'K',
+    'from_email' => 'FE',
+    'to_email' => 'TE',
+    'email' => %w(FE TE),
+    'date' => 'D',
+    'label' => 'L',
+    'source_id' => 'I',
+    'attachment_extension' => 'O',
+    'msgid' => 'Q',
+    'id' => 'Q',
+    'thread' => 'H',
+    'ref' => 'R',
+  }
+
+  PREFIX = NORMAL_PREFIX.merge BOOLEAN_PREFIX
+
+  MSGID_VALUENO = 0
+  THREAD_VALUENO = 1
+  DATE_VALUENO = 2
+
+  MAX_TERM_LENGTH = 245
+
+  # Xapian can very efficiently sort in ascending docid order. Sup always wants
+  # to sort by descending date, so this method maps between them. In order to
+  # handle multiple messages per second, we use a logistic curve centered
+  # around MIDDLE_DATE so that the slope (docid/s) is greatest in this time
+  # period. A docid collision is not an error - the code will pick the next
+  # smallest unused one.
+  DOCID_SCALE = 2.0**32
+  TIME_SCALE = 2.0**27
+  MIDDLE_DATE = Time.gm(2011)
+  def assign_docid m, truncated_date
+    t = (truncated_date.to_i - MIDDLE_DATE.to_i).to_f
+    docid = (DOCID_SCALE - DOCID_SCALE/(Math::E**(-(t/TIME_SCALE)) + 1)).to_i
+    while docid > 0 and docid_exists? docid
+      docid -= 1
+    end
+    docid > 0 ? docid : nil
+  end
+
+  # XXX is there a better way?
+  def docid_exists? docid
     begin
-      require "sup/#{type}_index"
-      @klass = Redwood.const_get "#{type.capitalize}Index"
-      @obj = @klass.init
-    rescue LoadError, NameError => e
-      raise "unknown index type #{type.inspect}: #{e.message}"
+      @xapian.doclength docid
+      true
+    rescue RuntimeError #Xapian::DocNotFoundError
+      raise unless $!.message =~ /DocNotFoundError/
+      false
+    end
+  end
+
+  def term_docids term
+    @xapian.postlist(term).map { |x| x.docid }
+  end
+
+  def find_docid id
+    docids = term_docids(mkterm(:msgid,id))
+    fail unless docids.size <= 1
+    docids.first
+  end
+
+  def find_doc id
+    return unless docid = find_docid(id)
+    @xapian.document docid
+  end
+
+  def get_id docid
+    return unless doc = @xapian.document(docid)
+    doc.value MSGID_VALUENO
+  end
+
+  def get_entry id
+    return unless doc = find_doc(id)
+    Marshal.load doc.data
+  end
+
+  def thread_killed? thread_id
+    not run_query(Q.new(Q::OP_AND, mkterm(:thread, thread_id), mkterm(:label, :Killed)), 0, 1).empty?
+  end
+
+  def synchronize &b
+    @index_mutex.synchronize &b
+  end
+
+  def run_query xapian_query, offset, limit, checkatleast=0
+    synchronize do
+      @enquire.query = xapian_query
+      @enquire.mset(offset, limit-offset, checkatleast)
+    end
+  end
+
+  def run_query_ids xapian_query, offset, limit
+    matchset = run_query xapian_query, offset, limit
+    matchset.matches.map { |r| r.document.value MSGID_VALUENO }
+  end
+
+  Q = Xapian::Query
+  def build_xapian_query opts
+    labels = ([opts[:label]] + (opts[:labels] || [])).compact
+    neglabels = [:spam, :deleted, :killed].reject { |l| (labels.include? l) || opts.member?("load_#{l}".intern) }
+    pos_terms, neg_terms = [], []
+
+    pos_terms << mkterm(:type, 'mail')
+    pos_terms.concat(labels.map { |l| mkterm(:label,l) })
+    pos_terms << opts[:qobj] if opts[:qobj]
+    pos_terms << mkterm(:source_id, opts[:source_id]) if opts[:source_id]
+
+    if opts[:participants]
+      participant_terms = opts[:participants].map { |p| [:from,:to].map { |d| mkterm(:email, d, (Redwood::Person === p) ? p.email : p) } }.flatten
+      pos_terms << Q.new(Q::OP_OR, participant_terms)
+    end
+
+    neg_terms.concat(neglabels.map { |l| mkterm(:label,l) })
+
+    pos_query = Q.new(Q::OP_AND, pos_terms)
+    neg_query = Q.new(Q::OP_OR, neg_terms)
+
+    if neg_query.empty?
+      pos_query
+    else
+      Q.new(Q::OP_AND_NOT, [pos_query, neg_query])
+    end
+  end
+
+  def sync_message m, overwrite
+    doc = synchronize { find_doc(m.id) }
+    existed = doc != nil
+    doc ||= Xapian::Document.new
+    do_index_static = overwrite || !existed
+    old_entry = !do_index_static && doc.entry
+    snippet = do_index_static ? m.snippet : old_entry[:snippet]
+
+    entry = {
+      :message_id => m.id,
+      :source_id => m.source.id,
+      :source_info => m.source_info,
+      :date => truncate_date(m.date),
+      :snippet => snippet,
+      :labels => m.labels.to_a,
+      :from => [m.from.email, m.from.name],
+      :to => m.to.map { |p| [p.email, p.name] },
+      :cc => m.cc.map { |p| [p.email, p.name] },
+      :bcc => m.bcc.map { |p| [p.email, p.name] },
+      :subject => m.subj,
+      :refs => m.refs.to_a,
+      :replytos => m.replytos.to_a,
+    }
+
+    if do_index_static
+      doc.clear_terms
+      doc.clear_values
+      index_message_static m, doc, entry
+    end
+
+    index_message_threading doc, entry, old_entry
+    index_message_labels doc, entry[:labels], (do_index_static ? [] : old_entry[:labels])
+    doc.entry = entry
+
+    synchronize do
+      unless docid = existed ? doc.docid : assign_docid(m, truncate_date(m.date))
+        # Could be triggered by spam
+        warn "docid underflow, dropping #{m.id.inspect}"
+        return
+      end
+      @xapian.replace_document docid, doc
+    end
+
+    m.labels.each { |l| LabelManager << l }
+    true
+  end
+
+  ## Index content that can't be changed by the user
+  def index_message_static m, doc, entry
+    # Person names are indexed with several prefixes
+    person_termer = lambda do |d|
+      lambda do |p|
+        doc.index_text p.name, PREFIX["#{d}_name"] if p.name
+        doc.index_text p.email, PREFIX['email_text']
+        doc.add_term mkterm(:email, d, p.email)
+      end
+    end
+
+    person_termer[:from][m.from] if m.from
+    (m.to+m.cc+m.bcc).each(&(person_termer[:to]))
+
+    # Full text search content
+    subject_text = m.indexable_subject
+    body_text = m.indexable_body
+    doc.index_text subject_text, PREFIX['subject']
+    doc.index_text body_text, PREFIX['body']
+    m.attachments.each { |a| doc.index_text a, PREFIX['attachment'] }
+
+    # Miscellaneous terms
+    doc.add_term mkterm(:date, m.date) if m.date
+    doc.add_term mkterm(:type, 'mail')
+    doc.add_term mkterm(:msgid, m.id)
+    doc.add_term mkterm(:source_id, m.source.id)
+    m.attachments.each do |a|
+      a =~ /\.(\w+)$/ or next
+      doc.add_term mkterm(:attachment_extension, $1)
+    end
+
+    # Date value for range queries
+    date_value = begin
+      Xapian.sortable_serialise m.date.to_i
+    rescue TypeError
+      Xapian.sortable_serialise 0
+    end
+
+    doc.add_value MSGID_VALUENO, m.id
+    doc.add_value DATE_VALUENO, date_value
+  end
+
+  def index_message_labels doc, new_labels, old_labels
+    return if new_labels == old_labels
+    added = new_labels.to_a - old_labels.to_a
+    removed = old_labels.to_a - new_labels.to_a
+    added.each { |t| doc.add_term mkterm(:label,t) }
+    removed.each { |t| doc.remove_term mkterm(:label,t) }
+  end
+
+  ## Assign a set of thread ids to the document. This is a hybrid of the runtime
+  ## search done by the Ferret index and the index-time union done by previous
+  ## versions of the Xapian index. We first find the thread ids of all messages
+  ## with a reference to or from us. If that set is empty, we use our own
+  ## message id. Otherwise, we use all the thread ids we previously found. In
+  ## the common case there's only one member in that set, but if we're the
+  ## missing link between multiple previously unrelated threads we can have
+  ## more. XapianIndex#each_message_in_thread_for follows the thread ids when
+  ## searching so the user sees a single unified thread.
+  def index_message_threading doc, entry, old_entry
+    return if old_entry && (entry[:refs] == old_entry[:refs]) && (entry[:replytos] == old_entry[:replytos])
+    children = term_docids(mkterm(:ref, entry[:message_id])).map { |docid| @xapian.document docid }
+    parent_ids = entry[:refs] + entry[:replytos]
+    parents = parent_ids.map { |id| find_doc id }.compact
+    thread_members = SavingHash.new { [] }
+    (children + parents).each do |doc2|
+      thread_ids = doc2.value(THREAD_VALUENO).split ','
+      thread_ids.each { |thread_id| thread_members[thread_id] << doc2 }
+    end
+    thread_ids = thread_members.empty? ? [entry[:message_id]] : thread_members.keys
+    thread_ids.each { |thread_id| doc.add_term mkterm(:thread, thread_id) }
+    parent_ids.each { |ref| doc.add_term mkterm(:ref, ref) }
+    doc.add_value THREAD_VALUENO, (thread_ids * ',')
+  end
+
+  def truncate_date date
+    if date < MIN_DATE
+      debug "warning: adjusting too-low date #{date} for indexing"
+      MIN_DATE
+    elsif date > MAX_DATE
+      debug "warning: adjusting too-high date #{date} for indexing"
+      MAX_DATE
+    else
+      date
     end
-    debug "using #{type} index"
-    @obj
   end
 
-  def self.instance; @obj end
-  def self.method_missing m, *a, &b; @obj.send(m, *a, &b) end
-  def self.const_missing x; @obj.class.const_get(x) end
+  # Construct a Xapian term
+  def mkterm type, *args
+    case type
+    when :label
+      PREFIX['label'] + args[0].to_s.downcase
+    when :type
+      PREFIX['type'] + args[0].to_s.downcase
+    when :date
+      PREFIX['date'] + args[0].getutc.strftime("%Y%m%d%H%M%S")
+    when :email
+      case args[0]
+      when :from then PREFIX['from_email']
+      when :to then PREFIX['to_email']
+      else raise "Invalid email term type #{args[0]}"
+      end + args[1].to_s.downcase
+    when :source_id
+      PREFIX['source_id'] + args[0].to_s.downcase
+    when :attachment_extension
+      PREFIX['attachment_extension'] + args[0].to_s.downcase
+    when :msgid, :ref, :thread
+      PREFIX[type.to_s] + args[0][0...(MAX_TERM_LENGTH-1)]
+    else
+      raise "Invalid term type #{type}"
+    end
+  end
 end
 
 end
+
+class Xapian::Document
+  def entry
+    Marshal.load data
+  end
+
+  def entry=(x)
+    self.data = Marshal.dump x
+  end
+
+  def index_text text, prefix, weight=1
+    term_generator = Xapian::TermGenerator.new
+    term_generator.stemmer = Xapian::Stem.new(Redwood::XapianIndex::STEM_LANGUAGE)
+    term_generator.document = self
+    term_generator.index_text text, weight, prefix
+  end
+
+  alias old_add_term add_term
+  def add_term term
+    if term.length <= Redwood::XapianIndex::MAX_TERM_LENGTH
+      old_add_term term, 0
+    else
+      warn "dropping excessively long term #{term}"
+    end
+  end
+end
diff --git a/lib/sup/message.rb b/lib/sup/message.rb
@@ -178,7 +178,7 @@ class Message
 
   ## sanitize message ids by removing spaces and non-ascii characters.
   ## also, truncate to 255 characters. all these steps are necessary
-  ## to make ferret happy. of course, we probably fuck up a couple
+  ## to make the index happy. of course, we probably fuck up a couple
   ## valid message ids as well. as long as we're consistent, this
   ## should be fine, though.
   ##
diff --git a/lib/sup/modes/console-mode.rb b/lib/sup/modes/console-mode.rb
@@ -20,7 +20,6 @@ class Console
   end
 
   def xapian; Index.instance.instance_variable_get :@xapian; end
-  def ferret; Index.instance.instance_variable_get :@index; end
 
   def loglevel; Redwood::Logger.level; end
   def set_loglevel(level); Redwood::Logger.level = level; end
@@ -29,7 +28,7 @@ class Console
 
   ## files that won't cause problems when reloaded
   ## TODO expand this list / convert to blacklist
-  RELOAD_WHITELIST = %w(sup/xapian_index.rb sup/modes/console-mode.rb)
+  RELOAD_WHITELIST = %w(sup/index.rb sup/modes/console-mode.rb)
 
   def reload
     old_verbose = $VERBOSE
diff --git a/lib/sup/modes/search-results-mode.rb b/lib/sup/modes/search-results-mode.rb
@@ -32,7 +32,7 @@ class SearchResultsMode < ThreadIndexMode
     BufferManager.flash "Search saved as \"#{name}\"" if SearchManager.add name, @query[:text].strip
   end
 
-  ## a proper is_relevant? method requires some way of asking ferret
+  ## a proper is_relevant? method requires some way of asking the index
   ## if an in-memory object satisfies a query. i'm not sure how to do
   ## that yet. in the worst case i can make an in-memory index, add
   ## the message, and search against it to see if i have > 0 results,
diff --git a/lib/sup/xapian_index.rb b/lib/sup/xapian_index.rb
@@ -1,618 +0,0 @@
-ENV["XAPIAN_FLUSH_THRESHOLD"] = "1000"
-
-require 'xapian'
-require 'set'
-
-module Redwood
-
-# This index implementation uses Xapian for searching and storage. It
-# tends to be slightly faster than Ferret for indexing and significantly faster
-# for searching due to precomputing thread membership.
-class XapianIndex < BaseIndex
-  STEM_LANGUAGE = "english"
-  INDEX_VERSION = '2'
-
-  ## dates are converted to integers for xapian, and are used for document ids,
-  ## so we must ensure they're reasonably valid. this typically only affect
-  ## spam.
-  MIN_DATE = Time.at 0
-  MAX_DATE = Time.at(2**31-1)
-
-  HookManager.register "custom-search", <<EOS
-Executes before a string search is applied to the index,
-returning a new search string.
-Variables:
-  subs: The string being searched.
-EOS
-
-  def initialize dir=BASE_DIR
-    super
-
-    @index_mutex = Monitor.new
-  end
-
-  def load_index
-    path = File.join(@dir, 'xapian')
-    if File.exists? path
-      @xapian = Xapian::WritableDatabase.new(path, Xapian::DB_OPEN)
-      db_version = @xapian.get_metadata 'version'
-      db_version = '0' if db_version.empty?
-      if db_version == '1'
-        info "Upgrading index format 1 to 2"
-        @xapian.set_metadata 'version', INDEX_VERSION
-      elsif db_version != INDEX_VERSION
-        fail "This Sup version expects a v#{INDEX_VERSION} index, but you have an existing v#{db_version} index. Please downgrade to your previous version and dump your labels before upgrading to this version (then run sup-sync --restore)."
-      end
-    else
-      @xapian = Xapian::WritableDatabase.new(path, Xapian::DB_CREATE)
-      @xapian.set_metadata 'version', INDEX_VERSION
-    end
-    @enquire = Xapian::Enquire.new @xapian
-    @enquire.weighting_scheme = Xapian::BoolWeight.new
-    @enquire.docid_order = Xapian::Enquire::ASCENDING
-  end
-
-  def save_index
-    info "Flushing Xapian updates to disk. This may take a while..."
-    @xapian.flush
-  end
-
-  def optimize
-  end
-
-  def size
-    synchronize { @xapian.doccount }
-  end
-
-  def contains_id? id
-    synchronize { find_docid(id) && true }
-  end
-
-  def source_for_id id
-    synchronize { get_entry(id)[:source_id] }
-  end
-
-  def delete id
-    synchronize { @xapian.delete_document mkterm(:msgid, id) }
-  end
-
-  def build_message id
-    entry = synchronize { get_entry id }
-    return unless entry
-
-    source = SourceManager[entry[:source_id]]
-    raise "invalid source #{entry[:source_id]}" unless source
-
-    m = Message.new :source => source, :source_info => entry[:source_info],
-                    :labels => entry[:labels], :snippet => entry[:snippet]
-
-    mk_person = lambda { |x| Person.new(*x.reverse!) }
-    entry[:from] = mk_person[entry[:from]]
-    entry[:to].map!(&mk_person)
-    entry[:cc].map!(&mk_person)
-    entry[:bcc].map!(&mk_person)
-
-    m.load_from_index! entry
-    m
-  end
-
-  def add_message m; sync_message m, true end
-  def update_message m; sync_message m, true end
-  def update_message_state m; sync_message m, false end
-
-  def num_results_for query={}
-    xapian_query = build_xapian_query query
-    matchset = run_query xapian_query, 0, 0, 100
-    matchset.matches_estimated
-  end
-
-  EACH_ID_PAGE = 100
-  def each_id query={}
-    offset = 0
-    page = EACH_ID_PAGE
-
-    xapian_query = build_xapian_query query
-    while true
-      ids = run_query_ids xapian_query, offset, (offset+page)
-      ids.each { |id| yield id }
-      break if ids.size < page
-      offset += page
-    end
-  end
-
-  def each_id_by_date query={}
-    each_id(query) { |id| yield id, lambda { build_message id } }
-  end
-
-  def each_message_in_thread_for m, opts={}
-    # TODO thread by subject
-    return unless doc = find_doc(m.id)
-    queue = doc.value(THREAD_VALUENO).split(',')
-    msgids = [m.id]
-    seen_threads = Set.new
-    seen_messages = Set.new [m.id]
-    while not queue.empty?
-      thread_id = queue.pop
-      next if seen_threads.member? thread_id
-      return false if opts[:skip_killed] && thread_killed?(thread_id)
-      seen_threads << thread_id
-      docs = term_docids(mkterm(:thread, thread_id)).map { |x| @xapian.document x }
-      docs.each do |doc|
-        msgid = doc.value MSGID_VALUENO
-        next if seen_messages.member? msgid
-        msgids << msgid
-        seen_messages << msgid
-        queue.concat doc.value(THREAD_VALUENO).split(',')
-      end
-    end
-    msgids.each { |id| yield id, lambda { build_message id } }
-    true
-  end
-
-  def load_contacts emails, opts={}
-    contacts = Set.new
-    num = opts[:num] || 20
-    each_id_by_date :participants => emails do |id,b|
-      break if contacts.size >= num
-      m = b.call
-      ([m.from]+m.to+m.cc+m.bcc).compact.each { |p| contacts << [p.name, p.email] }
-    end
-    contacts.to_a.compact.map { |n,e| Person.new n, e }[0...num]
-  end
-
-  # TODO share code with the Ferret index
-  def parse_query s
-    query = {}
-
-    subs = HookManager.run("custom-search", :subs => s) || s
-    begin
-      subs = SearchManager.expand subs
-    rescue SearchManager::ExpansionError => e
-      raise ParseError, e.message
-    end
-    subs = subs.gsub(/\b(to|from):(\S+)\b/) do
-      field, value = $1, $2
-      email_field, name_field = %w(email name).map { |x| "#{field}_#{x}" }
-      if(p = ContactManager.contact_for(value))
-        "#{email_field}:#{p.email}"
-      elsif value == "me"
-        '(' + AccountManager.user_emails.map { |e| "#{email_field}:#{e}" }.join(' OR ') + ')'
-      else
-        "(#{email_field}:#{value} OR #{name_field}:#{value})"
-      end
-    end
-
-    ## if we see a label:deleted or a label:spam term anywhere in the query
-    ## string, we set the extra load_spam or load_deleted options to true.
-    ## bizarre? well, because the query allows arbitrary parenthesized boolean
-    ## expressions, without fully parsing the query, we can't tell whether
-    ## the user is explicitly directing us to search spam messages or not.
-    ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
-    ## search spam messages or not?
-    ##
-    ## so, we rely on the fact that turning these extra options ON turns OFF
-    ## the adding of "-label:deleted" or "-label:spam" terms at the very
-    ## final stage of query processing. if the user wants to search spam
-    ## messages, not adding that is the right thing; if he doesn't want to
-    ## search spam messages, then not adding it won't have any effect.
-    query[:load_spam] = true if subs =~ /\blabel:spam\b/
-    query[:load_deleted] = true if subs =~ /\blabel:deleted\b/
-
-    ## gmail style "is" operator
-    subs = subs.gsub(/\b(is|has):(\S+)\b/) do
-      field, label = $1, $2
-      case label
-      when "read"
-        "-label:unread"
-      when "spam"
-        query[:load_spam] = true
-        "label:spam"
-      when "deleted"
-        query[:load_deleted] = true
-        "label:deleted"
-      else
-        "label:#{$2}"
-      end
-    end
-
-    ## gmail style attachments "filename" and "filetype" searches
-    subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
-      field, name = $1, ($3 || $4)
-      case field
-      when "filename"
-        debug "filename: translated #{field}:#{name} to attachment:\"#{name.downcase}\""
-        "attachment:\"#{name.downcase}\""
-      when "filetype"
-        debug "filetype: translated #{field}:#{name} to attachment_extension:#{name.downcase}"
-        "attachment_extension:#{name.downcase}"
-      end
-    end
-
-    if $have_chronic
-      lastdate = 2<<32 - 1
-      firstdate = 0
-      subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
-        field, datestr = $1, ($3 || $4)
-        realdate = Chronic.parse datestr, :guess => false, :context => :past
-        if realdate
-          case field
-          when "after"
-            debug "chronic: translated #{field}:#{datestr} to #{realdate.end}"
-            "date:#{realdate.end.to_i}..#{lastdate}"
-          when "before"
-            debug "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
-            "date:#{firstdate}..#{realdate.end.to_i}"
-          else
-            debug "chronic: translated #{field}:#{datestr} to #{realdate}"
-            "date:#{realdate.begin.to_i}..#{realdate.end.to_i}"
-          end
-        else
-          raise ParseError, "can't understand date #{datestr.inspect}"
-        end
-      end
-    end
-
-    ## limit:42 restrict the search to 42 results
-    subs = subs.gsub(/\blimit:(\S+)\b/) do
-      lim = $1
-      if lim =~ /^\d+$/
-        query[:limit] = lim.to_i
-        ''
-      else
-        raise ParseError, "non-numeric limit #{lim.inspect}"
-      end
-    end
-
-    debug "translated query: #{subs.inspect}"
-
-    qp = Xapian::QueryParser.new
-    qp.database = @xapian
-    qp.stemmer = Xapian::Stem.new(STEM_LANGUAGE)
-    qp.stemming_strategy = Xapian::QueryParser::STEM_SOME
-    qp.default_op = Xapian::Query::OP_AND
-    qp.add_valuerangeprocessor(Xapian::NumberValueRangeProcessor.new(DATE_VALUENO, 'date:', true))
-    NORMAL_PREFIX.each { |k,vs| vs.each { |v| qp.add_prefix k, v } }
-    BOOLEAN_PREFIX.each { |k,vs| vs.each { |v| qp.add_boolean_prefix k, v } }
-
-    begin
-      xapian_query = qp.parse_query(subs, Xapian::QueryParser::FLAG_PHRASE|Xapian::QueryParser::FLAG_BOOLEAN|Xapian::QueryParser::FLAG_LOVEHATE|Xapian::QueryParser::FLAG_WILDCARD)
-    rescue RuntimeError => e
-      raise ParseError, "xapian query parser error: #{e}"
-    end
-
-    debug "parsed xapian query: #{xapian_query.description}"
-
-    raise ParseError if xapian_query.nil? or xapian_query.empty?
-    query[:qobj] = xapian_query
-    query[:text] = s
-    query
-  end
-
-  private
-
-  # Stemmed
-  NORMAL_PREFIX = {
-    'subject' => 'S',
-    'body' => 'B',
-    'from_name' => 'FN',
-    'to_name' => 'TN',
-    'name' => %w(FN TN),
-    'attachment' => 'A',
-    'email_text' => 'E',
-    '' => %w(S B FN TN A E),
-  }
-
-  # Unstemmed
-  BOOLEAN_PREFIX = {
-    'type' => 'K',
-    'from_email' => 'FE',
-    'to_email' => 'TE',
-    'email' => %w(FE TE),
-    'date' => 'D',
-    'label' => 'L',
-    'source_id' => 'I',
-    'attachment_extension' => 'O',
-    'msgid' => 'Q',
-    'id' => 'Q',
-    'thread' => 'H',
-    'ref' => 'R',
-  }
-
-  PREFIX = NORMAL_PREFIX.merge BOOLEAN_PREFIX
-
-  MSGID_VALUENO = 0
-  THREAD_VALUENO = 1
-  DATE_VALUENO = 2
-
-  MAX_TERM_LENGTH = 245
-
-  # Xapian can very efficiently sort in ascending docid order. Sup always wants
-  # to sort by descending date, so this method maps between them. In order to
-  # handle multiple messages per second, we use a logistic curve centered
-  # around MIDDLE_DATE so that the slope (docid/s) is greatest in this time
-  # period. A docid collision is not an error - the code will pick the next
-  # smallest unused one.
-  DOCID_SCALE = 2.0**32
-  TIME_SCALE = 2.0**27
-  MIDDLE_DATE = Time.gm(2011)
-  def assign_docid m, truncated_date
-    t = (truncated_date.to_i - MIDDLE_DATE.to_i).to_f
-    docid = (DOCID_SCALE - DOCID_SCALE/(Math::E**(-(t/TIME_SCALE)) + 1)).to_i
-    while docid > 0 and docid_exists? docid
-      docid -= 1
-    end
-    docid > 0 ? docid : nil
-  end
-
-  # XXX is there a better way?
-  def docid_exists? docid
-    begin
-      @xapian.doclength docid
-      true
-    rescue RuntimeError #Xapian::DocNotFoundError
-      raise unless $!.message =~ /DocNotFoundError/
-      false
-    end
-  end
-
-  def term_docids term
-    @xapian.postlist(term).map { |x| x.docid }
-  end
-
-  def find_docid id
-    docids = term_docids(mkterm(:msgid,id))
-    fail unless docids.size <= 1
-    docids.first
-  end
-
-  def find_doc id
-    return unless docid = find_docid(id)
-    @xapian.document docid
-  end
-
-  def get_id docid
-    return unless doc = @xapian.document(docid)
-    doc.value MSGID_VALUENO
-  end
-
-  def get_entry id
-    return unless doc = find_doc(id)
-    Marshal.load doc.data
-  end
-
-  def thread_killed? thread_id
-    not run_query(Q.new(Q::OP_AND, mkterm(:thread, thread_id), mkterm(:label, :Killed)), 0, 1).empty?
-  end
-
-  def synchronize &b
-    @index_mutex.synchronize &b
-  end
-
-  def run_query xapian_query, offset, limit, checkatleast=0
-    synchronize do
-      @enquire.query = xapian_query
-      @enquire.mset(offset, limit-offset, checkatleast)
-    end
-  end
-
-  def run_query_ids xapian_query, offset, limit
-    matchset = run_query xapian_query, offset, limit
-    matchset.matches.map { |r| r.document.value MSGID_VALUENO }
-  end
-
-  Q = Xapian::Query
-  def build_xapian_query opts
-    labels = ([opts[:label]] + (opts[:labels] || [])).compact
-    neglabels = [:spam, :deleted, :killed].reject { |l| (labels.include? l) || opts.member?("load_#{l}".intern) }
-    pos_terms, neg_terms = [], []
-
-    pos_terms << mkterm(:type, 'mail')
-    pos_terms.concat(labels.map { |l| mkterm(:label,l) })
-    pos_terms << opts[:qobj] if opts[:qobj]
-    pos_terms << mkterm(:source_id, opts[:source_id]) if opts[:source_id]
-
-    if opts[:participants]
-      participant_terms = opts[:participants].map { |p| [:from,:to].map { |d| mkterm(:email, d, (Redwood::Person === p) ? p.email : p) } }.flatten
-      pos_terms << Q.new(Q::OP_OR, participant_terms)
-    end
-
-    neg_terms.concat(neglabels.map { |l| mkterm(:label,l) })
-
-    pos_query = Q.new(Q::OP_AND, pos_terms)
-    neg_query = Q.new(Q::OP_OR, neg_terms)
-
-    if neg_query.empty?
-      pos_query
-    else
-      Q.new(Q::OP_AND_NOT, [pos_query, neg_query])
-    end
-  end
-
-  def sync_message m, overwrite
-    doc = synchronize { find_doc(m.id) }
-    existed = doc != nil
-    doc ||= Xapian::Document.new
-    do_index_static = overwrite || !existed
-    old_entry = !do_index_static && doc.entry
-    snippet = do_index_static ? m.snippet : old_entry[:snippet]
-
-    entry = {
-      :message_id => m.id,
-      :source_id => m.source.id,
-      :source_info => m.source_info,
-      :date => truncate_date(m.date),
-      :snippet => snippet,
-      :labels => m.labels.to_a,
-      :from => [m.from.email, m.from.name],
-      :to => m.to.map { |p| [p.email, p.name] },
-      :cc => m.cc.map { |p| [p.email, p.name] },
-      :bcc => m.bcc.map { |p| [p.email, p.name] },
-      :subject => m.subj,
-      :refs => m.refs.to_a,
-      :replytos => m.replytos.to_a,
-    }
-
-    if do_index_static
-      doc.clear_terms
-      doc.clear_values
-      index_message_static m, doc, entry
-    end
-
-    index_message_threading doc, entry, old_entry
-    index_message_labels doc, entry[:labels], (do_index_static ? [] : old_entry[:labels])
-    doc.entry = entry
-
-    synchronize do
-      unless docid = existed ? doc.docid : assign_docid(m, truncate_date(m.date))
-        # Could be triggered by spam
-        warn "docid underflow, dropping #{m.id.inspect}"
-        return
-      end
-      @xapian.replace_document docid, doc
-    end
-
-    m.labels.each { |l| LabelManager << l }
-    true
-  end
-
-  ## Index content that can't be changed by the user
-  def index_message_static m, doc, entry
-    # Person names are indexed with several prefixes
-    person_termer = lambda do |d|
-      lambda do |p|
-        doc.index_text p.name, PREFIX["#{d}_name"] if p.name
-        doc.index_text p.email, PREFIX['email_text']
-        doc.add_term mkterm(:email, d, p.email)
-      end
-    end
-
-    person_termer[:from][m.from] if m.from
-    (m.to+m.cc+m.bcc).each(&(person_termer[:to]))
-
-    # Full text search content
-    subject_text = m.indexable_subject
-    body_text = m.indexable_body
-    doc.index_text subject_text, PREFIX['subject']
-    doc.index_text body_text, PREFIX['body']
-    m.attachments.each { |a| doc.index_text a, PREFIX['attachment'] }
-
-    # Miscellaneous terms
-    doc.add_term mkterm(:date, m.date) if m.date
-    doc.add_term mkterm(:type, 'mail')
-    doc.add_term mkterm(:msgid, m.id)
-    doc.add_term mkterm(:source_id, m.source.id)
-    m.attachments.each do |a|
-      a =~ /\.(\w+)$/ or next
-      doc.add_term mkterm(:attachment_extension, $1)
-    end
-
-    # Date value for range queries
-    date_value = begin
-      Xapian.sortable_serialise m.date.to_i
-    rescue TypeError
-      Xapian.sortable_serialise 0
-    end
-
-    doc.add_value MSGID_VALUENO, m.id
-    doc.add_value DATE_VALUENO, date_value
-  end
-
-  def index_message_labels doc, new_labels, old_labels
-    return if new_labels == old_labels
-    added = new_labels.to_a - old_labels.to_a
-    removed = old_labels.to_a - new_labels.to_a
-    added.each { |t| doc.add_term mkterm(:label,t) }
-    removed.each { |t| doc.remove_term mkterm(:label,t) }
-  end
-
-  ## Assign a set of thread ids to the document. This is a hybrid of the runtime
-  ## search done by the Ferret index and the index-time union done by previous
-  ## versions of the Xapian index. We first find the thread ids of all messages
-  ## with a reference to or from us. If that set is empty, we use our own
-  ## message id. Otherwise, we use all the thread ids we previously found. In
-  ## the common case there's only one member in that set, but if we're the
-  ## missing link between multiple previously unrelated threads we can have
-  ## more. XapianIndex#each_message_in_thread_for follows the thread ids when
-  ## searching so the user sees a single unified thread.
-  def index_message_threading doc, entry, old_entry
-    return if old_entry && (entry[:refs] == old_entry[:refs]) && (entry[:replytos] == old_entry[:replytos])
-    children = term_docids(mkterm(:ref, entry[:message_id])).map { |docid| @xapian.document docid }
-    parent_ids = entry[:refs] + entry[:replytos]
-    parents = parent_ids.map { |id| find_doc id }.compact
-    thread_members = SavingHash.new { [] }
-    (children + parents).each do |doc2|
-      thread_ids = doc2.value(THREAD_VALUENO).split ','
-      thread_ids.each { |thread_id| thread_members[thread_id] << doc2 }
-    end
-    thread_ids = thread_members.empty? ? [entry[:message_id]] : thread_members.keys
-    thread_ids.each { |thread_id| doc.add_term mkterm(:thread, thread_id) }
-    parent_ids.each { |ref| doc.add_term mkterm(:ref, ref) }
-    doc.add_value THREAD_VALUENO, (thread_ids * ',')
-  end
-
-  def truncate_date date
-    if date < MIN_DATE
-      debug "warning: adjusting too-low date #{date} for indexing"
-      MIN_DATE
-    elsif date > MAX_DATE
-      debug "warning: adjusting too-high date #{date} for indexing"
-      MAX_DATE
-    else
-      date
-    end
-  end
-
-  # Construct a Xapian term
-  def mkterm type, *args
-    case type
-    when :label
-      PREFIX['label'] + args[0].to_s.downcase
-    when :type
-      PREFIX['type'] + args[0].to_s.downcase
-    when :date
-      PREFIX['date'] + args[0].getutc.strftime("%Y%m%d%H%M%S")
-    when :email
-      case args[0]
-      when :from then PREFIX['from_email']
-      when :to then PREFIX['to_email']
-      else raise "Invalid email term type #{args[0]}"
-      end + args[1].to_s.downcase
-    when :source_id
-      PREFIX['source_id'] + args[0].to_s.downcase
-    when :attachment_extension
-      PREFIX['attachment_extension'] + args[0].to_s.downcase
-    when :msgid, :ref, :thread
-      PREFIX[type.to_s] + args[0][0...(MAX_TERM_LENGTH-1)]
-    else
-      raise "Invalid term type #{type}"
-    end
-  end
-end
-
-end
-
-class Xapian::Document
-  def entry
-    Marshal.load data
-  end
-
-  def entry=(x)
-    self.data = Marshal.dump x
-  end
-
-  def index_text text, prefix, weight=1
-    term_generator = Xapian::TermGenerator.new
-    term_generator.stemmer = Xapian::Stem.new(Redwood::XapianIndex::STEM_LANGUAGE)
-    term_generator.document = self
-    term_generator.index_text text, weight, prefix
-  end
-
-  alias old_add_term add_term
-  def add_term term
-    if term.length <= Redwood::XapianIndex::MAX_TERM_LENGTH
-      old_add_term term, 0
-    else
-      warn "dropping excessively long term #{term}"
-    end
-  end
-end
diff --git a/sup-files.rb b/sup-files.rb
@@ -1,5 +1,5 @@
 SUP_LIB_DIRS = %w(lib lib/sup lib/sup/modes lib/sup/mbox)
-SUP_EXECUTABLES = %w(sup sup-add sup-config sup-dump sup-recover-sources sup-sync sup-sync-back sup-tweak-labels sup-convert-ferret-index)
+SUP_EXECUTABLES = %w(sup sup-add sup-config sup-dump sup-recover-sources sup-sync sup-sync-back sup-tweak-labels)
 SUP_EXTRA_FILES = %w(CONTRIBUTORS README.txt LICENSE History.txt ReleaseNotes)
 SUP_FILES =
   SUP_EXTRA_FILES +