Description: <short summary of the patch>
 TODO: Put a short summary on the line above and replace this paragraph
 with a longer explanation of this change. Complete the meta-information
 with other relevant fields (see below for details). To make it easier, the
 information below has been extracted from the changelog. Adjust it or drop
 it.
 .
 bbdb3 (3.1.2-7) unstable; urgency=medium
 .
   * switch from flavor to debian-emacs-flavor (closes: #849277)
Author: Barak A. Pearlmutter <bap@debian.org>
Bug-Debian: https://bugs.debian.org/849277

---
The information above should follow the Patch Tagging Guidelines, please
checkout http://dep.debian.net/deps/dep3/ to learn about the format. Here
are templates for supplementary fields that you might want to add:

Origin: <vendor|upstream|other>, <url of original patch>
Bug: <url in upstream bugtracker>
Bug-Debian: https://bugs.debian.org/<bugnumber>
Bug-Ubuntu: https://launchpad.net/bugs/<bugnumber>
Forwarded: <no|not-needed|url proving that it has been forwarded>
Reviewed-By: <name and email of someone who approved the patch>
Last-Update: 2016-12-24

--- bbdb3-3.1.2.orig/ChangeLog
+++ bbdb3-3.1.2/ChangeLog
@@ -1,3 +1,302 @@
+2016-10-02  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-com.el, lisp/bbdb-gnus.el, lisp/bbdb-ispell.el:
+	* lisp/bbdb-message.el, lisp/bbdb-mhe.el, lisp/bbdb-migrate.el:
+	* lisp/bbdb-mu4e.el, lisp/bbdb-mua.el, lisp/bbdb-pgp.el:
+	* lisp/bbdb-print.el, lisp/bbdb-rmail.el, lisp/bbdb-sc.el:
+	* lisp/bbdb-site.el.in, lisp/bbdb-snarf.el, lisp/bbdb-vm.el:
+	* lisp/bbdb-wl.el, lisp/bbdb.el: Use lexical binding.
+
+	* lisp/bbdb.el (bbdb-alist-with-header): Start name of unused
+	variables with underscore.
+	(bbdb-display-record-multi-line, bbdb-display-records): Remove
+	unused variable.
+	* lisp/bbdb-com.el (bbdb-omit-record):
+	* lisp/bbdb-snarf.el (bbdb-snarf-surrounding-space)
+	(bbdb-snarf-empty-lines):
+	* lisp/bbdb-migrate.el (bbdb-undocumented-variables): Start name
+	of unused variables with underscore.
+	* lisp/bbdb-mua.el (bbdb-get-address-components):
+	* lisp/bbdb-print.el (bbdb-print-record): Remove unused variable.
+	* lisp/bbdb-gnus.el: Autoload message-make-domain.
+	(bbdb/gnus-score-as-text): Start name of unused variables with
+	underscore.
+
+2016-07-20  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb.el (bbdb-display-record-one-line)
+	* lisp/bbdb-snarf.el (bbdb-snarf-label, bbdb-snarf-phone-nanp):
+	Use 2nd arg of looking-back.
+
+2016-07-20  Roland Winkler  <winkler@gnu.org>
+	Update copyright year in all files.
+
+2016-07-20  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-mua.el (bbdb-mua-mode-alist): Add support for
+	mu4e-compose-mode and notmuch-message-mode which are derived from
+	message-mode.
+
+2016-07-20  Roland Winkler  <winkler@gnu.org>
+	* m4/emacs_wl.m4: New file
+	* configure.ac: Use it.
+	* NEWS, README: Document support for Wanderlust
+
+2016-07-20  David Maus  <dmaus@dmaus.name>
+	Add basic support for Wanderlust.
+	* lisp/Makefile.am, lisp/makefile-temp: Support Wanderlust.
+	* lisp/bbdb-mua.el (bbdb-mua-mode-alist, bbdb-mua)
+	(bbdb-message-header, bbdb-mua-update-records, bbdb-mua-wrapper):
+	Add support for Wanderlust.
+	(bbdb-mua-auto-update-init): Add wanderlust to list of auto-update
+	muas.
+	* lisp/bbdb.el (bbdb-init-forms): Add support for Wanderlust.
+	* lisp/bbdb-wl.el: New file.
+
+2016-07-20 Marco Wahl <marcowahlsoft@gmail.com>
+	* lisp/bbdb-com.el (bbdb-omit-record): Fix arg list of
+	bbdb-redisplay-record.
+
+2016-07-20  Roland Winkler  <winkler@gnu.org>
+	Make bbdb-hashtable a proper hash table.
+	* lisp/bbdb.el (bbdb-hashtable): Use make-hash-table.
+	(bbdb-puthash, bbdb-gethash, bbdb-remhash, bbdb-buffer)
+	* lisp/bbdb-com.el (bbdb-completion-predicate)
+	(bbdb-completing-read-records, bbdb-complete-mail): Use it.
+
+2016-07-20  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb.el (bbdb-add-to-list): Remove.
+	(bbdb-pushnew, bbdb-pushnewq, bbdb-pushnewt): New macros.
+	(bbdb-record-set-xfield, bbdb-record-set-field)
+	(bbdb-merge-concat-remove-duplicates, bbdb-parse-records)
+	(bbdb-change-record)
+	* lisp/bbdb-com.el (bbdb-mail-aliases, bbdb-get-mail-aliases)
+	(bbdb-add-mail-alias)
+	* lisp/bbdb-mua.el (bbdb-update-records): Use them.
+
+2015-11-14  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb.el (bbdb-auto-revert, bbdb-dedicated-window)
+	(bbdb-default-domain, bbdb-mua-pop-up)
+	(bbdb-horiz-pop-up-window-size, bbdb-xfields-sort-order)
+	(bbdb-mua-summary-unification-list, bbdb-mail-avoid-redundancy)
+	* lisp/bbdb-snarf.el (bbdb-snarf-address-us-country)
+	(bbdb-snarf-address-eu-country)
+	* lisp/bbdb-anniv.el (bbdb-anniv-alist)
+	* lisp/bbdb-vm.el (bbdb/vm-virtual-real-folders)
+	* lisp/bbdb-gnus.el (bbdb/gnus-score-default)
+	(bbdb/gnus-split-myaddr-regexp, bbdb/gnus-split-private-field)
+	(bbdb/gnus-split-public-field)
+	* lisp/bbdb-sc.el (bbdb-sc-update-attrib-p): Fix defcustom.
+
+2015-11-08  Roland Winkler  <winkler@gnu.org>
+	Add new snarfing rule eu for many continental European countries.
+	Improve snarfing algorithm.
+	* lisp/bbdb-snarf.el (bbdb-snarf-rule-alist): Add new rule eu.
+	(bbdb-snarf-phone-nanp-regexp, bbdb-snarf-postcode-us-regexp)
+	(bbdb-snarf-url-regexp): Improve regexp.  Use first subexpression.
+	(bbdb-snarf-mail-regexp): New variable.
+	(bbdb-snarf-mail): Use it.
+	(bbdb-snarf-address-us-country): New variable.
+	(bbdb-snarf-address-us): Use it.  Check whether we actually
+	snarfed an address.
+	(bbdb-snarf-phone-eu-regexp, bbdb-snarf-postcode-eu-regexp)
+	(bbdb-snarf-address-eu-country): New variables.
+	(bbdb-snarf-label): Use save-match-data.
+	(bbdb-snarf-phone-nanp): Use save-match-data.  Reverse order of
+	snarfed phone numbers.
+	(bbdb-snarf-phone-eu, bbdb-snarf-address-eu): New functions.
+
+2015-11-08  Roland Winkler  <winkler@gnu.org>
+	Simplify re-sorting of records when a record has been changed.
+	Re-display re-sorted records.
+	* lisp/bbdb.el (bbdb-need-to-sort): Removed.
+	(bbdb-record-set-name): Simplify accordingly.
+	(bbdb-record-set-sortkey): Always evaluate new sortkey.
+	(bbdb-record-sortkey): Simplify accordingly.
+	(bbdb-change-record): Sort records if we have a new sort key.
+	(bbdb-redisplay-record-globally): Rename from
+	bbdb-maybe-update-display.  New optional arg sort.
+	(bbdb-delete-record-internal, bbdb-insert-record-internal): Do not
+	unset sort key.
+	(bbdb-display-records): Put point at beginning of buffer.
+	(bbdb-redisplay-record): New optional arg sort.  Throw error if
+	record was not displayed previously.
+	(bbdb-sort-records): Clarify status message.  Redisplay sorted
+	records.
+	* lisp/bbdb-com.el (bbdb-fix-records): Sort records.
+	(bbdb-create, bbdb-create-internal, bbdb-merge-records): Use nil
+	for unused second arg of bbdb-change-record.
+	(bbdb-edit-field, bbdb-transpose-fields): Do not worry about
+	re-sorting records.
+	* lisp/bbdb-mua.el (bbdb-annotate-message): Use nil
+	for unused second arg of bbdb-change-record.
+
+2015-09-10  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-anniv.el, lisp/bbdb-mu4e.el, lisp/bbdb-print.el:
+	* lisp/bbdb-snarf.el, lisp/bbdb-com.el, lisp/bbdb-message.el:
+	* lisp/bbdb-mua.el, lisp/bbdb-rmail.el, lisp/bbdb-gnus.el:
+	* lisp/bbdb-mhe.el, lisp/bbdb-pgp.el, lisp/bbdb-sc.el:
+	* lisp/bbdb-vm.el, lisp/bbdb-ispell.el, lisp/bbdb-migrate.el:
+	* lisp/bbdb-site.el.in, lisp/bbdb.el: Conform to Emacs Lisp
+	package format convention.
+	(Bug#45910)
+
+2015-09-10  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb.el (bbdb-separator-alist): Use two newline characters
+	to separate records.
+
+2015-09-07  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-com.el (bbdb-search-changed): Fix docstring.
+
+2015-09-07  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-com.el (bbdb-delete-field-or-record): Use delete for
+	phone and address fields.
+
+2015-09-07  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-com.el (bbdb-copy-records-as-kill): Fix docstring.
+	Delete unused local variable marker.
+
+2015-09-07  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-com.el (bbdb-copy-fields-as-kill): New command.
+	* lisp/bbdb.el (bbdb-separator-alist, bbdb-mode-map): Update
+	accordingly.
+
+2015-05-23  Eric Abrahamsen <eric@ericabrahamsen.net>
+	* lisp/bbdb.el (bbdb-record-set-field, bbdb-parse-records): Use
+	equal for comparison when populating lists of labels.
+
+2015-05-22  Roland Winkler  <winkler@gnu.org>
+	Add basic support for mu4e mailer.
+	* NEWS, README: Update accordingly.
+	* m4/emacs_mu4e.m4: New file.
+	* configure.ac: Use it.
+	* lisp/bbdb-mu4e.el: New file.
+	* lisp/Makefile.am, lisp/makefile-temp: Compile it.
+	* lisp/bbdb.el (bbdb-init-forms): Add entry for mu4e.
+	(bbdb-initialize): Update docstring.
+	* lisp/bbdb-mua.el: Define mu4e~view-buffer-name.
+	(bbdb-mua-mode-alist): Add element for mu4e.
+	(bbdb-mua): Update docstring.
+	(bbdb-mua-update-records, bbdb-mua-wrapper): Handle mu4e.
+
+2015-05-22  Roland Winkler  <winkler@gnu.org>
+	Remove variables bbdb/MUA-update-records-p.
+	* lisp/bbdb-mua.el (bbdb-update-records): Rely only on arg
+	update-p.
+	* lisp/bbdb-gnus.el (bbdb/gnus-update-records-p): Remove.
+	* lisp/bbdb-message.el (bbdb/mail-update-records-p)
+	(bbdb/message-update-records-p): Remove.
+	* lisp/bbdb-mh.el (bbdb/mh-update-records-p): Remove.
+	* lisp/bbdb-rmail.el (bbdb/rmail-update-records-p): Remove.
+	* lisp/bbdb-vm.el (bbdb/vm-update-records-p): Remove.
+	* README, NEWS: Update accordingly.
+
+2015-05-22  Roland Winkler  <winkler@gnu.org>
+	Handle prefix command bbdb-do-all-records more robustly.
+	* lisp/bbdb.el (bbdb-do-all-records): New variable.
+	(bbdb-modeline-info): Add two new slots.
+	(bbdb-mode): Use them.
+	* lisp/bbdb-com.el (bbdb-prefix-message): New function.
+	(bbdb-do-all-records, bbdb-do-records): Use variable
+	bbdb-do-all-records.
+	(bbdb-append-display-p): Update displayed message.
+	(bbdb-append-display): Use bbdb-prefix-message.
+	(bbdb-search-invert): Ditto.  Simplify.
+
+2015-05-22  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb.el (bbdb-redisplay-record): Display an undisplayed
+	record only if we do not want to delete it.
+	(bbdb-maybe-update-display): Only consider records that are
+	already displayed.  Improve docstring.
+
+2015-05-22  Roland Winkler  <winkler@gnu.org>
+	Update copyright year in all files.
+
+2014-08-30  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-print.el (bbdb-print-require): Improve docstring.
+
+2014-08-30  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-print.el (bbdb-print): Clarify prompt for file name.
+	Issue message on what to do with TeX file.
+
+2014-08-30  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-print.el (bbdb-print-record): Handle xfields the value
+	of which are sexps.
+
+2014-08-09  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-snarf.el (bbdb-snarf): Always install and display the
+	new record.
+
+2014-08-01  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-com.el (bbdb-mail-alias-list): New function.
+	(bbdb-add-mail-alias): Handle multiple records via * prefix.
+	Allow addition or deletion of multiple aliases per record.  Fix
+	docstring.
+
+2014-08-01  Roland Winkler  <winkler@gnu.org>
+	* lisp/makefile-temp: Fix previous change.
+
+2014-07-22  Roland Winkler  <winkler@gnu.org>
+	* lisp/Makefile.am: Do not load init files or site files for byte
+	compilation (Bug#42482). Use long options.
+	* lisp/makefile-temp: Ditto.  New variable emacs_compile.
+
+2014-05-15  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb.el (bbdb-redisplay-record): Delete record from
+	bbdb-records if record is undisplayed.
+	* lisp/bbdb-com.el (bbdb-omit-record): Simplify. Handle records at
+	beginning and end of bbdb-buffer properly.
+
+2014-05-15  Roland Winkler  <winkler@gnu.org>
+	Fix and improve previous patch.
+	* lisp/bbdb.el (bbdb-update-unchanged-records): Renamed from
+	bbdb-save-unchanged-records.
+	(bbdb-with-print-loadably): Put at beginning of bbdb.el.
+	(bbdb-change-record): Return record only if we updated it.
+	* lisp/bbdb-com.el (bbdb-touch-records): Use
+	bbdb-update-unchanged-records.
+	(bbdb-insert-field, bbdb-edit-field): Issue message if record
+	remained unchanged.
+
+2014-05-12  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb.el (bbdb-change-record): If an editing command did not
+	change a record compared to its value in bbdb-buffer, do not call
+	bbdb-change-hook and do not save it.
+	(bbdb-save-unchanged-records): New internal variable.
+	* lisp/bbdb-com.el (bbdb-touch-records): New command.
+
+2014-05-12  Roland Winkler  <winkler@gnu.org>
+	* lisp/makefile-temp: Create bbdb-pkg.el from bbdb-pkg.el.in.
+
+2014-05-06  Roland Winkler  <winkler@gnu.org>
+	Do not treat bbdb-change-hook special when inside
+	bbdb-notice-mail-hook or bbdb-notice-record-hook.
+	* lisp/bbdb.el (bbdb-notice-mail-hook, bbdb-notice-record-hook):
+	Update docstring.
+	(bbdb-notice-hook-pending): Remove.
+	(bbdb-change-record): Always call bbdb-change-hook if a record was
+	changed.
+	* lisp/bbdb-mua.el (bbdb-update-records, bbdb-annotate-message):
+	Change accordingly.
+
+2014-05-06  Roland Winkler  <winkler@gnu.org>
+	Allow arbitrary lisp expressions as values of xfields.
+	* lisp/bbdb.el (bbdb-record-type): Update accordingly.
+	(bbdb-string-trim): New optional arg null.
+	(bbdb-record-xfield-intern): Return xfield value unmodified if it
+	is not a string.
+	(bbdb-record-xfield-string): New function.
+	(bbdb-record-xfield-split): Throw error if xfield value is not a
+	string.
+	(bbdb-record-set-xfield, bbdb-record-set-field)
+	(bbdb-merge-xfield, bbdb-display-record-one-line)
+	(bbdb-display-record-multi-line)
+	* lisp/bbdb-com.el (bbdb-search, bbdb-read-field)
+	(bbdb-edit-field, bbdb-read-xfield): Allow xfield values that are
+	not a string.
+	(bbdb-add-mail-alias): Simplify.
+
+2014-05-06  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb.el (bbdb-parse-postcode): Finish immediately if one
+	test succeeds.
+
 2014-04-27  Roland Winkler  <winkler@gnu.org>
 	* configure.ac: Increase BBDB version number to 3.1.2.
 	* NEWS: Update for release.
@@ -1865,7 +2164,7 @@
 ;; coding: utf-8
 ;; End:
 
-  Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+  Copyright (C) 2010-2016 Roland Winkler <winkler@gnu.org>
 
   This file is part of the Insidious Big Brother Database (aka BBDB),
 
--- bbdb3-3.1.2.orig/Makefile.am
+++ bbdb3-3.1.2/Makefile.am
@@ -1,7 +1,7 @@
 # main Makefile.am for BBDB
 #
 # Copyright (C) 2013 Christian Egli <christian.egli@sbs.ch>
-# Copyright (C) 2013-2014 Roland Winkler <winkler@gnu.org>
+# Copyright (C) 2013-2016 Roland Winkler <winkler@gnu.org>
 #
 # This file is part of the Insidious Big Brother Database (aka BBDB),
 #
--- bbdb3-3.1.2.orig/NEWS
+++ bbdb3-3.1.2/NEWS
@@ -1,10 +1,25 @@
 BBDB NEWS -- history of user-visible changes.
 
-Copyright (C) 2013-2014 Roland Winkler <winkler@gnu.org>
+Copyright (C) 2013-2016 Roland Winkler <winkler@gnu.org>
 See the end of the file for license conditions.
 
 This file is about changes in BBDB version 3.
 
+* BBDB 3.2
+** Support for Mu4e and Wanderlust has been added.
+
+** Incompatible Changes in BBDB 3.2
+
+*** The variables bbdb/MUA-update-records-p have been removed.
+This includes the variables bbdb/gnus-update-records-p,
+bbdb/mail-update-records-p, bbdb/message-update-records-p,
+bbdb/mh-update-records-p, bbdb/rmail-update-records-p,
+bbdb/vm-update-records-p.
+
+These fall-back variables collided with the user variables
+bbdb-mua-update-interactive-p and bbdb-mua-auto-update-p.
+Use function bbdb-mua to define your own function to get
+MUA-specific values.
 
 * BBDB 3.1.2
 ** Bug fix release
--- bbdb3-3.1.2.orig/README
+++ bbdb3-3.1.2/README
@@ -1,11 +1,11 @@
-Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+Copyright (C) 2010-2016 Roland Winkler <winkler@gnu.org>
 See the end of the file for license conditions.
 
 BBDB is the Insidious Big Brother Database for GNU Emacs.
 It provides an address book for email and snail mail addresses,
 phone numbers and the like.  It can be linked with various Emacs mail
-clients (Message and Mail mode, Rmail, Gnus, MH-E, and VM).
-BBDB is fully customizable.
+clients (Message and Mail mode, Rmail, Gnus, MH-E, Mu4e, VM, and 
+Wanderlust).  BBDB is fully customizable.
 
 BBDB is available at
 http://savannah.nongnu.org/projects/bbdb/
@@ -37,9 +37,15 @@ To compile and install BBDB with `make':
 
    The `configure' script comes with various options:
 
+   `--with-mu4e-dir=DIR' specifies the path where Mu4e can be found.
+     Without this option the resulting BBDB build does not support Mu4e.
+
    `--with-vm-dir=DIR' specifies the path where VM can be found.
      Without this option the resulting BBDB build does not support VM.
 
+   `--with-wl-dir=DIR' specifies the path where Wanderlust can be found.
+     Without this option the resulting BBDB build does not support WL.
+
    `--with-lispdir=DIR' specifies where to install the lisp files.
 
    Use `configure --help' to see all available options.
@@ -97,6 +103,9 @@ your init file.  All user variables for
 at the beginning of bbdb.el.  Some extensions of BBDB 3 define their
 user variables at the beginning of the respective files.
 
+Those upgrading from BBDB 2.x may find this Emacs wiki page helpful:
+https://www.emacswiki.org/emacs/UpgradeBBDB
+
 Generally the default values for user variables are chosen such that they make
 BBDB the least aggressive.  You can customize this behavior in many ways.
 See below for an overview.
@@ -108,7 +117,7 @@ BBDB interface with mail user agents (MU
 ===========================================
 
 BBDB can interface with various mail user agents (MUAs).
-These include Rmail, Gnus, VM, MH-E, Message and Mail mode.
+These include Rmail, Gnus, VM, MH-E, Mu4e, Wanderlust, Message and Mail mode.
 This lets you
 
  - display the BBDB records for the sender and/or recipients of a
@@ -158,11 +167,8 @@ WITHOUT-PREFIX and WITH-PREFIX may take
  read         Read the value interactively.
 
 BBDB 2 also used MUA-specific variables bbdb/MUA-update-records-mode
-to control its interfaces with MUAs.  In BBDB 3 the variables
-bbdb/MUA-update-records-p are only used as fallback if the generic
-(MUA-independent) variables bbdb-mua-update-interactive-p,
-bbdb-update-records-p or bbdb-mua-auto-update-p result in a value of
-nil for the arg UPDATE-P of bbdb-update-records.
+to control its interfaces with MUAs.  Use function bbdb-mua to define
+your own function to get MUA-specific values.
 
 Noninteractive functions
 ------------------------
@@ -206,7 +212,7 @@ sequence of calls is
 
 ==================================================================
 
-Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+Copyright (C) 2010-2016 Roland Winkler <winkler@gnu.org>
 
 This file is part of the Insidious Big Brother Database (aka BBDB),
 
--- bbdb3-3.1.2.orig/TODO
+++ bbdb3-3.1.2/TODO
@@ -1,6 +1,6 @@
 BBDB todo List                                                   -*-outline-*-
 
-Copyright (C) 2011-2014 Roland Winkler <winkler@gnu.org>
+Copyright (C) 2011-2016 Roland Winkler <winkler@gnu.org>
 See the end of the file for license conditions.
 
 * Bug fixes
@@ -41,6 +41,19 @@ See the end of the file for license cond
 
 ** Import / export BBDB records (e.g. vcard or its XML derivative)
    2011-04-05 Leo <sdl.web@gmail.com>
+   See https://github.com/trebb/bbdb-vcard (latest commit Apr 2010)
+   or its fork
+   https://github.com/tohojo/bbdb-vcard (latest commit Jul 2015)
+
+** Import from Google Contacts (aka Gmail contacts)
+   2016-10-24 Barak A. Pearlmutter <barak@pearlmutter.net>
+   See https://github.com/tohojo/bbdb-vcard (last commit Sep 2015) which imports only name and email.
+   See also the ASynK program, http://asynk.io/, https://github.com/skarra/ASynK (last commit May 2016), which is a python program that does bi-directional sync between bbdb, Google Contacts, MS Outlook, MS Exchange, and CardDAV.
+
+** Incremental search of BBDB records like bbdb-
+   2016-10-24 Barak A. Pearlmutter <barak@pearlmutter.net>
+   The bbdb- package adds a lovely incremental search facility to bbdb.
+   See https://github.com/aki2o/bbdb- (last commit Feb 2014) which includes a gif showing an incremental search, selection of three records, and their being blasted into the To: and Cc: fields in an email composition buffer.
 
 ** Allow splitting of bbdb-file into multiple files
 
@@ -52,7 +65,7 @@ See the end of the file for license cond
    2011-05-05 Leo <sdl.web@gmail.com>
 
 
-Copyright (C) 2011-2014 Roland Winkler <winkler@gnu.org>
+Copyright (C) 2011-2016 Roland Winkler <winkler@gnu.org>
 
 This file is part of the Insidious Big Brother Database (aka BBDB),
 
--- bbdb3-3.1.2.orig/autogen.sh
+++ bbdb3-3.1.2/autogen.sh
@@ -2,7 +2,7 @@
 ### autogen.sh - tool to help build BBDB from a git checkout
 
 ## Copyright (C) 2013 Christian Egli <christian.egli@sbs.ch>
-## Copyright (C) 2013-2014 Roland Winkler <winkler@gnu.org>
+## Copyright (C) 2013-2016 Roland Winkler <winkler@gnu.org>
 ##
 ## This file is part of the Insidious Big Brother Database (aka BBDB),
 ##
--- bbdb3-3.1.2.orig/configure.ac
+++ bbdb3-3.1.2/configure.ac
@@ -1,7 +1,7 @@
 # configure.ac --- configuration setup for BBDB
 
 # Copyright (C) 2000-2001 Didier Verna <didier@xemacs.org>
-# Copyright (C) 2011-2014 Roland Winkler <winkler@gnu.org>
+# Copyright (C) 2011-2016 Roland Winkler <winkler@gnu.org>
 # 
 # Author:        Didier Verna <didier@xemacs.org>
 # Maintainer:    Roland Winkler <winkler@gnu.org>
@@ -40,6 +40,8 @@ AS_IF([test "$EMACS" = no], [AC_MSG_ERRO
 
 # Checks for libraries.
 EMACS_VM
+EMACS_MU4E
+EMACS_WL
 AC_SUBST([AM_ELCFLAGS])
 
 # Generate lisp/bbdb-site.el via lisp/Makefile as pkgdatadir is only known
--- bbdb3-3.1.2.orig/doc/Makefile.am
+++ bbdb3-3.1.2/doc/Makefile.am
@@ -1,7 +1,7 @@
 # doc/Makefile.am for BBDB
 #
 # Copyright (C) 2013 Christian Egli <christian.egli@sbs.ch>
-# Copyright (C) 2013-2014 Roland Winkler <winkler@gnu.org>
+# Copyright (C) 2013-2016 Roland Winkler <winkler@gnu.org>
 # 
 # This file is part of the Insidious Big Brother Database (aka BBDB),
 # 
--- bbdb3-3.1.2.orig/doc/bbdb.texi
+++ bbdb3-3.1.2/doc/bbdb.texi
@@ -7,7 +7,7 @@
 @copying
 This file documents the Insidious Big Brother Database (BBDB)
 
-Copyright (C) 2011-2014 Roland Winkler <winkler@@gnu.org>
+Copyright (C) 2011-2016 Roland Winkler <winkler@@gnu.org>
 
 @quotation
 Permission is granted to copy, distribute and/or modify this document
--- bbdb3-3.1.2.orig/lisp/Makefile.am
+++ bbdb3-3.1.2/lisp/Makefile.am
@@ -1,6 +1,6 @@
 # lisp/Makefile.am for BBDB
 #
-# Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+# Copyright (C) 2010-2016 Roland Winkler <winkler@gnu.org>
 
 # Author: Roland Winkler <winkler@gnu.org>
 #  	  Christian Egli <christian.egli@sbs.ch>
@@ -20,6 +20,9 @@
 # You should have received a copy of the GNU General Public License
 # along with BBDB.  If not, see <http://www.gnu.org/licenses/>.
 
+# --batch implies --no-init-file, yet let's be explicit about what we want
+AM_ELCFLAGS += --no-init-file --no-site-file
+
 dist_lisp_LISP = 				\
 	bbdb.el					\
 	bbdb-anniv.el				\
@@ -43,6 +46,18 @@ dist_lisp_LISP += bbdb-vm.el
 # in the Emacs load path when compiling BBDB with VM support.
 endif
 
+if MU4E
+dist_lisp_LISP += bbdb-mu4e.el
+# We use the Automake variable AM_ELCFLAGS to include the Mu4e lisp directory
+# in the Emacs load path when compiling BBDB with Mu4e support.
+endif
+
+if WL
+dist_lisp_LISP += bbdb-wl.el
+# We use the Automake variable AM_ELCFLAGS to include the WL lisp directory
+# in the Emacs load path when compiling BBDB with WL support.
+endif
+
 lisp_DATA = bbdb-loaddefs.el
 
 MOSTLYCLEANFILES = bbdb-loaddefs.el
@@ -70,10 +85,11 @@ bbdb-loaddefs.el: $(dist_lisp_LISP)
 	@echo "" >> $@;
 #	Generated autoload-file must have an absolute path,
 #	$srcdir can be relative.
-	$(EMACS) -batch -l autoload \
+	$(EMACS) --batch $(AM_ELCFLAGS) $(ELCFLAGS) \
+		--load autoload \
 		--eval '(setq generated-autoload-file "'$(abs_builddir)/$@'")' \
 		--eval '(setq make-backup-files nil)' \
-		-f batch-update-autoloads $(srcdir)
+		--funcall batch-update-autoloads $(srcdir)
 
 # Generate bbdb-site.el here as pkgdatadir is only known at "make" time.
 # We protect the autoconf variables in the sed regular expressions
--- bbdb3-3.1.2.orig/lisp/bbdb-anniv.el
+++ bbdb3-3.1.2/lisp/bbdb-anniv.el
@@ -1,6 +1,6 @@
 ;;; bbdb-anniv.el --- get anniversaries from BBDB
 
-;; Copyright (C) 2011-2014 Roland Winkler <winkler@gnu.org>
+;; Copyright (C) 2011-2016 Roland Winkler <winkler@gnu.org>
 
 ;; This file is part of the Insidious Big Brother Database (aka BBDB),
 
@@ -33,6 +33,11 @@
 ;; call `bbdb-initialize' with arg `anniv'.
 ;;
 ;; See the BBDB info manual for documentation.
+;;
+;;; FIXME: As we rely on `diary-date-forms', this is not compatible
+;;; with lexical binding for this file.
+
+;;; Code:
 
 (require 'bbdb)
 (require 'bbdb-com)
@@ -54,7 +59,7 @@ If FORM is nil, use the text following t
 as format string."
   :type '(repeat (cons :tag "Rule"
                        (symbol :tag "Label")
-                       (choice (regexp)
+                       (choice (string)
                                (const nil))))
   :group 'bbdb-utilities-anniv)
 
@@ -167,3 +172,5 @@ To enable this feature, put the followin
                      ""))))))))))
 
 (provide 'bbdb-anniv)
+
+;;; bbdb-anniv.el ends here
--- bbdb3-3.1.2.orig/lisp/bbdb-com.el
+++ bbdb3-3.1.2/lisp/bbdb-com.el
@@ -1,7 +1,7 @@
-;;; bbdb-com.el --- user-level commands of BBDB
+;;; bbdb-com.el --- user-level commands of BBDB -*- lexical-binding: t -*-
 
 ;; Copyright (C) 1991, 1992, 1993 Jamie Zawinski <jwz@netscape.com>.
-;; Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+;; Copyright (C) 2010-2016 Roland Winkler <winkler@gnu.org>
 
 ;; This file is part of the Insidious Big Brother Database (aka BBDB),
 
@@ -22,6 +22,8 @@
 ;;; This file contains most of the user-level interactive commands for BBDB.
 ;;; See the BBDB info manual for documentation.
 
+;;; Code:
+
 (require 'bbdb)
 (require 'mailabbrev)
 
@@ -62,23 +64,33 @@ If FULL is non-nil, assume that RECORDS
         (if (vectorp records) (list records) records))))
 
 ;; Note about BBDB prefix commands:
-;; - `bbdb-do-all-records' behaves more like a proper prefix command
-;;   in the sense that it must immediately precede the main command.
-;;   YET: a simple M-x makes the prefix go away...
-;; - `bbdb-append-display' and `bbdb-search-invert' are fake prefix
-;;   commands. They need not precede the main commands.
-;;   Also, `bbdb-append-display' can act on multiple commands.
-;; FIXME: Make this more uniform and robust.
+;; `bbdb-do-all-records', `bbdb-append-display' and `bbdb-search-invert'
+;; are fake prefix commands. They need not precede the main commands.
+;; Also, `bbdb-append-display' can act on multiple commands.
+
+(defun bbdb-prefix-message ()
+  "Display a message about selected BBDB prefix commands."
+  (let ((msg (bbdb-concat " " (elt bbdb-modeline-info 1)
+                          (elt bbdb-modeline-info 3)
+                          (elt bbdb-modeline-info 5))))
+    (unless (string= "" msg) (message "%s" msg))))
 
 ;;;###autoload
-(defun bbdb-do-all-records ()
+(defun bbdb-do-all-records (&optional arg)
   "Command prefix for operating on all records currently displayed.
+With prefix ARG a positive number, operate on all records.
+With prefix ARG a negative number, operate on current record only.
 This only works for certain commands."
-  (interactive)
-  (message (substitute-command-keys
-            "\\<bbdb-mode-map>\\[bbdb-do-all-records]"))
-  (setq prefix-arg current-prefix-arg
-        last-command this-command))
+  (interactive "P")
+  (setq bbdb-do-all-records
+        (or (and (numberp arg) (< 0 arg))
+            (and (not (numberp arg)) (not bbdb-do-all-records))))
+  (aset bbdb-modeline-info 4 (if bbdb-do-all-records "all"))
+  (aset bbdb-modeline-info 5
+        (if bbdb-do-all-records
+            (substitute-command-keys
+             "\\<bbdb-mode-map>\\[bbdb-do-all-records]")))
+  (bbdb-prefix-message))
 
 ;;;###autoload
 (defun bbdb-do-records (&optional full)
@@ -87,8 +99,12 @@ Normally this list includes only the cur
 It includes all currently displayed records if the command prefix \
 \\<bbdb-mode-map>\\[bbdb-do-all-records] is used.
 If FULL is non-nil, the list of records includes display information."
-  (if (eq last-command 'bbdb-do-all-records)
-      (if full bbdb-records (mapcar 'car bbdb-records))
+  (if bbdb-do-all-records
+      (progn
+        (setq bbdb-do-all-records nil)
+        (aset bbdb-modeline-info 4 nil)
+        (aset bbdb-modeline-info 5 nil)
+        (if full bbdb-records (mapcar 'car bbdb-records)))
     (list (bbdb-current-record full))))
 
 ;;;###autoload
@@ -107,7 +123,8 @@ If FULL is non-nil, the list of records
            (aset bbdb-modeline-info 0
                  (format "(add %dx)" bbdb-append-display)))
           ((not bbdb-append-display)
-           (aset bbdb-modeline-info 0 nil)))
+           (aset bbdb-modeline-info 0 nil)
+           (aset bbdb-modeline-info 1 nil)))
     job))
 
 ;;;###autoload
@@ -128,13 +145,11 @@ With ARG a negative number do not append
               ((eq t bbdb-append-display) "Add")
               (bbdb-append-display "add")
               (t nil)))
-  (aset bbdb-modeline-info 2
+  (aset bbdb-modeline-info 1
         (if bbdb-append-display
             (substitute-command-keys
              "\\<bbdb-mode-map>\\[bbdb-append-display]")))
-  (let ((msg (bbdb-concat " " (elt bbdb-modeline-info 2)
-                          (elt bbdb-modeline-info 3))))
-    (unless (string= "" msg) (message "%s" msg))))
+  (bbdb-prefix-message))
 
 (defsubst bbdb-layout-prefix ()
   "Set the LAYOUT arg interactively using the prefix arg."
@@ -147,7 +162,7 @@ With ARG a negative number do not append
 To set it again, use command `bbdb-search-invert'."
   (let ((result bbdb-search-invert))
     (setq bbdb-search-invert nil)
-    (aset bbdb-modeline-info 1 nil)
+    (aset bbdb-modeline-info 2 nil)
     (aset bbdb-modeline-info 3 nil)
     result))
 
@@ -157,18 +172,14 @@ To set it again, use command `bbdb-searc
 With prefix ARG a positive number, invert next search.
 With prefix ARG a negative number, do not invert next search."
   (interactive "P")
-  (if (setq bbdb-search-invert
-            (or (and (numberp arg) (< 0 arg))
-                (and (not (numberp arg)) (not bbdb-search-invert))))
-      (progn
-        (aset bbdb-modeline-info 1 "inv")
-        (aset bbdb-modeline-info 3
-              (substitute-command-keys
-               "\\<bbdb-mode-map>\\[bbdb-search-invert]")))
-    (aset bbdb-modeline-info 1 nil)
-    (aset bbdb-modeline-info 3 nil))
-  (message "%s" (bbdb-concat " " (elt bbdb-modeline-info 2)
-                             (elt bbdb-modeline-info 3))))
+  (setq bbdb-search-invert
+        (or (and (numberp arg) (< 0 arg))
+            (and (not (numberp arg)) (not bbdb-search-invert))))
+  (aset bbdb-modeline-info 2 (if bbdb-search-invert "inv"))
+  (aset bbdb-modeline-info 3 (if bbdb-search-invert
+                                 (substitute-command-keys
+                                  "\\<bbdb-mode-map>\\[bbdb-search-invert]")))
+  (bbdb-prefix-message))
 
 (defmacro bbdb-search (records &optional name-re org-re mail-re xfield-re
                                phone-re address-re)
@@ -257,13 +268,14 @@ but not allowing for regexps."
         (push `(cond ((stringp ,xfield-re)
                       ;; check xfield `bbdb-default-xfield'
                       (string-match ,xfield-re
-                                    (or (bbdb-record-xfield record bbdb-default-xfield) "")))
+                                    (or (bbdb-record-xfield-string
+                                         record bbdb-default-xfield) "")))
                      ((eq (car ,xfield-re) '*)
                       ;; check all xfields
                       (let ((labels bbdb-xfield-label-list) done tmp)
                         (if (bbdb-record-xfields record)
                             (while (and (not done) labels)
-                              (setq tmp (bbdb-record-xfield record (car labels))
+                              (setq tmp (bbdb-record-xfield-string record (car labels))
                                     done (and tmp (string-match (cdr ,xfield-re)
                                                                 tmp))
                                     labels (cdr labels)))
@@ -273,7 +285,7 @@ but not allowing for regexps."
                         done))
                      (t ; check one field
                       (string-match (cdr ,xfield-re)
-                                    (or (bbdb-record-xfield
+                                    (or (bbdb-record-xfield-string
                                          record (car ,xfield-re)) ""))))
               clauses))
     `(let ((case-fold-search bbdb-case-fold-search)
@@ -352,8 +364,9 @@ in either the name(s), organization, add
 
 ;;;###autoload
 (defun bbdb-search-changed (&optional layout)
-  "Display all records in the bbdb database which have changed since
-the database was last saved."
+  ;; FIXME: "changes" in BBDB lingo are often called "modifications"
+  ;; in Emacs lingo
+  "Display records which have been changed since BBDB was last saved."
   (interactive (list (bbdb-layout-prefix)))
   (if (bbdb-search-invert-p)
       (let (unchanged-records)
@@ -485,7 +498,7 @@ The search results are displayed in the
 (defun bbdb-fix-records (records)
   "Fix broken RECORDS.
 Interactively, use BBDB prefix \
-\\<bbdb-mode-map>\\[bbdb-do-all-records], see `bbdb-do-all-records',"
+\\<bbdb-mode-map>\\[bbdb-do-all-records], see `bbdb-do-all-records'."
   (interactive (list (bbdb-do-records)))
   (bbdb-editable)
   (dolist (record (bbdb-record-list records))
@@ -497,7 +510,18 @@ Interactively, use BBDB prefix \
     (bbdb-record-set-field record 'organization (bbdb-record-organization record))
     (bbdb-record-set-field record 'aka (bbdb-record-aka record))
     (bbdb-record-set-field record 'mail (bbdb-record-mail record))
-    (bbdb-change-record record)))
+    (bbdb-change-record record))
+  (bbdb-sort-records))
+
+(defun bbdb-touch-records (records)
+  "Touch RECORDS by calling `bbdb-change-hook' unconditionally.
+Interactively, use BBDB prefix \
+\\<bbdb-mode-map>\\[bbdb-do-all-records], see `bbdb-do-all-records'."
+  (interactive (list (bbdb-do-records)))
+  (bbdb-editable)
+  (let ((bbdb-update-unchanged-records t))
+    (dolist (record (bbdb-record-list records))
+      (bbdb-change-record record))))
 
 ;;; Time-based functions
 
@@ -742,7 +766,7 @@ Return cons with first and last name."
 When called interactively read all relevant info.
 Do not call this from a program; call `bbdb-create-internal' instead."
   (interactive (list (bbdb-read-record current-prefix-arg)))
-  (bbdb-change-record record t t)
+  (bbdb-change-record record nil t)
   (bbdb-display-records (list record)))
 
 (defun bbdb-create-internal (&optional name affix aka organization mail
@@ -792,7 +816,7 @@ If CHECK is non-nil throw an error if an
      (vector firstname lastname affix aka organization phone
              address mail xfields
              (make-vector bbdb-cache-length nil))
-     t t)))
+     nil t)))
 
 ;;;###autoload
 (defun bbdb-insert-field (record field value)
@@ -862,20 +886,20 @@ A non-nil prefix arg is passed on to `bb
          (bbdb-record-set-field record 'aka value))
         ;; xfields
         ((assq field (bbdb-record-xfields record))
-         (error "xfield \"%s\" already exists" field))
+         (error "Xfield \"%s\" already exists" field))
         (t
          (bbdb-record-set-xfield record field value)))
-  (let (bbdb-layout)
-    (bbdb-change-record record)))
+  (unless (bbdb-change-record record)
+    (message "Record unchanged")))
 
 (defun bbdb-read-field (record field &optional flag)
-  "For RECORD read FIELD interactively.
-If inserting a new phone number, the phone number style
-is controlled via `bbdb-phone-style'.  A non-nil FLAG inverts the style,
-
-If inserting a new mail address lacking a domain, BBDB appends
-`bbdb-default-domain' if this variable non-nil.  With non-nil FLAG
-\(or `bbdb-default-domain' being nil) do not alter the mail address."
+  "For RECORD read new FIELD interactively.
+- The phone number style is controlled via `bbdb-phone-style'.
+  A prefix FLAG inverts the style,
+- If a mail address lacks a domain, append `bbdb-default-domain'
+  if this variable non-nil.  With prefix FLAG do not alter the mail address.
+- The value of an xfield is a string.  With prefix FLAG the value may be
+  any lisp object."
   (let* ((init-f (intern-soft (concat "bbdb-init-" (symbol-name field))))
          (init (if (and init-f (functionp init-f))
                    (funcall init-f record))))
@@ -918,7 +942,7 @@ If inserting a new mail address lacking
                (y-or-n-p
                 (format "\"%s\" is an unknown field name.  Define it? " field))
                (error "Aborted"))
-           (bbdb-read-xfield field init)))))
+           (bbdb-read-xfield field init flag)))))
 
 ;;;###autoload
 (defun bbdb-edit-field (record field &optional value flag)
@@ -927,7 +951,10 @@ If point is in the middle of a multi-lin
 then the entire field is edited, not just the current line.
 For editing phone numbers or addresses, VALUE must be the phone number
 or address that gets edited. An error is thrown when attempting to edit
-a phone number or address with VALUE being nil."
+a phone number or address with VALUE being nil.
+
+- The value of an xfield is a string.  With prefix FLAG the value may be
+  any lisp object."
   (interactive
    (save-excursion
      (bbdb-editable)
@@ -943,8 +970,7 @@ a phone number or address with VALUE bei
                  field ; not an xfield
                (elt value 0)) ; xfield
              value current-prefix-arg))))
-  ;; Some editing commands require re-sorting records
-  (let (bbdb-need-to-sort edit-str)
+  (let (edit-str)
     (cond ((memq field '(firstname lastname xfields))
            ;; FIXME: We could also edit first and last names.
            (error "Field `%s' not editable this way." field))
@@ -954,7 +980,7 @@ a phone number or address with VALUE bei
              record 'name
              (bbdb-read-name
               (if flag
-                  ;; Here we try to obey the name-format field for
+                  ;; Here we try to obey the name-format xfield for
                   ;; editing the name field.  Is this useful?  Or is this
                   ;; irritating overkill and we better obey consistently
                   ;; `bbdb-read-name-format'?
@@ -985,8 +1011,9 @@ a phone number or address with VALUE bei
           (t ; xfield
            (bbdb-record-set-xfield
             record field
-            (bbdb-read-xfield field (bbdb-record-xfield record field)))))
-    (bbdb-change-record record bbdb-need-to-sort)))
+            (bbdb-read-xfield field (bbdb-record-xfield record field) flag)))))
+  (unless (bbdb-change-record record)
+    (message "Record unchanged")))
 
 (defun bbdb-edit-foo (record field &optional nvalue)
   "For RECORD edit some FIELD (mostly interactively).
@@ -1071,13 +1098,16 @@ of FIELD is the cdr of this variable."
       (bbdb-insert-field record field
                          (bbdb-read-field record field)))))
 
-(defun bbdb-read-xfield (field &optional init)
+(defun bbdb-read-xfield (field &optional init sexp)
   "Read xfield FIELD with optional INIT.
 This calls bbdb-read-xfield-FIELD if it exists."
   (let ((read-fun (intern-soft (format "bbdb-read-xfield-%s" field))))
-    (if (fboundp read-fun)
-        (funcall read-fun init)
-      (bbdb-read-string (format "%s: " field) init))))
+    (cond ((fboundp read-fun)
+           (funcall read-fun init))
+          ((and (not sexp) (string-or-null-p init))
+           (bbdb-read-string (format "%s: " field) init))
+          (t (read-minibuffer (format "%s (sexp): " field)
+                              (prin1-to-string init))))))
 
 (defun bbdb-read-organization (&optional init)
   "Read organization."
@@ -1275,7 +1305,7 @@ irrespective of the value of ARG."
   (bbdb-editable)
   (let* ((ident (bbdb-ident-point))
          (record (and (car ident) (car (nth (car ident) bbdb-records))))
-         num1 num2 need-to-sort)
+         num1 num2)
     (cond ((not (car ident))
            (error "Point not in BBDB record"))
           ((not (nth 1 ident))
@@ -1283,8 +1313,7 @@ irrespective of the value of ARG."
           ((eq 'name (nth 1 ident))
            ;; Transpose firstname and lastname
            (bbdb-record-set-name record (bbdb-record-lastname record)
-                                 (bbdb-record-firstname record))
-           (setq need-to-sort t))
+                                 (bbdb-record-firstname record)))
           ((not (integerp arg))
            (error "Arg `%s' not an integer" arg))
           ((not (nth 2 ident))
@@ -1309,7 +1338,7 @@ irrespective of the value of ARG."
             record (nth 1 ident)
             (bbdb-list-transpose (bbdb-record-field record (nth 1 ident))
                                  num1 num2))))
-    (bbdb-change-record record need-to-sort)))
+    (bbdb-change-record record)))
 
 ;;;###autoload
 (defun bbdb-delete-field-or-record (records field &optional noprompt)
@@ -1342,8 +1371,11 @@ If prefix NOPROMPT is non-nil, do not co
           (cond ((memq type '(phone address))
                  (bbdb-record-set-field
                   record type
-                  (delq (nth 1 field)
-                        (bbdb-record-field record type))))
+                  ;; We use `delete' which deletes all phone and address
+                  ;; fields equal to the current one.  This works for
+                  ;; multiple records.
+                  (delete (nth 1 field)
+                          (bbdb-record-field record type))))
                 ((memq type '(affix organization mail aka))
                  (bbdb-record-set-field record type nil))
                 ((eq type 'xfields)
@@ -1459,12 +1491,15 @@ Interactively, use BBDB prefix \
   "Remove current record from the display without deleting it from BBDB.
 With prefix N, omit the next N records.  If negative, omit backwards."
   (interactive "p")
-  (while (not (= n 0))
-    (if (< n 0) (bbdb-prev-record 1))
-    (let ((record (bbdb-current-record t)))
-      (bbdb-redisplay-record (car record) t)
-      (setq bbdb-records (delete record bbdb-records)))
-    (setq n (if (> n 0) (1- n) (1+ n)))))
+  (let ((num  (get-text-property (if (and (not (bobp)) (eobp))
+                                     (1- (point)) (point))
+                                 'bbdb-record-number)))
+    (if (> n 0)
+        (setq n (min n (- (length bbdb-records) num)))
+      (setq n (min (- n) num))
+      (bbdb-prev-record n))
+    (dotimes (_i n)
+      (bbdb-redisplay-record (bbdb-current-record) nil t))))
 
 ;;; Fixing up bogus records
 
@@ -1556,7 +1591,7 @@ With prefix arg NEW-RECORD defaults to t
                          (bbdb-record-xfields old-record) t)
 
   (bbdb-delete-records (list old-record) 'noprompt)
-  (bbdb-change-record new-record t)
+  (bbdb-change-record new-record)
   new-record)
 
 ;; The following sorting functions are also intended for use
@@ -1805,21 +1840,18 @@ The primary mail of each of the records
 ;;; completion
 
 ;;;###autoload
-(defun bbdb-completion-predicate (symbol)
+(defun bbdb-completion-predicate (key records)
   "For use as the third argument to `completing-read'.
 Obey `bbdb-completion-list'."
   (cond ((null bbdb-completion-list)
          nil)
         ((eq t bbdb-completion-list)
          t)
-        ((not (boundp symbol))
-         nil) ; deleted (unhashed) record
         (t
-         (let ((key (symbol-name symbol)))
-           (catch 'bbdb-hash-ok
-             (dolist (record (symbol-value symbol))
-               (bbdb-hash-p key record bbdb-completion-list))
-             nil)))))
+         (catch 'bbdb-hash-ok
+           (dolist (record records)
+             (bbdb-hash-p key record bbdb-completion-list))
+           nil))))
 
 (defun bbdb-completing-read-records (prompt &optional omit-records)
   "Read and return list of records from the bbdb.
@@ -1827,15 +1859,13 @@ Completion is done according to `bbdb-co
 just hits return, nil is returned.  Otherwise, a valid response is forced."
   (let* ((completion-ignore-case t)
          (string (completing-read prompt bbdb-hashtable
-                                  'bbdb-completion-predicate t))
-         symbol ret)
-  (unless (string= "" string)
-    (setq symbol (intern-soft string bbdb-hashtable))
-    (if (and (boundp symbol) (symbol-value symbol))
-        (dolist (record (symbol-value symbol) (delete-dups ret))
+                                  'bbdb-completion-predicate t)))
+    (unless (string= "" string)
+      (let (records)
+        (dolist (record (gethash string bbdb-hashtable))
           (if (not (memq record omit-records))
-              (push record ret)))
-      (error "Selecting deleted (unhashed) record \"%s\"" symbol)))))
+              (push record records)))
+        (delete-dups records)))))
 
 (defun bbdb-completing-read-record (prompt &optional omit-records)
   "Prompt for and return a single record from the bbdb;
@@ -1963,17 +1993,14 @@ as part of the MUA insinuation."
                (string-match "," completion))
           (setq completion (substring completion 0 (match-beginning 0))))
 
-      ;; We cannot use the return value of the function `all-completions'
-      ;; to set the variable `all-completions' because this function
-      ;; converts all symbols into strings
-      (all-completions orig bbdb-hashtable
-                       (lambda (sym)
-                         (if (bbdb-completion-predicate sym)
-                             (push sym all-completions))))
+      (setq all-completions (all-completions orig bbdb-hashtable
+                                             'bbdb-completion-predicate))
       ;; Resolve the records matching ORIG:
       ;; Multiple completions may match the same record
       (let ((records (delete-dups
-                      (apply 'append (mapcar 'symbol-value all-completions)))))
+                      (apply 'append (mapcar (lambda (compl)
+                                               (gethash compl bbdb-hashtable))
+                                             all-completions)))))
         ;; Is there only one matching record?
         (setq one-record (and (not (cdr records))
                               (car records))))
@@ -2048,38 +2075,36 @@ as part of the MUA insinuation."
        (completion
         (let ((completion-list (if (eq t bbdb-completion-list)
                                    '(fl-name lf-name mail aka organization)
-                                 bbdb-completion-list))
-              sname)
+                                 bbdb-completion-list)))
           ;; Now collect all the dwim-addresses for each completion.
           ;; Add it if the mail is part of the completions
-          (dolist (sym all-completions)
-            (setq sname (symbol-name sym))
-            (dolist (record (symbol-value sym))
+          (dolist (key all-completions)
+            (dolist (record (gethash key bbdb-hashtable))
               (let ((mails (bbdb-record-mail record))
                     accept)
                 (when mails
                   (dolist (field completion-list)
                     (cond ((eq field 'fl-name)
-                           (if (bbdb-string= sname (bbdb-record-name record))
+                           (if (bbdb-string= key (bbdb-record-name record))
                                (push (car mails) accept)))
                           ((eq field 'lf-name)
-                           (if (bbdb-string= sname (bbdb-cache-lf-name
-                                                    (bbdb-record-cache record)))
+                           (if (bbdb-string= key (bbdb-cache-lf-name
+                                                  (bbdb-record-cache record)))
                                (push (car mails) accept)))
                           ((eq field 'aka)
-                           (if (member-ignore-case sname (bbdb-record-field
-                                                          record 'aka-all))
+                           (if (member-ignore-case key (bbdb-record-field
+                                                        record 'aka-all))
                                (push (car mails) accept)))
                           ((eq field 'organization)
-                           (if (member-ignore-case sname (bbdb-record-organization
-                                                          record))
+                           (if (member-ignore-case key (bbdb-record-organization
+                                                        record))
                                (push (car mails) accept)))
                           ((eq field 'primary)
-                           (if (bbdb-string= sname (car mails))
+                           (if (bbdb-string= key (car mails))
                                (push (car mails) accept)))
                           ((eq field 'mail)
                            (dolist (mail mails)
-                             (if (bbdb-string= sname mail)
+                             (if (bbdb-string= key mail)
                                  (push mail accept))))))
                   (dolist (mail (delete-dups accept))
                     (push (bbdb-dwim-mail record mail) dwim-completions))))))
@@ -2312,7 +2337,7 @@ Rebuilding the aliases is enforced if pr
                    (setq alias (format "%s%s" aliasstem count))))
             (setq count (1+ count))
 
-            (add-to-list 'mail-aliases (cons alias expansion))
+            (bbdb-pushnew (cons alias expansion) mail-aliases)
 
             (define-mail-abbrev alias expansion)
             (unless (setq f-alias (intern-soft (downcase alias) mail-abbrevs))
@@ -2364,46 +2389,67 @@ Rebuilding the aliases is enforced if pr
   (let ((records (bbdb-search (bbdb-records) nil nil nil
                               (cons bbdb-mail-alias-field ".")))
         result)
-    (dolist (record records result)
+    (dolist (record records)
       (dolist (alias (bbdb-record-xfield-split record bbdb-mail-alias-field))
-        (add-to-list 'result alias)))))
+        (bbdb-pushnew alias result)))
+    result))
 
 ;;;###autoload
-(defun bbdb-add-mail-alias (record &optional alias delete)
-  "Add ALIAS to RECORD.
-If pefix DELETE is non-nil, remove ALIAS from RECORD."
-  (interactive
-   (let* ((_ (bbdb-editable))
-          (record (bbdb-current-record))
-          (init-f (concat "bbdb-init-" (symbol-name bbdb-mail-alias-field)))
-          (init (if (and (setq init-f (intern-soft init-f))
-                         (functionp init-f))
-                    (funcall init-f record))))
-     (list record
-           (completing-read
-            (format "%s mail alias: "
-                    (if current-prefix-arg "Remove" "Add"))
-            (if current-prefix-arg
-                (or (bbdb-record-xfield-split record bbdb-mail-alias-field)
-                    (error "Record has no alias"))
-              (bbdb-get-mail-aliases))
-            nil nil init) current-prefix-arg)))
-  (setq alias (bbdb-string-trim alias))
-  (unless (string= "" alias)
-    (let ((aliases (bbdb-record-xfield-split record bbdb-mail-alias-field)))
-      (if delete
-          (setq aliases (delete alias aliases))
-        ;; Add alias only if it is not there yet
-        (add-to-list 'aliases alias))
-      (setq aliases (bbdb-concat bbdb-mail-alias-field aliases))
-      (bbdb-record-set-xfield record bbdb-mail-alias-field aliases))
-    (bbdb-change-record record)
-    ;; Rebuilt mail aliases
-    (setq bbdb-mail-aliases-need-rebuilt
+(defsubst bbdb-mail-alias-list (alias)
+  (if (stringp alias)
+      (bbdb-split bbdb-mail-alias-field alias)
+    alias))
+
+(defun bbdb-add-mail-alias (records &optional alias delete)
+  "Add ALIAS to RECORDS.
+If prefix DELETE is non-nil, remove ALIAS from RECORDS.
+Interactively, use BBDB prefix \
+\\<bbdb-mode-map>\\[bbdb-do-all-records], see `bbdb-do-all-records'.
+Arg ALIAS is ignored if list RECORDS contains more than one record.
+Instead read ALIAS interactively for each record in RECORDS.
+If the function `bbdb-init-mail-alias' is defined, it is called with
+one arg RECORD to define the default value for ALIAS of RECORD."
+  (interactive (list (bbdb-do-records) nil current-prefix-arg))
+  (bbdb-editable)
+  (setq records (bbdb-record-list records))
+  (if (< 1 (length records)) (setq alias nil))
+  (let* ((tmp (intern-soft
+               (concat "bbdb-init-" (symbol-name bbdb-mail-alias-field))))
+         (init-f (if (functionp tmp) tmp)))
+    (dolist (record records)
+      (let ((r-a-list (bbdb-record-xfield-split record bbdb-mail-alias-field))
+            (alias alias)
+            a-list)
+        (if alias
+            (setq a-list (bbdb-mail-alias-list alias))
+          (when init-f
+            (setq a-list (bbdb-mail-alias-list (funcall init-f record))
+                  alias (if a-list (bbdb-concat bbdb-mail-alias-field a-list))))
+          (let ((crm-separator
+                 (concat "[ \t\n]*"
+                         (cadr (assq bbdb-mail-alias-field bbdb-separator-alist))
+                         "[ \t\n]*"))
+                (crm-local-completion-map bbdb-crm-local-completion-map)
+                (prompt (format "%s mail alias:%s " (if delete "Remove" "Add")
+                                (if alias (format " (default %s)" alias) "")))
+                (collection (if delete
+                                (or r-a-list (error "Record has no alias"))
+                              (bbdb-get-mail-aliases))))
+            (setq a-list (if (string< "24.3" (substring emacs-version 0 4))
+                             (completing-read-multiple prompt collection nil
+                                                       delete nil nil alias)
+                          (bbdb-split bbdb-mail-alias-field
+                                      (completing-read prompt collection nil
+                                                       delete nil nil alias))))))
+        (dolist (a a-list)
           (if delete
-              'deleted
-            (if (bbdb-record-mail record)
-                'new)))))
+              (setq r-a-list (delete a r-a-list))
+            ;; Add alias only if it is not there yet
+            (bbdb-pushnew a r-a-list)))
+        ;; This also handles `bbdb-mail-aliases-need-rebuilt'
+        (bbdb-record-set-xfield record bbdb-mail-alias-field
+                                (bbdb-concat bbdb-mail-alias-field r-a-list))
+        (bbdb-change-record record)))))
 
 ;;; Dialing numbers from BBDB
 
@@ -2499,11 +2545,11 @@ Default is the first URL."
 
 ;;;###autoload
 (defun bbdb-copy-records-as-kill (records)
-  "Copy displayed RECORDS to kill ring.
+  "Copy RECORDS to kill ring.
 Interactively, use BBDB prefix \
 \\<bbdb-mode-map>\\[bbdb-do-all-records], see `bbdb-do-all-records'."
   (interactive (list (bbdb-do-records t)))
-  (let (drec marker)
+  (let (drec)
     (dolist (record (bbdb-record-list records t))
       (push (buffer-substring (nth 2 record)
                               (or (nth 2 (car (cdr (memq record bbdb-records))))
@@ -2513,6 +2559,56 @@ Interactively, use BBDB prefix \
                "[ \t\n]*\\'" "\n"
                (mapconcat 'identity (nreverse drec) "")))))
 
+;;;###autoload
+(defun bbdb-copy-fields-as-kill (records field &optional num)
+  "For RECORDS copy values of FIELD at point to kill ring.
+If FIELD is an address or phone with a label, copy only field values
+with the same label.  With numeric prefix NUM, if the value of FIELD
+is a list, copy only the NUMth list element.
+Interactively, use BBDB prefix \
+\\<bbdb-mode-map>\\[bbdb-do-all-records], see `bbdb-do-all-records'."
+  (interactive
+   (list (bbdb-do-records t) (bbdb-current-field)
+         (and current-prefix-arg
+              (prefix-numeric-value current-prefix-arg))))
+  (unless field (error "Not a field"))
+  (let* ((type (if (eq (car field) 'xfields)
+                   (car (nth 1 field))
+                 (car field)))
+         (label (if (memq type '(phone address))
+                    (aref (cadr field) 0)))
+	 (ident (and (< 1 (length records))
+                     (not (eq type 'name))))
+	 val-list)
+    (dolist (record (bbdb-record-list records))
+      (let ((raw-val (bbdb-record-field (car record) type))
+            value)
+        (if raw-val
+            (cond ((eq type 'phone)
+                   (dolist (elt raw-val)
+                     (if (equal label (aref elt 0))
+                         (push (bbdb-phone-string elt) value)))
+                   (setq value (bbdb-concat 'phone (nreverse value))))
+                  ((eq type 'address)
+                   (dolist (elt raw-val)
+                     (if (equal label (aref elt 0))
+                         (push (bbdb-format-address
+                                elt (if (eq (nth 1 record) 'one-line) 3 2))
+                               value)))
+                   (setq value (bbdb-concat 'address (nreverse value))))
+                  ((consp raw-val)
+                   (setq value (if num (nth num raw-val)
+                                 (bbdb-concat type raw-val))))
+                  (t (setq value raw-val))))
+        (if value
+            (push (if ident
+                      (bbdb-concat 'name-field
+                                   (bbdb-record-name (car record)) value)
+                    value) val-list))))
+    (let ((str (bbdb-concat 'record (nreverse val-list))))
+      (kill-new str)
+      (message "%s" str))))
+
 ;;; Help and documentation
 
 ;;;###autoload
@@ -2531,3 +2627,5 @@ mode help: \\[describe-mode]; \
 info: \\[bbdb-info]")))
 
 (provide 'bbdb-com)
+
+;;; bbdb-com.el ends here
--- bbdb3-3.1.2.orig/lisp/bbdb-gnus.el
+++ bbdb3-3.1.2/lisp/bbdb-gnus.el
@@ -1,7 +1,7 @@
-;;; bbdb-gnus.el --- BBDB interface to Gnus
+;;; bbdb-gnus.el --- BBDB interface to Gnus -*- lexical-binding: t -*-
 
 ;; Copyright (C) 1991, 1992, 1993 Jamie Zawinski <jwz@netscape.com>.
-;; Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+;; Copyright (C) 2010-2016 Roland Winkler <winkler@gnu.org>
 
 ;; This file is part of the Insidious Big Brother Database (aka BBDB),
 
@@ -22,54 +22,17 @@
 ;;; This file contains the BBDB interface to Gnus.
 ;;; See the BBDB info manual for documentation.
 
+;;; Code:
+
 (require 'bbdb)
 (require 'bbdb-com)
 (require 'bbdb-mua)
 (require 'gnus)
 
-(defcustom bbdb/gnus-update-records-p
-  (lambda () (let ((bbdb-update-records-p 'query))
-               (bbdb-select-message)))
-  "How `bbdb-mua-update-records' processes mail addresses in Gnus.
-This Gnus-specific variable is normally not used.  It is a fallback
-if the generic (MUA-independent) variables `bbdb-mua-auto-update-p',
-`bbdb-update-records-p' or `bbdb-mua-update-interactive-p' result
-in a value of nil for the arg UPDATE-P of `bbdb-update-records'.
-
-Allowed values are:
- nil          Do nothing.
- search       Search for existing records.
- update       Search for existing records, update if necessary.
- query        Update existing records or query for creating new ones.
- create or t  Update existing records or create new ones.
- a function   This functions will be called with no arguments.
-                It should return one of the above values."
-  :group 'bbdb-mua-gnus
-  :type '(choice (const :tag "do nothing" nil)
-                 (const :tag "search for existing records"
-                        (lambda () (let ((bbdb-update-records-p 'search))
-                                     (bbdb-select-message))))
-                 (const :tag "update existing records"
-                        (lambda () (let ((bbdb-update-records-p 'update))
-                                     (bbdb-select-message))))
-                 (const :tag "query annotation of all messages"
-                        (lambda () (let ((bbdb-update-records-p 'query))
-                                     (bbdb-select-message))))
-                 (const :tag "annotate (query) only new messages"
-                        (if (equal "" (gnus-summary-article-mark
-                                       (gnus-summary-article-number)))
-                            (bbdb-select-message) 'search))
-                 (const :tag "annotate all messages"
-                        (lambda () (let ((bbdb-update-records-p 'create))
-                                     (bbdb-select-message))))
-                 (const :tag "accept messages" bbdb-accept-message)
-                 (const :tag "ignore messages" bbdb-ignore-message)
-                 (const :tag "select messages" bbdb-select-message)
-                 (sexp  :tag "user defined")))
+(eval-and-compile
+  (autoload 'message-make-domain "message"))
 
-;;
 ;; Scoring
-;;
 
 (defcustom bbdb/gnus-score-field 'gnus-score
   "This variable contains the name of the BBDB field which should be
@@ -82,7 +45,7 @@ checked for a score to add to the mail a
 an associated score field will be assigned this score.  A value of nil
 implies a default score of zero."
   :group 'bbdb-mua-gnus-scoring
-  :type '(choice (const :tag "Do not assign default score")
+  :type '(choice (const :tag "Do not assign default score" nil)
                  (integer :tag "Assign this default score" 0)))
 
 (defvar bbdb/gnus-score-default-internal nil
@@ -121,7 +84,7 @@ addresses better than the traditionally
                   (ding) (sit-for 2)
                   nil)))))
 
-(defun bbdb/gnus-score-as-text (group)
+(defun bbdb/gnus-score-as-text (_group)
   "Returns a SCORE file format string built from the BBDB."
   (cond ((or (cond ((/= (or bbdb/gnus-score-default 0)
                         (or bbdb/gnus-score-default-internal 0))
@@ -213,7 +176,7 @@ excellent choice."
   "This regular expression should match your address as found in the
 From header of your mail."
   :group 'bbdb-mua-gnus-splitting
-  :type  'string)
+  :type  'regexp)
 
 (defcustom bbdb/gnus-split-crosspost-default nil
   "If this variable is not nil, then if the BBDB could not identify a
@@ -228,7 +191,7 @@ identified."
 associated group when saving private mail for a mail address known to
 the BBDB.  The value of the xfield should be the name of a mail group."
   :group 'bbdb-mua-gnus-splitting
-  :type  'string)
+  :type  'symbol)
 
 (defcustom bbdb/gnus-split-public-field 'gnus-public
   "This variable is used to determine the xfield to reference to find the
@@ -238,7 +201,7 @@ should be the name of a mail group, foll
 expression to match on the envelope sender to verify that this mail came
 from the list in question."
   :group 'bbdb-mua-gnus-splitting
-  :type  'string)
+  :type  'symbol)
 
 ;; The split function works by assigning one of four spooling priorities
 ;; to each group that is associated with an address in the message.  The
@@ -434,3 +397,5 @@ Do not call this in your init file.  Use
   ;;    'bbdb/gnus-score))
 
 (provide 'bbdb-gnus)
+
+;;; bbdb-gnus.el ends here
--- bbdb3-3.1.2.orig/lisp/bbdb-ispell.el
+++ bbdb3-3.1.2/lisp/bbdb-ispell.el
@@ -1,7 +1,7 @@
-;;; bbdb-ispell.el --- export names from BBDB to personal ispell dictionaries
+;;; bbdb-ispell.el --- export names from BBDB to personal ispell dictionaries -*- lexical-binding: t -*-
 
 ;; Copyright (C) 2011-2013 Ivan Kanis <ivan.kanis@googlemail.com>
-;; Copyright (C) 2011-2014 Roland Winkler <winkler@gnu.org>
+;; Copyright (C) 2011-2016 Roland Winkler <winkler@gnu.org>
 
 ;; Author: Ivan Kanis <ivan.kanis@googlemail.com>
 
@@ -124,3 +124,5 @@ Allowed elements are as in the return va
         ((sequencep field) (mapc 'bbdb-ispell-collect-words field))))
 
 (provide 'bbdb-ispell)
+
+;;; bbdb-ispell.el ends here
--- bbdb3-3.1.2.orig/lisp/bbdb-message.el
+++ bbdb3-3.1.2/lisp/bbdb-message.el
@@ -1,6 +1,6 @@
-;;; bbdb-message.el --- BBDB interface to Mail Composition Packages.
+;;; bbdb-message.el --- BBDB interface to Mail Composition Packages. -*- lexical-binding: t -*-
 
-;; Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+;; Copyright (C) 2010-2016 Roland Winkler <winkler@gnu.org>
 
 ;; This file is part of the Insidious Big Brother Database (aka BBDB),
 
@@ -21,48 +21,12 @@
 ;;; This file contains the BBDB interface to Mail Composition Packages.
 ;;; See the BBDB info manual for documentation.
 
+;;; Code:
+
 (require 'bbdb)
 (require 'message)
 (require 'sendmail)
 
-(defcustom bbdb/message-update-records-p 'bbdb-select-message
-  "How `bbdb-mua-update-records' processes mail addresses in outgoing messages.
-This MUA-specific variable is normally not used.  It is a fallback
-if the generic (MUA-independent) variables `bbdb-mua-auto-update-p',
-`bbdb-update-records-p' or `bbdb-mua-update-interactive-p' result
-in a value of nil for the arg UPDATE-P of `bbdb-update-records'.
-
-Allowed values are:
- nil          Do nothing.
- search       Search for existing records.
- update       Search for existing records, update if necessary.
- query        Update existing records or query for creating new ones.
- create or t  Update existing records or create new ones.
- a function   This functions will be called with no arguments.
-                It should return one of the above values."
-  :group 'bbdb-mua-message
-  :type '(choice (const :tag "do nothing"
-                        nil)
-                 (const :tag "search for existing records"
-                        (lambda () (let ((bbdb-update-records-p 'search))
-                                     (bbdb-select-message))))
-                 (const :tag "update existing records"
-                        (lambda () (let ((bbdb-update-records-p 'update))
-                                     (bbdb-select-message))))
-                 (const :tag "query annotation of all messages"
-                        (lambda () (let ((bbdb-update-records-p 'query))
-                                     (bbdb-select-message))))
-                 (const :tag "annotate all messages"
-                        (lambda () (let ((bbdb-update-records-p 'create))
-                                     (bbdb-select-message))))
-                 (const :tag "accept messages" bbdb-accept-message)
-                 (const :tag "ignore messages" bbdb-ignore-message)
-                 (const :tag "select messages" bbdb-select-message)
-                 (sexp  :tag "user defined function")))
-(defvaralias 'bbdb/mail-update-records-p 'bbdb/message-update-records-p)
-
-
-
 ;;;###autoload
 (defun bbdb-insinuate-message ()
   "Hook BBDB into Message Mode.
@@ -88,3 +52,5 @@ Do not call this in your init file.  Use
       (define-key mail-mode-map "\M-\t" 'bbdb-complete-mail)))
 
 (provide 'bbdb-message)
+
+;;; bbdb-message.el ends here
--- bbdb3-3.1.2.orig/lisp/bbdb-mhe.el
+++ bbdb3-3.1.2/lisp/bbdb-mhe.el
@@ -1,9 +1,9 @@
-;;; bbdb-mhe.el --- BBDB interface to mh-e
+;;; bbdb-mhe.el --- BBDB interface to mh-e -*- lexical-binding: t -*-
 
 ;; Copyright (C) 1991 Todd Kaufmann <toad@cs.cmu.edu>
 ;; Modified: 28-Jul-94 by Fritz Knabe <knabe@ecrc.de>
 ;;                        Jack Repenning <jackr@dblues.wpd.sgi.com>
-;; Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+;; Copyright (C) 2010-2016 Roland Winkler <winkler@gnu.org>
 
 ;; This file is part of the Insidious Big Brother Database (aka BBDB),
 
@@ -24,6 +24,8 @@
 ;;; This file contains the BBDB interface to mh-e.
 ;;; See the BBDB info manual for documentation.
 
+;;; Code:
+
 (require 'bbdb)
 (require 'bbdb-com)
 (require 'bbdb-mua)
@@ -32,46 +34,6 @@
     (require 'mh-comp))              ; For mh-e 4.x
 (require 'advice)
 
-(defcustom bbdb/mh-update-records-p
-  (lambda () (let ((bbdb-update-records-p 'query))
-               (bbdb-select-message)))
-  "How `bbdb-mua-update-records' processes mail addresses in MH-E.
-This MH-E-specific variable is normally not used.  It is a fallback
-if the generic (MUA-independent) variables `bbdb-mua-auto-update-p',
-`bbdb-update-records-p' or `bbdb-mua-update-interactive-p' result
-in a value of nil for the arg UPDATE-P of `bbdb-update-records'.
-
-Allowed values are:
- nil          Do nothing.
- search       Search for existing records.
- update       Search for existing records, update if necessary.
- query        Update existing records or query for creating new ones.
- create or t  Update existing records or create new ones.
- a function   This functions will be called with no arguments.
-                It should return one of the above values."
-  :group 'bbdb-mua-gnus
-  :type '(choice (const :tag "do nothing" nil)
-                 (const :tag "search for existing records"
-                        (lambda () (let ((bbdb-update-records-p 'search))
-                                     (bbdb-select-message))))
-                 (const :tag "update existing records"
-                        (lambda () (let ((bbdb-update-records-p 'update))
-                                     (bbdb-select-message))))
-                 (const :tag "query annotation of all messages"
-                        (lambda () (let ((bbdb-update-records-p 'query))
-                                     (bbdb-select-message))))
-                 (const :tag "annotate (query) only new messages"
-                        (if (equal "" (gnus-summary-article-mark
-                                       (gnus-summary-article-number)))
-                            (bbdb-select-message) 'search))
-                 (const :tag "annotate all messages"
-                        (lambda () (let ((bbdb-update-records-p 'create))
-                                     (bbdb-select-message))))
-                 (const :tag "accept messages" bbdb-accept-message)
-                 (const :tag "ignore messages" bbdb-ignore-message)
-                 (const :tag "select messages" bbdb-select-message)
-                 (sexp  :tag "user defined")))
-
 ;; A simplified `mail-fetch-field'.  We could use instead (like rmail):
 ;; (mail-header (intern-soft (downcase header)) (mail-header-extract))
 (defun bbdb/mh-header (header)
@@ -136,3 +98,5 @@ Do not call this in your init file.  Use
       (define-key mh-letter-mode-map "\e\t" 'bbdb-complete-mail)))
 
 (provide 'bbdb-mhe)
+
+;;; bbdb-mhe.el ends here
--- bbdb3-3.1.2.orig/lisp/bbdb-migrate.el
+++ bbdb3-3.1.2/lisp/bbdb-migrate.el
@@ -1,7 +1,7 @@
-;;; bbdb-migrate.el --- migration functions for BBDB
+;;; bbdb-migrate.el --- migration functions for BBDB -*- lexical-binding: t -*-
 
 ;; Copyright (C) 1991, 1992, 1993, 1994 Jamie Zawinski <jwz@netscape.com>.
-;; Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+;; Copyright (C) 2010-2016 Roland Winkler <winkler@gnu.org>
 
 ;; This file is part of the Insidious Big Brother Database (aka BBDB),
 
@@ -22,6 +22,8 @@
 ;;; This file contains the migration functions for BBDB.
 ;;; See the BBDB info manual for documentation.
 
+;;; Code:
+
 (require 'bbdb)
 
 ;;; Migrating the BBDB
@@ -285,8 +287,10 @@ for outdated BBDB variables that are set
     (if message
         (if list
             (apply 'message (concat "Undocumented variables: "
-                                    (mapconcat (lambda (m) "%s") list " ")) list)
+                                    (mapconcat (lambda (_m) "%s") list " ")) list)
           (message "No undocumented variables `%s...'" name-space)))
     list))
 
 (provide 'bbdb-migrate)
+
+;;; bbdb-migrate.el ends here
--- /dev/null
+++ bbdb3-3.1.2/lisp/bbdb-mu4e.el
@@ -0,0 +1,43 @@
+;;; bbdb-mu4e.el --- BBDB interface to mu4e -*- lexical-binding: t -*-
+
+;; Copyright (C) 2015 David Sterratt <david@sterratt.me.uk>
+;; Copyright (C) 2015-2016 Roland Winkler <winkler@gnu.org>
+
+;; This file is part of the Insidious Big Brother Database (aka BBDB),
+
+;; BBDB is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; BBDB is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with BBDB.  If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;;; This file contains the BBDB interface to mu4e.
+;;; See the BBDB info manual for documentation.
+
+;;; Code:
+
+(require 'bbdb)
+(require 'mu4e-view)
+
+;;;###autoload
+(defun bbdb-insinuate-mu4e ()
+  "Hook BBDB into mu4e.
+Do not call this in your init file.  Use `bbdb-initialize'."
+  ;; Tackle headers later
+  ;; (define-key mu4e-headers-mode-map ":" 'bbdb-mua-display-sender)
+  ;; (define-key mu4e-headers-mode-map ";" 'bbdb-mua-edit-field-sender)
+  ;; Do we need keybindings for more commands?  Suggestions welcome.
+  (define-key mu4e-view-mode-map ":" 'bbdb-mua-display-sender)
+  (define-key mu4e-view-mode-map ";" 'bbdb-mua-edit-field-sender))
+
+(provide 'bbdb-mu4e)
+
+;;; bbdb-mu4e.el ends here
--- bbdb3-3.1.2.orig/lisp/bbdb-mua.el
+++ bbdb3-3.1.2/lisp/bbdb-mua.el
@@ -1,7 +1,7 @@
-;;; bbdb-mua.el --- various MUA functionality for BBDB
+;;; bbdb-mua.el --- various MUA functionality for BBDB -*- lexical-binding: t -*-
 
 ;; Copyright (C) 1991, 1992, 1993 Jamie Zawinski <jwz@netscape.com>.
-;; Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+;; Copyright (C) 2010-2016 Roland Winkler <winkler@gnu.org>
 
 ;; This file is part of the Insidious Big Brother Database (aka BBDB),
 
@@ -33,6 +33,8 @@
 ;;;
 ;;; Read the docstrings; read the texinfo file.
 
+;;; Code:
+
 (require 'bbdb)
 (require 'bbdb-com)
 
@@ -54,6 +56,10 @@
   (autoload 'mh-show "mh-show")
   (defvar mh-show-buffer)
 
+  (defvar mu4e~view-buffer-name)
+
+  (autoload 'bbdb/wl-header "bbdb-wl")
+
   (autoload 'message-field-value "message")
   (autoload 'mail-decode-encoded-word-string "mail-parse"))
 
@@ -62,7 +68,9 @@
     (gnus gnus-summary-mode gnus-article-mode gnus-tree-mode)
     (rmail rmail-mode rmail-summary-mode)
     (mh mhe-mode mhe-summary-mode mh-folder-mode)
-    (message message-mode)
+    (mu4e mu4e-view-mode)  ; Tackle `mu4e-headers-mode' later
+    (wl wl-summary-mode wl-draft-mode)
+    (message message-mode mu4e-compose-mode notmuch-message-mode)
     (mail mail-mode))
   "Alist of MUA modes supported by BBDB.
 Each element is of the form (MUA MODE MODE ...), where MODEs are used by MUA.")
@@ -74,6 +82,8 @@ Return values include
   rmail     Reading Mail in Emacs
   vm        Viewmail
   mh        Emacs interface to the MH mail system (aka MH-E)
+  mu4e      Mu4e
+  wl        Wanderlust
   message   Mail and News composition mode that goes with Gnus
   mail      Emacs Mail Mode."
   (let ((mm-alist bbdb-mua-mode-alist)
@@ -108,6 +118,8 @@ MIME encoded headers are decoded.  Retur
                     ((eq mua 'vm) (bbdb/vm-header header))
                     ((eq mua 'rmail) (bbdb/rmail-header header))
                     ((eq mua 'mh) (bbdb/mh-header header))
+                    ((eq mua 'mu4e) (message-field-value header))
+                    ((eq mua 'wl) (bbdb/wl-header header))
                     ((memq mua '(message mail)) (message-field-value header))
                     (t (error "BBDB/%s: header function undefined" mua)))))
     (if val (mail-decode-encoded-word-string val))))
@@ -169,7 +181,7 @@ is ignored. If IGNORE-ADDRESS is nil, us
                            bbdb-message-headers))
         (mua (bbdb-mua))
         (ignore-address (or ignore-address bbdb-user-mail-address-re))
-        address-list address name mail mail-list content)
+        address-list name mail mail-list content)
     (dolist (headers message-headers)
       (dolist (header (cdr headers))
         (when (setq content (bbdb-message-header header))
@@ -212,11 +224,9 @@ UPDATE-P may take the following values:
                 query for creation of a new record if the record does not exist.
  create or t  Search for existing records matching ADDRESS;
                 create a new record if it does not yet exist.
+ nil          Do nothing.
  a function   This functions will be called with no arguments.
                 It should return one of the above values.
- nil          Take the MUA-specific variable `bbdb/MUA-update-records-p'
-                which may take one of the above values.
-                If this still gives nil, `bbdb-update-records' returns nil.
 
 If SORT is non-nil, sort records according to `bbdb-record-lessp'.
 Ottherwise, the records are ordered according to ADDRESS-LIST.
@@ -228,19 +238,10 @@ Usually this function is called by the w
   ;; We resolve UPDATE-P repeatedly.  This is needed, for example,
   ;; with the chain `bbdb-mua-auto-update-p' -> `bbdb-select-message'
   ;; -> `bbdb-update-records-p'.
-  (let (done fallback)
-    (while (not done)
-      (cond ((and (functionp update-p)
-                  ;; Bad! `search' is a function in `cl-seq.el'.
-                  (not (eq update-p 'search)))
-             (setq update-p (funcall update-p)))
-            ((not (or update-p fallback))
-             ;; The fallback is applied at most once.
-             (setq update-p (symbol-value
-                             (intern-soft (format "bbdb/%s-update-records-p"
-                                                  (bbdb-mua))))
-                   fallback t))
-            ((setq done t)))))
+  (while (and (functionp update-p)
+              ;; Bad! `search' is a function in `cl-seq.el'.
+              (not (eq update-p 'search)))
+    (setq update-p (funcall update-p)))
   (cond ((eq t update-p)
          (setq update-p 'create))
         ((not (memq update-p '(search update query create nil)))
@@ -283,8 +284,7 @@ Usually this function is called by the w
                  (setq address-list nil))
                 ((not (eq task 'next))
                  (dolist (hit (delq nil (nreverse hits)))
-                   ;; people should be listed only once so we use `add-to-list'
-                   (add-to-list 'records hit))))
+                   (bbdb-pushnew hit records))))
           (if (and records (not bbdb-message-all-addresses))
               (setq address-list nil))))
       (setq records
@@ -298,9 +298,8 @@ Usually this function is called by the w
 
     (unless bbdb-read-only
       (bbdb-editable)
-      (let ((bbdb-notice-hook-pending t))
-        (dolist (record records)
-          (run-hook-with-args 'bbdb-notice-record-hook record))))
+      (dolist (record records)
+        (run-hook-with-args 'bbdb-notice-record-hook record)))
 
     records))
 
@@ -446,7 +445,7 @@ Return the records matching ADDRESS or n
                       record 'aka (cons old-name (bbdb-record-aka record)))
                    (bbdb-remhash old-name record)))
                (bbdb-record-set-field record 'name (cons fname lname))
-               (setq change-p 'sort))
+               (setq change-p 'name))
 
               ;; make new name an AKA?
               ((and old-name
@@ -456,7 +455,7 @@ Return the records matching ADDRESS or n
                                             name old-name)))
                (bbdb-record-set-field
                 record 'aka (cons name (bbdb-record-aka record)))
-               (setq change-p 'sort)))
+               (setq change-p 'name)))
 
         ;; Is MAIL redundant compared with the mail addresses
         ;; that are already known for RECORD?
@@ -553,21 +552,20 @@ Return the records matching ADDRESS or n
                      (message "created %s's record with address \"%s\""
                               (bbdb-record-name record) mail)
                    (message "created record with naked address \"%s\"" mail)))
-               (bbdb-change-record record t t))
+               (bbdb-change-record record nil t))
 
               (change-p
                (unless bbdb-silent
-                 (cond ((eq change-p 'sort)
+                 (cond ((eq change-p 'name)
                         (message "noticed \"%s\"" (bbdb-record-name record)))
                        ((bbdb-record-name record)
                         (message "noticed %s's address \"%s\""
                                  (bbdb-record-name record) mail))
                        (t
                         (message "noticed naked address \"%s\"" mail))))
-               (bbdb-change-record record (eq change-p 'sort))))
+               (bbdb-change-record record)))
 
-        (let ((bbdb-notice-hook-pending t))
-          (run-hook-with-args 'bbdb-notice-mail-hook record))
+        (run-hook-with-args 'bbdb-notice-mail-hook record)
         (push record new-records)))
 
     (nreverse new-records)))
@@ -603,7 +601,16 @@ If SORT is non-nil, sort records accordi
         (set-buffer rmail-buffer)
         (bbdb-update-records (bbdb-get-address-components header-class)
                              update-p sort))
-       ;; Message and Mail
+       ;; mu4e
+       ((eq mua 'mu4e)
+        (set-buffer mu4e~view-buffer-name)
+        (bbdb-update-records (bbdb-get-address-components header-class)
+                             update-p sort))
+       ;; Wanderlust
+       ((eq mua 'wl)
+        (bbdb-update-records (bbdb-get-address-components header-class)
+                             update-p sort))
+      ;; Message and Mail
        ((memq mua '(message mail))
         (bbdb-update-records (bbdb-get-address-components header-class)
                              update-p sort))))))
@@ -620,10 +627,10 @@ If SORT is non-nil, sort records accordi
             (save-current-buffer
               (gnus-summary-select-article) ; sets buffer `gnus-summary-buffer'
               ,@body))
-           ((memq mua '(mail message rmail mh vm))
+           ((memq mua '(mail message rmail mh vm mu4e wl))
             (cond ((eq mua 'vm) (vm-follow-summary-cursor))
                   ((eq mua 'mh) (mh-show)))
-            ;; rmail, mail and message do not require any wrapper
+            ;; rmail, mail, message, mu4e and wl do not require any wrapper
             ,@body))))
 
 (defun bbdb-mua-update-interactive-p ()
@@ -899,7 +906,8 @@ See `bbdb-mua-auto-update' for details a
                  (rmail . rmail-show-message-hook)
                  (gnus . gnus-article-prepare-hook)
                  (mh . mh-show-hook)
-                 (vm . vm-select-message-hook)))
+                 (vm . vm-select-message-hook)
+                 (wl . wl-message-redisplay-hook)))
     (if (memq (car mua) muas)
         (add-hook (cdr mua) 'bbdb-mua-auto-update)
       (remove-hook (cdr mua) 'bbdb-mua-auto-update))))
@@ -1052,3 +1060,5 @@ if this xfield is in the poster's record
         " "))))
 
 (provide 'bbdb-mua)
+
+;;; bbdb-mua.el ends here
--- bbdb3-3.1.2.orig/lisp/bbdb-pgp.el
+++ bbdb3-3.1.2/lisp/bbdb-pgp.el
@@ -1,8 +1,8 @@
-;;; bbdb-pgp.el --- use BBDB to handle PGP preferences
+;;; bbdb-pgp.el --- use BBDB to handle PGP preferences -*- lexical-binding: t -*-
 
 ;; Copyright (C) 1997,1999 Kevin Davidson
 ;; Copyright (C) 2013 Gijs Hillenius
-;; Copyright (C) 2013-2014 Roland Winkler <winkler@gnu.org>
+;; Copyright (C) 2013-2016 Roland Winkler <winkler@gnu.org>
 
 ;; This file is part of the Insidious Big Brother Database (aka BBDB),
 
@@ -236,3 +236,5 @@ to call the command `bbdb-pgp' manually,
                          (setq ranked-actions nil)))))))))))
 
 (provide 'bbdb-pgp)
+
+;;; bbdb-pgp.el ends here
--- bbdb3-3.1.2.orig/lisp/bbdb-print.el
+++ bbdb3-3.1.2/lisp/bbdb-print.el
@@ -1,7 +1,7 @@
-;;; bbdb-print.el -- for printing BBDB databases using TeX.
+;;; bbdb-print.el --- for printing BBDB databases using TeX. -*- lexical-binding: t -*-
 
 ;; Copyright (C) 1993 Boris Goldowsky
-;; Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+;; Copyright (C) 2010-2016 Roland Winkler <winkler@gnu.org>
 
 ;; Authors: Boris Goldowsky <boris@cs.rochester.edu>
 ;;          Dirk Grunwald <grunwald@cs.colorado.edu>
@@ -81,14 +81,15 @@ See also `bbdb-print-require'."
 
 (defcustom bbdb-print-require '(or address phone)
   "What fields are required for printing a record.
-This is evaluated for each record, and the record will be printed only
-if it returns non-nil.  The symbols name, organization, mail, phone,
-address, and notes will be set to appropriate values when this is
-evaluated; they will be nil if the field does not exist or is elided.
+This is a lisp expression and a record will be printed only if the evaluation
+of this expression yields a non-nil value for this records.
+The symbols name, organization, mail, phone, address, and notes will be set
+to appropriate values when this is evaluated; they will be nil if the field
+does not exist or is elided.
 
 The value of this variable can be any lisp expression, but typically
-it will be used for a boolean combination of the field variables, as
-in the following examples:
+it will be a boolean combination of the field variables, as in
+the following examples:
 
   Print only people whose phone numbers are known:
     (setq bbdb-print-require 'phone)
@@ -345,7 +346,7 @@ of the printout, notably the variables `
   (interactive
    (list (bbdb-do-records)
          (read-file-name
-          (format "Print to file (default %s): "
+          (format "TeX file: (default %s) "
                   (abbreviate-file-name bbdb-print-file))
           (file-name-directory bbdb-print-file)
           bbdb-print-file)
@@ -397,7 +398,8 @@ of the printout, notably the variables `
             (bbdb-print-record record current-letter
                                       brief pofl n-phones n-addresses)))
     (insert bbdb-print-epilog)
-    (goto-char (point-min))))
+    (goto-char (point-min)))
+  (message "Process this file with TeX (not LaTeX)"))
 
 (defun bbdb-print-record (record current-letter
                                  brief pofl n-phones n-addresses)
@@ -428,7 +430,7 @@ The return value is the new CURRENT-LETT
                     (t
                      (bbdb-print-tex-quote (bbdb-record-name-lf record)))))
         (organization (bbdb-record-organization record))
-        (affix   (bbdb-record-affix record))
+        ; (affix   (bbdb-record-affix record))
         (mail    (bbdb-record-mail record))
         (phone   (bbdb-record-phone record))
         (address (bbdb-record-address record))
@@ -514,13 +516,14 @@ The return value is the new CURRENT-LETT
       ;; xfields
       (dolist (xfield xfields)
         (when (bbdb-print-field-p (car xfield))
-          (if (eq 'notes (car xfield))
-              (insert (format "\\notes{%s}\n"
-                              (bbdb-print-tex-quote (cdr xfield))))
-            (insert (format "\\note{%s}{%s}\n"
-                            (bbdb-print-tex-quote (symbol-name (car xfield)))
-                            (bbdb-print-tex-quote (cdr xfield)))))))
-
+          ;; The value of the xfield may be a sexp.  Ideally, a sexp
+          ;; should be formatted by `pp-to-string' then printed verbatim.
+          (let ((value (bbdb-print-tex-quote (format "%s" (cdr xfield)))))
+            (insert (if (eq 'notes (car xfield))
+                        (format "\\notes{%s}\n" value)
+                      (format "\\note{%s}{%s}\n"
+                              (bbdb-print-tex-quote (symbol-name (car xfield)))
+                              value))))))
       ;; Mark end of the record.
       (insert "\\endrecord\n%\n")
       (setq current-letter first-letter)))
@@ -538,4 +541,4 @@ Omit-area-code is one of the allowed sym
 
 (provide 'bbdb-print)
 
-;;; bbdb-print ends here.
+;;; bbdb-print ends here
--- bbdb3-3.1.2.orig/lisp/bbdb-rmail.el
+++ bbdb3-3.1.2/lisp/bbdb-rmail.el
@@ -1,7 +1,7 @@
-;;; bbdb-rmail.el --- BBDB interface to Rmail
+;;; bbdb-rmail.el --- BBDB interface to Rmail -*- lexical-binding: t -*-
 
 ;; Copyright (C) 1991, 1992 Jamie Zawinski <jwz@netscape.com>.
-;; Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+;; Copyright (C) 2010-2016 Roland Winkler <winkler@gnu.org>
 
 ;; This file is part of the Insidious Big Brother Database (aka BBDB),
 
@@ -22,6 +22,8 @@
 ;;; This file contains the BBDB interface to Rmail.
 ;;; See the BBDB info manual for documentation.
 
+;;; Code:
+
 (require 'bbdb)
 (require 'bbdb-com)
 (require 'bbdb-mua)
@@ -29,49 +31,6 @@
 (require 'rmailsum)
 (require 'mailheader)
 
-(defcustom bbdb/rmail-update-records-p
-  (lambda ()
-    (let ((bbdb-update-records-p
-           (if (bbdb/rmail-new-flag) 'query 'search)))
-      (bbdb-select-message)))
-  "How `bbdb-mua-update-records' processes mail addresses in Rmail.
-This Rmail-specific variable is normally not used.  It is a fallback
-if the generic (MUA-independent) variables `bbdb-mua-auto-update-p',
-`bbdb-update-records-p' or `bbdb-mua-update-interactive-p' result
-in a value of nil for the arg UPDATE-P of `bbdb-update-records'.
-
-Allowed values are:
- nil          Do nothing.
- search       Search for existing records.
- update       Search for existing records, update if necessary.
- query        Update existing records or query for creating new ones.
- create or t  Update existing records or create new ones.
- a function   This functions will be called with no arguments.
-                It should return one of the above values."
-  :group 'bbdb-mua-rmail
-  :type '(choice (const :tag "do nothing" nil)
-                 (const :tag "search for existing records"
-                        (lambda () (let ((bbdb-update-records-p 'search))
-                                     (bbdb-select-message))))
-                 (const :tag "update existing records"
-                        (lambda () (let ((bbdb-update-records-p 'update))
-                                     (bbdb-select-message))))
-                 (const :tag "query annotation of all messages"
-                        (lambda () (let ((bbdb-update-records-p 'query))
-                                     (bbdb-select-message))))
-                 (const :tag "annotate (query) only new messages"
-                        (lambda ()
-                          (let ((bbdb-update-records-p
-                                 (if (bbdb/rmail-new-flag) 'query 'search)))
-                            (bbdb-select-message))))
-                 (const :tag "annotate all messages"
-                        (lambda () (let ((bbdb-update-records-p 'create))
-                                     (bbdb-select-message))))
-                 (const :tag "accept messages" bbdb-accept-message)
-                 (const :tag "ignore messages" bbdb-ignore-message)
-                 (const :tag "select messages" bbdb-select-message)
-                 (sexp  :tag "user defined function")))
-
 (defun bbdb/rmail-new-flag ()
   "Returns t if the current message in buffer BUF is new."
   (rmail-message-labels-p rmail-current-message ", ?\\(unseen\\),"))
@@ -100,3 +59,5 @@ Do not call this in your init file.  Use
   (define-key rmail-summary-mode-map ";" 'bbdb-mua-edit-field-sender))
 
 (provide 'bbdb-rmail)
+
+;;; bbdb-rmail.el ends here
--- bbdb3-3.1.2.orig/lisp/bbdb-sc.el
+++ bbdb3-3.1.2/lisp/bbdb-sc.el
@@ -1,7 +1,7 @@
-;;; bbdb-sc.el --- BBDB interface to Supercite
+;;; bbdb-sc.el --- BBDB interface to Supercite -*- lexical-binding: t -*-
 
 ;; Copyright (C) 1991, 1992 Jamie Zawinski <jwz@netscape.com>.
-;; Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+;; Copyright (C) 2010-2016 Roland Winkler <winkler@gnu.org>
 
 ;; This file is part of the Insidious Big Brother Database (aka BBDB),
 
@@ -65,6 +65,8 @@
 ;;                                          (bbdb-sc-update-from)
 ;;                                          (setq sc-mail-headers-end (point))))))
 
+;;; Code:
+
 (require 'bbdb-com)
 (require 'bbdb-mua)
 (require 'supercite)
@@ -94,9 +96,9 @@ Allowed values include
  query  Query before creating or modifying the attribution field.
  t      Create or modify the attribution field."
  :group 'bbdb-utilities-sc
- :type '(choice (const "Do nothing" nil)
-                (const "Query before updating the attribution field" query)
-                (const "Update the attribution field" t)))
+ :type '(choice (const :tag "Do nothing" nil)
+                (const :tag "Query before updating the attribution field" query)
+                (const :tag "Update the attribution field" t)))
 
 ;;; Internal variables
 (defvar bbdb-sc-last-attrib ""
@@ -191,4 +193,4 @@ BBDB into Supercite."
 
 (provide 'bbdb-sc)
 
-;;; end of bbdb-sc.el
+;;; bbdb-sc.el ends here
--- bbdb3-3.1.2.orig/lisp/bbdb-site.el.in
+++ bbdb3-3.1.2/lisp/bbdb-site.el.in
@@ -1,6 +1,6 @@
-;;; bbdb-site.el.in --- site-specific variables for BBDB
+;;; bbdb-site.el.in --- site-specific variables for BBDB -*- lexical-binding: t -*-
 
-;; Copyright (C) 2013-2014 Roland Winkler <winkler@gnu.org>
+;; Copyright (C) 2013-2016 Roland Winkler <winkler@gnu.org>
 
 ;; This file is part of the Insidious Big Brother Database (aka BBDB),
 
@@ -33,3 +33,5 @@
   :type '(repeat (directory :tag "Directory")))
 
 (provide 'bbdb-site)
+
+;;; bbdb-site.el.in ends here
--- bbdb3-3.1.2.orig/lisp/bbdb-snarf.el
+++ bbdb3-3.1.2/lisp/bbdb-snarf.el
@@ -1,7 +1,7 @@
-;;; bbdb-snarf.el -- convert free-form text to BBDB records
+;;; bbdb-snarf.el --- convert free-form text to BBDB records -*- lexical-binding: t -*-
 
 ;; Copyright (C) 1997 John Heidemann <johnh@isi.edu>
-;; Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+;; Copyright (C) 2010-2016 Roland Winkler <winkler@gnu.org>
 
 ;; This file is part of the Insidious Big Brother Database (aka BBDB),
 
@@ -25,31 +25,48 @@
 ;;; out of a (buffer) string.  Things are recognized by context (e.g., URLs
 ;;; start with http:// or www.).  See `bbdb-snarf-rule-alist' for details.
 ;;;
-;;; Currently this code is much biased towards the US.  Hopefully,
-;;; the concept of customizable rules allows you to develop new rules
-;;; suitable for other parts of the world, too.  Please let me know
-;;; if you get such rules working.
-;;; `mail' is a simple rule that can pick a single address from, say,
-;;; a long list of mail addresses in a message.
+;;; The rule `eu' should work out of the box for many continental
+;;; European countries.  It can be further customized by defining
+;;; a suitable postcode regexp passed to `bbdb-snarf-address-eu'.
+;;; `mail' is a simple rule that can pick a single mail address from,
+;;; say, a long list of mail addresses in a message.
 ;;;
 ;;; RW: `bbdb-snarf' is an interesting proof of concept.  Yet I find
-;;; its snarfing algorithms too simplistic to be useful in real life.
+;;; its snarfing algorithms often too simplistic to be useful in real life.
 ;;; How can this possibly be improved?  Suggestions welcome.
 
+;;; Code:
+
 (require 'bbdb-com)
 
 (defcustom bbdb-snarf-rule-alist
-  '((us bbdb-snarf-surrounding-space bbdb-snarf-phone-nanp
-        bbdb-snarf-url bbdb-snarf-mail bbdb-snarf-empty-lines
-        bbdb-snarf-name bbdb-snarf-address-us bbdb-snarf-empty-lines
-        bbdb-snarf-notes bbdb-snarf-name-mail)
-    (mail bbdb-snarf-mail-address))
+  '((us bbdb-snarf-surrounding-space
+        bbdb-snarf-phone-nanp
+        bbdb-snarf-url
+        bbdb-snarf-mail
+        bbdb-snarf-empty-lines
+        bbdb-snarf-name
+        bbdb-snarf-address-us
+        bbdb-snarf-empty-lines
+        bbdb-snarf-notes
+        bbdb-snarf-name-mail) ; currently useless
+    (eu bbdb-snarf-surrounding-space
+        bbdb-snarf-phone-eu
+        bbdb-snarf-url
+        bbdb-snarf-mail
+        bbdb-snarf-empty-lines
+        bbdb-snarf-name
+        bbdb-snarf-address-eu
+        bbdb-snarf-empty-lines
+        bbdb-snarf-notes
+        bbdb-snarf-name-mail) ; currently useless
+   (mail bbdb-snarf-mail-address))
   "Alist of rules for snarfing.
 Each rule is of the form (KEY FUNCTION FUNCTION ...).
 The symbol KEY identifies the rule, see also `bbdb-snarf-rule-default'.
 
-Snarfing is a cumulative process.  The text is copied to a snarf buffer
-that becomes current during snarfing.
+Snarfing is a cumulative process.  The text is copied to a temporary
+snarf buffer that becomes current during snarfing.
 Each FUNCTION is called with one arg, the RECORD we are snarfing,
 and with point at the beginning of the snarf buffer.  FUNCTION should populate
 the fields of RECORD.  It may delete the part of the snarf buffer
@@ -68,29 +85,69 @@ hash table for RECORD which is done at t
   :type 'symbol)
 
 (defcustom bbdb-snarf-name-regexp
-   "^[ \t'\"]*\\([- .,[:word:]]*[[:word:]]\\)"
+  "^[ \t'\"]*\\([- .,[:word:]]*[[:word:]]\\)"
   "Regexp matching a name.  Case is ignored.
 The first subexpression becomes the name."
   :group 'bbdb-utilities-snarf
   :type 'regexp)
 
+(defcustom bbdb-snarf-mail-regexp
+  (concat "\\(?:\\(?:mailto:\\|e?mail:?\\)[ \t]*\\)?"
+          "<?\\([^ \t\n<]+@[^ \t\n>]+\\)>?")
+  "Regexp matching a mail address.  Case is ignored.
+The first subexpression becomes the mail address."
+  :group 'bbdb-utilities-snarf
+  :type 'regexp)
+
 (defcustom bbdb-snarf-phone-nanp-regexp
-  (concat "\\(([2-9][0-9][0-9])[-. ]?\\|[2-9][0-9][0-9][-. ]\\)?"
+  (concat "\\(?:phone:?[ \t]*\\)?"
+          "\\(\\(?:([2-9][0-9][0-9])[-. ]?\\|[2-9][0-9][0-9][-. ]\\)?"
           "[0-9][0-9][0-9][-. ][0-9][0-9][0-9][0-9]"
-          "\\( *\\(x\\|ext\\.?\\) *[0-9]+\\)?")
+          "\\(?: *\\(?:x\\|ext\\.?\\) *[0-9]+\\)?\\)")
   "Regexp matching a NANP phone number.  Case is ignored.
-NANP is the North American Numbering Plan used in North and Central America."
+NANP is the North American Numbering Plan used in North and Central America.
+The first subexpression becomes the phone number."
+  :group 'bbdb-utilities-snarf
+  :type 'regexp)
+
+(defcustom bbdb-snarf-phone-eu-regexp
+  (concat "\\(?:phone?:?[ \t]*\\)?"
+          "\\(\\(?:\\+[1-9]\\|(\\)[-0-9()\s]+\\)")
+  "Regexp matching a European phone number.
+The first subexpression becomes the phone number."
   :group 'bbdb-utilities-snarf
   :type 'regexp)
 
 (defcustom bbdb-snarf-postcode-us-regexp
-  (concat "\\<[0-9][0-9][0-9][0-9][0-9]"
+  ;; US postcode appears at end of line
+  (concat "\\(\\<[0-9][0-9][0-9][0-9][0-9]"
           "\\(-[0-9][0-9][0-9][0-9]\\)?"
-          "\\>$")
-  "Regexp matching US postcodes."
+          "\\>\\)$")
+  "Regexp matching US postcodes.
+The first subexpression becomes the postcode."
   :group 'bbdb-utilities-snarf
   :type 'regexp)
 
+(defcustom bbdb-snarf-address-us-country nil
+  "Country to use for US addresses.  If nil leave country blank."
+  :group 'bbdb-utilities-snarf
+  :type '(choice (const :tag "Leave blank" nil)
+                 (string :tag "Country")))
+
+(defcustom bbdb-snarf-postcode-eu-regexp
+  "^\\([0-9][0-9][0-9][0-9][0-9]?\\)" ; four or five digits
+  "Regexp matching many European postcodes.
+`bbdb-snarf-address-eu' assumes that the address appears at the beginning
+of a line followed by the name of the city."
+  :group 'bbdb-utilities-snarf
+  :type 'regexp)
+
+(defcustom bbdb-snarf-address-eu-country nil
+  "Country to use for EU addresses.  If nil leave country blank."
+  :group 'bbdb-utilities-snarf
+  :type '(choice (const :tag "Leave blank" nil)
+                 (string :tag "Country")))
+
 (defcustom bbdb-snarf-default-label-alist
   '((phone . "work") (address . "work"))
   "Default labels for snarfing.
@@ -106,12 +163,13 @@ The string LABEL denotes the default lab
   :group 'bbdb-utilities-snarf
   :type 'symbol)
 
-(defcustom bbdb-snarf-url-regexp  "\\(http://\\|www\.\\)[^ \t\n]+"
-  "Regexp matching a URL.  Case is ignored."
+(defcustom bbdb-snarf-url-regexp "\\(\\(?:http://\\|www\.\\)[^ \t\n]+\\)"
+  "Regexp matching a URL.  Case is ignored.
+The first subexpression becomes the URL."
   :group 'bbdb-utilities-snarf
   :type 'regexp)
 
-(defun bbdb-snarf-surrounding-space (record)
+(defun bbdb-snarf-surrounding-space (_record)
   "Discard beginning and trailing space when snarfing RECORD."
   (while (re-search-forward "^[ \t]+" nil t)
     (replace-match ""))
@@ -119,7 +177,7 @@ The string LABEL denotes the default lab
   (while (re-search-forward "\\s-+$" nil t)
     (replace-match "")))
 
-(defun bbdb-snarf-empty-lines (record)
+(defun bbdb-snarf-empty-lines (_record)
   "Discard empty lines when snarfing RECORD."
   (while (re-search-forward "^[ \t]*\n" nil t)
     (replace-match "")))
@@ -137,6 +195,8 @@ The string LABEL denotes the default lab
 
 (defun bbdb-snarf-name-mail (record)
   "Snarf name from mail address for RECORD."
+  ;; Fixme: This is currently useless because `bbdb-snarf-mail-regexp'
+  ;; cannot handle names in RFC 5322-like addresses "John Smith <foo@bar.com>".
   (let ((name (bbdb-record-lastname record)))
     (when (and (not name)
                (bbdb-record-mail record)
@@ -158,37 +218,56 @@ The string LABEL denotes the default lab
     (bbdb-record-set-mail record (list (cadr data)))
     (delete-region (point-min) (point-max))))
 
+(defun bbdb-snarf-mail (record)
+  "Snarf mail addresses for RECORD.
+This uses the first subexpresion of `bbdb-snarf-mail-regexp'."
+  (let ((case-fold-search t) mails)
+    (while (re-search-forward bbdb-snarf-mail-regexp nil t)
+      (push (match-string 1) mails)
+      (replace-match ""))
+    (bbdb-record-set-mail record (nconc (bbdb-record-mail record) mails))))
+
 (defun bbdb-snarf-label (field)
   "Extract the label before point, or return default label for FIELD."
-  (if (looking-back "[\n,:]\\([^\n,:]+\\):[ \t]*")
-      (prog1 (match-string 1)
-        (delete-region (match-beginning 1) (match-end 0)))
-    (cdr (assq field bbdb-snarf-default-label-alist))))
+  (save-match-data
+    (if (looking-back "\\(?:^\\|[,:]\\)\\([^\n,:]+\\):[ \t]*"
+                      (line-beginning-position))
+        (prog1 (match-string 1)
+          (delete-region (match-beginning 1) (match-end 0)))
+      (cdr (assq field bbdb-snarf-default-label-alist)))))
 
 (defun bbdb-snarf-phone-nanp (record)
-  "Snarf NANP Phone Numbers for RECORD.
-NANP is the North American Numbering Plan used in North and Central America."
+  "Snarf NANP phone numbers for RECORD.
+NANP is the North American Numbering Plan used in North and Central America.
+This uses the first subexpresion of `bbdb-snarf-phone-nanp-regexp'."
   (let ((case-fold-search t) phones)
     (while (re-search-forward bbdb-snarf-phone-nanp-regexp nil t)
-      (let ((begin (match-beginning 0))
-            (end (match-end 0)))
-        (goto-char begin)
-        (forward-char -1)
-        (if (looking-at "[0-9A-Z]") ;; not really a phone number
-            (goto-char end)
-          (let ((number (bbdb-parse-phone (buffer-substring begin end))))
-            (delete-region begin end)
-            (push (vconcat (list (bbdb-snarf-label 'phone)) number)
-                  phones)))))
-    (bbdb-record-set-phone record (nconc (bbdb-record-phone record) phones))))
-
-(defun bbdb-snarf-mail (record)
-  "Snarf mail addresses for RECORD."
-  (let (mails)
-    (while (re-search-forward "[^ \t\n<]+@[^ \t\n>]+" nil t)
-      (push (match-string 0) mails)
+      (goto-char (match-beginning 0))
+      (if (save-match-data
+            (looking-back "[0-9A-Z]" nil)) ;; not really an NANP phone number
+          (goto-char (match-end 0))
+        (push (vconcat (list (bbdb-snarf-label 'phone))
+                       (save-match-data
+                         (bbdb-parse-phone (match-string 1))))
+              phones)
+        (replace-match "")))
+    (bbdb-record-set-phone record (nconc (bbdb-record-phone record)
+                                         (nreverse phones)))))
+
+(defun bbdb-snarf-phone-eu (record &optional phone-regexp)
+  "Snarf European phone numbers for RECORD.
+PHONE-REGEXP is the regexp to match a phone number.
+It defaults to `bbdb-snarf-phone-eu-regexp'."
+  (let ((case-fold-search t) phones)
+    (while (re-search-forward (or phone-regexp
+                                  bbdb-snarf-phone-eu-regexp) nil t)
+      (goto-char (match-beginning 0))
+      (push (vector (bbdb-snarf-label 'phone)
+                    (match-string 1))
+            phones)
       (replace-match ""))
-    (bbdb-record-set-mail record (nconc (bbdb-record-mail record) mails))))
+    (bbdb-record-set-phone record (nconc (bbdb-record-phone record)
+                                         (nreverse phones)))))
 
 (defun bbdb-snarf-streets (address)
   "Snarf streets for ADDRESS.  This assumes a narrowed region."
@@ -205,7 +284,7 @@ NANP is the North American Numbering Pla
              ;; Postcode
              (goto-char (match-beginning 0))
              (bbdb-address-set-postcode address
-              (bbdb-parse-postcode (match-string 0)))
+              (bbdb-parse-postcode (match-string 1)))
              ;; State
              (skip-chars-backward " \t")
              (let ((pos (point)))
@@ -232,22 +311,56 @@ NANP is the North American Numbering Pla
              (narrow-to-region (point-min) (match-beginning 0))
              (goto-char (point-min))
              (bbdb-snarf-streets address))))
-    ;; Fixme: There are no labels anymore.  `bbdb-snarf-streets' snarfed
-    ;; everything that was left!
-    (bbdb-address-set-label address (bbdb-snarf-label 'address))
-    (bbdb-record-set-address record
-                             (nconc (bbdb-record-address record)
-                                    (list address)))))
+    (when (bbdb-address-city address)
+      (if bbdb-snarf-address-us-country
+          (bbdb-address-set-country address bbdb-snarf-address-us-country))
+      ;; Fixme: There are no labels anymore.  `bbdb-snarf-streets' snarfed
+      ;; everything that was left!
+      (bbdb-address-set-label address (bbdb-snarf-label 'address))
+      (bbdb-record-set-address record
+                               (nconc (bbdb-record-address record)
+                                      (list address))))))
+
+(defun bbdb-snarf-address-eu (record &optional postcode-regexp country)
+  "Snarf a European address for RECORD.
+POSTCODE-REGEXP is a regexp matching the postcode assumed to appear
+at the beginning of a line followed by the name of the city.  This format
+is used in many continental European countries.
+POSTCODE-REGEXP defaults to `bbdb-snarf-postcode-eu-regexp'.
+COUNTRY is the country to use.  It defaults to `bbdb-snarf-address-eu-country'."
+  (when (re-search-forward (or postcode-regexp
+                               bbdb-snarf-postcode-eu-regexp) nil t)
+    (let ((address (make-vector bbdb-address-length nil)))
+      (save-restriction
+        (goto-char (match-end 0))
+        (narrow-to-region (point-min) (line-end-position))
+        ;; Postcode
+        (bbdb-address-set-postcode address (match-string 1))
+        ;; City
+        (skip-chars-forward " \t")
+        (bbdb-address-set-city address (buffer-substring (point) (point-max)))
+        ;; Toss it
+        (delete-region (match-beginning 0) (point-max))
+        ;; Streets
+        (goto-char (point-min))
+        (bbdb-snarf-streets address))
+      (unless country (setq country bbdb-snarf-address-eu-country))
+      (if country (bbdb-address-set-country address country))
+      (bbdb-address-set-label address (bbdb-snarf-label 'address))
+      (bbdb-record-set-address record
+                               (nconc (bbdb-record-address record)
+                                      (list address))))))
 
 (defun bbdb-snarf-url (record)
-  "Snarf URL for RECORD."
+  "Snarf URL for RECORD.
+This uses the first subexpresion of `bbdb-snarf-url-regexp'."
   (when (and bbdb-snarf-url
              (let ((case-fold-search t))
                (re-search-forward bbdb-snarf-url-regexp nil t)))
     (bbdb-record-set-xfields
      record
      (nconc (bbdb-record-xfields record)
-            (list (cons bbdb-snarf-url (match-string 0)))))
+            (list (cons bbdb-snarf-url (match-string 1)))))
     (replace-match "")))
 
 (defun bbdb-snarf-notes (record)
@@ -295,7 +408,7 @@ See `bbdb-snarf-rule-alist' for details.
 
 ;;;###autoload
 (defun bbdb-snarf (string &optional rule)
-  "Snarf a BBDB record in STRING using RULE.  Return this record.
+  "Snarf a BBDB record in STRING using RULE.  Display and return this record.
 Interactively, STRING is the current region.
 RULE defaults to `bbdb-snarf-rule-default'.
 See `bbdb-snarf-rule-alist' for details."
@@ -318,15 +431,16 @@ See `bbdb-snarf-rule-alist' for details.
                                          (bbdb-record-firstname record)
                                          (bbdb-record-lastname record))
                             (car (bbdb-record-mail record))))))
-      (if old-record
-          (bbdb-merge-records old-record record)
-        ;; create new record
-        (bbdb-change-record record t t)
-        (bbdb-display-records (list record))
-        record))))
+      ;; Install RECORD after searching for OLD-RECORD
+      (bbdb-change-record record nil t)
+      (if old-record (bbdb-merge-records old-record record)))
+    (bbdb-display-records (list record))
+    record))
 
 ;; Some test cases
 ;;
+;; US:
+;;
 ;; another test person
 ;; 1234 Gridley St.
 ;; Los Angeles, CA 91342
@@ -339,7 +453,7 @@ See `bbdb-snarf-rule-alist' for details.
 ;; 1234 Gridley St.
 ;; St. Los Angeles, CA 91342-1234
 ;; 555-1212
-;; test@person.net
+;; <test@person.net>
 ;;
 ;; x test person
 ;; 1234 Gridley St.
@@ -353,5 +467,23 @@ See `bbdb-snarf-rule-alist' for details.
 ;; Los Angeles, CA
 ;; 555-1212
 ;; test@person.net
+;;
+;; z test person
+;; 555-1212
+;; test@person.net
+;;
+;; EU:
+;;
+;; Maja Musterfrau
+;; Strasse 15
+;; 12345 Ort
+;; +49 12345
+;; phon: (110) 123 456
+;; mobile: (123) 456 789
+;; xxx.xxx@xxxx.xxx
+;; http://www.xxx.xx
+;; notes bla bla bla
 
 (provide 'bbdb-snarf)
+
+;;; bbdb-snarf.el ends here
--- bbdb3-3.1.2.orig/lisp/bbdb-vm.el
+++ bbdb3-3.1.2/lisp/bbdb-vm.el
@@ -1,7 +1,7 @@
-;;; bbdb-vm.el --- BBDB interface to VM
+;;; bbdb-vm.el --- BBDB interface to VM -*- lexical-binding: t -*-
 
 ;; Copyright (C) 1991, 1992, 1993 Jamie Zawinski <jwz@netscape.com>.
-;; Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+;; Copyright (C) 2010-2016 Roland Winkler <winkler@gnu.org>
 
 ;; This file is part of the Insidious Big Brother Database (aka BBDB),
 
@@ -22,6 +22,8 @@
 ;;; This file contains the BBDB interface to VM.
 ;;; See the BBDB info manual for documentation.
 
+;;; Code:
+
 (require 'bbdb)
 (require 'bbdb-com)
 (require 'bbdb-mua)
@@ -35,52 +37,6 @@
 (require 'vm-message)
 (require 'vm-misc)
 
-(defcustom bbdb/vm-update-records-p
-  (lambda ()
-    (let ((bbdb-update-records-p
-           (if (vm-new-flag (car vm-message-pointer))
-               'query 'search)))
-      (bbdb-select-message)))
-  "How `bbdb-mua-update-records' processes mail addresses in VM.
-This VM-specific variable is normally not used.  It is a fallback
-if the generic (MUA-independent) variables `bbdb-mua-auto-update-p',
-`bbdb-update-records-p' or `bbdb-mua-update-interactive-p' result
-in a value of nil for the arg UPDATE-P of `bbdb-update-records'.
-
-Allowed values are:
- nil          Do nothing.
- search       Search for existing records.
- update       Search for existing records, update if necessary.
- query        Update existing records or query for creating new ones.
- create or t  Update existing records or create new ones.
- a function   This functions will be called with no arguments.
-                It should return one of the above values."
-  :group 'bbdb-mua-vm
-  :type '(choice (const :tag "do nothing"
-                        nil)
-                 (const :tag "search for existing records"
-                        (lambda () (let ((bbdb-update-records-p 'search))
-                                     (bbdb-select-message))))
-                 (const :tag "update existing records"
-                        (lambda () (let ((bbdb-update-records-p 'update))
-                                     (bbdb-select-message))))
-                 (const :tag "query annotation of all messages"
-                        (lambda () (let ((bbdb-update-records-p 'query))
-                                     (bbdb-select-message))))
-                 (const :tag "annotate (query) only new messages"
-                        (lambda ()
-                          (let ((bbdb-update-records-p
-                                 (if (vm-new-flag (car vm-message-pointer))
-                                     'query 'search)))
-                            (bbdb-select-message))))
-                 (const :tag "annotate all messages"
-                        (lambda () (let ((bbdb-update-records-p 'create))
-                                     (bbdb-select-message))))
-                 (const :tag "accept messages" bbdb-accept-message)
-                 (const :tag "ignore messages" bbdb-ignore-message)
-                 (const :tag "select messages" bbdb-select-message)
-                 (sexp  :tag "user defined function")))
-
 (defun bbdb/vm-header (header)
   (save-current-buffer
     (vm-select-folder-buffer)
@@ -146,7 +102,8 @@ The order in this list is the order how
   "Real folders used for defining virtual folders.
 If nil use `vm-primary-inbox'."
   :group 'bbdb-mua-vm
-  :type 'symbol)
+  :type '(choice (const :tag "Use vm-primary-inbox" nil)
+                 (repeat (string :tag "Real folder"))))
 
 ;;;###autoload
 (defun bbdb/vm-auto-folder ()
@@ -361,3 +318,5 @@ Do not call this in your init file.  Use
             (lambda (m) (bbdb-mua-summary-mark (vm-su-from m))))))
 
 (provide 'bbdb-vm)
+
+;;; bbdb-vm.el ends here
--- /dev/null
+++ bbdb3-3.1.2/lisp/bbdb-wl.el
@@ -0,0 +1,55 @@
+;;; bbdb-wl.el --- BBDB interface to Wanderlust -*- lexical-binding: t -*-
+
+;; Copyright (C) 2015 David Maus <dmaus@dmaus.name>
+;; Copyright (C) 2015-2016 Roland Winkler <winkler@gnu.org>
+
+;; This file is part of the Insidious Big Brother Database (aka BBDB),
+
+;; BBDB is free software: you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation, either version 3 of the License, or
+;; (at your option) any later version.
+
+;; BBDB is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+;; GNU General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with BBDB.  If not, see <http://www.gnu.org/licenses/>.
+
+;;; Commentary:
+;;; This file contains the BBDB interface to Wl.
+;;; See the BBDB info manual for documentation.
+
+;;; Code:
+
+(require 'bbdb)
+(require 'bbdb-mua)
+
+(eval-when-compile
+  (defvar wl-summary-mode-map)
+  (defvar wl-draft-mode-map)
+  (defvar wl-summary-buffer-elmo-folder)
+  (autoload 'wl-summary-message-number "wl-summary")
+  (autoload 'elmo-message-entity "elmo-msgdb")
+  (autoload 'elmo-message-entity-field "elmo-msgdb"))
+
+(defun bbdb/wl-header (header)
+  (elmo-message-entity-field
+   (elmo-message-entity wl-summary-buffer-elmo-folder
+                        (wl-summary-message-number))
+   (intern (downcase header)) 'string))
+
+;;;###autoload
+(defun bbdb-insinuate-wl ()
+  "Hook BBDB into Wanderlust."
+  (define-key wl-summary-mode-map (kbd ":") #'bbdb-mua-display-sender)
+  (define-key wl-summary-mode-map (kbd ";") #'bbdb-mua-edit-field-sender)
+  (when bbdb-complete-mail
+    (define-key wl-draft-mode-map (kbd "M-;") #'bbdb-complete-mail)
+    (define-key wl-draft-mode-map (kbd "M-<tab>") #'bbdb-complete-mail)))
+
+(provide 'bbdb-wl)
+
+;;; bbdb-wl.el ends here
--- bbdb3-3.1.2.orig/lisp/bbdb.el
+++ bbdb3-3.1.2/lisp/bbdb.el
@@ -1,7 +1,7 @@
-;;; bbdb.el --- core of BBDB
+;;; bbdb.el --- core of BBDB -*- lexical-binding: t -*-
 
 ;; Copyright (C) 1991, 1992, 1993, 1994 Jamie Zawinski <jwz@netscape.com>.
-;; Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+;; Copyright (C) 2010-2016 Roland Winkler <winkler@gnu.org>
 
 ;; This file is part of the Insidious Big Brother Database (aka BBDB),
 
@@ -33,6 +33,8 @@
 ;;; |  version of BBDB you have.                                            |
 ;;;  -----------------------------------------------------------------------
 
+;;; Code:
+
 (require 'timezone)
 (require 'bbdb-site)
 
@@ -187,7 +189,7 @@ If nil or the database has been changed
 before reverting."
   :group 'bbdb
   :type '(choice (const :tag "Revert unchanged database without querying" t)
-                 (const :tag "Ask before reverting database")))
+                 (const :tag "Ask before reverting database" nil)))
 
 (defcustom bbdb-check-auto-save-file nil
   "If t BBDB will check its auto-save file.
@@ -308,7 +310,7 @@ Allowed values include nil (not dedicate
 and t (strongly dedicated)."
   :group 'bbdb-record-display
   :type '(choice (const :tag "BBDB window not dedicated" nil)
-                 (const :tag "BBDB window weakly dedicated" 'bbdb)
+                 (const :tag "BBDB window weakly dedicated" bbdb)
                  (const :tag "BBDB window strongly dedicated" t)))
 
 (defcustom bbdb-layout-alist
@@ -533,7 +535,10 @@ This is used for fields which do not hav
   :type '(list regexp string))
 
 (defcustom bbdb-separator-alist
-  '((name-first-last "[ ,;]" " ") (name-last-first "[ ,;]" ", ")
+  '((record "\n\n" "\n\n") ; used by `bbdb-copy-fields-as-kill'
+    (name-first-last "[ ,;]" " ") (name-last-first "[ ,;]" ", ")
+    (name-field ":\n" ":\n") ; used by `bbdb-copy-fields-as-kill'
+    (phone "[,;]" ", ") (address ";\n" ";\n") ; ditto
     (organization "[,;]" ", ") (affix "[,;]"  ", ") (aka "[,;]" ", ")
     (mail "[,;]" ", ") (mail-alias "[,;]" ", ") (vm-folder "[,;]" ", ")
     (birthday "\n" "\n") (wedding "\n" "\n") (anniversary "\n" "\n")
@@ -650,7 +655,7 @@ The address is not altered if `bbdb-defa
 or if a prefix argument is given to the command `bbdb-insert-field'."
   :group 'bbdb-record-edit
   :type '(choice (const :tag "none" nil)
-                 (string :tag "Default Domain" :value nil)))
+                 (string :tag "Default Domain")))
 
 (defcustom bbdb-phone-style 'nanp
   "Phone numbering plan assumed by BBDB.
@@ -930,8 +935,8 @@ If t accept all messages.  If nil do not
 See also `bbdb-ignore-message-alist', which has the opposite effect."
   :group 'bbdb-mua
   :type '(repeat (cons
-          (string :tag "Header name")
-          (regexp :tag "Regexp to match on header value"))))
+                  (string :tag "Header name")
+                  (regexp :tag "Regexp to match on header value"))))
 
 (defcustom bbdb-ignore-message-alist nil
   "Alist describing which messages not to automatically create BBDB records for.
@@ -947,8 +952,8 @@ If t ignore all messages.  If nil do not
 See also `bbdb-accept-message-alist', which has the opposite effect."
   :group 'bbdb-mua
   :type '(repeat (cons
-          (string :tag "Header name")
-          (regexp :tag "Regexp to match on header value"))))
+                  (string :tag "Header name")
+                  (regexp :tag "Regexp to match on header value"))))
 
 (defcustom bbdb-user-mail-address-re
   (and (stringp user-mail-address)
@@ -1114,10 +1119,6 @@ to determine the header and class of the
 to `bbdb-message-headers'.  See `bbdb-auto-notes' for how to annotate records
 using `bbdb-update-records-address' and the headers of a mail message.
 
-The record need not have been modified for this hook to be called;
-use `bbdb-change-hook' for that.  `bbdb-change-hook' will NOT be called
-as a result of modifications you may make to the record inside this hook.
-
 If a message contains multiple mail addresses belonging to one BBDB record,
 this hook is run for each mail address.  Use `bbdb-notice-record-hook'
 if you want to notice each record only once per message."
@@ -1132,10 +1133,6 @@ contains multiple mail addresses belongi
 is nonetheless run only once.  Use `bbdb-notice-mail-hook' if you want to run
 a hook function for each mail address in a message.
 
-The record need not have been modified for this hook to be called;
-use `bbdb-change-hook' for that.  `bbdb-change-hook' will NOT be called
-as a result of modifications you may make to the record inside this hook.
-
 Hook is run with one argument, the record."
   :group 'bbdb-mua
   :type 'hook)
@@ -1143,9 +1140,9 @@ Hook is run with one argument, the recor
 (define-widget 'bbdb-alist-with-header 'group
   "My group"
   :match 'bbdb-alist-with-header-match
-  :value-to-internal (lambda (widget value)
+  :value-to-internal (lambda (_widget value)
                        (if value (list (car value) (cdr value))))
-  :value-to-external (lambda (widget value)
+  :value-to-external (lambda (_widget value)
                        (if value (append (list (car value)) (cadr value)))))
 
 (defun bbdb-alist-with-header-match (widget value)
@@ -1272,8 +1269,8 @@ The elements may have the following valu
 See also `bbdb-auto-notes-ignore-headers'."
   :group 'bbdb-mua
   :type '(repeat (cons
-          (string :tag "Header name")
-          (regexp :tag "Regexp to match on header value"))))
+                  (string :tag "Header name")
+                  (regexp :tag "Regexp to match on header value"))))
 
 (defcustom bbdb-auto-notes-ignore-headers nil
   "Alist of headers and regexps to ignore in `bbdb-auto-notes'.
@@ -1290,8 +1287,8 @@ gatewayed to gnu.* newsgroups.
 See also `bbdb-auto-notes-ignore-messages'."
   :group 'bbdb-mua
   :type '(repeat (cons
-          (string :tag "Header name")
-          (regexp :tag "Regexp to match on header value"))))
+                  (string :tag "Header name")
+                  (regexp :tag "Regexp to match on header value"))))
 
 (defcustom bbdb-mua-pop-up t
   "If non-nil, display an auto-updated BBDB window while using a MUA.
@@ -1301,7 +1298,7 @@ If this is nil, BBDB is updated silently
 See also `bbdb-mua-pop-up-window-size' and `bbdb-horiz-pop-up-window-size'."
   :group 'bbdb-mua
   :type '(choice (const :tag "MUA BBDB window stacked vertically" t)
-                 (const :tag "MUA BBDB window stacked horizontally" 'horiz)
+                 (const :tag "MUA BBDB window stacked horizontally" horiz)
                  (const :tag "No MUA BBDB window" nil)))
 (define-obsolete-variable-alias 'bbdb-message-pop-up 'bbdb-mua-pop-up)
 
@@ -1325,7 +1322,8 @@ If it is an integer number, it is the nu
 If it is a fraction between 0 and 1, it is the fraction of the
 window width that BBDB will take over."
   :group 'bbdb-mua
-  :type '(cons (number) (number)))
+  :type '(cons (number :tag "Total number of columns")
+               (number :tag "Horizontal size of BBDB window")))
 
 
 ;;; xfields processing
@@ -1337,7 +1335,9 @@ If an xfield is not in the alist, it is
 with weights less then 100 will be in the beginning, and all xfields with
 weights more than 100 will be in the end."
   :group 'bbdb-mua
-  :type 'list)
+  :type '(repeat (cons
+                  (symbol :tag "xfield")
+                  (number :tag "Weight"))))
 (define-obsolete-variable-alias 'bbdb-notes-sort-order 'bbdb-xfields-sort-order)
 
 (defcustom bbdb-merge-xfield-function-alist
@@ -1366,7 +1366,7 @@ In addition, this list may also include
 These provide a fallback if a message does not have a matching RECORD
 or if some FIELD of RECORD is empty."
   :group 'bbdb-mua
-  :type 'list)
+  :type '(repeat (symbol :tag "Field")))
 
 (defcustom bbdb-mua-summary-mark-field 'mark-char
   "BBDB xfield whose value is used to mark message addresses known to BBDB.
@@ -1480,7 +1480,7 @@ If non-nil do not use full name in mail
 If value is mail-only never use full name."
   :group 'bbdb-sendmail
   :type '(choice (const :tag "Allow redundancy" nil)
-                 (const :tag "Never use full name" 'mail-only)
+                 (const :tag "Never use full name" mail-only)
                  (const :tag "Avoid redundancy" t)))
 
 (defcustom bbdb-complete-mail t
@@ -1500,7 +1500,7 @@ If a list of symbols, it specifies which
 If t, completion is done for all of the above.
 If nil, no completion is offered."
   ;; These symbols match the fields for which BBDB provides entries in
-  ;; `bbdb-hash-table'.
+  ;; `bbdb-hashtable'.
   :group 'bbdb-sendmail
   :type '(choice (const :tag "No Completion" nil)
                  (const :tag "Complete across all fields" t)
@@ -1637,7 +1637,7 @@ You really should not disable debugging.
            (repeat (vector string (repeat string) string string
                            string string)) ; address
            (repeat string) ; mail
-           (repeat (cons symbol string)) ; xfields
+           (repeat (cons symbol sexp)) ; xfields
            sexp) ; cache
   "Pseudo-code for the structure of a record.  Used by `bbdb-record-type'.")
 
@@ -1647,9 +1647,6 @@ You really should not disable debugging.
 (defvar bbdb-mail-aliases-need-rebuilt nil
   "Non-nil if mail aliases need to be rebuilt.")
 
-(defvar bbdb-need-to-sort nil
-  "Non-nil if records require sorting after editing.")
-
 (defvar bbdb-buffer nil "Buffer visiting `bbdb-file'.")
 
 (defvar bbdb-buffer-name "*BBDB*" "Name of the BBDB buffer.")
@@ -1658,10 +1655,6 @@ You really should not disable debugging.
   "Bind this to t to quiet things down - do not set it.
 See also `bbdb-silent'.")
 
-(defvar bbdb-notice-hook-pending nil
-  "Bound to t if inside `bbdb-notice-mail-hook' or `bbdb-notice-record-hook'.
-Calls of `bbdb-change-hook' are suppressed when this is non-nil.")
-
 (defvar bbdb-init-forms
   '((gnus                       ; gnus 3.15 or newer
      (add-hook 'gnus-startup-hook 'bbdb-insinuate-gnus))
@@ -1678,6 +1671,8 @@ Calls of `bbdb-change-hook' are suppress
             (add-hook 'mail-setup-hook 'bbdb-insinuate-mail)))
     (message                    ; the gnus mail user agent
      (add-hook 'message-setup-hook 'bbdb-insinuate-message))
+    (mu4e                       ; the mu4e user agent
+     (add-hook 'mu4e-main-mode-hook 'bbdb-insinuate-mu4e))
 
     (sc                         ; supercite
      (add-hook 'sc-load-hook 'bbdb-insinuate-sc))
@@ -1686,12 +1681,17 @@ Calls of `bbdb-change-hook' are suppress
     (pgp                        ; pgp-mail
      (progn
        (add-hook 'message-send-hook 'bbdb-pgp)
-       (add-hook 'mail-send-hook 'bbdb-pgp))))
+       (add-hook 'mail-send-hook 'bbdb-pgp)))
+    (wl
+     (add-hook 'wl-init-hook 'bbdb-insinuate-wl)))
   "Alist mapping features to insinuation forms.")
 
 (defvar bbdb-search-invert nil
   "Bind this variable to t in order to invert the result of `bbdb-search'.")
 
+(defvar bbdb-do-all-records nil
+  "Controls the behavior of the command `bbdb-do-all-records'.")
+
 (defvar bbdb-append-display nil
   "Controls the behavior of the command `bbdb-append-display'.")
 
@@ -1717,12 +1717,9 @@ Use `bbdb-search-changed' to display the
 (defvar bbdb-end-marker nil
   "Marker holding the buffer position of the end of the last record.")
 
-;; The value 127 is an arbitrary prime number.
-;; see elisp:Creating Symbols
-(defvar bbdb-hashtable (make-vector 127 0)
+(defvar bbdb-hashtable (make-hash-table :test 'equal)
   "Hash table for BBDB records.
-Hashes the fields first-last-name, last-first-name, organization, aka,
-and mail.  In elisp lingo, this is really an obarray.")
+Hashes the fields first-last-name, last-first-name, organization, aka, and mail.")
 
 (defvar bbdb-xfield-label-list nil
   "List of labels for xfields.")
@@ -1745,12 +1742,19 @@ and mail.  In elisp lingo, this is reall
 (defvar bbdb-country-list nil
   "List of countries known to BBDB.")
 
-(defvar bbdb-modeline-info (make-vector 4 nil)
+(defvar bbdb-modeline-info (make-vector 6 nil)
   "Precalculated mode line info for BBDB commands.
-This is a vector [APPEND-M INVERT-M APPEND INVERT].
+This is a vector [APPEND-M APPEND INVERT-M INVERT ALL-M ALL].
 APPEND-M is the mode line info if `bbdb-append-display' is non-nil.
 INVERT-M is the mode line info if `bbdb-search-invert' is non-nil.
-APPEND and INVERT appear in the message area.")
+ALL-M is the mode line info if `bbdb-do-all-records' is non-nil.
+APPEND, INVERT, and ALL appear in the message area.")
+
+(defvar bbdb-update-unchanged-records nil
+  "If non-nil update unchanged records in the database.
+Normally calls of `bbdb-change-hook' and updating of a record are suppressed,
+if an editing command did not really change the record.  Bind this to t
+if you want to call `bbdb-change-hook' and update the record unconditionally.")
 
 ;;; Keymap
 (defvar bbdb-mode-map
@@ -1784,7 +1788,8 @@ APPEND and INVERT appear in the message
     (define-key km "?"          'bbdb-help)
     ;; (define-key km "q"       'quit-window) ; part of `special-mode' bindings
     (define-key km "\C-x\C-t"   'bbdb-transpose-fields)
-    (define-key km "C"          'bbdb-copy-records-as-kill)
+    (define-key km "Cr"         'bbdb-copy-records-as-kill)
+    (define-key km "Cf"         'bbdb-copy-fields-as-kill)
     (define-key km "u"          'bbdb-browse-url)
     ;; (define-key km "P"       'bbdb-print)
     (define-key km "="          'delete-other-windows)
@@ -1867,6 +1872,7 @@ This is a child of `special-mode-map'.")
      ["Dial phone number" bbdb-dial t]
      ["Browse URL" bbdb-browse-url t]
      ["Copy records as kill" bbdb-copy-records-as-kill t]
+     ["Copy fields as kill" bbdb-copy-fields-as-kill t]
      "--"
      ["Print records" bbdb-print t])
     ("Manipulate database"
@@ -1912,16 +1918,18 @@ ARGS are passed to `message'."
   (ding t)
   (apply 'message args))
 
-(defsubst bbdb-string-trim (string)
+(defun bbdb-string-trim (string &optional null)
   "Remove leading and trailing whitespace and all properties from STRING.
-If STRING is nil return an empty string."
+If STRING is nil return an empty string unless NULL is non-nil."
   (if (null string)
-      ""
+      (unless null "")
+    (setq string (substring-no-properties string))
     (if (string-match "\\`[ \t\n]+" string)
-        (setq string (substring string (match-end 0))))
+        (setq string (substring-no-properties string (match-end 0))))
     (if (string-match "[ \t\n]+\\'" string)
-        (setq string (substring string 0 (match-beginning 0))))
-    (substring-no-properties string)))
+        (setq string (substring-no-properties string 0 (match-beginning 0))))
+    (unless (and null (string= "" string))
+      string)))
 
 (defsubst bbdb-string= (str1 str2)
   "Return t if strings STR1 and STR2 are equal, ignoring case."
@@ -1997,14 +2005,37 @@ COLLECTION and REQUIRE-MATCH have the sa
          (completing-read prompt collection nil require-match init))
      (read-string prompt init))))
 
-(defun bbdb-add-to-list (list-var element)
-  "Add ELEMENT to the value of LIST-VAR if it isn't there yet and non-nil.
+;; The following macros implement variants of `pushnew' (till emacs 24.2)
+;; or `cl-pushnew' (since emacs 24.3).  To be compatible with older and newer
+;; versions of emacs we use our own macros.  We call these macros often.
+;; So we keep them simple.  Nothing fancy is needed here.
+(defmacro bbdb-pushnew (element listname)
+  "Add ELEMENT to the value of LISTNAME if it isn't there yet.
+The test for presence of ELEMENT is done with `equal'.
+The return value is the new value of LISTNAME."
+  `(let ((elt ,element))
+     (if (member elt ,listname)
+         ,listname
+       (setq ,listname (cons elt ,listname)))))
+
+(defmacro bbdb-pushnewq (element listname)
+  "Add ELEMENT to the value of LISTNAME if it isn't there yet.
+The test for presence of ELEMENT is done with `eq'.
+The return value is the new value of LISTNAME."
+  `(let ((elt ,element))
+     (if (memq elt ,listname)
+         ,listname
+       (setq ,listname (cons elt ,listname)))))
+
+(defmacro bbdb-pushnewt (element listname)
+  "Add ELEMENT to the value of LISTNAME if it isn't there yet and non-nil.
 The test for presence of ELEMENT is done with `equal'.
-The return value is the new value of LIST-VAR."
-  (if (or (not element)
-          (member element (symbol-value list-var)))
-      (symbol-value list-var)
-    (set list-var (cons element (symbol-value list-var)))))
+The return value is the new value of LISTNAME."
+  `(let ((elt ,element))
+     (if (or (not elt)
+             (member elt ,listname))
+         ,listname
+       (setq ,listname (cons elt ,listname)))))
 
 (defun bbdb-current-record (&optional full)
   "Return the record point is at.
@@ -2033,6 +2064,21 @@ You really should not disable debugging.
       `(let ((debug-on-error t))
          ,@body)))
 
+;; inspired by `gnus-bind-print-variables'
+(defmacro bbdb-with-print-loadably (&rest body)
+  "Bind print-* variables for BBDB and evaluate BODY.
+This macro is used with `prin1', `prin1-to-string', etc. in order to ensure
+printed Lisp objects are loadable by BBDB."
+  (declare (indent 0))
+  `(let ((print-escape-newlines t) ;; BBDB needs this!
+         print-escape-nonascii print-escape-multibyte
+         print-quoted print-length print-level)
+         ;; print-circle print-gensym
+         ;; print-continuous-numbering
+         ;; print-number-table
+         ;; float-output-format
+     ,@body))
+
 (defun bbdb-timestamp (record)
   "For use as an element of `bbdb-change-hook'.
 Maintains an xfield `timestamp' for RECORD which contains
@@ -2335,6 +2381,8 @@ It is the caller's responsibility to mak
 ;; When an existing record is modified, the code that modifies the record
 ;; needs to update the hash table, too.  This includes removing the outdated
 ;; associations between KEYs and record as well as adding the new associations.
+;; This is one reason to modify records by calling `bbdb-record-set-field'
+;; which properly updates the hash table.
 ;; The hash table can be accessed via `bbdb-gethash'
 ;; and via functions like `completing-read'.
 
@@ -2342,10 +2390,11 @@ It is the caller's responsibility to mak
   "Associate RECORD with KEY in `bbdb-hashtable'.
 KEY must be a string or nil.  Empty strings and nil are ignored."
   (if (and key (not (string= "" key))) ; do not hash empty strings
-      (let ((sym (intern (downcase key) bbdb-hashtable)))
-        (if (boundp sym)
-            (add-to-list sym record nil 'eq)
-          (set sym (list record))))))
+      (let* ((key (downcase key))
+             (records (gethash key bbdb-hashtable)))
+        (puthash key (if records (bbdb-pushnewq record records)
+                       (list record))
+                 bbdb-hashtable))))
 
 (defun bbdb-gethash (key &optional predicate)
   "Return list of records associated with KEY in `bbdb-hashtable'.
@@ -2353,7 +2402,7 @@ KEY must be a string or nil.  Empty stri
 PREDICATE may take the same values as `bbdb-completion-list'."
   (when (and key (not (string= "" key)))
     (let* ((key (downcase key))
-           (all-records (symbol-value (intern-soft key bbdb-hashtable)))
+           (all-records (gethash key bbdb-hashtable))
            records)
       (if (or (not predicate) (eq t predicate))
           all-records
@@ -2393,12 +2442,13 @@ PREDICATE may take the same values as th
   "Remove RECORD from list of records associated with KEY.
 KEY must be a string or nil.  Empty strings and nil are ignored."
   (if (and key (not (string= "" key)))
-      (let ((sym (intern-soft (downcase key) bbdb-hashtable)))
-        (if sym
-            (let ((val (delq record (symbol-value sym))))
-              (if val
-                  (set sym val)
-                (unintern sym bbdb-hashtable)))))))
+      (let* ((key (downcase key))
+             (records (gethash key bbdb-hashtable)))
+        (when records
+          (setq records (delq record records))
+          (if records
+              (puthash key records bbdb-hashtable)
+            (remhash key bbdb-hashtable))))))
 
 (defun bbdb-hash-record (record)
   "Insert RECORD in `bbdb-hashtable'.
@@ -2468,8 +2518,7 @@ is generated and stored."
 (defun bbdb-record-set-name (record first last)
   "Record cache function: For RECORD set full name based on FIRST and LAST.
 If FIRST or LAST are t use respective existing entries of RECORD.
-Set full name in cache and hash. Also set `bbdb-need-to-sort'.
-Return first-last name."
+Set full name in cache and hash.  Return first-last name."
   (let* ((cache (bbdb-record-cache record))
          (fl-name (bbdb-cache-fl-name cache))
          (lf-name (bbdb-cache-lf-name cache)))
@@ -2477,15 +2526,9 @@ Return first-last name."
     (if lf-name (bbdb-remhash lf-name record)))
   (if (eq t first)
       (setq first (bbdb-record-firstname record))
-    (setq bbdb-need-to-sort
-          (or bbdb-need-to-sort
-              (not (equal first (bbdb-record-firstname record)))))
     (bbdb-record-set-firstname record first))
   (if (eq t last)
       (setq last (bbdb-record-lastname record))
-    (setq bbdb-need-to-sort
-          (or bbdb-need-to-sort
-              (not (equal last (bbdb-record-lastname record)))))
     (bbdb-record-set-lastname record last))
   (let ((fl-name (bbdb-concat 'name-first-last first last))
         (lf-name (bbdb-concat 'name-last-first last first))
@@ -2501,17 +2544,18 @@ Return first-last name."
 
 (defun bbdb-record-sortkey (record)
   "Record cache function: Return the sortkey for RECORD.
-Build and store it if necessary."
+Set and store it if necessary."
   (or (bbdb-cache-sortkey (bbdb-record-cache record))
-      (bbdb-cache-set-sortkey (bbdb-record-cache record)
-        (downcase
-         (bbdb-concat "" (bbdb-record-lastname record)
-                      (bbdb-record-firstname record)
-                      (bbdb-record-organization record))))))
-
-(defsubst bbdb-record-set-sortkey (record sortkey)
-  "Record cache function: Set and return RECORD's SORTKEY."
-  (bbdb-cache-set-sortkey (bbdb-record-cache record) sortkey))
+      (bbdb-record-set-sortkey record)))
+
+(defun bbdb-record-set-sortkey (record)
+  "Record cache function: Set and return RECORD's sortkey."
+  (bbdb-cache-set-sortkey
+   (bbdb-record-cache record)
+   (downcase
+    (bbdb-concat "" (bbdb-record-lastname record)
+                 (bbdb-record-firstname record)
+                 (bbdb-record-organization record)))))
 
 (defsubst bbdb-record-marker (record)
   "Record cache function: Return the marker for RECORD."
@@ -2526,19 +2570,30 @@ Build and store it if necessary."
 Return nil if xfield LABEL is undefined."
   (cdr (assq label (bbdb-record-xfields record))))
 
-;; The values of xfields are always strings.  The following function
+;; The values of xfields are normally strings.  The following function
 ;; comes handy if we want to treat these values as symbols.
 (defun bbdb-record-xfield-intern (record label)
   "For RECORD return interned value of xfield LABEL.
 Return nil if xfield LABEL does not exist."
   (let ((value (bbdb-record-xfield record label)))
-    (if value (intern value))))
+    ;; If VALUE is not a string, return whatever it is.
+    (if (stringp value) (intern value) value)))
+
+(defun bbdb-record-xfield-string (record label)
+  "For RECORD return value of xfield LABEL as string.
+Return nil if xfield LABEL does not exist."
+  (let ((value (bbdb-record-xfield record label)))
+    (if (string-or-null-p value)
+        value
+      (let ((print-escape-newlines t))
+        (prin1-to-string value)))))
 
 (defsubst bbdb-record-xfield-split (record label)
   "For RECORD return value of xfield LABEL split as a list.
 Splitting is based on `bbdb-separator-alist'."
   (let ((val (bbdb-record-xfield record label)))
-    (if val (bbdb-split label val))))
+    (cond ((stringp val) (bbdb-split label val))
+          (val (error "Cannot split `%s'" val)))))
 
 (defun bbdb-record-set-xfield (record label value)
   "For RECORD set xfield LABEL to VALUE.
@@ -2551,13 +2606,13 @@ Return VALUE."
       (error "xfield label `%s' illegal" label))
   (if (eq label 'mail-alias)
       (setq bbdb-mail-aliases-need-rebuilt 'edit))
-  (if (and value (string= "" value)) (setq value nil))
+  (if (stringp value) (setq value (bbdb-string-trim value t)))
   (let ((old-xfield (assq label (bbdb-record-xfields record))))
     ;; Do nothing if both OLD-XFIELD and VALUE are nil.
     (cond ((and old-xfield value) ; update
            (setcdr old-xfield value))
           (value ; new xfield
-           (add-to-list 'bbdb-xfield-label-list label nil 'eq)
+           (bbdb-pushnewq label bbdb-xfield-label-list)
            (bbdb-record-set-xfields record
                                     (append (bbdb-record-xfields record)
                                             (list (cons label value)))))
@@ -2768,7 +2823,7 @@ See also `bbdb-record-field'."
            (setq value (bbdb-list-strings value))
            (bbdb-hash-update record (bbdb-record-organization record) value)
            (dolist (organization value)
-             (add-to-list 'bbdb-organization-list organization))
+             (bbdb-pushnew organization bbdb-organization-list))
            (bbdb-record-set-organization record value))
 
           ;; AKA
@@ -2809,7 +2864,7 @@ See also `bbdb-record-field'."
                                                    value 'equal)))
            (if check (bbdb-check-type value (bbdb-record-phone record-type) t))
            (dolist (phone value)
-             (add-to-list 'bbdb-phone-label-list (bbdb-phone-label phone) nil 'eq))
+             (bbdb-pushnew (bbdb-phone-label phone) bbdb-phone-label-list))
            (bbdb-record-set-phone record value))
 
           ;; Address
@@ -2818,13 +2873,13 @@ See also `bbdb-record-field'."
                                                    value 'equal)))
            (if check (bbdb-check-type value (bbdb-record-address record-type) t))
            (dolist (address value)
-             (add-to-list 'bbdb-address-label-list (bbdb-address-label address) nil 'eq)
-             (mapc (lambda (street) (bbdb-add-to-list 'bbdb-street-list street))
+             (bbdb-pushnew (bbdb-address-label address) bbdb-address-label-list)
+             (mapc (lambda (street) (bbdb-pushnewt street bbdb-street-list))
                    (bbdb-address-streets address))
-             (bbdb-add-to-list 'bbdb-city-list (bbdb-address-city address))
-             (bbdb-add-to-list 'bbdb-state-list (bbdb-address-state address))
-             (bbdb-add-to-list 'bbdb-postcode-list (bbdb-address-postcode address))
-             (bbdb-add-to-list 'bbdb-country-list (bbdb-address-country address)))
+             (bbdb-pushnewt (bbdb-address-city address) bbdb-city-list)
+             (bbdb-pushnewt (bbdb-address-state address) bbdb-state-list)
+             (bbdb-pushnewt (bbdb-address-postcode address) bbdb-postcode-list)
+             (bbdb-pushnewt (bbdb-address-country address) bbdb-country-list))
            (bbdb-record-set-address record value))
 
           ;; all xfields
@@ -2838,9 +2893,9 @@ See also `bbdb-record-field'."
              (if check (bbdb-check-type new-xfields (bbdb-record-xfields record-type) t))
              (dolist (xfield (nreverse value))
                ;; Ignore junk
-               (when (and (cdr xfield) (not (string= "" (cdr xfield))))
+               (when (and (cdr xfield) (not (equal "" (cdr xfield))))
                  (push xfield new-xfields)
-                 (add-to-list 'bbdb-xfield-label-list (car xfield) nil 'eq)))
+                 (bbdb-pushnewq (car xfield) bbdb-xfield-label-list)))
              (bbdb-record-set-xfields record new-xfields)))
 
           ;; Single xfield
@@ -2848,7 +2903,8 @@ See also `bbdb-record-field'."
            (if merge
                (setq value (bbdb-merge-xfield field (bbdb-record-xfield record field)
                                               value)))
-           (if check (bbdb-check-type value 'string t))
+           ;; The following test always succeeds
+           ;; (if check (bbdb-check-type value 'sexp t))
            ;; This removes xfield FIELD if its value is nil.
            (bbdb-record-set-xfield record field value))
 
@@ -2865,7 +2921,7 @@ SEPARATOR defaults to \"\\n\"."
   "Concatenate STRING1 and STRING2, but remove duplicate lines."
   (let ((lines (split-string string1 "\n")))
     (dolist (line (split-string string2 "\n"))
-      (add-to-list 'lines line))
+      (bbdb-pushnew line lines))
     (bbdb-concat "\n" lines)))
 
 (defun bbdb-merge-string-least (string1 string2)
@@ -2900,18 +2956,18 @@ If L1 or L2 are not lists, they are repl
 If LABEL has an entry in `bbdb-merge-xfield-function-alist', use it.
 If VALUE1 or VALUE2 is a substring of the other, return the longer one.
 Otherwise use `bbdb-concat'.  Return nil if we have nothing to merge."
-  (setq value1 (bbdb-string-trim value1)) ; converts nil to ""
-  (setq value2 (bbdb-string-trim value2)) ; converts nil to ""
-  (let ((b1 (not (string= "" value1)))
-        (b2 (not (string= "" value2))))
-    (cond ((and b1 b2)
-           (let ((fun (cdr (assq label bbdb-merge-xfield-function-alist))))
-             (cond (fun (funcall fun value1 value2))
-                   ((string-match (regexp-quote value1) value2) value2)
-                   ((string-match (regexp-quote value2) value1) value1)
-                   (t (bbdb-concat label value1 value2)))))
-          (b1 value1)
-          (b2 value2))))
+  (if (stringp value1) (setq value1 (bbdb-string-trim value1 t)))
+  (if (stringp value2) (setq value2 (bbdb-string-trim value2 t)))
+  (cond ((and value1 value2)
+         (let ((fun (cdr (assq label bbdb-merge-xfield-function-alist))))
+           (cond (fun (funcall fun value1 value2))
+                 ((not (and (stringp value1) (stringp value2)))
+                  (cons value1 value2)) ; concatenate lists
+                 ((string-match (regexp-quote value1) value2) value2)
+                 ((string-match (regexp-quote value2) value1) value1)
+                 (t (bbdb-concat label value1 value2)))))
+        (value1)
+        (value2)))
 
 ;;; Parsing other things
 
@@ -2940,12 +2996,13 @@ LAST is always a string (possibly empty)
 (defun bbdb-parse-postcode (string)
   "Check whether STRING is a legal postcode.
 Do this only if `bbdb-check-postcode' is non-nil."
-  (if (and bbdb-check-postcode
-           (not (memq t (mapcar (lambda (regexp)
-                                  ;; if it matches, (not (not index-of-match)) returns t
-                                  (not (not (string-match regexp string))))
-                                bbdb-legal-postcodes))))
-      (error "not a valid postcode.")
+  (if bbdb-check-postcode
+      (let ((postcodes bbdb-legal-postcodes) re done)
+        (while (setq re (pop postcodes))
+          (if (string-match re string)
+              (setq done t postcodes nil)))
+        (if done string
+          (error "not a valid postcode.")))
     string))
 
 (defun bbdb-phone-string (phone)
@@ -3052,7 +3109,7 @@ copy it to `bbdb-file'."
       (dolist (hook (cons 'bbdb-after-save bbdb-after-save-hook))
         (add-hook 'after-save-hook hook nil t))
 
-      (fillarray bbdb-hashtable 0)
+      (clrhash bbdb-hashtable)
 
       (if (/= (point-min) (point-max))
           (bbdb-parse-records) ; normal case: nonempty db
@@ -3239,19 +3296,19 @@ If `bbdb-file' uses an outdated format,
 
           ;; Set the completion lists
           (dolist (phone (bbdb-record-phone record))
-            (add-to-list 'bbdb-phone-label-list (bbdb-phone-label phone) nil 'eq))
+            (bbdb-pushnew (bbdb-phone-label phone) bbdb-phone-label-list))
           (dolist (address (bbdb-record-address record))
-            (add-to-list 'bbdb-address-label-list (bbdb-address-label address) nil 'eq)
-            (mapc (lambda (street) (bbdb-add-to-list 'bbdb-street-list street))
+            (bbdb-pushnew (bbdb-address-label address) bbdb-address-label-list)
+            (mapc (lambda (street) (bbdb-pushnewt street bbdb-street-list))
                   (bbdb-address-streets address))
-            (bbdb-add-to-list 'bbdb-city-list (bbdb-address-city address))
-            (bbdb-add-to-list 'bbdb-state-list (bbdb-address-state address))
-            (bbdb-add-to-list 'bbdb-postcode-list (bbdb-address-postcode address))
-            (bbdb-add-to-list 'bbdb-country-list (bbdb-address-country address)))
+            (bbdb-pushnewt (bbdb-address-city address) bbdb-city-list)
+            (bbdb-pushnewt (bbdb-address-state address) bbdb-state-list)
+            (bbdb-pushnewt (bbdb-address-postcode address) bbdb-postcode-list)
+            (bbdb-pushnewt (bbdb-address-country address) bbdb-country-list))
           (dolist (xfield (bbdb-record-xfields record))
-            (add-to-list 'bbdb-xfield-label-list (car xfield) nil 'eq))
+            (bbdb-pushnewq (car xfield) bbdb-xfield-label-list))
           (dolist (organization (bbdb-record-organization record))
-            (add-to-list 'bbdb-organization-list organization))
+            (bbdb-pushnew organization bbdb-organization-list))
 
           (let ((name (bbdb-concat 'name-first-last
                                    (bbdb-record-firstname record)
@@ -3319,51 +3376,81 @@ If `bbdb-file' uses an outdated format,
       (if (eq major-mode 'bbdb-mode)
           (set-buffer-modified-p nil)))))
 
-(defun bbdb-change-record (record &optional need-to-sort new)
-  "Update the database after a change of RECORD.  Return RECORD.
-NEED-TO-SORT is t when the name has changed.
+(defun bbdb-change-record (record &optional ignored new)
+  "Update the database after a change of RECORD.
+Return RECORD if RECORD got changed compared with the database,
+return nil otherwise.
+IGNORED is ignored.  It is present only for backward compatibility.
 If NEW is t treat RECORD as new.  New records are hashed.
 If RECORD is not new, it is redisplayed.  Yet it is then the caller's
 responsibility to update the hash-table for RECORD."
   (if bbdb-read-only
       (error "The Insidious Big Brother Database is read-only."))
-  ;; Do the changing.
   ;; The call of `bbdb-records' checks file synchronization.
   ;; If RECORD refers to an existing record that has been changed,
   ;; yet in the meanwhile we reverted the BBDB file, then RECORD
   ;; no longer refers to a record in `bbdb-records'.  So we are stuck!
   ;; All changes will be lost.
-  ;; To avoid this problem we would have to inhibit that `bbdb-file'
-  ;; may change on disc.
-  (cond ((memq record (bbdb-records))
-         (unless bbdb-notice-hook-pending
-           (run-hook-with-args 'bbdb-change-hook record))
-         (if (not need-to-sort) ;; If we do not need to sort, overwrite RECORD.
-             (bbdb-overwrite-record-internal record)
-           ;; Since we need to sort, delete then insert RECORD.
-           ;; Do not mess with the hash table here.
-           ;; We assume it got updated by the caller.
-           (bbdb-delete-record-internal record)
-           (bbdb-insert-record-internal record))
-         ;; If RECORD is currently displayed update display.
-         (bbdb-maybe-update-display record))
-        (new ;; Record is new and not yet in database, so add it.
-         (run-hook-with-args 'bbdb-create-hook record)
-         (unless bbdb-notice-hook-pending
-           (run-hook-with-args 'bbdb-change-hook record))
-         (bbdb-insert-record-internal record)
-         (bbdb-hash-record record))
-        (t (error "Changes are lost.")))
-  (add-to-list 'bbdb-changed-records record nil 'eq)
-  (run-hook-with-args 'bbdb-after-change-hook record)
-  record)
+  ;; FIXME: Once all records have a UUID, we can identify the corresponding
+  ;; record on disk that got edited, so that the user can merge the edited
+  ;; record with what is now on disk (or do whatever with these two records).
+  ;; This implies, first of all, that *here* we make sure that UUIDs are
+  ;; always unique inside BBDB.  For this, include UUIDs in the hash table.
+  ;; If a new record happens to have the same UUID as an existing record,
+  ;; this should also throw an error / branch appropriately.  So the arg NEW
+  ;; will really not be needed anymore and all these things will have a natural
+  ;; solution.
+  (let ((tail (memq record (bbdb-records))))
+    (cond (tail ; RECORD is not new
+           ;; If the string we currently have for RECORD in `bbdb-buffer'
+           ;; is `equal' to the string we would write to `bbdb-buffer',
+           ;; we really did not change RECORD at all.  So we don't update RECORD
+           ;; unless `bbdb-update-unchanged-records' tells us to do so anyway.
+           ;; Also, we only call `bbdb-change-hook' and `bbdb-after-change-hook'
+           ;; if RECORD got changed.
+           (when (or bbdb-update-unchanged-records
+                     (not (string= (bbdb-with-db-buffer
+                                     (buffer-substring-no-properties
+                                      (bbdb-record-marker record)
+                                      (1- (if (cdr tail)
+                                              (bbdb-record-marker (cadr tail))
+                                            bbdb-end-marker))))
+                                   (let ((cache (bbdb-record-cache record))
+                                         (inhibit-quit t))
+                                     (bbdb-record-set-cache record nil)
+                                     (prog1 (bbdb-with-print-loadably
+                                              (prin1-to-string record))
+                                       (bbdb-record-set-cache record cache))))))
+             (run-hook-with-args 'bbdb-change-hook record)
+             (let ((sort (not (equal (bbdb-cache-sortkey (bbdb-record-cache record))
+                                     (bbdb-record-set-sortkey record)))))
+               (if (not sort) ;; If we do not need to sort, overwrite RECORD.
+                   (bbdb-overwrite-record-internal record)
+                 ;; Since we need to sort, delete then insert RECORD.
+                 ;; Do not mess with the hash table here.
+                 ;; We assume it got updated by the caller.
+                 (bbdb-delete-record-internal record)
+                 (bbdb-insert-record-internal record))
+               (bbdb-pushnewq record bbdb-changed-records)
+               (run-hook-with-args 'bbdb-after-change-hook record)
+               (bbdb-redisplay-record-globally record sort))
+             record))
+          (new ;; Record is new and not yet in database, so add it.
+           (run-hook-with-args 'bbdb-create-hook record)
+           (run-hook-with-args 'bbdb-change-hook record)
+           (bbdb-insert-record-internal record)
+           (bbdb-hash-record record)
+           (bbdb-pushnewq record bbdb-changed-records)
+           (run-hook-with-args 'bbdb-after-change-hook record)
+           record)
+          (t (error "Changes are lost")))))
 
 (defun bbdb-delete-record-internal (record &optional completely)
   "Delete RECORD in the database file.
 With COMPLETELY non-nil, also undisplay RECORD and remove it
 from the hash table."
   (unless (bbdb-record-marker record) (error "BBDB: marker absent"))
-  (if completely (bbdb-maybe-update-display record t))
+  (if completely (bbdb-redisplay-record-globally record nil t))
   (bbdb-with-db-buffer
     (let ((tail (memq record bbdb-records))
           (inhibit-quit t))
@@ -3381,23 +3468,7 @@ from the hash table."
         (dolist (mail (bbdb-record-mail-canon record))
           (bbdb-remhash mail record))
         (dolist (aka (bbdb-record-field record 'aka-all))
-          (bbdb-remhash aka record))))
-    (bbdb-record-set-sortkey record nil)))
-
-;; inspired by `gnus-bind-print-variables'
-(defmacro bbdb-with-print-loadably (&rest body)
-  "Bind print-* variables for BBDB and evaluate BODY.
-This macro is used with `prin1', `prin1-to-string', etc. in order to ensure
-printed Lisp objects are loadable by BBDB."
-  (declare (indent 0))
-  `(let ((print-escape-newlines t) ;; BBDB needs this!
-         print-escape-nonascii print-escape-multibyte
-         print-quoted print-length print-level)
-         ;; print-circle print-gensym
-         ;; print-continuous-numbering
-         ;; print-number-table
-         ;; float-output-format
-     ,@body))
+          (bbdb-remhash aka record))))))
 
 (defun bbdb-insert-record-internal (record)
   "Insert RECORD into the database file.  Return RECORD.
@@ -3406,9 +3477,6 @@ that calls the hooks, too."
   (unless (bbdb-record-marker record)
     (bbdb-record-set-marker record (make-marker)))
   (bbdb-with-db-buffer
-    ;; Set the sortkey to nil so that it will automatically be recalculated
-    ;; up-to-date for sorting
-    (bbdb-record-set-sortkey record nil)
     ;; splice record into `bbdb-records'
     (bbdb-debug (if (memq record bbdb-records)
                     (error "BBDB record not unique: - %s" record)))
@@ -3719,13 +3787,20 @@ FIELD-LIST is the list of actually displ
                    (bbdb-display-list aka 'aka "; "))))
             ;; xfields
             (t
-             (let ((xfield (assq field (bbdb-record-xfields record))))
-               (if xfield
-                   (bbdb-display-text (concat (replace-regexp-in-string
-                                               "\n" "; " (cdr xfield)) "; ")
-                                      `(xfields ,xfield)))))))
+             (let* ((xfield (assq field (bbdb-record-xfields record)))
+                    (value (cdr xfield)))
+               (if value
+                   (bbdb-display-text
+                    (concat (if (stringp value)
+                                (replace-regexp-in-string
+                                 "\n" "; " value)
+                              ;; value of xfield is a sexp
+                              (let ((print-escape-newlines t))
+                                (prin1-to-string value)))
+                            "; ")
+                    `(xfields ,xfield)))))))
     ;; delete the trailing "; "
-    (if (looking-back "; ")
+    (if (looking-back "; " nil)
         (backward-delete-char 2))
     (insert "\n")))
 
@@ -3739,12 +3814,12 @@ FIELD-LIST is the list of actually displ
          ;; The format string FMT adds three extra characters.
          ;; So we subtract those from the value of INDENT.
          (fmt (format " %%%ds: " (- indent 3)))
-         start field formatfun)
+         start formatfun)
     (dolist (field field-list)
       (setq start (point))
       (cond (;; customized formatting
              (setq formatfun (intern-soft (format "bbdb-display-%s-multi-line" field)))
-             (funcall formatfun record))
+             (funcall formatfun record indent))
             ;; phone
             ((eq field 'phone)
              (dolist (phone (bbdb-record-phone record))
@@ -3785,13 +3860,23 @@ FIELD-LIST is the list of actually displ
                  (bbdb-display-list aka 'aka "\n"))))
             ;; xfields
             (t
-             (let ((xfield (assq field (bbdb-record-xfields record))))
-               (when xfield
+             (let* ((xfield (assq field (bbdb-record-xfields record)))
+                    (value (cdr xfield)))
+               (when value
                  (bbdb-display-text (format fmt field)
                                     `(xfields ,xfield field-label)
                                     'bbdb-field-name)
                  (setq start (point))
-                 (insert (bbdb-indent-string (cdr xfield) indent) "\n")
+                 (insert (bbdb-indent-string
+                          (if (stringp value)
+                              value
+                            ;; value of xfield is a sexp
+                            (let ((string (pp-to-string value)))
+                              (if (string-match "[ \t\n]+\\'" string)
+                                  (substring-no-properties
+                                   string 0 (match-beginning 0))
+                                string)))
+                          indent) "\n")
                  (bbdb-field-property start `(xfields ,xfield)))))))
     (insert "\n")))
 
@@ -3863,7 +3948,7 @@ SELECT and HORIZ-P have the same meaning
   (interactive (list (bbdb-completing-read-records "Display records: ")
                      (bbdb-layout-prefix)))
   (if (bbdb-append-display-p) (setq append t))
-  ;; `bbdb-redisplay-records' calls `bbdb-display-records'
+  ;; `bbdb-redisplay-record' calls `bbdb-display-records'
   ;; with display information already amended to RECORDS.
   (unless (or (null records)
               (consp (car records)))
@@ -3912,13 +3997,13 @@ SELECT and HORIZ-P have the same meaning
       (unless (or bbdb-silent-internal bbdb-silent)
         (message "Formatting BBDB..."))
       (let ((record-number 0)
-            buffer-read-only all-records start)
+            buffer-read-only all-records)
         (erase-buffer)
         (bbdb-debug (setq all-records (bbdb-records)))
         (dolist (record records)
           (bbdb-debug (unless (memq (car record) all-records)
                         (error "Record %s does not exist" (car record))))
-          (setq start (set-marker (nth 2 record) (point)))
+          (set-marker (nth 2 record) (point))
           (bbdb-display-record (nth 0 record) (nth 1 record) record-number)
           (setq record-number (1+ record-number)))
 
@@ -3929,8 +4014,9 @@ SELECT and HORIZ-P have the same meaning
       (set-buffer-modified-p nil)
 
       (bbdb-pop-up-window select horiz-p)
-      ;; Put point on first new record in *BBDB* buffer.
-      (when first-new
+      (if (not first-new)
+          (goto-char (point-min))
+        ;; Put point on first new record in *BBDB* buffer.
         (goto-char (nth 2 (assq first-new bbdb-records)))
         (set-window-start (get-buffer-window (current-buffer)) (point))))))
 
@@ -3947,20 +4033,26 @@ If ALL-BUFFERS is non-nil undisplay reco
         (setq bbdb-records nil)
         (set-buffer-modified-p nil)))))
 
-(defun bbdb-redisplay-record (record &optional delete-p)
-  "Redisplay RECORD.
-If DELETE-P is non-nil RECORD is removed from the BBDB buffer.
-The BBDB buffer must be current when this is called."
+(defun bbdb-redisplay-record (record &optional sort delete-p)
+  "Redisplay RECORD in current BBDB buffer.
+If SORT is t, usually because RECORD has a new sortkey, re-sort
+the displayed records.
+If DELETE-P is non-nil RECORD is removed from the BBDB buffer."
   ;; For deletion in the *BBDB* buffer we use the full information
   ;; about the record in the database. Therefore, we need to delete
   ;; the record in the *BBDB* buffer before deleting the record in
   ;; the database.
   ;; FIXME: If point is initially inside RECORD, `bbdb-redisplay-record'
   ;; puts point at the beginning of the redisplayed RECORD.
-  ;; Ideally, `bbdb-redisplay-record' should put the point such that it
+  ;; Ideally, `bbdb-redisplay-record' should put point such that it
   ;; matches the previous value `bbdb-ident-point'.
   (let ((full-record (assq record bbdb-records)))
-    (if (null full-record) ; new record
+    (unless full-record
+      (error "Record `%s' not displayed" (bbdb-record-name record)))
+    (if (and sort (not delete-p))
+        ;; FIXME: For records requiring re-sorting it may be more efficient
+        ;; to insert these records in their proper location instead of
+        ;; re-displaying all records.
         (bbdb-display-records (list record) nil t)
       (let ((marker (nth 2 full-record))
             (end-marker (nth 2 (car (cdr (memq full-record bbdb-records)))))
@@ -3981,31 +4073,35 @@ The BBDB buffer must be current when thi
           (delete-region (point) (or end-marker (point-max)))
           ;; If we deleted a record we need to update the subsequent
           ;; record numbers.
-          (if delete-p
-              (let* ((markers (append (mapcar (lambda (x) (nth 2 x))
-                                              (cdr (memq full-record bbdb-records)))
-                                      (list (point-max))))
-                     (start (pop markers)))
-                (dolist (end markers)
-                  (put-text-property start end
-                                     'bbdb-record-number record-number)
-                  (setq start end
-                        record-number (1+ record-number)))))
+          (when delete-p
+            (let* ((markers (append (mapcar (lambda (x) (nth 2 x))
+                                            (cdr (memq full-record bbdb-records)))
+                                    (list (point-max))))
+                   (start (pop markers)))
+              (dolist (end markers)
+                (put-text-property start end
+                                   'bbdb-record-number record-number)
+                (setq start end
+                      record-number (1+ record-number))))
+            (setq bbdb-records (delq full-record bbdb-records)))
           (run-hooks 'bbdb-display-hook))))))
 
-(defun bbdb-maybe-update-display (record &optional delete-p)
-  "If RECORD is currently displayed update display.
-If DELETE-P is nil RECORD is removed from the BBDB buffers."
+(defun bbdb-redisplay-record-globally (record &optional sort delete-p)
+  "Redisplay RECORD in all BBDB buffers.
+If SORT is t, usually because RECORD has a new sortkey, re-sort
+the displayed records.
+If DELETE-P is non-nil RECORD is removed from the BBDB buffers."
   (dolist (buffer (buffer-list))
     (with-current-buffer buffer
       (if (and (eq major-mode 'bbdb-mode)
-               (memq record (bbdb-records)))
+               (memq record (mapcar 'car bbdb-records)))
           (let ((window (get-buffer-window bbdb-buffer-name)))
             (if window
                 (with-selected-window window
-                  (bbdb-redisplay-record record delete-p))
-              (bbdb-redisplay-record record delete-p)))))))
-
+                  (bbdb-redisplay-record record sort delete-p))
+              (bbdb-redisplay-record record sort delete-p)))))))
+(define-obsolete-function-alias 'bbdb-maybe-update-display
+  'bbdb-redisplay-record-globally)
 
 
 ;;; window configuration hackery
@@ -4193,7 +4289,8 @@ There are numerous hooks.  M-x apropos ^
                                 (length bbdb-records))))
               '(:eval (concat "  "
                               (bbdb-concat " " (elt bbdb-modeline-info 0)
-                                           (elt bbdb-modeline-info 1)))))
+                                           (elt bbdb-modeline-info 2)
+                                           (elt bbdb-modeline-info 4)))))
         mode-line-modified
         ;; For the mode-line we want to be fast. So we skip the checks
         ;; performed by `bbdb-with-db-buffer'.
@@ -4409,7 +4506,7 @@ however, after having used other program
     (bbdb-with-db-buffer
       (setq bbdb-records (sort bbdb-records 'bbdb-record-lessp))
       (if (equal records bbdb-records)
-          (message "BBDB need not be sorted")
+          (message "BBDB already sorted properly")
         (message "BBDB was mis-sorted; fixing...")
         (bbdb-goto-first-record)
         (delete-region (point) bbdb-end-marker)
@@ -4426,6 +4523,11 @@ however, after having used other program
             (bbdb-with-print-loadably (prin1 record buf))
             (bbdb-record-set-cache record cache)
             (insert ?\n)))
+        (dolist (buffer (buffer-list))
+          (with-current-buffer buffer
+            (if (eq major-mode 'bbdb-mode)
+                ; Redisplay all records
+                (bbdb-display-records nil nil t))))
         (message "BBDB was mis-sorted; fixing...done")))))
 
 
@@ -4437,10 +4539,12 @@ List MUAS may include the following symb
 mail/news readers, composers, and miscellaneous packages:
   gnus       Gnus mail/news reader.
   mh-e       MH-E mail reader.
+  mu4e       Mu4e mail reader.
   rmail      Rmail mail reader.
   vm         VM mail reader.
   mail       Mail (M-x mail).
   message    Message mode.
+  wl         Wanderlust mail reader.
 
   anniv      Anniversaries in Emacs diary.
 
@@ -4469,3 +4573,5 @@ for example only for outgoing messages."
 
 
 (provide 'bbdb)
+
+;;; bbdb.el ends here
--- bbdb3-3.1.2.orig/lisp/makefile-temp
+++ bbdb3-3.1.2/lisp/makefile-temp
@@ -1,5 +1,5 @@
 # Cheap BBDB makefile  -*- Makefile -*-
-# Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+# Copyright (C) 2010-2016 Roland Winkler <winkler@gnu.org>
 # 
 # This file is part of the Insidious Big Brother Database (aka BBDB),
 # 
@@ -43,20 +43,33 @@ EMACS = emacs
 EMACSOPT =
 
 # The actual Emacs command run in the targets below.
-emacs = LC_ALL=C $(EMACS) --batch --directory=./ $(EMACSOPT)
+# --batch implies --no-init-file, yet let's be explicit about what we want
+emacs = LC_ALL=C $(EMACS) --batch --no-init-file --no-site-file \
+		--directory=./ $(EMACSOPT)
+emacs_compile = $(emacs) --funcall batch-byte-compile
+
+# Mu4e is not part of GNU Emacs.  If you want to use BBDB with Mu4e
+# then the variable MU4EDIR should point to your mu4e lisp directory.
+MU4EDIR =
+MU4E = -eval '(unless (string= "$(MU4EDIR)" "") (push "$(MU4EDIR)" load-path))'
 
-# If you want to use BBDB with VM this should point to your vm/lisp directory.
-# See also the target all below.
+# VM is not part of GNU Emacs.  If you want to use BBDB with VM
+# then the variable VMDIR should point to your vm/lisp directory.
 VMDIR =
+VM = -eval '(unless (string= "$(VMDIR)" "") (push "$(VMDIR)" load-path))'
 
-VM = -eval '(unless (string-match "$(VMDIR)" "") (push "$(VMDIR)" load-path))'
+# WL is not part of GNU Emacs.  If you want to use BBDB with WL
+# then the variable WLDIR should point to your wl/lisp directory.
+WLDIR =
+WL = -eval '(unless (string= "$(WLDIR)" "") (push "$(WLDIR)" load-path))'
 
 .SUFFIXES: .elc .el .tar .Z .gz .uu
 
 SRCS =	bbdb.el bbdb-site.el bbdb-com.el bbdb-print.el bbdb-anniv.el \
 	bbdb-migrate.el bbdb-snarf.el \
 	bbdb-mua.el bbdb-message.el bbdb-rmail.el \
-	bbdb-gnus.el bbdb-mhe.el bbdb-vm.el bbdb-pgp.el bbdb-sc.el \
+	bbdb-gnus.el bbdb-mhe.el bbdb-mu4e.el bbdb-vm.el bbdb-pgp.el \
+	bbdb-sc.el bbdb-wl.el \
 	bbdb-ispell.el bbdb-pkg.el
 
 # ELC =	$(patsubst %.el,%.elc,$(SRCS)) # GNU Make
@@ -64,12 +77,14 @@ ELC =	bbdb.elc bbdb-site.elc bbdb-com.el
 	bbdb-migrate.elc bbdb-snarf.elc \
 	bbdb-mua.elc bbdb-message.elc bbdb-rmail.elc \
 	bbdb-gnus.elc bbdb-mhe.elc bbdb-pgp.elc bbdb-sc.elc \
-	bbdb-ispell.elc # bbdb-pkg.elc
+	bbdb-ispell.elc bbdb-wl.elc # bbdb-pkg.elc
 
 all: bbdb
 
 bbdb:	bbdb-loaddefs.el $(ELC)
+mu4e:	bbdb-mu4e.elc
 vm:	bbdb-vm.elc
+wl:	bbdb-wl.elc
 
 bbdb-loaddefs.el: $(SRCS)
 #	2011-12-11: We switched from bbdb-autoloads.el to bbdb-loaddefs.el.
@@ -89,51 +104,58 @@ bbdb-loaddefs.el: $(SRCS)
 	@echo "" >> $@;
 #	Generated autoload-file must have an absolute path,
 #	$(srcdir) can be relative.
-	$(emacs) -l autoload \
+	$(emacs) --load autoload \
 		--eval '(setq generated-autoload-file "'`pwd`/$@'")' \
 		--eval '(setq make-backup-files nil)' \
-		-f batch-update-autoloads `pwd`
+		--funcall batch-update-autoloads `pwd`
 
 .el.elc:
-	$(emacs) -f batch-byte-compile $<
+	$(emacs_compile) $<
 
 # Not perfect, but better than nothing:  If we do not have / do not use
 # autotools, we simply copy bbdb-site.el.in to bbdb-site.el.
 bbdb-site.el: bbdb-site.el.in
 	$(CP) $< $@
 bbdb-site.elc: bbdb-site.el
-	$(emacs) -f batch-byte-compile $(@:.elc=.el)
+	$(emacs_compile) $(@:.elc=.el)
+bbdb-pkg.el: bbdb-pkg.el.in
+	$(CP) $< $@
 
 bbdb.elc: bbdb.el bbdb-site.elc
-	$(emacs) -f batch-byte-compile $(@:.elc=.el)
+	$(emacs_compile) $(@:.elc=.el)
 
 bbdb-com.elc: bbdb-com.el bbdb.elc
-	$(emacs) -f batch-byte-compile $(@:.elc=.el)
+	$(emacs_compile) $(@:.elc=.el)
 bbdb-mua.elc: bbdb-mua.el bbdb-com.elc
 	$(emacs) -eval '(unless (string= "$(VMDIR)" "") (push "$(VMDIR)" load-path) (load "vm" t t))' \
-	-f batch-byte-compile $(@:.elc=.el)
+	 -eval '(unless (string= "$(MU4EDIR)" "") (push "$(MU4EDIR)" load-path) (load "mu4e" t t))' \
+	 -eval '(unless (string= "$(WLDIR)" "") (push "$(WLDIR)" load-path) (load "wl" t t))' \
+	 --funcall batch-byte-compile $(@:.elc=.el)
 bbdb-rmail.elc: bbdb-rmail.el bbdb-mua.elc
-	$(emacs) -f batch-byte-compile $(@:.elc=.el)
+	$(emacs_compile) $(@:.elc=.el)
 bbdb-gnus.elc: bbdb-gnus.el bbdb-mua.elc
-	$(emacs) -f batch-byte-compile $(@:.elc=.el)
+	$(emacs_compile) $(@:.elc=.el)
 bbdb-mhe.elc: bbdb-mhe.el bbdb-mua.elc
-	$(emacs) -f batch-byte-compile $(@:.elc=.el)
-# VM is not part of GNU Emacs
+	$(emacs_compile) $(@:.elc=.el)
+bbdb-mu4e.elc: bbdb-mu4e.el bbdb-mua.elc
+	$(emacs) $(MU4E) --funcall batch-byte-compile $(@:.elc=.el)
+bbdb-wl.elc: bbdb-wl.el bbdb-mua.elc
+	$(emacs_compile) $(@:.elc=.el)
 bbdb-vm.elc: bbdb-vm.el bbdb-mua.elc
-	$(emacs) $(VM) -f batch-byte-compile $(@:.elc=.el)
+	$(emacs) $(VM) --funcall batch-byte-compile $(@:.elc=.el)
 bbdb-sc.elc: bbdb-sc.el bbdb-mua.elc
-	$(emacs) -f batch-byte-compile $(@:.elc=.el)
+	$(emacs_compile) $(@:.elc=.el)
 
 bbdb-print.elc: bbdb-print.el bbdb-com.elc
-	$(emacs) -f batch-byte-compile $(@:.elc=.el)
+	$(emacs_compile) $(@:.elc=.el)
 bbdb-migrate.elc: bbdb-migrate.el bbdb.elc
-	$(emacs) -f batch-byte-compile $(@:.elc=.el)
+	$(emacs_compile) $(@:.elc=.el)
 bbdb-anniv.elc: bbdb-anniv.el bbdb-com.elc
-	$(emacs) -f batch-byte-compile $(@:.elc=.el)
+	$(emacs_compile) $(@:.elc=.el)
 bbdb-ispell.elc: bbdb-ispell.el bbdb.elc
-	$(emacs) -f batch-byte-compile $(@:.elc=.el)
+	$(emacs_compile) $(@:.elc=.el)
 bbdb-snarf.elc: bbdb-snarf.el bbdb-com.elc
-	$(emacs) -f batch-byte-compile $(@:.elc=.el)
+	$(emacs_compile) $(@:.elc=.el)
 
 install-el: all
 	$(INSTALL) -d -m 0755 "$(lispdir)/"
--- /dev/null
+++ bbdb3-3.1.2/m4/emacs_mu4e.m4
@@ -0,0 +1,39 @@
+### emacs_mu4e.m4
+
+## Copyright (C) 2015-2016 Roland Winkler <winkler@gnu.org>
+##
+## This file is part of the Insidious Big Brother Database (aka BBDB),
+##
+## BBDB is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## (at your option) any later version.
+##
+## BBDB is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with BBDB.  If not, see <http://www.gnu.org/licenses/>.
+
+AC_DEFUN([EMACS_MU4E],
+[
+AC_ARG_WITH([mu4e-dir],
+AS_HELP_STRING([--with-mu4e-dir=DIR], [where to find Mu4e lisp directory]),
+# if Mu4e was requested, make sure we have access to the source
+[if test "x$with_mu4e_dir" != xno -a "x$with_mu4e_dir" != "x"; then
+    AC_MSG_CHECKING([for Mu4e files])
+    # convert path to absolute and canonicalize it.
+    MU4EDIR=$(${EMACS} -batch --quick -eval "(message \"%s\" (expand-file-name \"${with_mu4e_dir}\"))" 2>&1)
+    MU4E_LOCATE=$(${EMACS} -batch --quick --directory="${MU4EDIR}" -eval "(if (locate-library \"mu4e-vars\") (message \"mu4e\"))" 2>&1)
+    if test "x$MU4E_LOCATE" = "x"; then
+       AC_MSG_ERROR([*** MU4E mu4e-vars.el must exist in directory passed to --with-mu4e-dir.])
+    fi
+    AC_MSG_RESULT($MU4EDIR)
+    # append MU4EDIR to AM_ELCFLAGS
+    AM_ELCFLAGS="--directory=$MU4EDIR $AM_ELCFLAGS"
+ fi])
+# New conditional MU4E
+AM_CONDITIONAL([MU4E], [test x$MU4EDIR != x])
+])
--- bbdb3-3.1.2.orig/m4/emacs_vm.m4
+++ bbdb3-3.1.2/m4/emacs_vm.m4
@@ -1,6 +1,6 @@
 ### emacs_vm.m4
 
-## Copyright (C) 2013-2014 Roland Winkler <winkler@gnu.org>
+## Copyright (C) 2013-2016 Roland Winkler <winkler@gnu.org>
 ##
 ## This file is part of the Insidious Big Brother Database (aka BBDB),
 ##
--- /dev/null
+++ bbdb3-3.1.2/m4/emacs_wl.m4
@@ -0,0 +1,39 @@
+### emacs_wl.m4
+
+## Copyright (C) 2016 Roland Winkler <winkler@gnu.org>
+##
+## This file is part of the Insidious Big Brother Database (aka BBDB),
+##
+## BBDB is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## (at your option) any later version.
+##
+## BBDB is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with BBDB.  If not, see <http://www.gnu.org/licenses/>.
+
+AC_DEFUN([EMACS_WL],
+[
+AC_ARG_WITH([wl-dir],
+AS_HELP_STRING([--with-wl-dir=DIR], [where to find Wl lisp directory]),
+# if Wl was requested, make sure we have access to the source
+[if test "x$with_wl_dir" != xno -a "x$with_wl_dir" != "x"; then
+    AC_MSG_CHECKING([for Wl files])
+    # convert path to absolute and canonicalize it.
+    WLDIR=$(${EMACS} -batch --quick -eval "(message \"%s\" (expand-file-name \"${with_wl_dir}\"))" 2>&1)
+    WL_LOCATE=$(${EMACS} -batch --quick --directory="${WLDIR}" -eval "(if (locate-library \"wl-vars\") (message \"wl\"))" 2>&1)
+    if test "x$WL_LOCATE" = "x"; then
+       AC_MSG_ERROR([*** WL wl-vars.el must exist in directory passed to --with-wl-dir.])
+    fi
+    AC_MSG_RESULT($WLDIR)
+    # append WLDIR to AM_ELCFLAGS
+    AM_ELCFLAGS="--directory=$WLDIR $AM_ELCFLAGS"
+ fi])
+# New conditional WL
+AM_CONDITIONAL([WL], [test x$WLDIR != x])
+])
--- bbdb3-3.1.2.orig/m4/package_date.m4
+++ bbdb3-3.1.2/m4/package_date.m4
@@ -1,6 +1,6 @@
 ### package_date.m4
 
-## Copyright (C) 2013-2014 Roland Winkler <winkler@gnu.org>
+## Copyright (C) 2013-2016 Roland Winkler <winkler@gnu.org>
 ##
 ## This file is part of the Insidious Big Brother Database (aka BBDB),
 ##
--- bbdb3-3.1.2.orig/tex/Makefile.am
+++ bbdb3-3.1.2/tex/Makefile.am
@@ -1,7 +1,7 @@
 # tex/Makefile.am for BBDB
 #
 # Copyright (C) 2013 Christian Egli <christian.egli@sbs.ch>
-# Copyright (C) 2013-2014 Roland Winkler <winkler@gnu.org>
+# Copyright (C) 2013-2015 Roland Winkler <winkler@gnu.org>
 # 
 # This file is part of the Insidious Big Brother Database (aka BBDB),
 # 
