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-9) unstable; urgency=medium
 .
   * track upstream changes
     - UUIDs, database format 9
   * bump policy
   * secure packaging repo URL
Author: Barak A. Pearlmutter <bap@debian.org>

---
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: 2017-11-22

--- bbdb3-3.1.2.orig/ChangeLog
+++ bbdb3-3.1.2/ChangeLog
@@ -1,3 +1,450 @@
+2017-10-17  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb.el (bbdb-parse-records): Bug fix, hash record after
+	checking for duplicates.
+
+2017-10-11  Roland Winkler  <winkler@gnu.org>
+	* configure.ac: Use it.
+	* lisp/bbdb.el: Mention new mailing list bbdb-user@nongnu.org.
+
+2017-10-11  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb.el (bbdb-parse-records): Query before migrating BBDB
+	to new format.
+	(bbdb-delete-record-internal, bbdb-insert-record-internal)
+	(bbdb-overwrite-record-internal): Barf if buffer is read-only.
+
+2017-10-11  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-com.el (bbdb-search, bbdb-split-maybe): Fix docstring.
+	(bbdb-read-record): Fix calling sequence for calls to set record.
+
+2017-08-09  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-migrate.el (bbdb-migrate-uuid-xfield): New variable.
+
+2017-08-09  Roland Winkler  <winkler@gnu.org>
+	New field uuid.  Make creation-date and timestamp immutable.
+	* lisp/bbdb.el (bbdb-create-hook, bbdb-change-hook): Use
+	defcustom.
+	(bbdb-merge-records-function): New variable.
+	(bbdb-layout-alist): Omit uuid.
+	(bbdb-xfields-sort-order, bbdb-merge-xfield-function-alist):
+	Ignore creation-date and timestamp.
+	(bbdb-file-format): Bump to 9.
+	(bbdb-record-type): Include uuid, creation-date and timestamp.
+	(bbdb-uuid-table): New variable.
+	(bbdb-timestamp, bbdb-creation-date): Declare obsolete.
+	(bbdb-uuid): New function.
+	(bbdb-hash-record): Hash uuid.
+	(bbdb-record-field, bbdb-record-set-field, bbdb-buffer)
+	(bbdb-display-record-one-line, bbdb-display-record-multi-line)
+	(bbdb-display-record): Handle uuid, creation-date and timestamp.
+	(bbdb-change-record): Use uuid.
+	* lisp/bbdb-com.el (bbdb-search): Use keywords for args.  Handle
+	uuid, creation-date and timestamp.  New option :bool.
+	(bbdb, bbdb-search-name, bbdb-search-organization)
+	(bbdb-search-address, bbdb-search-mail, bbdb-search-phone)
+	(bbdb-search-xfields, bbdb-mail-aliases, bbdb-get-mail-aliases):
+	Change accordingly.
+	(bbdb-compare-records): Compare any fields.
+	(bbdb-timestamp-older, bbdb-timestamp-newer, bbdb-creation-older)
+	(bbdb-creation-newer): Fix interactive spec.
+	(bbdb-creation-no-change): Use bbdb-record-timestamp.
+	(bbdb-read-record): Use bbdb-empty-record.
+	(bbdb-create): Fix call of bbdb-change-record.
+	(bbdb-split-maybe): New function.
+	(bbdb-create-internal): Use keywords for args.
+	(bbdb-edit-field, bbdb-edit-foo, bbdb-merge-records): Handle uuid,
+	creation-date and timestamp.
+	(bbdb-delete-records): Ignore records not known to BBDB.
+	* lisp/bbdb-snarf.el (bbdb-snarf)
+	* lisp/bbdb-mua.el (bbdb-annotate-message): Fix call of
+	bbdb-change-record.
+	* lisp/bbdb-migrate.el (bbdb-migration-features): Remove.
+	(bbdb-peel-the-onion): Merge with bbdb-migrate.
+	(bbdb-migrate): Handle format 9.
+	(bbdb-migrate-alist): Rename from bbdb-migration-spec.
+	(bbdb-migrate-record-lambda): Merge with bbdb-migrate-lambda.
+	(bbdb-migrate-lambda): Rename from bbdb-migrate-versions-lambda.
+	(bbdb-migrate-postcode-to-string): Rename from
+	bbdb-migrate-postcodes-to-strings.  Simplify.
+	(bbdb-migrate-dates): Rename from bbdb-migrate-change-dates.
+	Simplify.
+	(bbdb-migrate-add-country): Rename from
+	bbdb-migrate-add-country-field.
+	(bbdb-undocumented-variables): Handle byte-obsolete-variable.
+
+2017-07-25  Roland Winkler  <winkler@gnu.org>
+	* Makefile.am: Fix rule BBDB_ELPA_FILES. (Bug#51563)
+
+2017-07-25  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-tex.el: Improve documentation.
+
+2017-07-25  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-tex.el (bbdb-tex): Bug fix. (Bug#51564)
+
+2017-07-21  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb.el (bbdb-split): Fix previous patch.
+
+2017-07-21  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb.el (bbdb-split): Use arg TRIM of split-string with
+	emacs-version >= 24.4.
+
+2017-07-19  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-tex.el (bbdb-tex): Allow empty space when calling
+	\usepackage.
+
+2017-07-19  Roland Winkler  <winkler@gnu.org>
+	* tex/bbdb.sty: Use \RequirePackage.
+
+2017-07-19  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-tex.el (bbdb-tex-alist): Improve docstring.
+
+2017-07-03  Roland Winkler  <winkler@gnu.org>
+	Use LaTeX for TeXing BBDB.
+	* lisp/bbdb-tex.el: Replacement for lisp/bbdb-print.el.
+	* lisp/bbdb-site.el.in (bbdb-tex-path): Renamed from
+	bbdb-print-tex-path.  Allow new value t.
+	* lisp/bbdb.el (bbdb-utilities-tex): Renamed from
+	bbdb-utilities-print.
+	(bbdb-separator-alist): New element tex-name.  Fix docstring.
+	* lisp/makefile-temp, lisp/Makefile.am: Use bbdb-tex.
+	* tex/bbdb-print-brief.tex, tex/bbdb-cols.tex, tex/bbdb-print.tex:
+	Removed.
+	* tex/bbdb.sty: New file.
+	* tex/Makefile.am: Update accordingly.
+
+2017-01-31  Roland Winkler  <winkler@gnu.org>
+	* README: Really discontinue support for GNU Emacs 23.
+
+2017-01-30  Barak A. Pearlmutter <barak@pearlmutter.net>
+	* TODO: Extend feature wishlist.
+
+2017-01-30  Barak A. Pearlmutter <barak@pearlmutter.net>
+	* README: Add pointer to emacs wiki upgrade page.
+
+2017-01-30  Roland Winkler  <winkler@gnu.org>
+	* README, lisp/bbdb-site.el.in: Discontinue support for GNU Emacs
+	23.
+
+2017-01-28  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-anniv.el (bbdb-anniv-diary-entries): Propertize the
+	strings passed to diary-add-to-list.
+	(bbdb-anniv-goto-entry): New function used as
+	diary-goto-entry-function.
+
+2017-01-28  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-anniv.el (bbdb-anniv-diary-entries): Use cl-flet.
+
+2017-01-28  Roland Winkler  <winkler@gnu.org>
+	* lisp/bbdb-anniv.el: Use lexical binding.
+	* lisp/bbdb-anniv.el (bbdb-anniv-diary-entries): Use lexical
+	environment for eval.
+
+2017-01-28  Roland Winkler  <winkler@gnu.org>
+	Discontinue support for old GNU Emacs 23.
+	* lisp/bbdb.el (bbdb-buffer, bbdb-revert):
+	* lisp/bbdb-com.el (bbdb-complete-mail): Update accordingly.
+
+2017-01-28  Roland Winkler  <winkler@gnu.org>
+	Update copyright year in all files.
+
+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 +2312,7 @@
 ;; coding: utf-8
 ;; End:
 
-  Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+  Copyright (C) 2010-2017 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-2017 Roland Winkler <winkler@gnu.org>
 #
 # This file is part of the Insidious Big Brother Database (aka BBDB),
 #
@@ -24,7 +24,7 @@ doc_DATA = COPYING ChangeLog AUTHORS NEW
 
 EXTRA_DIST = autogen.sh
 
-BBDB_ELPA_FILES = README COPYING lisp/*.el doc/bbdb.info doc/dir tex/*.tex
+BBDB_ELPA_FILES = README COPYING lisp/*.el doc/*.info doc/dir tex/*.sty
 BBDB_ELPA_PACKAGE = bbdb-$(PACKAGE_VERSION).tar
 
 # doc/dir is needed for the ELPA package
--- bbdb3-3.1.2.orig/NEWS
+++ bbdb3-3.1.2/NEWS
@@ -1,10 +1,28 @@
 BBDB NEWS -- history of user-visible changes.
 
-Copyright (C) 2013-2014 Roland Winkler <winkler@gnu.org>
+Copyright (C) 2013-2017 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
+** BBDB 3.2 requires GNU Emacs 24 or newer.
+Support for GNU Emacs 23 has been discontinued.
+
+** 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-2017 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/
@@ -13,9 +13,9 @@ To check it out, use
 git clone git://git.savannah.nongnu.org/bbdb.git
 
 Questions, comments, suggestions, and bug reports may be directed to
-the BBDB mailing list at bbdb-info@lists.sourceforge.net.
-To subscribe, send mail to bbdb-info-request@lists.sourceforge.net,
-with 'subscribe' as the subject.
+the BBDB mailing list at bbdb-user@nongnu.org.
+To subscribe to this list, go to
+https://lists.nongnu.org/mailman/listinfo/bbdb-user.
 
 ==================================================================
 Installation:   (see also the generic file INSTALL)
@@ -33,13 +33,19 @@ To compile and install BBDB with `make':
 
    Run the `configure' script in the top directory of the BBDB code.
    This performs a number of checks on your system and generates the
-   Makefiles accordingly.  You need at least GNU Emacs 23.
+   Makefiles accordingly.  You need at least GNU Emacs 24.
 
    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.
@@ -81,8 +87,11 @@ To compile and install BBDB with `make':
 ===============================================================================
 Usage notes
 
-BBDB 3.1 is the first release of BBDB after a long time.
-It requires GNU Emacs 23 or newer.  Its code is still under development.
+BBDB 3 is the first release of BBDB after a long time.
+Up to BBDB 3.1.2 it requires GNU Emacs 23 or newer.
+More recent versions require GNU Emacs 24 or newer.
+
+The code of BBDB 3 is still under development.
 While it should work reliably, users of previous versions of BBDB
 are advised that the format of the BBDB database file has changed.
 Migration to the new format should happen automatically.
@@ -93,9 +102,11 @@ As compared with BBDB 2.xx, many variabl
 have changed in BBDB 3.  Most likely you will have to review your
 customizations carefully.  You may want to call bbdb-undocumented-variables
 to identify outdated (i.e., now usually undocumented) variables in
-your init file.  All user variables for the core of BBDB 3 are listed
-at the beginning of bbdb.el.  Some extensions of BBDB 3 define their
-user variables at the beginning of the respective files.
+your init file.  Those upgrading from BBDB 2.xx may also find this
+Emacs wiki page helpful: https://www.emacswiki.org/emacs/UpgradeBBDB
+All user variables for the core of BBDB 3 are listed at the beginning
+of bbdb.el.  Some extensions of BBDB 3 define their user variables
+at the beginning of the respective files.
 
 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.
@@ -108,7 +119,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 +169,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 +214,7 @@ sequence of calls is
 
 ==================================================================
 
-Copyright (C) 2010-2014 Roland Winkler <winkler@gnu.org>
+Copyright (C) 2010-2017 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-2017 Roland Winkler <winkler@gnu.org>
 See the end of the file for license conditions.
 
 * Bug fixes
@@ -41,6 +41,26 @@ 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 +72,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-2017 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-2017 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-2017 Roland Winkler <winkler@gnu.org>
 # 
 # Author:        Didier Verna <didier@xemacs.org>
 # Maintainer:    Roland Winkler <winkler@gnu.org>
@@ -23,7 +23,7 @@
 
 AC_PREREQ([2.69])
 
-AC_INIT([bbdb],[3.1.2],[bbdb-info@lists.sourceforge.net],[],[http://savannah.nongnu.org/projects/bbdb/]) 
+AC_INIT([bbdb],[3.1.2],[bbdb-user@nongnu.org],[],[http://savannah.nongnu.org/projects/bbdb/]) 
 AC_CONFIG_SRCDIR([lisp/bbdb.el])
 AC_CONFIG_MACRO_DIR([m4])
 # We need GNU Automake 1.13 for AM_ELCFLAGS.
@@ -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-2017 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-2017 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-2017 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				\
@@ -31,7 +34,7 @@ dist_lisp_LISP = 				\
 	bbdb-migrate.el				\
 	bbdb-mua.el				\
 	bbdb-pgp.el				\
-	bbdb-print.el				\
+	bbdb-tex.el				\
 	bbdb-rmail.el				\
 	bbdb-sc.el				\
 	bbdb-snarf.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
+;;; bbdb-anniv.el --- get anniversaries from BBDB -*- lexical-binding: t -*-
 
-;; 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),
 
@@ -34,9 +34,13 @@
 ;;
 ;; See the BBDB info manual for documentation.
 
+;;; Code:
+
 (require 'bbdb)
 (require 'bbdb-com)
 (require 'diary-lib)
+(eval-when-compile
+  (require 'cl-lib))
 
 (defcustom bbdb-anniv-alist
   '((birthday . "%n's %d%s birthday")
@@ -54,7 +58,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)
 
@@ -79,48 +83,44 @@ To enable this feature, put the followin
          (end-date (+ num-date number)))
     (while (<= (setq num-date (1+ num-date)) end-date)
       (let* ((date (calendar-gregorian-from-absolute num-date))
-             ;; The following variables may be used by `diary-date-forms'.
-             (day (calendar-extract-day date))
-             (month (calendar-extract-month date))
-             (current-year (calendar-extract-year date))
-             (non-leap (and (= month 3) (= day 1)
-                            (not (calendar-leap-year-p current-year))))
+             (dd (calendar-extract-day date))
+             (mm (calendar-extract-month date))
+             (yy (calendar-extract-year date))
+             ;; We construct a regexp that only uses shy groups,
+             ;; except for the part of the regexp matching the year.
+             ;; This way we can grab the year from the date string.
+             (year "\\([0-9]+\\)\\|\\*")
              (dayname (format "%s\\|%s\\.?" (calendar-day-name date)
                               (calendar-day-name date 'abbrev)))
-             (monthname (format "%s\\|%s" (calendar-month-name month)
-                                (calendar-month-name month 'abbrev)))
-             (day (format "0*%d" day))
-             (month (format "0*%d" month))
-             ;; We could use an explicitly numbered group to match the year.
-             ;; This requires emacs 23.
-             (year "\\([0-9]+\\)\\|\\*")
+             (lex-env `((day . ,(format "0*%d" dd))
+                        (month . ,(format "0*%d" mm)) (year . ,year)
+                        (dayname . ,dayname)
+                        (monthname . ,(format "%s\\|%s" (calendar-month-name mm)
+                                              (calendar-month-name mm 'abbrev)))))
+             ;; Require that the matched date is at the beginning of the string.
+             (fmt (format "\\`%s?\\(?:%%s\\)"
+                          (regexp-quote diary-nonmarking-symbol)))
              date-forms)
 
-        (dolist (date-form diary-date-forms)
-          ;; Require that the matched date is at the beginning of the string.
-          ;; Use shy groups so that we can grab the year more easily.
-          (push (cons (format "\\`%s?\\(?:%s\\)"
-                              (regexp-quote diary-nonmarking-symbol)
-                              (mapconcat 'eval (if (eq (car date-form) 'backup)
-                                                   (cdr date-form) date-form)
-                                         "\\)\\(?:"))
-                      (eq (car date-form) 'backup))
-                date-forms))
-
-        ;; The anniversary of February 29 is considered to be March 1
-        ;; in non-leap years.  So we search for February 29, too.
-        (when non-leap
-          (let* ((day "0*29") (month "0*2")
-                 (monthname (format "%s\\|%s" (calendar-month-name 2)
-                                    (calendar-month-name 2 'abbrev))))
-            (dolist (date-form diary-date-forms)
-              (push (cons (format "\\`%s?\\(?:%s\\)"
-                                  (regexp-quote diary-nonmarking-symbol)
-                                  (mapconcat 'eval (if (eq (car date-form) 'backup)
-                                                       (cdr date-form) date-form)
-                                             "\\)\\(?:"))
-                          (eq (car date-form) 'backup))
-                    date-forms))))
+        (cl-flet ((fun (date-form)
+                       (push (cons (format fmt
+                                           (mapconcat (lambda (form) (eval form lex-env))
+                                                      (if (eq (car date-form) 'backup)
+                                                          (cdr date-form) date-form)
+                                                      "\\)\\(?:"))
+                                   (eq (car date-form) 'backup))
+                             date-forms)))
+          (mapc #'fun diary-date-forms)
+
+          ;; The anniversary of February 29 is considered to be March 1
+          ;; in non-leap years.  So we search for February 29, too.
+          (when (and (= mm 3) (= dd 1)
+                     (not (calendar-leap-year-p yy)))
+            (setq lex-env `((day . "0*29") (month . "0*2") (year . ,year)
+                            (dayname . ,dayname)
+                            (monthname . ,(format "%s\\|%s" (calendar-month-name 2)
+                                                  (calendar-month-name 2 'abbrev)))))
+            (mapc #'fun diary-date-forms)))
 
         (dolist (record (bbdb-records))
           (dolist (rule bbdb-anniv-alist)
@@ -128,13 +128,13 @@ To enable this feature, put the followin
               (let ((date-forms date-forms)
                     (anniv-string (concat anniv " X")) ; for backup forms
                     (case-fold-search t)
-                    form yy text)
+                    form yr text)
                 (while (setq form (pop date-forms))
                   (when (string-match (car form) anniv-string)
                     (setq date-forms nil
-                          yy (match-string 1 anniv-string)
-                          yy (if (and yy (string-match-p "[0-9]+" yy))
-                                 (- current-year (string-to-number yy))
+                          yr (match-string 1 anniv-string)
+                          yr (if (and yr (string-match-p "[0-9]+" yr))
+                                 (- yy (string-to-number yr))
                                100) ; as in `diary-anniversary'
                           ;; For backup forms we should search backward in
                           ;; anniv-string from (match-end 0) for "\\<".
@@ -145,25 +145,67 @@ To enable this feature, put the followin
                           ;; Then we may simply step backward by one character.
                           text (substring anniv-string (if (cdr form) ; backup
                                                            (1- (match-end 0))
-                                                         (match-end 0)) -1)
+                                                         (match-end 0))
+                                          -1)
                           text (replace-regexp-in-string "\\`[ \t]+" "" text)
                           text (replace-regexp-in-string "[ \t]+\\'" "" text))
                     (if (cdr rule)
-                        (setq text (replace-regexp-in-string "%t" text (cdr rule))))))
-                ;; Add the anniversaries to `diary-entries-list'.
-                (if (and yy (> yy 0) (< 0 (length text)))
-                    (diary-add-to-list
-                     date
-                     (format
-                      ;; Text substitution similar to `diary-anniversary'.
-                      (replace-regexp-in-string "%n" (bbdb-record-name record) text)
-                      yy (diary-ordinal-suffix yy))
-                     ;; It would be nice to have a SPECIFIER that allowed us to jump
-                     ;; from the diary display buffer to the respective BBDB record.
-                     ;; Yet it seems that diary-lib does not support this for us.
-                     ;; So we use instead an empty string.  When clicking on the
-                     ;; anniversary entry in the diary display buffer, this give us
-                     ;; the message "Unable to locate this diary entry".
-                     ""))))))))))
+                        (setq text (replace-regexp-in-string "%t" text (cdr rule))))
+                    ;; Add the anniversaries to `diary-entries-list'.
+                    (if (and (numberp yr) (< 0 (length text)))
+                        (diary-add-to-list
+                         date
+                         ;; `diary-add-to-list' expects an arg SPECIFIER for being
+                         ;; able to jump to the location of the entry in the diary
+                         ;; file.  Here we only have BBDB records.  So we use
+                         ;; an empty string for SPECIFIER, but instead we `propertize'
+                         ;; the STRING passed to `diary-add-to-list'.
+                         (propertize
+                          (format
+                           ;; Text substitution similar to `diary-anniversary'.
+                           (replace-regexp-in-string "%n" (bbdb-record-name record) text)
+                           yr (diary-ordinal-suffix yr))
+                          'diary-goto-entry (list 'bbdb-display-records (list record)))
+                         ""))))))))))))
+
+;; based on `diary-goto-entry'
+(defun bbdb-anniv-goto-entry (button)
+  "Jump to the diary entry for the BUTTON at point.
+The character at point may have a text property `diary-goto-entry'
+which should be a list (FUNCTION ARG1 ARG2 ...).  Then call FUNCTION
+with args ARG1, ARG2, ... to locate the entry.  Otherwise follow
+the rules used by `diary-goto-entry'."
+  (let* ((fun-call (get-text-property (overlay-start button)
+                                      'diary-goto-entry))
+         (locator (button-get button 'locator))
+         (marker (car locator))
+         markbuf file)
+    (cond (fun-call
+           (apply (car fun-call) (cdr fun-call)))
+          ;; If marker pointing to diary location is valid, use that.
+          ((and marker (setq markbuf (marker-buffer marker)))
+           (pop-to-buffer markbuf)
+           (goto-char (marker-position marker)))
+          ;; Marker is invalid (eg buffer has been killed).
+          ((and (setq file (cadr locator))
+                (file-exists-p file)
+                (find-file-other-window file))
+           (when (eq major-mode (default-value 'major-mode)) (diary-mode))
+           (goto-char (point-min))
+           (if (re-search-forward (format "%s.*\\(%s\\)"
+                                          (regexp-quote (nth 2 locator))
+                                          (regexp-quote (nth 3 locator)))
+                                  nil t)
+               (goto-char (match-beginning 1))))
+          (t
+           (message "Unable to locate this diary entry")))))
+
+;; `diary-goto-entry-function' is rather inflexible if multiple packages
+;; want to use it for its purposes: this variable can be hijacked
+;; only once.  Here our function `bbdb-anniv-goto-entry' should work
+;; for other packages, too.
+(setq diary-goto-entry-function 'bbdb-anniv-goto-entry)
 
 (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-2017 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,132 +172,243 @@ 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))))
-
-(defmacro bbdb-search (records &optional name-re org-re mail-re xfield-re
-                               phone-re address-re)
-  "Search RECORDS for fields matching regexps.
-Regexp NAME-RE is matched against FIRST_LAST, LAST_FIRST, and AKA.
-Regexp XFIELD-RE is matched against xfield notes.
-XFIELD-RE may also be a cons (LABEL . RE).  Then RE is matched against
-xfield LABEL.  If LABEL is '* then RE is matched against any xfield.
-
-This macro only generates code for those fields actually being searched for;
-literal nils at compile-time cause no code to be generated.
-
-To reverse the search, bind variable `bbdb-search-invert' to t.
+  (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 &rest spec)
+  "Search RECORDS for fields matching SPEC.
+The following keywords are supported in SPEC to search fields in RECORDS
+matching the regexps RE:
+
+:name RE          Match RE against first-last name.
+:name-fl RE       Match RE against last-first name.
+:all-names RE     Match RE against first-last, last-first, and aka.
+:affix RE         Match RE against affixes.
+:aka RE           Match RE against akas.
+:organization RE  Match RE against organizations.
+:mail RE          Match RE against mail addresses.
+:xfield RE        Match RE against `bbdb-default-xfield'.
+                  RE may also be a cons (LABEL . REGEXP).
+                  Then REGEXP is matched against xfield LABEL.
+                  If LABEL is '* then RE is matched against all xfields.
+:creation-date RE Match RE against creation-date.
+:timestamp RE     Match RE against timestamp.
+
+Each of these keywords may appear multiple times.
+Other keywords:
+
+:bool BOOL        Combine the search for multiple fields using BOOL.
+                  BOOL may be either `or' (match either field)
+                  or `and' (match all fields) with default `or'.
 
+To reverse the search, bind `bbdb-search-invert' to t.
 See also `bbdb-message-search' for fast searches using `bbdb-hashtable'
-but not allowing for regexps."
-  (let (clauses)
-    ;; I did not protect these vars from multiple evaluation because that
-    ;; actually generates *less efficient code* in elisp, because the extra
-    ;; bindings cannot easily be optimized away without lexical scope.  fmh.
-    (or (stringp name-re) (symbolp name-re) (error "name-re must be atomic"))
-    (or (stringp org-re) (symbolp org-re) (error "org-re must be atomic"))
-    (or (stringp mail-re) (symbolp mail-re) (error "mail-re must be atomic"))
-    (or (stringp xfield-re) (symbolp xfield-re) (consp xfield-re)
-        (error "xfield-re must be atomic or cons"))
-    (or (stringp phone-re) (symbolp phone-re) (error "phone-re must be atomic"))
-    (or (stringp address-re) (symbolp address-re) (error "address-re must be atomic"))
-    (when name-re
-      (push `(string-match ,name-re (or (bbdb-record-name record) "")) clauses)
-      (push `(string-match ,name-re (or (bbdb-record-name-lf record) "")) clauses)
-      (push `(let ((akas (bbdb-record-field record 'aka-all))
-                   aka done)
-               (while (and (setq aka (pop akas)) (not done))
-                 (setq done (string-match ,name-re aka)))
-               done)
-            clauses))
-    (if org-re
-        (push `(let ((organizations (bbdb-record-organization record))
-                     org done)
-                 (if organizations
-                     (while (and (setq org (pop organizations)) (not done))
-                       (setq done (string-match ,org-re org)))
-                   ;; so that "^$" can be used to find records that
-                   ;; have no organization
-                   (setq done (string-match ,org-re "")))
-                 done)
-              clauses))
-
-    (if phone-re
-        (push `(let ((phones (bbdb-record-phone record))
-                     ph done)
-                 (if phones
-                     (while (and (setq ph (pop phones)) (not done))
-                       (setq done (string-match ,phone-re
-                                                (bbdb-phone-string ph))))
-                   ;; so that "^$" can be used to find records that
-                   ;; have no phones
-                   (setq done (string-match ,phone-re "")))
-                 done)
-              clauses))
-    (if address-re
-        (push `(let ((addresses (bbdb-record-address record))
-                     a done)
-                 (if addresses
-                     (while (and (setq a (pop addresses)) (not done))
-                       (setq done (string-match ,address-re
-                                                (bbdb-format-address a 2))))
-                   ;; so that "^$" can be used to find records that
-                   ;; have no addresses.
-                   (setq done (string-match ,address-re "")))
-                 done)
-              clauses))
-    (if mail-re
-        (push `(let ((mails (bbdb-record-mail record))
-                     (bbdb-case-fold-search t) ; there is no case for mails
-                     m done)
-                 (if mails
-                     (while (and (setq m (pop mails)) (not done))
-                       (setq done (string-match ,mail-re m)))
-                   ;; so that "^$" can be used to find records that
-                   ;; have no mail addresses.
-                   (setq done (string-match ,mail-re "")))
-                 done)
-              clauses))
-    (if xfield-re
-        (push `(cond ((stringp ,xfield-re)
-                      ;; check xfield `bbdb-default-xfield'
-                      (string-match ,xfield-re
-                                    (or (bbdb-record-xfield 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))
-                                    done (and tmp (string-match (cdr ,xfield-re)
-                                                                tmp))
-                                    labels (cdr labels)))
-                          ;; so that "^$" can be used to find records that
-                          ;; have no notes
-                          (setq done (string-match (cdr ,xfield-re) "")))
+but not allowing for regexps.
+
+For backward compatibility, SPEC may also consist of the optional args
+  NAME ORGANIZATION MAIL XFIELD PHONE ADDRESS
+which is equivalent to
+  :all-names NAME :organization ORGANIZATION :mail MAIL
+  :xfield XFIELD :phone PHONE :address ADDRESS
+This usage is discouraged."
+  (when (not (keywordp (car spec)))
+    ;; Old format for backward compatibility
+    (unless (get 'bbdb-search 'bbdb-outdated)
+      (put 'bbdb-search 'bbdb-outdated t)
+      (message "Outdated usage of `bbdb-search'")
+      (sit-for 2))
+    (let (newspec val)
+      (dolist (key '(:all-names :organization :mail :xfield :phone :address))
+        (if (setq val (pop spec))
+            (push (list key val) newspec)))
+      (setq spec (apply 'append newspec))))
+
+  (let* ((count 0)
+         (sym-list (mapcar (lambda (_)
+                             (make-symbol
+                              (format "bbdb-re-%d" (setq count (1+ count)))))
+                           spec))
+         (bool (make-symbol "bool"))
+         (not-invert (make-symbol "not-invert"))
+         (matches (make-symbol "matches"))
+         keyw re-list clauses)
+    (set bool ''or) ; default
+
+    ;; Check keys.
+    (while (keywordp (setq keyw (car spec)))
+      (setq spec (cdr spec))
+      (pcase keyw
+	(`:name
+         (let ((sym (pop sym-list)))
+           (push `(,sym ,(pop spec)) re-list)
+           (push `(string-match ,sym (bbdb-record-name record)) clauses)))
+
+	(`:name-lf
+         (let ((sym (pop sym-list)))
+           (push `(,sym ,(pop spec)) re-list)
+           (push `(string-match ,sym (bbdb-record-name-lf record)) clauses)))
+
+	(`:all-names
+         (let ((sym (pop sym-list)))
+           (push `(,sym ,(pop spec)) re-list)
+           (push `(or (string-match ,sym (bbdb-record-name record))
+                      (string-match ,sym (bbdb-record-name-lf record))
+                      (let ((akas (bbdb-record-field record 'aka-all))
+                            aka done)
+                        (while (and (setq aka (pop akas)) (not done))
+                          (setq done (string-match ,sym aka)))
                         done))
-                     (t ; check one field
-                      (string-match (cdr ,xfield-re)
-                                    (or (bbdb-record-xfield
-                                         record (car ,xfield-re)) ""))))
-              clauses))
+                 clauses)))
+
+	(`:affix
+         (let ((sym (pop sym-list)))
+           (push `(,sym ,(pop spec)) re-list)
+           (push `(let ((affixs (bbdb-record-field record 'affix-all))
+                        affix done)
+                    (if affix
+                        (while (and (setq affix (pop affixs)) (not done))
+                          (setq done (string-match ,sym affix)))
+                      ;; so that "^$" matches records without affix
+                      (setq done (string-match ,sym "")))
+                    done)
+                 clauses)))
+
+	(`:aka
+         (let ((sym (pop sym-list)))
+           (push `(,sym ,(pop spec)) re-list)
+           (push `(let ((akas (bbdb-record-field record 'aka-all))
+                        aka done)
+                    (if aka
+                        (while (and (setq aka (pop akas)) (not done))
+                          (setq done (string-match ,sym aka)))
+                      ;; so that "^$" matches records without aka
+                      (setq done (string-match ,sym "")))
+                    done)
+                 clauses)))
+
+	(`:organization
+         (let ((sym (pop sym-list)))
+           (push `(,sym ,(pop spec)) re-list)
+           (push `(let ((organizations (bbdb-record-organization record))
+                        org done)
+                    (if organizations
+                        (while (and (setq org (pop organizations)) (not done))
+                          (setq done (string-match ,sym org)))
+                      ;; so that "^$" matches records without organizations
+                      (setq done (string-match ,sym "")))
+                    done)
+                 clauses)))
+
+	(`:phone
+         (let ((sym (pop sym-list)))
+           (push `(,sym ,(pop spec)) re-list)
+           (push `(let ((phones (bbdb-record-phone record))
+                        ph done)
+                    (if phones
+                        (while (and (setq ph (pop phones)) (not done))
+                          (setq done (string-match ,sym
+                                                   (bbdb-phone-string ph))))
+                      ;; so that "^$" matches records without phones
+                      (setq done (string-match ,sym "")))
+                    done)
+                 clauses)))
+
+	(`:address
+         (let ((sym (pop sym-list)))
+           (push `(,sym ,(pop spec)) re-list)
+           (push `(let ((addresses (bbdb-record-address record))
+                        a done)
+                    (if addresses
+                        (while (and (setq a (pop addresses)) (not done))
+                          (setq done (string-match ,sym
+                                                   (bbdb-format-address a 2))))
+                      ;; so that "^$" matches records without addresses
+                      (setq done (string-match ,sym "")))
+                    done)
+                 clauses)))
+
+	(`:mail
+         (let ((sym (pop sym-list)))
+           (push `(,sym ,(pop spec)) re-list)
+           (push `(let ((mails (bbdb-record-mail record))
+                        (bbdb-case-fold-search t) ; there is no case for mails
+                        m done)
+                    (if mails
+                        (while (and (setq m (pop mails)) (not done))
+                          (setq done (string-match ,sym m)))
+                      ;; so that "^$" matches records without mail
+                      (setq done (string-match ,sym "")))
+                    done)
+                 clauses)))
+
+	(`:xfield
+         (let ((sym (pop sym-list)))
+           (push `(,sym ,(pop spec)) re-list)
+           (push `(cond ((stringp ,sym)
+                         ;; check xfield `bbdb-default-xfield'
+                         ;; "^$" matches records without notes field
+                         (string-match ,sym
+                                       (or (bbdb-record-xfield-string
+                                            record bbdb-default-xfield) "")))
+                        ((eq (car ,sym) '*)
+                         ;; check all xfields
+                         (let ((labels bbdb-xfield-label-list) done tmp)
+                           (while (and (not done) labels)
+                             (setq tmp (bbdb-record-xfield-string record (car labels))
+                                   done (and tmp (string-match (cdr ,sym)
+                                                               tmp))
+                                   labels (cdr labels)))
+                           done))
+                        (t ; check one field
+                         (string-match (cdr ,sym)
+                                       (or (bbdb-record-xfield-string
+                                            record (car ,sym)) ""))))
+                 clauses)))
+
+	(`:creation-date
+         (let ((sym (pop sym-list)))
+           (push `(,sym ,(pop spec)) re-list)
+           (push `(string-match ,sym (bbdb-record-creation-date record))
+                 clauses)))
+
+	(`:timestamp
+         (let ((sym (pop sym-list)))
+           (push `(,sym ,(pop spec)) re-list)
+           (push `(string-match ,sym (bbdb-record-timestamp record))
+                 clauses)))
+
+        (`:bool
+         (set bool (pop spec)))
+
+        ;; Do we need other keywords?
+
+        (_ (error "Keyword `%s' undefines" keyw))))
+
     `(let ((case-fold-search bbdb-case-fold-search)
-           (invert (bbdb-search-invert-p))
-           matches)
-       (dolist (record ,records)
-         (unless (eq (not invert) (not (or ,@clauses)))
-           (push record matches)))
-       (nreverse matches))))
+           (,not-invert (not (bbdb-search-invert-p)))
+           ,@re-list ,matches)
+       ;; Are there any use cases for `bbdb-search' where BOOL is only
+       ;; known at run time?  A smart byte compiler will hopefully
+       ;; simplify the code below if we know BOOL already at compile time.
+       ;; Alternatively, BOOL could also be a user function that
+       ;; defines more complicated boolian expressions.  Yet then we loose
+       ;; the efficiency of `and' and `or' that evaluate its arguments
+       ;; as needed.  We would need instead boolian macros that the compiler
+       ;; can analyze at compile time.
+       (if (eq 'and ,(symbol-value bool))
+           (dolist (record ,records)
+             (unless (eq ,not-invert (not (and ,@clauses)))
+                 (push record ,matches)))
+         (dolist (record ,records)
+           (unless (eq ,not-invert (not (or ,@clauses)))
+               (push record ,matches))))
+       (nreverse ,matches))))
 
 (defun bbdb-search-read (&optional field)
   "Read regexp to search FIELD values of records."
@@ -295,8 +421,10 @@ but not allowing for regexps."
   "Display all records in the BBDB matching REGEXP
 in either the name(s), organization, address, phone, mail, or xfields."
   (interactive (list (bbdb-search-read) (bbdb-layout-prefix)))
-  (let ((records (bbdb-search (bbdb-records) regexp regexp regexp
-                              (cons '* regexp) regexp regexp)))
+  (let ((records (bbdb-search (bbdb-records) :all-names regexp
+                              :organization regexp :mail regexp
+                              :xfield (cons '* regexp)
+                              :phone regexp :address regexp :bool 'or)))
     (if records
         (bbdb-display-records records layout nil t)
       (message "No records matching '%s'" regexp))))
@@ -306,33 +434,34 @@ in either the name(s), organization, add
   "Display all records in the BBDB matching REGEXP in the name
 \(or ``alternate'' names\)."
   (interactive (list (bbdb-search-read "names") (bbdb-layout-prefix)))
-  (bbdb-display-records (bbdb-search (bbdb-records) regexp) layout))
+  (bbdb-display-records (bbdb-search (bbdb-records) :all-names regexp) layout))
 
 ;;;###autoload
 (defun bbdb-search-organization (regexp &optional layout)
   "Display all records in the BBDB matching REGEXP in the organization field."
   (interactive (list (bbdb-search-read "organization") (bbdb-layout-prefix)))
-  (bbdb-display-records (bbdb-search (bbdb-records) nil regexp) layout))
+  (bbdb-display-records (bbdb-search (bbdb-records) :organization regexp)
+                        layout))
 
 ;;;###autoload
 (defun bbdb-search-address (regexp &optional layout)
   "Display all records in the BBDB matching REGEXP in the address fields."
   (interactive (list (bbdb-search-read "address") (bbdb-layout-prefix)))
-  (bbdb-display-records (bbdb-search (bbdb-records) nil nil nil nil nil regexp)
+  (bbdb-display-records (bbdb-search (bbdb-records) :address regexp)
                         layout))
 
 ;;;###autoload
 (defun bbdb-search-mail (regexp &optional layout)
   "Display all records in the BBDB matching REGEXP in the mail address."
   (interactive (list (bbdb-search-read "mail address") (bbdb-layout-prefix)))
-  (bbdb-display-records (bbdb-search (bbdb-records) nil nil regexp) layout))
+  (bbdb-display-records (bbdb-search (bbdb-records) :mail regexp) layout))
 
 ;;;###autoload
 (defun bbdb-search-phone (regexp &optional layout)
   "Display all records in the BBDB matching REGEXP in the phones field."
   (interactive (list (bbdb-search-read "phone") (bbdb-layout-prefix)))
   (bbdb-display-records
-   (bbdb-search (bbdb-records) nil nil nil nil regexp) layout))
+   (bbdb-search (bbdb-records) :phone regexp) layout))
 
 ;;;###autoload
 (defun bbdb-search-xfields (field regexp &optional layout)
@@ -345,15 +474,15 @@ in either the name(s), organization, add
                                    "any xfield"
                                  field))
            (bbdb-layout-prefix))))
-  (bbdb-display-records (bbdb-search (bbdb-records) nil nil nil
-                                     (cons field regexp))
+  (bbdb-display-records (bbdb-search (bbdb-records) :xfield (cons field regexp))
                         layout))
 (define-obsolete-function-alias 'bbdb-search-notes 'bbdb-search-xfields)
 
 ;;;###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)
@@ -363,11 +492,11 @@ the database was last saved."
         (bbdb-display-records unchanged-records layout))
     (bbdb-display-records bbdb-changed-records layout)))
 
-(defun bbdb-search-prog (function &optional layout)
-  "Search records using FUNCTION.
-FUNCTION is called with one argument, the record, and should return
+(defun bbdb-search-prog (fun &optional layout)
+  "Search records using function FUN.
+FUN is called with one argument, the record, and should return
 the record to be displayed or nil otherwise."
-  (bbdb-display-records (delq nil (mapcar function (bbdb-records))) layout))
+  (bbdb-display-records (delq nil (mapcar fun (bbdb-records))) layout))
 
 
 ;; clean-up functions
@@ -485,7 +614,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,16 +626,27 @@ 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
 
 (defmacro bbdb-compare-records (cmpval label compare)
   "Builds a lambda comparison function that takes one argument, RECORD.
 RECORD is returned if (COMPARE VALUE CMPVAL) is t, where VALUE
-is the value of xfield LABEL of RECORD."
+is the value of field LABEL of RECORD."
   `(lambda (record)
-     (let ((val (bbdb-record-xfield record ,label)))
+     (let ((val (bbdb-record-field record ,label)))
        (if (and val (,compare val ,cmpval))
            record))))
 
@@ -518,7 +658,7 @@ is the value of xfield LABEL of RECORD."
 (defun bbdb-timestamp-older (date &optional layout)
   "Display records with timestamp older than DATE.
 DATE must be in yyyy-mm-dd format."
-  (interactive (list (read-string "Older than date (yyyy-mm-dd): ")
+  (interactive (list (read-string "Timestamp older than: (yyyy-mm-dd) ")
                      (bbdb-layout-prefix)))
   (bbdb-search-prog (bbdb-compare-records date 'timestamp string<) layout))
 
@@ -526,7 +666,7 @@ DATE must be in yyyy-mm-dd format."
 (defun bbdb-timestamp-newer (date &optional layout)
   "Display records with timestamp newer than DATE.
 DATE must be in yyyy-mm-dd format."
-  (interactive (list (read-string "Newer than date (yyyy-mm-dd): ")
+  (interactive (list (read-string "Timestamp newer than: (yyyy-mm-dd) ")
                      (bbdb-layout-prefix)))
   (bbdb-search-prog (bbdb-compare-records date 'timestamp bbdb-string>) layout))
 
@@ -534,7 +674,7 @@ DATE must be in yyyy-mm-dd format."
 (defun bbdb-creation-older (date &optional layout)
   "Display records with creation-date older than DATE.
 DATE must be in yyyy-mm-dd format."
-  (interactive (list (read-string "Older than date (yyyy-mm-dd): ")
+  (interactive (list (read-string "Creation older than: (yyyy-mm-dd) ")
                      (bbdb-layout-prefix)))
   (bbdb-search-prog (bbdb-compare-records date 'creation-date string<) layout))
 
@@ -542,7 +682,7 @@ DATE must be in yyyy-mm-dd format."
 (defun bbdb-creation-newer (date &optional layout)
   "Display records with creation-date newer than DATE.
 DATE must be in yyyy-mm-dd format."
-  (interactive (list (read-string "Newer than date (yyyy-mm-dd): ")
+  (interactive (list (read-string "Creation newer than: (yyyy-mm-dd) ")
                      (bbdb-layout-prefix)))
   (bbdb-search-prog (bbdb-compare-records date 'creation-date bbdb-string>) layout))
 
@@ -551,9 +691,10 @@ DATE must be in yyyy-mm-dd format."
   "Display records that have the same timestamp and creation-date."
   (interactive (list (bbdb-layout-prefix)))
   (bbdb-search-prog
-   ;; RECORD is bound in `bbdb-search-prog'.
-   (bbdb-compare-records (bbdb-record-xfield record 'timestamp)
-                         'creation-date string=) layout))
+   ;; RECORD is bound in `bbdb-compare-records'.
+   (bbdb-compare-records (bbdb-record-timestamp record)
+                         'creation-date string=)
+   layout))
 
 ;;; Parsing phone numbers
 ;;; XXX this needs expansion to handle international prefixes properly
@@ -659,49 +800,57 @@ See `bbdb-search' for searching records
 Does not insert it into the database or update the hashtables,
 but does ensure that there will not be name collisions."
   (bbdb-editable)
-  (let (name)
-    (bbdb-error-retry
-     (setq name (bbdb-read-name first-and-last))
-     (bbdb-check-name (car name) (cdr name)))
-    (let ((organizations (bbdb-read-organization))
-          ;; mail
-          (mail (bbdb-split 'mail (bbdb-read-string "E-Mail Addresses: ")))
-          ;; address
-          (addresses
-           (let (addresses label address)
-             (while (not (string= ""
-                                  (setq label
-                                        (bbdb-read-string
-                                         "Snail Mail Address Label [RET when done]: "
-                                         nil
-                                         bbdb-address-label-list))))
-               (setq address (make-vector bbdb-address-length nil))
-               (bbdb-record-edit-address address label t)
-               (push address addresses))
-             (nreverse addresses)))
-          ;; phones
-          (phones
-           (let (phones phone-list label)
-             (while (not (string= ""
-                                  (setq label
-                                        (bbdb-read-string
-                                         "Phone Label [RET when done]: " nil
-                                         bbdb-phone-label-list))))
-               (setq phone-list
-                     (bbdb-error-retry
-                      (bbdb-parse-phone
-                       (read-string "Phone: "
-                                    (and (integerp bbdb-default-area-code)
-                                         (format "(%03d) "
-                                                 bbdb-default-area-code))))))
-               (push (apply 'vector label phone-list) phones))
-             (nreverse phones)))
-          ;; `bbdb-default-xfield'
-          (xfield (bbdb-read-xfield bbdb-default-xfield)))
-      (vector (car name) (cdr name) nil nil organizations phones addresses
-              mail (unless (string= xfield "")
-                     (list (cons bbdb-default-xfield xfield)))
-              (make-vector bbdb-cache-length nil)))))
+  (let ((record (bbdb-empty-record)))
+    (let (name)
+      (bbdb-error-retry
+       (setq name (bbdb-read-name first-and-last))
+       (bbdb-check-name (car name) (cdr name)))
+      (bbdb-record-set-firstname record (car name))
+      (bbdb-record-set-lastname record (cdr name)))
+
+    ;; organization
+    (bbdb-record-set-organization record (bbdb-read-organization))
+
+    ;; mail
+    (bbdb-record-set-mail
+     record (bbdb-split 'mail (bbdb-read-string "E-Mail Addresses: ")))
+    ;; address
+    (let (addresses label address)
+      (while (not (string= ""
+                           (setq label
+                                 (bbdb-read-string
+                                  "Snail Mail Address Label [RET when done]: "
+                                  nil
+                                  bbdb-address-label-list))))
+        (setq address (make-vector bbdb-address-length nil))
+        (bbdb-record-edit-address address label t)
+        (push address addresses))
+      (bbdb-record-set-address record (nreverse addresses)))
+
+    ;; phones
+    (let (phones phone-list label)
+      (while (not (string= ""
+                           (setq label
+                                 (bbdb-read-string
+                                  "Phone Label [RET when done]: " nil
+                                  bbdb-phone-label-list))))
+        (setq phone-list
+              (bbdb-error-retry
+               (bbdb-parse-phone
+                (read-string "Phone: "
+                             (and (integerp bbdb-default-area-code)
+                                  (format "(%03d) "
+                                          bbdb-default-area-code))))))
+        (push (apply 'vector label phone-list) phones))
+      (bbdb-record-set-phone record (nreverse phones)))
+
+    ;; `bbdb-default-xfield'
+    (let ((xfield (bbdb-read-xfield bbdb-default-xfield)))
+      (unless (string= "" xfield)
+        (bbdb-record-set-xfields
+         record (list (cons bbdb-default-xfield xfield)))))
+
+    record))
 
 (defun bbdb-read-name (&optional first-and-last dfirst dlast)
   "Read name for a record from minibuffer.
@@ -742,57 +891,122 @@ 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)
   (bbdb-display-records (list record)))
 
-(defun bbdb-create-internal (&optional name affix aka organization mail
-                                       phone address xfields check)
-  "Add a new record to the database and return it.
+(defsubst bbdb-split-maybe (separator string)
+  "Split STRING into list of substrings bounded by matches for SEPARATORS.
+If STRING is a list, return STRING.  Throw error if STRING is neither a string
+nor a list."
+  (cond ((stringp string)
+         (bbdb-split separator string))
+        ((listp string) string)
+        (t (error "Cannot convert %s to list" string))))
 
-NAME is a string or a cons cell (FIRST . LAST), the name of the person to add.
-An error is thrown if NAME is already in use and `bbdb-allow-duplicates' is nil.
-ORGANIZATION is a list of strings.
-MAIL is a comma-separated list of mail address, or a list of strings.
-An error is thrown if a mail address in MAIL is already in use
-and `bbdb-allow-duplicates' is nil.
-ADDRESS is a list of address objects.  An address is a vector of the form
-\[\"label\" (\"line1\" \"line2\" ... ) \"City\" \"State\" \"Postcode\" \"Country\"].
-PHONE is a list of phone-number objects.  A phone-number is a vector of
-the form [\"label\" areacode prefix suffix extension-or-nil]
-or [\"label\" \"phone-number\"]
-XFIELDS is an alist associating symbols with strings.
+;;;###autoload
+(defun bbdb-create-internal (&rest spec)
+  "Add a new record to the database and return it.
 
-If CHECK is non-nil throw an error if an argument is not syntactically correct."
+The following keywords are supported in SPEC:
+:name VAL          String or a cons cell (FIRST . LAST), the name of the person.
+                   An error is thrown if VAL is already in use
+                   and `bbdb-allow-duplicates' is nil.
+:affix VAL         List of strings.
+:aka VAL           List of strings.
+:organization VAL  List of strings.
+:mail VAL          String with comma-separated mail address
+                   or a list of strings.
+                   An error is thrown if a mail address in MAIL is already
+                   in use and `bbdb-allow-duplicates' is nil.
+:phone VAL         List of phone-number objects.  A phone-number is a vector
+                   [\"label\" areacode prefix suffix extension-or-nil]
+                   or [\"label\" \"phone-number\"]
+:address VAL       List of addresses.  An address is a vector of the form
+                   \[\"label\" (\"line1\" \"line2\" ... ) \"City\"
+                   \"State\" \"Postcode\" \"Country\"].
+:xfields VAL       Alist associating symbols with strings.
+:uuid VAL          String, the uuid.
+:creation-date VAL String, the creation date.
+:check             If present, throw an error if a field value is not
+                   syntactically correct."
   (bbdb-editable)
-  ;; name
-  (cond ((stringp name)
-         (setq name (bbdb-divide-name name)))
-        (check (bbdb-check-type name '(or (const nil) (cons string string)) t)))
-  (let ((firstname (car name))
-        (lastname (cdr name))
-        (record-type (cdr bbdb-record-type)))
-    (bbdb-check-name firstname lastname)
-    ;; mail addresses
-    (cond ((stringp mail)
-           (setq mail (bbdb-split 'mail mail)))
-          (check (bbdb-check-type mail (bbdb-record-mail record-type) t)))
-    (unless bbdb-allow-duplicates
-      (dolist (elt mail)
-        (if (bbdb-gethash elt '(mail))
-            (error "%s is already in the database" elt))))
-    ;; other fields
-    (when check
-      (bbdb-check-type affix (bbdb-record-affix record-type) t)
-      (bbdb-check-type aka (bbdb-record-aka record-type) t)
-      (bbdb-check-type organization (bbdb-record-organization record-type) t)
-      (bbdb-check-type phone (bbdb-record-phone record-type) t)
-      (bbdb-check-type address (bbdb-record-address record-type) t)
-      (bbdb-check-type xfields (bbdb-record-xfields record-type) t))
-    (bbdb-change-record
-     (vector firstname lastname affix aka organization phone
-             address mail xfields
-             (make-vector bbdb-cache-length nil))
-     t t)))
+  (let ((record (bbdb-empty-record))
+        (record-type (cdr bbdb-record-type))
+        (check (prog1 (memq :check spec)
+                 (setq spec (delq :check spec))))
+        keyw)
+
+    ;; Check keys.
+    (while (keywordp (setq keyw (car spec)))
+      (setq spec (cdr spec))
+      (pcase keyw
+	(`:name
+         (let ((name (pop spec)))
+           (cond ((stringp name)
+                  (setq name (bbdb-divide-name name)))
+                 (check (bbdb-check-type name '(or (const nil)
+                                                   (cons string string))
+                                         t)))
+           (let ((firstname (car name))
+                 (lastname (cdr name)))
+             (bbdb-check-name firstname lastname) ; check for duplicates
+             (bbdb-record-set-firstname record firstname)
+             (bbdb-record-set-lastname record lastname))))
+
+        (`:affix
+         (let ((affix (bbdb-split-maybe 'affix (pop spec))))
+           (if check (bbdb-check-type affix (bbdb-record-affix record-type) t))
+           (bbdb-record-set-affix record affix)))
+
+        (`:organization
+         (let ((organization (bbdb-split-maybe 'organization (pop spec))))
+           (if check (bbdb-check-type
+                      organization (bbdb-record-organization record-type) t))
+           (bbdb-record-set-organization record organization)))
+
+        (`:aka
+         (let ((aka (bbdb-split-maybe 'aka (pop spec))))
+           (if check (bbdb-check-type aka (bbdb-record-aka record-type) t))
+           (bbdb-record-set-aka record aka)))
+
+        (`:mail
+         (let ((mail (bbdb-split-maybe 'mail (pop spec))))
+           (if check (bbdb-check-type mail (bbdb-record-mail record-type) t))
+           (unless bbdb-allow-duplicates
+             (dolist (elt mail)
+               (if (bbdb-gethash elt '(mail))
+                   (error "%s is already in the database" elt))))
+           (bbdb-record-set-mail record mail)))
+
+        (`:phone
+         (let ((phone (pop spec)))
+           (if check (bbdb-check-type phone (bbdb-record-phone record-type) t))
+           (bbdb-record-set-phone phone record)))
+
+        (`:address
+         (let ((address (pop spec)))
+           (if check (bbdb-check-type address (bbdb-record-address record-type) t))
+           (bbdb-record-set-address record address)))
+
+        (`:xfields
+         (let ((xfields (pop spec)))
+           (if check (bbdb-check-type xfields (bbdb-record-xfields record-type) t))
+           (bbdb-record-set-xfields record xfields)))
+
+        (`:uuid
+         (let ((uuid (pop spec)))
+           (if check (bbdb-check-type uuid (bbdb-record-uuid record-type) t))
+           (bbdb-record-set-uuid record uuid)))
+
+        (`:creation-date
+         (let ((creation-date (pop spec)))
+           (if check (bbdb-check-type
+                      creation-date (bbdb-record-creation-date record-type) t))
+           (bbdb-record-set-creation-date record creation-date)))
+
+        (_ (error "Keyword `%s' undefined" keyw))))
+
+    (bbdb-change-record record)))
 
 ;;;###autoload
 (defun bbdb-insert-field (record field value)
@@ -862,20 +1076,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 +1132,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 +1141,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)
@@ -939,12 +1156,12 @@ a phone number or address with VALUE bei
             (value (nth 1 field-l)))
        (unless field (error "Point not in a field"))
        (list (bbdb-current-record)
-             (if (memq field '(name affix organization aka mail phone address))
+             (if (memq field '(name affix organization aka mail phone address
+                                    uuid creation-date timestamp))
                  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 +1171,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'?
@@ -982,11 +1199,23 @@ a phone number or address with VALUE bei
                                (format "%s: " (cdr edit-str))
                                (bbdb-concat field
                                             (bbdb-record-field record field))))))
+          ((eq field 'uuid)
+           (bbdb-record-set-field
+            record 'uuid (bbdb-read-string "uuid (edit at your own risk): " (bbdb-record-uuid record))))
+          ((eq field 'creation-date)
+           (bbdb-record-set-creation-date
+            record (bbdb-read-string "creation-date: " (bbdb-record-creation-date record))))
+          ;; The timestamp is set automatically whenever we save a modified record.
+          ;; So any editing gets overwritten.
+          ((eq field 'timestamp)) ; do nothing
           (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))))
+    (cond ((eq field 'timestamp)
+           (message "timestamp not editable"))
+          ((bbdb-change-record record))
+          (t (message "Record unchanged")))))
 
 (defun bbdb-edit-foo (record field &optional nvalue)
   "For RECORD edit some FIELD (mostly interactively).
@@ -997,7 +1226,8 @@ field.
 
 Interactively, if called without a prefix, the value of FIELD is the car
 of the variable `bbdb-edit-foo'.  When called with a prefix, the value
-of FIELD is the cdr of this variable."
+of FIELD is the cdr of this variable.  Then use minibuffer completion
+to select the field."
   (interactive
    (let* ((_ (bbdb-editable))
           (record (bbdb-current-record))
@@ -1005,17 +1235,17 @@ of FIELD is the cdr of this variable."
           (field (if (memq tmp '(current-fields all-fields))
                      ;; Do not require match so that we can define new xfields.
                      (intern (completing-read
-                              "Field: " (mapcar 'list (if (eq tmp 'all-fields)
-                                                          (append '(name affix organization aka mail phone address)
-                                                                  bbdb-xfield-label-list)
-                                                        (append (if (bbdb-record-name record) '(name))
-                                                                (if (bbdb-record-affix record) '(affix))
-                                                                (if (bbdb-record-organization record) '(organization))
-                                                                (if (bbdb-record-aka record) '(aka))
-                                                                (if (bbdb-record-mail record) '(mail))
-                                                                (if (bbdb-record-phone record) '(phone))
-                                                                (if (bbdb-record-address record) '(address))
-                                                                (mapcar 'car (bbdb-record-xfields record)))))))
+                              "Edit field: " (mapcar 'list (if (eq tmp 'all-fields)
+                                                               (append '(name affix organization aka mail phone address uuid creation-date)
+                                                                       bbdb-xfield-label-list)
+                                                             (append (if (bbdb-record-affix record) '(affix))
+                                                                     (if (bbdb-record-organization record) '(organization))
+                                                                     (if (bbdb-record-aka record) '(aka))
+                                                                     (if (bbdb-record-mail record) '(mail))
+                                                                     (if (bbdb-record-phone record) '(phone))
+                                                                     (if (bbdb-record-address record) '(address))
+                                                                     (mapcar 'car (bbdb-record-xfields record))
+                                                                     '(name uuid creation-date))))))
                    tmp))
           ;; Multiple phone and address fields may use the same label.
           ;; So we cannot use these labels to uniquely identify
@@ -1029,9 +1259,8 @@ of FIELD is the cdr of this variable."
                                                             (cons (format "%d" n) (bbdb-phone-label (nth n phones))))
                                                           (number-sequence 0 (1- (length phones))))))
                                 (completion-extra-properties
-                                 '(:annotation-function
-                                   (lambda (s) (format "  (%s)" (cdr (assoc s collection)))))))
-                                ; (completion-annotate-function (cadr completion-extra-properties))) ; Emacs 23
+                                 `(:annotation-function
+                                   (lambda (s) (format "  (%s)" (cdr (assoc s ',collection)))))))
                            (if (< 0 (length phones))
                                (completing-read "Phone field: " collection nil t)
                              "new")))
@@ -1042,9 +1271,8 @@ of FIELD is the cdr of this variable."
                                                             (cons (format "%d" n) (bbdb-address-label (nth n addresses))))
                                                           (number-sequence 0 (1- (length addresses))))))
                                 (completion-extra-properties
-                                 '(:annotation-function
-                                   (lambda (s) (format "  (%s)" (cdr (assoc s collection)))))))
-                                ; (completion-annotate-function (cadr completion-extra-properties))) ; Emacs 23
+                                 `(:annotation-function
+                                   (lambda (s) (format "  (%s)" (cdr (assoc s ',collection)))))))
                            (if (< 0 (length addresses))
                                (completing-read "Address field: " collection nil t)
                              "new"))))))
@@ -1061,7 +1289,8 @@ of FIELD is the cdr of this variable."
                                      (t (error "%s: nvalue %s meaningless" field nvalue)))))))
     (if (and (numberp nvalue) (not value))
         (error "%s: nvalue %s out of range" field nvalue))
-    (if (or (and (eq field 'affix) (bbdb-record-affix record))
+    (if (or (memq field '(name uuid creation-date))
+            (and (eq field 'affix) (bbdb-record-affix record))
             (and (eq field 'organization) (bbdb-record-organization record))
             (and (eq field 'mail) (bbdb-record-mail record))
             (and (eq field 'aka) (bbdb-record-aka record))
@@ -1071,13 +1300,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 +1507,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 +1515,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 +1540,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 +1573,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)
@@ -1359,15 +1593,18 @@ Interactively, use BBDB prefix \
 If prefix NOPROMPT is non-nil, do not confirm deletion."
   (interactive (list (bbdb-do-records) current-prefix-arg))
   (bbdb-editable)
-  (dolist (record (bbdb-record-list records))
-    (when (or noprompt
-              (y-or-n-p (format "Delete the BBDB record of %s? "
-                                (or (bbdb-record-name record)
-                                    (car (bbdb-record-mail record))))))
-      (bbdb-delete-record-internal record t)
-      (setq bbdb-records (delq (assq record bbdb-records) bbdb-records))
-      ;; Possibly we changed RECORD before deleting it.
-      (setq bbdb-changed-records (delq record bbdb-changed-records)))))
+  (let ((all-records (bbdb-with-db-buffer bbdb-records)))
+    (dolist (record (bbdb-record-list records))
+      (cond ((not (memq record all-records))
+             ;; Possibly we changed RECORD before deleting it.
+             ;; Otherwise, do nothing if RECORD is unknown to BBDB.
+             (setq bbdb-changed-records (delq record bbdb-changed-records)))
+            ((or noprompt
+                 (y-or-n-p (format "Delete the BBDB record of %s? "
+                                   (or (bbdb-record-name record)
+                                       (car (bbdb-record-mail record))))))
+             (bbdb-delete-record-internal record t)
+             (setq bbdb-changed-records (delq record bbdb-changed-records)))))))
 
 ;;;###autoload
 (defun bbdb-display-all-records (&optional layout)
@@ -1459,105 +1696,109 @@ 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
 
 ;;;###autoload
-(defun bbdb-merge-records (old-record new-record)
-  "Merge OLD-RECORD into NEW-RECORD, return NEW-RECORD.
-This copies all the data in OLD-RECORD into NEW-RECORD.  Then OLD-RECORD
-is deleted.  If both records have names ask which to use.
-Affixes, organizations, phone numbers, addresses, and mail addresses
-are simply concatenated.
+(defun bbdb-merge-records (record1 record2)
+  "Merge RECORD1 into RECORD2, then delete RECORD1 and return RECORD2.
+If both records have name fields ask which one to use.
+Concatenate other fields, ignoring duplicates.
+RECORD1 need not be known to BBDB, its hash and cache are ignored.
+Update hash and cache for RECORD2.
 
-Interactively, OLD-RECORD is the current record.  NEW-RECORD is prompted for.
-With prefix arg NEW-RECORD defaults to the first record with the same name."
+Interactively, RECORD1 is the current record; prompt for RECORD2.
+With prefix, RECORD2 defaults to the first record with the same name."
   (interactive
    (let* ((_ (bbdb-editable))
-          (old-record (bbdb-current-record))
-          (name (bbdb-record-name old-record))
-          (new-record (and current-prefix-arg
+          (record1 (bbdb-current-record))
+          (name (bbdb-record-name record1))
+          (record2 (and current-prefix-arg
                            ;; take the first record with the same name
-                           (car (delq old-record
-                                      (bbdb-search (bbdb-records) name))))))
-     (when new-record
+                           (car (delq record1
+                                      (bbdb-search (bbdb-records) :all-names name))))))
+     (when record2
        (message "Merge current record with duplicate record `%s'" name)
        (sit-for 1))
-     (list old-record
-           (or new-record
+     (list record1
+           (or record2
                (bbdb-completing-read-record
                 (format "merge record \"%s\" into: "
-                        (or (bbdb-record-name old-record)
-                            (car (bbdb-record-mail old-record))
+                        (or (bbdb-record-name record1)
+                            (car (bbdb-record-mail record1))
                             "???"))
-                (list old-record))))))
+                (list record1))))))
 
   (bbdb-editable)
-  (cond ((eq old-record new-record) (error "Records are equal"))
-        ((null new-record) (error "No record to merge with")))
+  (cond ((eq record1 record2) (error "Records are equal"))
+        ((null record2) (error "No record to merge with")))
 
   ;; Merge names
-  (let* ((new-name (bbdb-record-name new-record))
-         (old-name (bbdb-record-name old-record))
-         (old-aka  (bbdb-record-aka  old-record))
+  (let* ((new-name (bbdb-record-name record2))
+         (old-name (bbdb-record-name record1))
+         (old-aka  (bbdb-record-aka  record1))
          extra-name
          (name
           (cond ((or (string= "" old-name)
                      (bbdb-string= old-name new-name))
-                 (cons (bbdb-record-firstname new-record)
-                       (bbdb-record-lastname new-record)))
+                 (cons (bbdb-record-firstname record2)
+                       (bbdb-record-lastname record2)))
                 ((string= "" new-name)
-                 (cons (bbdb-record-firstname old-record)
-                       (bbdb-record-lastname old-record)))
+                 (cons (bbdb-record-firstname record1)
+                       (bbdb-record-lastname record1)))
                 (t (prog1
                        (if (y-or-n-p
                             (format "Use name \"%s\" instead of \"%s\"? "
                                     old-name new-name))
                            (progn
                              (setq extra-name new-name)
-                             (cons (bbdb-record-firstname old-record)
-                                   (bbdb-record-lastname old-record)))
+                             (cons (bbdb-record-firstname record1)
+                                   (bbdb-record-lastname record1)))
                          (setq extra-name old-name)
-                         (cons (bbdb-record-firstname new-record)
-                               (bbdb-record-lastname new-record)))
+                         (cons (bbdb-record-firstname record2)
+                               (bbdb-record-lastname record2)))
                      (unless (bbdb-eval-spec
-                              (bbdb-add-job bbdb-add-aka new-record extra-name)
+                              (bbdb-add-job bbdb-add-aka record2 extra-name)
                               (format "Keep \"%s\" as an alternate name? "
                                       extra-name))
                        (setq extra-name nil)))))))
 
-    (bbdb-record-set-name new-record (car name) (cdr name))
+    (bbdb-record-set-name record2 (car name) (cdr name))
 
     (if extra-name (push extra-name old-aka))
-    ;; It is better to delete OLD-RECORD at the end.
-    ;; So we must temporarily allow duplicates in NEW-RECORD.
+    ;; It is better to delete RECORD1 at the end.
+    ;; So we must temporarily allow duplicates in RECORD2.
     (let ((bbdb-allow-duplicates t))
-      (bbdb-record-set-field new-record 'aka old-aka t)))
+      (bbdb-record-set-field record2 'aka old-aka t)))
 
   ;; Merge other stuff
-  (bbdb-record-set-field new-record 'affix
-                         (bbdb-record-affix old-record) t)
-  (bbdb-record-set-field new-record 'organization
-                         (bbdb-record-organization old-record) t)
-  (bbdb-record-set-field new-record 'phone
-                         (bbdb-record-phone old-record) t)
-  (bbdb-record-set-field new-record 'address
-                         (bbdb-record-address old-record) t)
+  (bbdb-record-set-field record2 'affix
+                         (bbdb-record-affix record1) t)
+  (bbdb-record-set-field record2 'organization
+                         (bbdb-record-organization record1) t)
+  (bbdb-record-set-field record2 'phone
+                         (bbdb-record-phone record1) t)
+  (bbdb-record-set-field record2 'address
+                         (bbdb-record-address record1) t)
   (let ((bbdb-allow-duplicates t))
-    (bbdb-record-set-field new-record 'mail
-                           (bbdb-record-mail old-record) t))
-  (bbdb-record-set-field new-record 'xfields
-                         (bbdb-record-xfields old-record) t)
-
-  (bbdb-delete-records (list old-record) 'noprompt)
-  (bbdb-change-record new-record t)
-  new-record)
+    (bbdb-record-set-field record2 'mail
+                           (bbdb-record-mail record1) t))
+  (bbdb-record-set-field record2 'xfields
+                         (bbdb-record-xfields record1) t)
+
+  ;; `bbdb-delete-records' does nothing if RECORD1 is not known to BBDB.
+  (bbdb-delete-records (list record1) 'noprompt)
+  (bbdb-change-record record2)
+  record2)
 
 ;; The following sorting functions are also intended for use
 ;; in `bbdb-change-hook'.  Then they will be called with one arg, the record.
@@ -1805,21 +2046,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 +2065,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 +2199,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 +2281,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))))))
@@ -2158,32 +2389,24 @@ as part of the MUA insinuation."
 
     (when (member done '(choose cycle-choose))
       ;; Pop up a completions window using DWIM-COMPLETIONS.
-      ;; Too bad: The following requires at least GNU Emacs 23.2
-      ;; which introduced the variable `completion-base-position'.
-      ;; For an older Emacs there is really no satisfactory workaround
-      ;; (see GNU Emacs bug #4699), unless we use something radical like
-      ;; advicing `choose-completion-string' (used by BBDB v2).
-      (if (string< (substring emacs-version 0 4) "23.2")
-          (message "*Completions* buffer requires at least GNU Emacs 23.2")
-        ;; `completion-in-region' does not work here as `dwim-completions'
-        ;; is not a collection for completion in the usual sense, but it
-        ;; is really a list of replacements.
-        (let ((status (not (eq (selected-window) (minibuffer-window))))
-              (completion-base-position (list beg end))
-              ;; If we even have `completion-list-insert-choice-function'
-              ;; (introduced in GNU Emacs 24.1) that is yet better.
-              ;; Then we first call the default value of this variable
-              ;; before performing our own stuff.
-              (completion-list-insert-choice-function
-               `(lambda (beg end text)
-                  ,(if (boundp 'completion-list-insert-choice-function)
+      ;; `completion-in-region' does not work here as DWIM-COMPLETIONS
+      ;; is not a collection for completion in the usual sense, but it
+      ;; is really a list of replacements.
+      (let ((status (not (eq (selected-window) (minibuffer-window))))
+            (completion-base-position (list beg end))
+            ;; We first call the default value of
+            ;; `completion-list-insert-choice-function'
+            ;; before performing our own stuff.
+            (completion-list-insert-choice-function
+             `(lambda (beg end text)
+                ,(if (boundp 'completion-list-insert-choice-function)
                      `(funcall ',completion-list-insert-choice-function
                                beg end text))
-                 (bbdb-complete-mail-cleanup text beg))))
-          (if status (message "Making completion list..."))
-          (with-output-to-temp-buffer "*Completions*"
-            (display-completion-list dwim-completions))
-          (if status (message "Making completion list...done")))))
+                (bbdb-complete-mail-cleanup text beg))))
+        (if status (message "Making completion list..."))
+        (with-output-to-temp-buffer "*Completions*"
+          (display-completion-list dwim-completions))
+        (if status (message "Making completion list...done"))))
 
     ;; If DONE is `nothing' return nil so that possibly some other code
     ;; can take over.
@@ -2246,8 +2469,7 @@ Rebuilding the aliases is enforced if pr
   ;; we should just do what's necessary, i.e. remove deleted records
   ;; and add new records
   ;; Calling `bbdb-records' can change `bbdb-mail-aliases-need-rebuilt'
-  (let ((records (bbdb-search (bbdb-records) nil nil nil
-                              (cons bbdb-mail-alias-field ".")))
+  (let ((records (bbdb-search (bbdb-records) :xfield (cons bbdb-mail-alias-field ".")))
         results match)
     (if (not (or force-rebuilt bbdb-mail-aliases-need-rebuilt))
         (if noisy (message "BBDB mail alias: nothing to do"))
@@ -2312,7 +2534,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))
@@ -2361,49 +2583,69 @@ Rebuilding the aliases is enforced if pr
 
 (defun bbdb-get-mail-aliases ()
   "Return a list of mail aliases used in the BBDB."
-  (let ((records (bbdb-search (bbdb-records) nil nil nil
-                              (cons bbdb-mail-alias-field ".")))
+  (let ((records (bbdb-search (bbdb-records) :xfield (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 +2741,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 +2755,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 +2823,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-2017 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-2017 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-2017 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-2017 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-2017 Roland Winkler <winkler@gnu.org>
 
 ;; This file is part of the Insidious Big Brother Database (aka BBDB),
 
@@ -22,226 +22,214 @@
 ;;; This file contains the migration functions for BBDB.
 ;;; See the BBDB info manual for documentation.
 
+;; Changes in `bbdb-file-format':
+;;   3  Date format for `creation-date' and `timestamp' changed
+;;      from "dd mmm yy" (ex: 25 Sep 97) to "yyyy-mm-dd" (ex: 1997-09-25).
+;;   4  Country field added.
+;;   5  Streets are lists.
+;;   6  Postcodes are plain strings.
+;;   7  New field `affix'.  Organizations are a list.
+;;      Xfields is always a list.
+;;  (8  Skipped format in "official BBDB": Some BBDB users introduced
+;;      an xfield uuid in their format 8.  To bring them back, we jump
+;;      straight from 7 to 9.)
+;;   9  New field uuid.  Make `creation-date' and `timestamp' immutable fields.
+
+
+;;; Code:
+
 (require 'bbdb)
 
 ;;; Migrating the BBDB
 
-;; Unused
-(defconst bbdb-migration-features
-  '((3 . "* Date format for `creation-date' and `timestamp' has changed,
-  from \"dd mmm yy\" (ex: 25 Sep 97) to \"yyyy-mm-dd\" (ex: 1997-09-25).")
-    (4 . "* Country field added.")
-    (5 . "* More flexible street address.")
-    (6 . "* postcodes are stored as plain strings.")
-    (7 . "* Xfields is always a list.  Organizations are stored as list.
-  New field `affix'."))
-  "BBDB Features that have changed in various database revisions.
-Format ((VERSION . DIFFERENCES) ... ).")
-
-(defun bbdb-peel-the-onion (lis)
-  "Remove outer layers of parens around singleton lists.
-This is done until we get a list which is either not a singleton list
-or does not contain a list.  This is a utility function used in recovering
-slightly munged old BBDB files."
-  (while (and (consp lis)
-	      (null (cdr lis))
-	      (listp (car lis)))
-    (setq lis (car lis)))
-  lis)
+(defvar bbdb-migrate-uuid-xfield 'uuid
+  "Xfield holding a uuid in file format 8.")
 
 ;;;###autoload
-(defun bbdb-migrate (records old-format)
-  "Migrate the BBDB from the version on disk to the current version
-\(in `bbdb-file-format')."
+(defun bbdb-migrate (records old)
+  "Migrate RECORDS from format OLD to `bbdb-file-format'."
   ;; Some BBDB files were corrupted by random outer layers of
   ;; parentheses surrounding the actual correct data.  We attempt to
   ;; compensate for this.
-  (setq records (bbdb-peel-the-onion records))
+  (while (and (consp records)
+	      (listp (car records))
+	      (null (cdr records)))
+    (setq records (car records)))
+
+  ;; `bbdb-migrate-lambda' uses the usual functions to access and set
+  ;; the fields of a record.  So if a new record format changes
+  ;; the set of fields, we need to make these changes first.
+
+  ;; Format 7: Add new field `affix'.
+  (if (< old 7)
+      (let (new-records)
+        (dolist (record records)
+          (push (vector (elt record 0) (elt record 1) nil
+                        (elt record 2) (elt record 3) (elt record 4)
+                        (elt record 5) (elt record 6) (elt record 7)
+                        (elt record 8))
+                new-records))
+        (setq records (nreverse new-records))))
+
+  ;; Format 9: New field `uuid'.
+  ;; Make `creation-date' and `timestamp' immutable fields.
+  (if (< old 9)
+      (let (new-records)
+        (dolist (record records)
+          (let ((uuid (or (cdr (assq bbdb-migrate-uuid-xfield (elt record 8)))
+                          (bbdb-uuid)))
+                (creation-date (or (cdr (assq 'creation-date (elt record 8)))
+                                   (format-time-string bbdb-time-stamp-format nil t)))
+                (timestamp (or (cdr (assq 'timestamp (elt record 8)))
+                               (format-time-string bbdb-time-stamp-format nil t))))
+            (push (vector (elt record 0) (elt record 1) (elt record 2)
+                          (elt record 3) (elt record 4) (elt record 5)
+                          (elt record 6) (elt record 7)
+                          (let ((xfields (elt record 8)))
+                            (dolist (elt '(uuid creation-date timestamp))
+                              (setq xfields (assq-delete-all elt xfields)))
+                            xfields)
+                          uuid creation-date timestamp
+                          (elt record 9))
+                  new-records)))
+        (setq records (nreverse new-records))))
 
-  ;; Add new field `affix'.
-  (if (< old-format 7)
-      (let ((temp records) record)
-        (while (setq record (car temp))
-          (setcar temp (vector (elt record 0) (elt record 1) nil
-                               (elt record 2) (elt record 3) (elt record 4)
-                               (elt record 5) (elt record 6) (elt record 7)
-                               (elt record 8)))
-          (setq temp (cdr temp)))))
-  (mapc (bbdb-migrate-versions-lambda old-format) records)
+  (mapc (bbdb-migrate-lambda old) records)
   records)
 
-(defconst bbdb-migration-spec
-  '((2 (bbdb-record-xfields bbdb-record-set-xfields
-        bbdb-migrate-change-dates))
-    (3 (bbdb-record-address bbdb-record-set-address
-        bbdb-migrate-add-country-field))
+(defconst bbdb-migrate-alist
+  '((3 (bbdb-record-xfields bbdb-record-set-xfields
+        bbdb-migrate-dates))
     (4 (bbdb-record-address bbdb-record-set-address
-        bbdb-migrate-streets-to-list))
+        bbdb-migrate-add-country))
     (5 (bbdb-record-address bbdb-record-set-address
-        bbdb-migrate-postcodes-to-strings))
-    (6 (bbdb-record-xfields bbdb-record-set-xfields
+        bbdb-migrate-streets-to-list))
+    (6 (bbdb-record-address bbdb-record-set-address
+        bbdb-migrate-postcode-to-string))
+    (7 (bbdb-record-xfields bbdb-record-set-xfields
         bbdb-migrate-xfields-to-list)
        (bbdb-record-organization bbdb-record-set-organization
         bbdb-migrate-organization-to-list)))
-  "The alist of (version . migration-spec-list).
-See `bbdb-migrate-record-lambda' for details.")
-
-(defun bbdb-migrate-record-lambda (changes)
-  "Return a function which will migrate a single record.
-CHANGES is a `migration-spec-list' containing entries of the form
-
-        (GET SET FUNCTION)
-
-where GET is the function to be used to retrieve the field to be
-modified, and SET is the function to be used to set the field to be
-modified.  FUNCTION will be applied to the result of GET, and its
-results will be saved with SET."
-  (byte-compile `(lambda (record)
-                  ,@(mapcar (lambda (ch)
-                              `(,(cadr ch) record
-                                (,(car (cddr ch))
-                                 (,(car ch) record))))
-                            changes)
-                  record)))
-
-(defun bbdb-migrate-versions-lambda (v0)
-  "Return the function to migrate from V0 to `bbdb-file-format'."
+  ;; Formats 8 and 9: do nothing
+  "Alist (VERSION . CHANGES).
+CHANGES is a list with elements (GET SET FUNCTION) that expands
+to action (SET record (FUNCTION (GET record))).")
+
+(defun bbdb-migrate-lambda (old)
+  "Return the function to migrate from OLD to `bbdb-file-format'.
+The manipulations are defined by `bbdb-migrate-alist'."
   (let (spec)
-    (while (< v0 bbdb-file-format)
-      (setq spec (append spec (cdr (assoc v0 bbdb-migration-spec)))
-            v0 (1+ v0)))
-    (bbdb-migrate-record-lambda spec)))
+    (while (<= old bbdb-file-format)
+      (setq spec (append spec (cdr (assoc old bbdb-migrate-alist)))
+            old (1+ old)))
+    `(lambda (record)
+       ,@(mapcar (lambda (change)
+                   ;; (SET record (FUNCTION (GET record)))
+                   `(,(nth 1 change) record ; SET
+                     (,(nth 2 change) ; FUNCTION
+                      (,(nth 0 change) record)))) ; GET
+                 spec)
+       record)))
 
-(defun bbdb-migrate-postcodes-to-strings (addresses)
+(defun bbdb-migrate-postcode-to-string (addresses)
   "Make all postcodes plain strings.
 This uses the code that used to be in `bbdb-address-postcode'."
   ;; apply the function to all addresses in the list and return a
   ;; modified list of addresses
   (mapcar (lambda (address)
-            (let ((postcode (if (stringp (bbdb-address-postcode address))
-                                (bbdb-address-postcode address)
-                              ;; if not a string, make it a string...
-                              (if (consp (bbdb-address-postcode address))
-                                  ;; if a cons cell with two strings
-                                  (if (and (stringp (car (bbdb-address-postcode address)))
-                                           (stringp (car (cdr (bbdb-address-postcode address)))))
-                                      ;; if the second string starts with 4 digits
-                                      (if (string-match "^[0-9][0-9][0-9][0-9]"
-                                                        (car (cdr (bbdb-address-postcode address))))
-                                          (concat (car (bbdb-address-postcode address))
-                                                  "-"
-                                                  (car (cdr (bbdb-address-postcode address))))
-                                        ;; if ("abc" "efg")
-                                        (concat (car (bbdb-address-postcode address))
-                                                " "
-                                                (car (cdr (bbdb-address-postcode address)))))
-                                    ;; if ("SE" (123 45))
-                                    (if (and (stringp (nth 0 (bbdb-address-postcode address)))
-                                             (consp (nth 1 (bbdb-address-postcode address)))
-                                             (integerp (nth 0 (nth 1 (bbdb-address-postcode address))))
-                                             (integerp (nth 1 (nth 1 (bbdb-address-postcode address)))))
-                                        (format "%s-%d %d"
-                                                (nth 0 (bbdb-address-postcode address))
-                                                (nth 0 (nth 1 (bbdb-address-postcode address)))
-                                                (nth 1 (nth 1 (bbdb-address-postcode address))))
-                                      ;; if a cons cell with two numbers
-                                      (if (and (integerp (car (bbdb-address-postcode address)))
-                                               (integerp (car (cdr (bbdb-address-postcode address)))))
-                                          (format "%05d-%04d" (car (bbdb-address-postcode address))
-                                                  (car (cdr (bbdb-address-postcode address))))
-                                        ;; else a cons cell with a string an a number (possible error
-                                        ;; if a cons cell with a number and a string -- note the
-                                        ;; order!)
-                                        (format "%s-%d" (car (bbdb-address-postcode address))
-                                                (car (cdr (bbdb-address-postcode address)))))))
-                                ;; if nil or zero
-                                (if (or (zerop (bbdb-address-postcode address))
-                                        (null (bbdb-address-postcode address)))
-                                    ""
-                                  ;; else a number, could be 3 to 5 digits (possible error: assuming
-                                  ;; no leading zeroes in postcodes)
-                                  (format "%d" (bbdb-address-postcode address)))))))
-              (bbdb-address-set-postcode address postcode))
+            (let ((postcode (bbdb-address-postcode address)))
+              (bbdb-address-set-postcode
+               address
+               (cond ((stringp postcode)
+                      postcode)
+                     ;; nil or zero
+                     ((or (zerop postcode)
+                          (null postcode))
+                      "")
+                     ;; a number
+                     ((numberp postcode)
+                      (format "%d" postcode))
+                     ;; list with two strings
+                     ((and (stringp (nth 0 postcode))
+                           (stringp (nth 1 postcode)))
+                      ;; the second string starts with 4 digits
+                      (if (string-match "^[0-9][0-9][0-9][0-9]"
+                                        (nth 1 postcode))
+                          (format "%s-%s" (nth 0 postcode) (nth 1 postcode))
+                        ;; ("abc" "efg")
+                        (format "%s %s" (nth 0 postcode) (nth 1 postcode))))
+                     ;; list with two numbers
+                     ((and (integerp (nth 0 postcode))
+                           (integerp (nth 1 postcode)))
+                      (format "%05d-%04d" (nth 0 postcode) (nth 1 postcode)))
+                     ;; list with a string and a number
+                     ((and (stringp (nth 0 postcode))
+                           (integerp (nth 1 postcode)))
+                      (format "%s-%d" (nth 0 postcode) (nth 1 postcode)))
+                     ;; ("SE" (123 45))
+                     ((and (stringp (nth 0 postcode))
+                           (integerp (nth 0 (nth 1 postcode)))
+                           (integerp (nth 1 (nth 1 postcode))))
+                      (format "%s-%d %d" (nth 0 postcode) (nth 0 (nth 1 postcode))
+                              (nth 1 (nth 1 postcode))))
+                     ;; last possibility
+                     (t (format "%s" postcode)))))
             address)
           addresses))
 
-(defun bbdb-migrate-change-dates (record)
+(defun bbdb-migrate-dates (xfields)
   "Change date formats.
 Formats are changed in timestamp and creation-date fields from
 \"dd mmm yy\" to \"yyyy-mm-dd\"."
-  (unless (stringp record)
-    (mapc (lambda (rr)
-                 (when (memq (car rr) '(creation-date timestamp))
-                   (bbdb-migrate-change-dates-change-field rr)))
-               record)
-    record))
-
-(defun bbdb-migrate-change-dates-change-field (field)
-  "Migrate the date field (the cdr of FIELD) from \"dd mmm yy\" to
-\"yyyy-mm-dd\"."
-  (let ((date (cdr field))
-    parsed)
-    ;; Verify and extract - this is fairly hideous
-    (and (equal (setq parsed (timezone-parse-date (concat date " 00:00:00")))
-        ["0" "0" "0" "0" nil])
-     (equal (setq parsed (timezone-parse-date date))
-        ["0" "0" "0" "0" nil])
-     (cond ((string-match
-         "^\\([0-9]\\{4\\}\\)[-/]\\([ 0-9]?[0-9]\\)[-/]\\([ 0-9]?[0-9]\\)" date)
-        (setq parsed (vector (string-to-number (match-string 1 date))
-                     (string-to-number (match-string 2 date))
-                     (string-to-number (match-string 3 date))))
-        ;; This should be fairly loud for GNU Emacs users
-        (bbdb-warn "BBDB is treating %s field value %s as %s %d %d"
-               (car field) (cdr field)
-               (upcase-initials
-                (downcase (car (rassoc (aref parsed 1)
-                           timezone-months-assoc))))
-               (aref parsed 2) (aref parsed 0)))
-           ((string-match
-         "^\\([ 0-9]?[0-9]\\)[-/]\\([ 0-9]?[0-9]\\)[-/]\\([0-9]\\{4\\}\\)" date)
-        (setq parsed (vector (string-to-number (match-string 3 date))
-                     (string-to-number (match-string 1 date))
-                     (string-to-number (match-string 2 date))))
-        ;; This should be fairly loud for GNU Emacs users
-        (bbdb-warn "BBDB is treating %s field value %s as %s %d %d"
-               (car field) (cdr field)
-               (upcase-initials
-                (downcase (car (rassoc (aref parsed 1)
-                           timezone-months-assoc))))
-               (aref parsed 2) (aref parsed 0)))
-           (t ["0" "0" "0" "0" nil])))
-
-    ;; I like numbers
-    (and (stringp (aref parsed 0))
-     (aset parsed 0 (string-to-number (aref parsed 0))))
-    (and (stringp (aref parsed 1))
-     (aset parsed 1 (string-to-number (aref parsed 1))))
-    (and (stringp (aref parsed 2))
-     (aset parsed 2 (string-to-number (aref parsed 2))))
+  (unless (stringp xfields)
+    (mapc (lambda (xfield)
+            (when (memq (car xfield) '(creation-date timestamp))
+              (bbdb-migrate-date xfield)))
+          xfields)
+    xfields))
+
+(defun bbdb-migrate-date (field)
+  "Convert date field FIELD from \"dd mmm yy\" to \"yyyy-mm-dd\"."
+  (let* ((date (cdr field))
+         (parsed (timezone-parse-date (concat date " 00:00:00"))))
+    ;; If `timezone-parse-date' cannot make sense of its arg DATE
+    ;; it returns ["0" "0" "0" "0" nil].
+    (if (equal parsed ["0" "0" "0" "0" nil])
+        (setq parsed (timezone-parse-date date)))
+    (when (equal parsed ["0" "0" "0" "0" nil])
+      (cond ((string-match
+              "^\\([0-9]\\{4\\}\\)[-/]\\([ 0-9]?[0-9]\\)[-/]\\([ 0-9]?[0-9]\\)" date)
+             (setq parsed (vector (match-string 1 date) (match-string 2 date)
+                                  (match-string 3 date))))
+            ((string-match
+              "^\\([ 0-9]?[0-9]\\)[-/]\\([ 0-9]?[0-9]\\)[-/]\\([0-9]\\{4\\}\\)" date)
+             (setq parsed (vector (match-string 3 date) (match-string 1 date)
+                                  (match-string 2 date))))))
+
+    ;; We need numbers for the following sanity check
+    (dotimes (i 3)
+      (if (stringp (aref parsed i))
+          (aset parsed i (string-to-number (aref parsed i)))))
 
     ;; Sanity check
-    (cond ((and (< 0 (aref parsed 0))
-        (< 0 (aref parsed 1)) (>= 12 (aref parsed 1))
-        (< 0 (aref parsed 2))
-        (>= (timezone-last-day-of-month (aref parsed 1)
-                        (aref parsed 0))
-            (aref parsed 2)))
-       (setcdr field (format "%04d-%02d-%02d" (aref parsed 0)
-                 (aref parsed 1) (aref parsed 2)))
-       field)
-      (t
-       (error "BBDB cannot parse %s header value %S for upgrade"
-          field date)))))
+    (if (and (< 0 (aref parsed 0))
+             (< 0 (aref parsed 1)) (< (aref parsed 1) 13)
+             (< 0 (aref parsed 2))
+             (<= (aref parsed 2)
+                 (timezone-last-day-of-month (aref parsed 1) (aref parsed 0))))
+        (setcdr field (format "%04d-%02d-%02d" (aref parsed 0)
+                              (aref parsed 1) (aref parsed 2)))
+      (error "BBDB cannot parse %s header value %S for upgrade"
+             field date))))
 
-(defun bbdb-migrate-add-country-field (addrl)
+(defun bbdb-migrate-add-country (addrl)
   "Add a country field to each address in the address list."
-  (mapcar (lambda (address) (vconcat address [""])) addrl))
+  (mapcar (lambda (address) (vconcat address [bbdb-default-country])) addrl))
 
 (defun bbdb-migrate-streets-to-list (addrl)
   "Convert the streets to a list."
   (mapcar (lambda (address)
-            (vector (aref address 0) ; tag
+            (vector (aref address 0) ; key
                     (delq nil (delete "" ; nuke empties
                                       (list (aref address 1) ; street1
                                             (aref address 2) ; street2
@@ -255,7 +243,7 @@ Formats are changed in timestamp and cre
 (defun bbdb-migrate-xfields-to-list (xfields)
   "Migrate XFIELDS to list."
   (if (stringp xfields)
-      (list (cons 'notes xfields))
+      `((notes . ,xfields))
     xfields))
 
 (defun bbdb-migrate-organization-to-list (organization)
@@ -280,13 +268,16 @@ for outdated BBDB variables that are set
     (mapatoms (lambda (vv)
                 (if (and (boundp vv)
                          (string-match re (symbol-name vv))
-                         (not (get vv 'variable-documentation)))
+                         (not (get vv 'variable-documentation))
+                         (not (get vv 'byte-obsolete-variable)))
                     (push vv list))))
     (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-2017 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-2017 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))
 
               (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-2017 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-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-2017 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-2017 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-2017 Roland Winkler <winkler@gnu.org>
 
 ;; This file is part of the Insidious Big Brother Database (aka BBDB),
 
@@ -21,15 +21,20 @@
 
 (defconst bbdb-version "@PACKAGE_VERSION@" "Version of BBDB.")
 
-(if (< emacs-major-version 23)
-  (error "BBDB %s requires GNU Emacs 23 or later" bbdb-version))
+(if (< emacs-major-version 24)
+  (error "BBDB %s requires GNU Emacs 24 or later" bbdb-version))
 
 (defconst bbdb-version-date "@PACKAGE_DATE@"
   "Version date of BBDB.")
 
-(defcustom bbdb-print-tex-path '("@pkgdatadir@")
-  "List of directories with the BBDB tex files."
+(defcustom bbdb-tex-path '("@pkgdatadir@")
+  "List of directories with the BBDB TeX files.
+If this is t assume that these files reside in directories
+that are part of the regular TeX search path"
   :group 'bbdb-utilities-print
-  :type '(repeat (directory :tag "Directory")))
+  :type '(choice (const :tag "Files in TeX path" t)
+                 (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-2017 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)
+      (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
--- /dev/null
+++ bbdb3-3.1.2/lisp/bbdb-tex.el
@@ -0,0 +1,558 @@
+;;; bbdb-tex.el --- feed BBDB into LaTeX  -*- lexical-binding: t -*-
+
+;; Copyright (C) 1993 Boris Goldowsky
+;; Copyright (C) 2010-2017 Roland Winkler <winkler@gnu.org>
+
+;; Authors: Boris Goldowsky <boris@cs.rochester.edu>
+;;          Dirk Grunwald <grunwald@cs.colorado.edu>
+;;          Luigi Semenzato <luigi@paris.cs.berkeley.edu>
+
+;; 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 lets you feed BBDB into LaTeX.
+;; See the BBDB info manual for documentation.
+;;
+;; In the *BBDB* buffer, type M-x `bbdb-tex' to convert the listing
+;; to LaTeX format.
+;;
+;; TeX macros appearing in the output:
+;;   \name{first}{last}
+;;   \organization{foo bar}
+;;   \affix{foo bar}
+;;   \aka{foo bar}
+;;   \phone{key}{123 456 7890}
+;;   \address{key}{foo bar}
+;;   \mail{foo@bar.com}{Smith <foo@bar.com>}
+;;   \xfield{key}{value}
+;; Each macro may appear multiple times.
+;;
+;; The detailed grammar of the output is defined in `bbdb-tex-alist'.
+;; The output starts with a prolog where you can specify LaTeX packages
+;; and other customizations in the usual way.  The above macros should get
+;; defined, too. By default, this happens in the style file bbdb.sty that
+;; is shipped with BBDB.
+;;
+;; The body of the output contains the BBDB records.  Usually, the records
+;; are placed inside some "bbdb" environment.  You can customize which fields
+;; of each record should appear in the listing and in which order.
+;; Also, you can put separators between individual fields.  A separator macro
+;; can also separate records when the first character of the last name differs
+;; from the first character of the last name of the previous record.
+;; The listing ends with an epilog.
+
+;; A few notes on "advanced usage" of `bbdb-tex':
+;;
+;; It should be possible to use `bbdb-tex' with all the bells and whistles
+;; of LaTeX by loading the appropriate LaTeX style files and packages or
+;; embedding the output of `bbdb-tex' into more complex LaTeX documents.
+;; For this you can customize the rules in `bbdb-tex-alist' and use
+;; customized style files for interpreting the TeX macros used by `bbdb-tex'.
+;;
+;; Generally, lisp customizations for `bbdb-tex' are intended to provide control
+;; of *what* appears in the TeX listing.  But there are no lisp customization
+;; options to control the actual layout that should be handled by LaTeX.
+;; BBDB is shipped with one basic LaTeX style file bbdb.sty to handle
+;; the TeX macros listed above.  You should customize this LaTeX style file
+;; to match your taste and / or your needs.  Note also that `bbdb-tex-alist'
+;; allows you to specify an arbitrary number of rules that may use different
+;; style files for the above TeX macros.
+
+;; Generally, it will be advantageous to make all relevant style files
+;; and packages known to LaTeX by putting them in the appropriate directories
+;; of your TeX installation.  Likely, the user variable `bbdb-tex-path'
+;; should not be used in such advanced cases.  The main purpose of the
+;; inlining mechanism provided via `bbdb-tex-path' is that we can ship
+;; and install BBDB without worrying about the tricky question where to
+;; (auto-) install the basic style file bbdb.sty shipped with BBDB so that
+;; TeX finds it.  Most often, it will be best to manually install even bbdb.sty
+;; in a directory where TeX finds it and bind `bbdb-tex-path' to t to fully
+;; suppress the inlining.
+;;
+;; Before generating the TeX output, the field values of a record are massaged
+;; by `bbdb-tex-field' that passes these values by default to `bbdb-tex-replace',
+;; see also `bbdb-tex-replace-list'.  Instead the user may also define functions
+;; `bbdb-tex-output-...' that take precedence, see `bbdb-tex-field'.
+;;
+;; `bbdb-tex' understands one new BBDB xfield: tex-name, see also
+;; `bbdb-tex-name'.  If this xfield is defined for a record,
+;; this will be used for the TeXed listing instead of the name field
+;; of that record.  The value of the xfield tex-name is used verbatim,
+;; it does not see `bbdb-tex-field' and `bbdb-tex-replace-list'.
+;;
+;;
+;; This program was adapted for BBDB by Boris Goldowsky
+;; <boris@cs.rochester.edu> and Dirk Grunwald
+;; <grunwald@cs.colorado.edu> using a TeX format designed by Luigi
+;; Semenzato <luigi@paris.cs.berkeley.edu>.
+;; We are also grateful to numerous people on the bbdb-info
+;; mailing list for suggestions and bug reports.
+
+;;; Code:
+
+(require 'bbdb)
+(require 'bbdb-com)
+
+;;; Variables:
+
+(defcustom bbdb-tex-name 'tex-name
+  "Xfield holding the name in TeX format.
+The string in this field gets split into first and last name
+using `bbdb-separator-alist'.  The separator defaults to \"#\"."
+  :group 'bbdb-utilities-tex
+  :type '(symbol :tag "Xfield"))
+
+(defcustom bbdb-tex-alist
+  `((multi-line
+     (demand (or address phone))
+     (prolog ,(concat "\\documentclass{article}\n\\usepackage{bbdb}\n"
+                      "\\usepackage{multicol}\n"
+                      "\\begin{document}\n\\begin{multicols}{2}"))
+     (record "\\begin{bbdbrecord}" name organization ; affix aka
+             (address t) (phone t) (mail t)
+             (xfields t nil
+                      (omit ,bbdb-tex-name mail-alias creation-date timestamp))
+             "\\end{bbdbrecord}\n")
+     (separator "\\bbdbseparator{%s}\n")
+     (epilog ,(concat "\\noindent\\hrulefill\\\\\nPrinted \\today\n"
+                      "\\end{multicols}\n\\end{document}"))
+     (options (bbdb-tex-linebreak "\\\\\\\\\n")
+              (bbdb-tex-address-layout 2)))
+
+    (one-line
+     (demand phone)
+     (prolog ,(concat "\\documentclass{article}\n\\usepackage{bbdb}\n"
+                      "\\begin{document}\n\\begin{bbdb}{llllll}"))
+     (record name "&" (organization 1) "&" (phone 2 "&") "&" (mail 1)
+             "&" (address 1) "\\\\")
+     (separator "\\bbdbseparator{%s}")
+     (epilog "\\end{bbdb}\n\\end{document}")
+     (options (bbdb-tex-linebreak ", ")
+              (bbdb-tex-address-layout 3)))
+
+    (phone
+     (demand phone)
+     (prolog ,(concat "\\documentclass{article}\n\\usepackage{bbdb}\n"
+                      "\\begin{document}\n\\begin{bbdb}{ll}"))
+     (record name "&" (phone 2 "&") "\\\\")
+     (separator "\\bbdbseparator{%s}")
+     (epilog "\\end{bbdb}\n\\end{document}")
+     (options (bbdb-tex-linebreak ", ")
+              (bbdb-tex-address-layout 3)))
+
+    (example ; another rule with more examples
+     (demand (or address phone))
+     (prolog ,(concat "\\documentclass{article}\n\\usepackage{bbdb}\n"
+                      "\\usepackage{multicol}\n"
+                      "\\begin{document}\n\\begin{multicols}{2}"))
+     (record "\\begin{bbdbrecord}" name organization
+             (address 1 nil (omit "work"))
+             (phone 2 nil (admit "home" "cell"))
+             (mail t)
+             (birthday t)
+             (xfields t nil
+                      (omit ,bbdb-tex-name mail-alias creation-date timestamp))
+             "\\end{bbdbrecord}\n")
+     (separator "\\bbdbseparator{%s}\n")
+     (epilog ,(concat "\\noindent\\hrulefill\\\\\nPrinted \\today\n"
+                      "\\end{multicols}\n\\end{document}"))
+     (options (bbdb-tex-linebreak "\\\\\\\\\n")
+              (bbdb-tex-address-layout 2))))
+
+  "Alist of rules for passing BBDB to LaTeX.
+Each rule has the form (RULE LIST1 LIST2 ...).
+The symbol RULE identifies the rule.
+The remainder are lists LIST that should have one of these forms:
+
+ (demand FORM)
+
+  Here FORM is a lisp expression.  A record will be TeXed only
+  if evaluating FORM yields a non-nil value for this record.
+  When FORM is evaluated, the symbols name, affix, organization, mail,
+  phone, address, and xfields are set to the corresponding values
+  of this record; these symbols are nil if the respective field
+  does not exist for this record.
+
+ (prolog STRING)
+
+  The string STRING is inserted at the beginning of the buffer.
+  If STRING contains the substring \"\\usepackage{foo}\" and
+  a file \"foo.sty\" exists within `bbdb-tex-path', replace
+  \"\\usepackage{foo}\" with the content of the file \"foo.sty\",
+  surrounded by \"\\makeatletter\" and \"\\makeatother\".
+  Note: This fails with more sophisticated LaTeX style files
+  using, e.g., optional arguments for the \"\\usepackage\" macro.
+
+ (record ELT1 ELT2 ...)
+
+  Here ELT may be one of the following:
+
+  IF ELT is name, this expands to \"\\name{first}{last}\"
+
+  If ELT is affix, organization, or aka, ELT expands to \"\\ELT{value}\".
+    Here the elements of ELT are concatenated to get one value.
+
+  If ELT is the key of an xfield, ELT expands to \"\\xfield{ELT}{value}\".
+
+  If ELT is a string, this is inserted \"as is\" in the TeX buffer.
+
+  ELT may also be a loop (FLD COUNT [SEPARATOR] [OPT...])
+  looping over the values of FLD.
+
+  If FLD is mail, this expands to \"\\mail{short}{long}\",
+    such as \"\\mail{foo@bar.com}{Smith <foo@bar.com>}\",
+  If FLD is phone, this expands to \"\\phone{key}{number}\"
+  If FLD is address, this expands to \"\\address{key}{value}\".
+  If FLD is xfields, this expands to \"\\xfield{key}{value}\".
+  If FLD is the key of an xfield, split the value of FLD
+    using `bbdb-separator-alist' to generate a list of values,
+    which then expand to \"\\xfield{FLD}{value}\".
+
+  If COUNT is a number, process at most COUNT values of FLD.
+  IF COUNT is t, process all values of FLD.
+
+  If SEPARATOR is non-nil, it is a string that is inserted between
+  the values of FLD.  Insert COUNT - 1 instances of SEPARATOR,
+  even if there are fewer values of FLD.
+
+  If FLD is mail, phone, address, or xfields,
+  OPT may be a list (admit KEY ...) or (omit KEY ...).
+  Then a value is admitted or omitted if its key KEY is listed here.
+
+ (separator STRING)
+
+  When the first letter of the records' sortkey increases compared with
+  the previous record in the TeX listing, the new letter is formatted
+  using the format string STRING to generate a separator macro.
+
+ (epilog STRING)
+
+  The string STRING is inserted at the end of the buffer."
+  :group 'bbdb-utilities-tex)
+
+(defcustom bbdb-tex-rule-default 'multi-line
+  "Default rule for BBDB tex.
+This symbol should be a key in `bbdb-tex-alist'."
+  :group 'bbdb-utilities-tex
+  :type '(symbol :tag "rule"))
+
+;; FIXME
+;; (defcustom bbdb-tex-empty-fields nil
+;;   "If non-nil generate TeX output even for empty fields."
+;;   :group 'bbdb-utilities-tex)
+
+(defcustom bbdb-tex-replace-list
+  '(("[#$%&_]" . "\\\\\\&")
+    ("<" . "\\\\textless ")
+    (">" . "\\\\textgreater ")
+    ("~" . "\\\\textasciitilde ")
+    ("{" . "\\\\textbraceleft ")
+    ("}" . "\\\\textbraceright "))
+  "Replacement list for TeX's special characters.
+Each element is of the form (REGEXP . REPLACE)."
+  :group 'bbdb-utilities-tex
+  :type '(repeat (cons regexp string)))
+
+(defcustom bbdb-tex-linebreak "\\\\\\\\\n"
+  "Replacement for linebreaks."
+  :group 'bbdb-utilities-tex
+  :type 'string)
+
+(defcustom bbdb-tex-address-format-list bbdb-address-format-list
+  "List of address formatting rules for `bbdb-tex'.
+Each element may take the same values as in `bbdb-address-format-list'.
+The elements EDIT of `bbdb-address-format-list' are ignored."
+  :group 'bbdb-utilities-tex
+  :type '(repeat (list (choice (const :tag "Default" t)
+                               (function :tag "Function")
+                               (repeat (string)))
+                       (choice (string)
+                               (function :tag "Function"))
+                       (choice (string)
+                               (function :tag "Function"))
+                       (choice (string)
+                               (function :tag "Function")))))
+
+(defcustom bbdb-tex-address-layout 2
+  "Address layout according to `bbdb-tex-address-format-list'.
+2 is multi-line layout, 3 is one-line layout."
+  :group 'bbdb-utilities-tex)
+
+(defcustom bbdb-tex-file "~/bbdb.tex"
+  "Default file name for TeXing BBDB."
+  :group 'bbdb-utilities-tex
+  :type 'file)
+
+;;; Internal variables
+
+(defvar bbdb-tex-rule-last bbdb-tex-rule-default
+  "Last rule used for TeXing BBDB.")
+
+(defvar bbdb-tex-file-last bbdb-tex-file
+  "Last used TeX file")
+
+;;; Functions:
+
+;; While we use `bbdb-tex-replace' only once in `bbdb-tex-field',
+;; we keep it as a separate function so that it can also be used
+;; inside user-defined functions `bbdb-tex-output-...'.
+(defun bbdb-tex-replace (string)
+  "Apply replacement rules `bbdb-tex-replace-list' to STRING.
+Also, replace linebreaks by `bbdb-tex-linebreak'."
+  (if (not string)
+      ""
+    (dolist (elt bbdb-tex-replace-list)
+      (setq string (replace-regexp-in-string (car elt) (cdr elt) string)))
+    (replace-regexp-in-string "\n" bbdb-tex-linebreak string)))
+
+(defun bbdb-tex-field (field str)
+  "Massage string STR for LaTeX.
+By default, STR is passed to `bbdb-tex-replace'.
+The user may also define a function `bbdb-tex-output-FIELD'
+that takes precedence."
+  (let ((fun (intern-soft (format "bbdb-tex-output-%s" field))))
+    (if fun
+        (funcall fun str)
+      (bbdb-tex-replace str))))
+
+(defun bbdb-tex-list (list rule fun)
+  "Use function FUN to generate output for LIST according to RULE.
+LIST is a list of field values such as a list of addresses.
+RULE is an element of a record list as in `bbdb-tex-alist'
+used to select the elements of LIST that get processed by calling FUN."
+  (let ((admit (cdr (assq 'admit rule)))
+        (omit (cdr (assq 'omit rule)))
+        (num (if (numberp (nth 1 rule)) (nth 1 rule)))
+        (sep (if (nth 2 rule) (concat (nth 2 rule) "\n")))
+        (i -1)
+        new-list elt)
+
+    ;; Select the relevant elements of LIST.
+    (cond (admit
+           (dolist (l list)
+             (if (member (elt l 0) admit)
+                 (push l new-list)))
+           (setq new-list (nreverse new-list)))
+
+          (omit
+           (dolist (l list)
+             (unless (member (elt l 0) omit)
+               (push l new-list)))
+           (setq new-list (nreverse new-list)))
+
+          (t
+           (setq new-list list)))
+
+    (cond ((not num)
+           (insert (mapconcat fun new-list (or sep ""))))
+          ((not sep)
+           (while (and (< (setq i (1+ i)) num)
+                       (setq elt (pop new-list)))
+             (insert (funcall fun elt))))
+          (t
+           (while (< (setq i (1+ i)) num)
+             (if (setq elt (pop new-list))
+                 (insert (funcall fun elt)))
+             (if (< (1+ i) num)
+                 (insert sep)))))))
+
+;;;###autoload
+(defun bbdb-tex (records file rule)
+  "Generate FILE for TeXing RECORDS.
+Interactively, use BBDB prefix \
+\\<bbdb-mode-map>\\[bbdb-do-all-records], see `bbdb-do-all-records'.
+RULE should be an element of `bbdb-tex-alist'."
+  (interactive
+   (list (bbdb-do-records)
+         (read-file-name
+          (format "TeX file: (default %s) "
+                  (abbreviate-file-name bbdb-tex-file-last))
+          (file-name-directory bbdb-tex-file-last)
+          bbdb-tex-file-last)
+         (intern (completing-read (format "Rule: (default %s) "
+                                          bbdb-tex-rule-last)
+                                  bbdb-tex-alist nil t
+                                  nil nil (symbol-name bbdb-tex-rule-last)))))
+  ;; Remember our choice for `bbdb-tex-file-last'.
+  (setq bbdb-tex-file-last (expand-file-name file))
+
+  (find-file bbdb-tex-file-last)
+  (let* ((buffer-undo-list t)
+         (rule (assq rule bbdb-tex-alist))
+         (demand (nth 1 (assq 'demand rule)))
+         (separator (nth 1 (assq 'separator rule)))
+         current-letter p-symbols p-values)
+    (erase-buffer)
+
+    ;; Options
+    (dolist (option (cdr (assq 'options rule)))
+      (push (car option) p-symbols)
+      (push (cadr option) p-values))
+    (cl-progv p-symbols p-values
+
+      ;; Prolog
+      (let ((prolog (nth 1 (assq 'prolog rule))))
+        (when prolog
+          (insert prolog)
+          (when (consp bbdb-tex-path)
+            (goto-char (point-min))
+            (while (re-search-forward "\\\\usepackage[ \t\n]*{\\([^}]+\\)}" nil t)
+              (let ((sty (locate-file (match-string 1) bbdb-tex-path '(".sty"))))
+                (when sty
+                  (replace-match (format "\n\\\\makeatletter\n%% begin %s\n%% end %s\n\\\\makeatother\n" sty sty))
+                  (save-excursion
+                    (forward-line -2)
+                    (insert-file-contents sty))))))
+          (goto-char (point-max))
+          (unless (bolp) (insert "\n"))
+          (insert "% end BBDB prolog\n")))
+
+      ;; Process Records
+      (dolist (record (bbdb-record-list records))
+        (let* ((first-letter
+                (substring (bbdb-record-sortkey record) 0 1))
+               (firstname (bbdb-record-firstname record))
+               (lastname (bbdb-record-lastname record))
+               (name    (bbdb-record-name record))
+               (name-lf (bbdb-record-name-lf record))
+               (organization (bbdb-record-organization record))
+               (affix   (bbdb-record-affix record))
+               (aka     (bbdb-record-aka record))
+               (mail    (bbdb-record-mail record))
+               (phone   (bbdb-record-phone record))
+               (address (bbdb-record-address record))
+               (xfields (bbdb-record-xfields record))
+               (lex-env `((firstname . ,firstname) (lastname . ,lastname)
+                          (name . ,name) (name-lf . ,name-lf) (aka . ,aka)
+                          (organization . ,organization) (affix . ,affix)
+                          (mail . ,mail) (phone . ,phone)
+                          (address . ,address) (xfields . ,xfields)))
+               (bbdb-address-format-list bbdb-tex-address-format-list))
+
+          ;; A record is processed only if the form DEMAND
+          ;; evaluates to a non-nil value.
+          (when (or (not demand)
+                    (eval demand lex-env))
+
+            ;; Separator
+            (if (and separator
+                     (not (and current-letter
+                               (equal first-letter current-letter))))
+                (insert (format separator (upcase first-letter)) "\n"))
+            (setq current-letter first-letter)
+
+            (dolist (elt (cdr (assq 'record rule)))
+              (cond ((stringp elt)
+                     (insert elt "\n"))
+
+                    ((eq elt 'name) ; name of record
+                     (let ((tex-name (and bbdb-tex-name
+                                          (bbdb-record-field record bbdb-tex-name)))
+                           (fmt "\\name{%s}{%s}\n"))
+                       (if tex-name
+                           (let ((first-last (bbdb-split bbdb-tex-name tex-name)))
+                             (cond ((eq 2 (length first-last))
+                                    (insert (format fmt (car first-last) (cadr first-last))))
+                                   ((eq 1 (length first-last))
+                                    (insert (format fmt "" (car first-last))))
+                                   (t (error "TeX name %s cannot be split" tex-name))))
+                         (insert (format fmt
+                                         (bbdb-tex-field 'firstname firstname)
+                                         (bbdb-tex-field 'lastname  lastname))))))
+
+                    ;; organization, affix or aka as single string
+                    ((memq elt '(organization affix aka))
+                     (let ((val (bbdb-record-field record elt)))
+                       (if val
+                           (insert (format "\\%s{%s}\n" elt
+                                           (bbdb-tex-field elt (bbdb-concat elt val)))))))
+
+                    ;; organization, affix or aka as list of strings
+                    ((memq (car elt) '(organization affix aka))
+                     (bbdb-tex-list
+                      (bbdb-record-field record (car elt))
+                      elt
+                      `(lambda (o)
+                         (format "\\%s{%s}\n" ',(car elt)
+                                 (bbdb-tex-field ',(car elt) o)))))
+
+                    ((eq (car elt) 'mail) ; mail
+                     (bbdb-tex-list
+                      mail elt
+                      (lambda (m)
+                        (format "\\mail{%s}{%s}\n"
+                                ;; No processing of plain mail address
+                                (nth 1 (bbdb-decompose-bbdb-address m))
+                                (bbdb-tex-field 'mail m)))))
+
+                    ((eq (car elt) 'address) ; address
+                     (bbdb-tex-list
+                      address elt
+                      (lambda (a)
+                        (format "\\address{%s}{%s}\n"
+                                (bbdb-tex-field 'address-label (bbdb-address-label a))
+                                (bbdb-tex-field 'address (bbdb-format-address
+                                                          a bbdb-tex-address-layout))))))
+
+                    ((eq (car elt) 'phone) ; phone
+                     (bbdb-tex-list
+                      phone elt
+                      (lambda (p)
+                        (format "\\phone{%s}{%s}\n"
+                                (bbdb-tex-field 'phone-label (bbdb-phone-label p))
+                                (bbdb-tex-field 'phone (bbdb-phone-string p))))))
+
+                    ((eq (car elt) 'xfields) ; list of xfields
+                     (bbdb-tex-list
+                      (bbdb-record-field record 'xfields)
+                      elt
+                      (lambda (x)
+                        (format "\\xfield{%s}{%s}\n"
+                                (bbdb-tex-field 'xfield-label (symbol-name (car x)))
+                                (bbdb-tex-field 'xfield (cdr x))))))
+
+                    ((symbolp elt) ; xfield as single string
+                     ;; The value of an xfield may be a sexp instead of a string.
+                     ;; Ideally, a sexp should be formatted by `pp-to-string',
+                     ;; then printed verbatim.
+                     (let ((val (format "%s" (bbdb-record-field record elt))))
+                       (if val
+                           (insert (format "\\xfield{%s}{%s}\n" elt
+                                           (bbdb-tex-field elt (bbdb-concat elt val)))))))
+
+                    ((consp elt) ; xfield as list of strings
+                     (bbdb-tex-list
+                      (bbdb-split (car elt)
+                                  (format "%s" (bbdb-record-field record (car elt))))
+                      elt
+                      `(lambda (x)
+                         (format "\\xfield{%s}{%s}\n" ',(car elt)
+                                 (bbdb-tex-field ',(car elt) x)))))
+
+                    (t (error "Rule `%s' undefined" elt)))))))
+
+      ;; Epilog
+      (let ((epilog (nth 1 (assq 'epilog rule))))
+        (when epilog
+          (insert "% begin BBDB epilog\n" epilog)
+          (unless (bolp) (insert "\n"))))))
+  (setq buffer-undo-list nil)
+  (save-buffer))
+
+(provide 'bbdb-tex)
+
+;;; bbdb-tex.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-2017 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-2017 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-2017 Roland Winkler <winkler@gnu.org>
 
 ;; This file is part of the Insidious Big Brother Database (aka BBDB),
 
@@ -24,15 +24,15 @@
 ;;;
 ;;;  -----------------------------------------------------------------------
 ;;; |  There is a mailing list for discussion of BBDB:                      |
-;;; |         bbdb-info@lists.sourceforge.net                               |
-;;; |  To join, send mail to bbdb-info-request@lists.sourceforge.net        |
-;;; |  (do not forget the "-request" part or you'll look silly in front of  |
-;;; |  lots of people who have the ability to remember it indefinitely...)  |
+;;; |         bbdb-user@nongnu.org                                          |
+;;; |  To join, go to https://lists.nongnu.org/mailman/listinfo/bbdb-user   |
 ;;; |                                                                       |
 ;;; |  When joining this list or reporting bugs, please mention which       |
 ;;; |  version of BBDB you have.                                            |
 ;;;  -----------------------------------------------------------------------
 
+;;; Code:
+
 (require 'timezone)
 (require 'bbdb-site)
 
@@ -46,6 +46,7 @@
   (autoload 'bbdb-dwim-mail "bbdb-com")
   (autoload 'bbdb-layout-prefix "bbdb-com")
   (autoload 'bbdb-completing-read-records "bbdb-com")
+  (autoload 'bbdb-merge-records "bbdb-com")
   (autoload 'mail-position-on-field "sendmail")
   (autoload 'vm-select-folder-buffer "vm-folder")
 
@@ -110,10 +111,10 @@
   "BBDB Customizations for phone number dialing"
   :group 'bbdb)
 
-(defgroup bbdb-utilities-print nil
-  "Customizations for printing the BBDB."
+(defgroup bbdb-utilities-tex nil
+  "Customizations for TeXing BBDB."
   :group 'bbdb)
-(put 'bbdb-utilities-print 'custom-loads '(bbdb-print))
+(put 'bbdb-utilities-tex 'custom-loads '(bbdb-tex))
 
 (defgroup bbdb-utilities-anniv nil
   "Customizations for BBDB Anniversaries"
@@ -187,7 +188,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.
@@ -206,42 +207,34 @@ If this file is newer than `bbdb-file',
   :group 'bbdb
   :type 'hook)
 
-;; The default element of `bbdb-create-hook' is `bbdb-creation-date'.
-;; The default element of `bbdb-change-hook' is `bbdb-timestamp'.
-;; -- We have a problem here:
-;; Usually, hook variables are not set, but functions are added
-;; by calling `add-hook' and removed by calling `remove-hook'.
-;; If the user calls `add-hook' in the init file (usually before loading
-;; the package that defines the hook variable), this also initializes
-;; the respective hook variable.  Yet this collides with a non-nil
-;; default value of a hook variable because a non-nil INITVALUE for `defvar'
-;; or `defcustom' has no effect if a variable is already bound.
-;; Therefore, the following code calls `add-hook' unconditionally.
-;; Yet this is not a perfect solution either for two reasons.
-;; First, `defcustom' gets confused if the default is set outside `defcustom'.
-;; So we use `defvar', though these are really user variables.
-;; Second, if the user wants to remove the default functions from the
-;; respective hooks, the current solution requires that he or she calls
-;; `remove-hook' *after* loading bbdb.el.  However, it is more likely that
-;; users call `add-hook' on these variables in their init files than calling
-;; `remove-hook'.  In that sense, the following should work for most people.
-;; Nonetheless, suggestions for better solutions are appreciated!
-(defvar bbdb-create-hook nil
+(defcustom bbdb-create-hook nil
   "*Hook run each time a new BBDB record is created.
 Run with one argument, the new record.  This is called before the record is
 added to the database, followed by a call of `bbdb-change-hook'.
 
 If a record has been created by analyzing a mail message, hook functions
 can use the variable `bbdb-update-records-address' to determine the header
-and class of the mail address according to `bbdb-message-headers'.")
-(add-hook 'bbdb-create-hook 'bbdb-creation-date)
+and class of the mail address according to `bbdb-message-headers'."
+  :group 'bbdb
+  :type 'hook)
 
-(defvar bbdb-change-hook nil
+(defcustom bbdb-change-hook nil
   "*Hook run each time a BBDB record is changed.
 Run with one argument, the record.  This is called before the database
 is modified.  If a new bbdb record is created, `bbdb-create-hook' is called
-first, followed by a call of this hook.")
-(add-hook 'bbdb-change-hook 'bbdb-timestamp)
+first, followed by a call of this hook."
+  :group 'bbdb
+  :type 'hook)
+
+(defcustom bbdb-merge-records-function nil
+  "If non-nil, a function for merging two records.
+This function is called when loading a record into BBDB that has the same uuid
+as an exisiting record.  If nil use `bbdb-merge-records'.
+This function should take two arguments RECORD1 and RECORD2, with RECORD2
+being the already existing record.  It should merge RECORD1 into RECORD2,
+and return RECORD2."
+  :group 'bbdb
+  :type 'function)
 
 (defcustom bbdb-time-stamp-format "%Y-%m-%d %T %z"
   "The BBDB time stamp format.  See `format-time-string'.
@@ -308,19 +301,19 @@ 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
   '((one-line           (order     . (phone mail-alias mail notes))
                         (name-end  . 24)
                         (toggle    . t))
-    (multi-line         (omit      . (creation-date timestamp
-                                                    name-format name-face))
+    (multi-line         (omit      . (uuid creation-date timestamp
+                                           name-format name-face))
                         (toggle    . t)
                         (indentation . 21))
-    (pop-up-multi-line  (omit      . (creation-date timestamp
-                                                    name-format name-face))
+    (pop-up-multi-line  (omit      . (uuid creation-date timestamp
+                                           name-format name-face))
                         (indentation . 21))
     (full-multi-line    (indentation . 21)))
   "Alist describing each display layout.
@@ -505,7 +498,7 @@ Each formatting element may contain one
 A formatting element will be applied only if the corresponding part
 of the address is a non-empty string.
 
-See also `bbdb-print-address-format-list'."
+See also `bbdb-tex-address-format-list'."
   :group 'bbdb-record-display
   :type '(repeat (list (choice (const :tag "Default" t)
                                (function :tag "Function")
@@ -528,18 +521,23 @@ and SE-132 54."
 
 (defcustom bbdb-default-separator '("[,;]" ", ")
   "The default field separator.  It is a list (SPLIT-RE JOIN).
-This is used for fields which do not have an entry in `bbdb-separator-alist'."
+This is used for fields which do not have an entry in `bbdb-separator-alist'.
+Whitespace surrounding SPLIT-RE is ignored."
   :group 'bbdb-record-display
   :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")
-    (notes "\n" "\n"))
+    (notes "\n" "\n") (tex-name "#" " # "))
   "Alist of field separators.
 Each element is of the form (FIELD SPLIT-RE JOIN).
+Whitespace surrounding SPLIT-RE is ignored.
 For fields lacking an entry here `bbdb-default-separator' is used instead."
   :group 'bbdb-record-display
   :type '(repeat (list symbol regexp string)))
@@ -650,7 +648,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 +928,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 +945,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 +1112,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 +1126,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 +1133,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 +1262,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 +1280,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 +1291,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,25 +1315,26 @@ 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
 (defcustom bbdb-xfields-sort-order
   '((notes . 0) (url . 1) (ftp . 2) (gopher . 3) (telnet . 4) (mail-alias . 5)
-    (mail-folder . 6) (lpr . 7) (creation-date . 1000) (timestamp . 1001))
+    (mail-folder . 6) (lpr . 7))
   "The order for sorting the xfields.
 If an xfield is not in the alist, it is assigned weight 100, so all xfields
 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
-  '((creation-date . bbdb-merge-string-least)
-    (timestamp . bbdb-merge-string-most))
-  "An alist defining specific merging function for xfields.
+(defcustom bbdb-merge-xfield-function-alist nil
+  "Alist defining merging functions for particular xfields.
 Each element is of the form (LABEL . MERGE-FUN).
 For merging xfield LABEL, this will use MERGE-FUN."
   :group 'bbdb-mua
@@ -1366,7 +1357,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 +1471,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 +1491,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)
@@ -1623,7 +1614,7 @@ If none of these schemes succeeds, the f
     "Enable debugging if non-nil during compile time.
 You really should not disable debugging.  But it will speed things up."))
 
-(defconst bbdb-file-format 7
+(defconst bbdb-file-format 9
   "BBDB file format.")
 
 (defconst bbdb-record-type
@@ -1637,9 +1628,12 @@ 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
+           (cons symbol string) ; uuid
+           (cons symbol string) ; creation-date
+           (cons symbol string) ; timestamp
            sexp) ; cache
-  "Pseudo-code for the structure of a record.  Used by `bbdb-record-type'.")
+  "Pseudo-code for the structure of a record.  Used by `bbdb-check-type'.")
 
 (defconst bbdb-file-coding-system 'utf-8
   "Coding system used for reading and writing `bbdb-file'.")
@@ -1647,9 +1641,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 +1649,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 +1665,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 +1675,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 +1711,12 @@ 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-uuid-table (make-hash-table :test 'equal)
+  "Hash table for uuid's of BBDB records.")
 
 (defvar bbdb-xfield-label-list nil
   "List of labels for xfields.")
@@ -1745,12 +1739,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,9 +1785,10 @@ 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 "\C-c\C-t"   'bbdb-tex)
     (define-key km "="          'delete-other-windows)
 
     ;; Search keys
@@ -1867,8 +1869,9 @@ 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])
+     ["TeX records" bbdb-tex t])
     ("Manipulate database"
      ["Prefix: do all records" bbdb-do-all-records t]
      "--"
@@ -1912,16 +1915,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."
@@ -1939,10 +1944,13 @@ Almost the inverse function of `bbdb-con
   (if (symbolp separator)
       (setq separator (car (or (cdr (assq separator bbdb-separator-alist))
                                bbdb-default-separator))))
-  (unless (string-match separator " \t\n")
-    (setq separator (concat "[ \t\n]*" separator "[ \t\n]*")))
-  ;; `split-string' applied to an empty STRING gives nil.
-  (split-string (bbdb-string-trim string) separator t))
+  (if (<= 24.4 (string-to-number emacs-version))
+      ;; `split-string' applied to an empty STRING gives nil.
+      (split-string string separator t
+                    (unless (string-match separator " \t\n") "[ \t\n]*"))
+    (unless (string-match separator " \t\n")
+      (setq separator (concat "[ \t\n]*" separator "[ \t\n]*")))
+    (split-string (bbdb-string-trim string) separator t)))
 
 (defun bbdb-concat (separator &rest strings)
   "Concatenate STRINGS to a string sticking in SEPARATOR.
@@ -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 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 (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 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,19 +2064,61 @@ You really should not disable debugging.
       `(let ((debug-on-error t))
          ,@body)))
 
-(defun bbdb-timestamp (record)
-  "For use as an element of `bbdb-change-hook'.
-Maintains an xfield `timestamp' for RECORD which contains
-the time when it was last modified.  If such a field already exists,
-it is changed, otherwise it is added."
-  (bbdb-record-set-xfield record 'timestamp
-                          (format-time-string bbdb-time-stamp-format nil t)))
-
-(defun bbdb-creation-date (record)
-  "For use as an element of `bbdb-create-hook'.
-Adds an xfield `creation-date' for RECORD which is the current time string."
-  (bbdb-record-set-xfield record 'creation-date
-                          (format-time-string bbdb-time-stamp-format nil t)))
+;; 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)
+  ""
+  (unless (get 'bbdb-timestamp 'bbdb-obsolete)
+    (put 'bbdb-timestamp 'bbdb-obsolete t)
+    (message "Function `bbdb-timestamp' is obsolete.  Remove it from any hooks.")
+    (sit-for 2)))
+(make-obsolete 'bbdb-timestamp nil "2017-08-09")
+
+(defun bbdb-creation-date (_record)
+  ""
+  (unless (get 'bbdb-creation-date 'bbdb-obsolete)
+    (put 'bbdb-creation-date 'bbdb-obsolete t)
+    (message "Function `bbdb-creation-date' is obsolete.  Remove it from any hooks.")
+    (sit-for 2)))
+(make-obsolete 'bbdb-creation-date nil "2017-08-09")
+
+;; Copied from org-id.el
+(defun bbdb-uuid ()
+  "Return string with random (version 4) UUID."
+  (let ((rnd (md5 (format "%s%s%s%s%s%s%s"
+			  (random)
+			  (current-time)
+			  (user-uid)
+			  (emacs-pid)
+			  (user-full-name)
+			  user-mail-address
+			  (recent-keys)))))
+    (format "%s-%s-4%s-%s%s-%s"
+	    (substring rnd 0 8)
+	    (substring rnd 8 12)
+	    (substring rnd 13 16)
+	    (format "%x"
+		    (logior
+		     #b10000000
+		     (logand
+		      #b10111111
+		      (string-to-number
+		       (substring rnd 16 18) 16))))
+	    (substring rnd 18 20)
+	    (substring rnd 20 32))))
 
 (defun bbdb-multiple-buffers-default ()
   "Default function for guessing a name for new *BBDB* buffers.
@@ -2290,7 +2363,8 @@ internals."
 
 ;; Define RECORD:
 (bbdb-defstruct record
-  firstname lastname affix aka organization phone address mail xfields cache)
+  firstname lastname affix aka organization phone address mail xfields
+  uuid creation-date timestamp cache)
 
 ;; Define PHONE:
 (bbdb-defstruct phone
@@ -2335,6 +2409,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 +2418,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 +2430,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 +2470,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'.
@@ -2410,7 +2488,8 @@ Do not call this for existing records th
     (bbdb-puthash organization record))
   (dolist (aka (bbdb-record-aka record))
     (bbdb-puthash aka record))
-  (bbdb-puthash-mail record))
+  (bbdb-puthash-mail record)
+  (puthash (bbdb-record-uuid record) record bbdb-uuid-table))
 
 (defun bbdb-puthash-mail (record)
   "For RECORD put mail into `bbdb-hashtable'."
@@ -2450,6 +2529,7 @@ may correspond to RECORD without raising
 
 (defun bbdb-record-name (record)
   "Record cache function: Return the full name FIRST_LAST of RECORD.
+Return empty string if both the first and last name are nil.
 If the name is not available in the name cache, the name cache value
 is generated and stored."
   (or (bbdb-cache-fl-name (bbdb-record-cache record))
@@ -2468,8 +2548,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 +2556,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 +2574,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 +2600,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 +2636,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)))))
@@ -2674,6 +2759,9 @@ FIELD may take the following values
  mail-canon    Return the list of canonical mail addresses.
  phone         Return the list of phone numbers
  address       Return the list of addresses
+ uuid          Return the uuid of RECORD
+ creation-date Return the creation-date
+ timestamp     Return the timestamp
  xfields       Return the list of all xfields
 
 Any other symbol is interpreted as the label for an xfield.
@@ -2694,6 +2782,9 @@ See also `bbdb-record-set-field'."
                                       (bbdb-record-mail-aka record)))
         ((eq field 'phone)    (bbdb-record-phone record))
         ((eq field 'address)  (bbdb-record-address record))
+        ((eq field 'uuid)     (bbdb-record-uuid record))
+        ((eq field 'creation-date) (bbdb-record-creation-date record))
+        ((eq field 'timestamp) (bbdb-record-timestamp record))
         ;; Return all xfields
         ((eq field 'xfields)  (bbdb-record-xfields record))
         ;; Return xfield FIELD (e.g., `notes') or nil if FIELD is not defined.
@@ -2719,6 +2810,9 @@ FIELD may take the following values
  mail          VALUE is the list of email addresses
  phone         VALUE is the list of phone numbers
  address       VALUE is the list of addresses
+ uuid          VALUE is the uuid of RECORD
+ creation-date VALUE is the creation-date
+ timestamp     VALUE is the timestamp
  xfields       VALUE is the list of all xfields
 
 Any other symbol is interpreted as the label for an xfield.
@@ -2768,7 +2862,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 +2903,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,37 +2912,64 @@ 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))
 
+          ;; uuid
+          ((eq field 'uuid)
+           ;; MERGE not meaningful
+           (if check (bbdb-check-type value (bbdb-record-uuid record-type) t))
+           (let ((old-uuid (bbdb-record-uuid record)))
+             (unless (string= old-uuid value)
+               (remhash old-uuid bbdb-uuid-table)
+               (bbdb-record-set-uuid record value)
+               (puthash value record bbdb-uuid-table))))
+
+          ;; creation-date
+          ((eq field 'creation-date)
+           ;; MERGE not meaningful
+           (if check (bbdb-check-type value (bbdb-record-creation-date record-type) t))
+           (bbdb-record-set-creation-date record value))
+
+          ;; timestamp
+          ((eq field 'timestamp)
+           ;; MERGE not meaningful
+           (if check (bbdb-check-type value (bbdb-record-timestamp record-type) t))
+           (bbdb-record-set-timestamp record value))
+
           ;; all xfields
           ((eq field 'xfields)
-           (let (xfield new-xfields)
-             (if merge
-                 (dolist (ov (bbdb-record-xfields record))
-                   (if (setq xfield (assq (car ov) value))
-                       (setcdr xfield (bbdb-merge-xfield (car ov) (cdr xfield) (cdr ov)))
-                     (setq value (append value (list ov))))))
-             (if check (bbdb-check-type new-xfields (bbdb-record-xfields record-type) t))
-             (dolist (xfield (nreverse value))
+           (if merge
+               (let ((xfields (bbdb-record-xfields record))
+                     xfield)
+                 (dolist (nv value)
+                   (if (setq xfield (assq (car nv) xfields))
+                       (setcdr xfield (bbdb-merge-xfield
+                                       (car nv) (cdr xfield) (cdr nv)))
+                     (setq xfields (append xfields (list nv)))))
+                 (setq value xfields)))
+           (if check (bbdb-check-type value (bbdb-record-xfields record-type) t))
+           (let (new-xfields)
+             (dolist (xfield 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-record-set-xfields record new-xfields)))
+                 (bbdb-pushnewq (car xfield) bbdb-xfield-label-list)))
+             (bbdb-record-set-xfields record (nreverse new-xfields))))
 
           ;; Single xfield
           ((symbolp 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 +2986,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 +3021,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 +3061,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)
@@ -3018,7 +3140,7 @@ copy it to `bbdb-file'."
 
   ;; Make sure `bbdb-buffer' is not out of sync with disk.
   (with-current-buffer bbdb-buffer
-    (cond ((verify-visited-file-modtime bbdb-buffer)) ; arg for Emacs 23
+    (cond ((verify-visited-file-modtime))
           ((bbdb-revert-buffer))
           ;; This is the case where `bbdb-file' has changed; the buffer
           ;; has changed as well; and the user has answered "no" to the
@@ -3052,7 +3174,8 @@ 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)
+      (clrhash bbdb-uuid-table)
 
       (if (/= (point-min) (point-max))
           (bbdb-parse-records) ; normal case: nonempty db
@@ -3135,7 +3258,7 @@ Return nil otherwise."
              (set-buffer-modified-p nil)
              (bbdb-undisplay-records t)))
           ;; If nothing has changed do nothing, return t.
-          ((and (verify-visited-file-modtime bbdb-buffer) ; arg for Emacs 23
+          ((and (verify-visited-file-modtime)
                 (not (buffer-modified-p))))
           ((or (and (not (verify-visited-file-modtime bbdb-buffer))
                     ;; File changed on disk
@@ -3170,136 +3293,159 @@ Return nil otherwise."
 
 (defun bbdb-parse-records ()
   "Parse BBDB records and initialize various internal variables.
-If `bbdb-file' uses an outdated format, it is migrated to `bbdb-file-format'."
-  (unless bbdb-silent (message "Parsing BBDB..."))
+If `bbdb-file' uses an outdated format, migrate to `bbdb-file-format'."
   (save-excursion
     (save-restriction
       (widen)
       (bbdb-goto-first-record)
-      ;; look backwards for file-format, and convert if necessary.
-      (let ((file-format (save-excursion
-                           (if (re-search-backward
-                                "^;+[ \t]*file-\\(format\\|version\\):[ \t]*\\([0-9]+\\)[ \t]*$" nil t)
-                               (string-to-number (match-string 2)))))
-            migrate records)
-        (unless file-format ; current file-format, but no file-format: line.
-          (error "BBDB corrupted: no file-format line"))
+      (let* ((file (abbreviate-file-name buffer-file-name))
+             (file-format (save-excursion
+                            (if (re-search-backward
+                                 "^;+[ \t]*file-\\(format\\|version\\):[ \t]*\\([0-9]+\\)[ \t]*$" nil t)
+                                (string-to-number (match-string 2))
+                              ;; No file-format line.
+                              (error "BBDB corrupted: no file-format line"))))
+             (migrate (< file-format bbdb-file-format))
+             records)
         (if (> file-format bbdb-file-format)
             (error "BBDB version %s understands file format %s but not %s."
-                   bbdb-version bbdb-file-format file-format)
-          (setq migrate (< file-format bbdb-file-format)))
-
-        (or (eobp) (looking-at "\\[")
-            (error "BBDB corrupted: no following bracket"))
-
-        ;; narrow the buffer to skip over the rubbish before the first record.
-        (narrow-to-region (point) (point-max))
-        (let ((modp (buffer-modified-p))
-              ;; Make sure those parens get cleaned up.
-              ;; This code had better stay simple!
-              (inhibit-quit t)
-              (buffer-undo-list t)
-              buffer-read-only)
-          (goto-char (point-min)) (insert "(\n")
-          (goto-char (point-max)) (insert "\n)")
-          (goto-char (point-min))
-          (unwind-protect
-              (setq records (read (current-buffer)))
-            (goto-char (point-min)) (delete-char 2)
-            (goto-char (point-max)) (delete-char -2)
-            (set-buffer-modified-p modp)))
-        (widen)
-
-        ;; Migrate if `bbdb-file' is outdated.
-        (if migrate (setq records (bbdb-migrate records file-format)))
-
-        ;; We could first set `bbdb-phone-label-list' and
-        ;; `bbdb-address-label-list' to their customized values.  Bother?
-        (setq bbdb-records records
-              bbdb-xfield-label-list nil
-              bbdb-organization-list nil
-              bbdb-street-list nil
-              bbdb-city-list nil
-              bbdb-state-list nil
-              bbdb-postcode-list nil
-              bbdb-country-list nil)
-
-        (bbdb-goto-first-record)
-        (dolist (record records)
-          ;; We assume that the markers for each record need to go at each
-          ;; newline.  If this is not the case, things can go *very* wrong.
-          (bbdb-debug
-            (unless (looking-at "\\[")
-              (error "BBDB corrupted: junk between records at %s" (point))))
-
-          (bbdb-cache-set-marker
-           (bbdb-record-set-cache record (make-vector bbdb-cache-length nil))
-           (point-marker))
-          (forward-line 1)
-
-          ;; Set the completion lists
-          (dolist (phone (bbdb-record-phone record))
-            (add-to-list 'bbdb-phone-label-list (bbdb-phone-label phone) nil 'eq))
-          (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-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)))
-          (dolist (xfield (bbdb-record-xfields record))
-            (add-to-list 'bbdb-xfield-label-list (car xfield) nil 'eq))
-          (dolist (organization (bbdb-record-organization record))
-            (add-to-list 'bbdb-organization-list organization))
-
-          (let ((name (bbdb-concat 'name-first-last
-                                   (bbdb-record-firstname record)
-                                   (bbdb-record-lastname record))))
-            (when (and (not bbdb-allow-duplicates)
-                       (bbdb-gethash name '(fl-name aka)))
-              ;; This does not check for duplicate mail fields.
-              ;; Yet under normal circumstances, this should really
-              ;; not be necessary each time BBDB is loaded as BBDB checks
-              ;; whether creating a new record or modifying an existing one
-              ;; results in duplicates.
-              ;; Alternatively, you can use `bbdb-search-duplicates'.
-              (message "Duplicate BBDB record encountered: %s" name)
-              (sit-for 1)))
-
-          ;; We hash every record even if it is a duplicate and
-          ;; `bbdb-allow-duplicates' is nil.  Otherwise, an unhashed
-          ;; record would not be available for things like completion
-          ;; (and we would not know which record to keeep and which one
-          ;; to hide).  We trust the user she knows what she wants
-          ;; if she keeps duplicate records in the database though
-          ;; `bbdb-allow-duplicates' is nil.
-          (bbdb-hash-record record))
-
-        ;; Note that `bbdb-xfield-label-list' serves two purposes:
-        ;;  - check whether an xfield is new to BBDB
-        ;;  - list of known xfields for minibuffer completion
-        ;; Only in the latter case, we might want to exclude
-        ;; those xfields that are handled automatically.
-        ;; So the following is not a satisfactory solution.
-
-        ;; (dolist (label (bbdb-layout-get-option 'multi-line 'omit))
-        ;;   (setq bbdb-xfield-label-list (delq label bbdb-xfield-label-list)))
-
-        ;; `bbdb-end-marker' allows to put comments at the end of `bbdb-file'
-        ;; that are ignored.
-        (setq bbdb-end-marker (point-marker))
+                   bbdb-version bbdb-file-format file-format))
 
-        (when migrate
-          (dolist (record bbdb-records)
-            (bbdb-overwrite-record-internal record))
-          ;; update file format
-          (goto-char (point-min))
-          (if (re-search-forward (format "^;;; file-\\(version\\|format\\): %d$"
-                                         file-format) nil t)
-              (replace-match (format ";;; file-format: %d" bbdb-file-format)))))))
+        (if (and migrate
+                 (not (yes-or-no-p
+                       (format (concat "Migrate `%s' to BBDB file format %s "
+                                       "(back-up recommended)? ")
+                               file bbdb-file-format))))
+            (progn
+              (message "Abort loading %s" file)
+              (sleep-for 2)
+              (setq bbdb-records nil
+                    ;; Avoid unexpected surprises
+                    buffer-read-only t)
+              'abort)
+
+          (or (eobp) (looking-at "\\[")
+              (error "BBDB corrupted: no following bracket"))
+
+          (unless bbdb-silent (message "Parsing BBDB file `%s'..." file))
+
+          ;; narrow the buffer to skip over the rubbish before the first record.
+          (narrow-to-region (point) (point-max))
+          (let ((modp (buffer-modified-p))
+                ;; Make sure those parens get cleaned up.
+                ;; This code had better stay simple!
+                (inhibit-quit t)
+                (buffer-undo-list t)
+                buffer-read-only)
+            (goto-char (point-min)) (insert "(\n")
+            (goto-char (point-max)) (insert "\n)")
+            (goto-char (point-min))
+            (unwind-protect
+                (setq records (read (current-buffer)))
+              (goto-char (point-min)) (delete-char 2)
+              (goto-char (point-max)) (delete-char -2)
+              (set-buffer-modified-p modp)))
+          (widen)
+
+          ;; Migrate if `bbdb-file' is outdated.
+          (if migrate (setq records (bbdb-migrate records file-format)))
+
+          ;; We could first set `bbdb-phone-label-list' and
+          ;; `bbdb-address-label-list' to their customized values.  Bother?
+          (setq bbdb-records records
+                bbdb-xfield-label-list nil
+                bbdb-organization-list nil
+                bbdb-street-list nil
+                bbdb-city-list nil
+                bbdb-state-list nil
+                bbdb-postcode-list nil
+                bbdb-country-list nil)
+
+          (bbdb-goto-first-record)
+          (dolist (record records)
+            ;; We assume that the markers for each record need to go at each
+            ;; newline.  If this is not the case, things can go *very* wrong.
+            (bbdb-debug
+              (unless (looking-at "\\[")
+                (error "BBDB corrupted: junk between records at %s" (point))))
+
+            (bbdb-cache-set-marker
+             (bbdb-record-set-cache record (make-vector bbdb-cache-length nil))
+             (point-marker))
+            (forward-line 1)
+
+            ;; Every record must have a unique uuid in `bbdb-uuid-table'.
+            (if (gethash (bbdb-record-uuid record) bbdb-uuid-table)
+                ;; Is there a more useful action than throwing an error?
+                ;; We are just loading BBDB, so we are not yet ready
+                ;; for sophisticated solutions.
+                (error "Duplicate UUID %s" (bbdb-record-uuid record)))
+
+            ;; Set the completion lists
+            (dolist (phone (bbdb-record-phone record))
+              (bbdb-pushnew (bbdb-phone-label phone) bbdb-phone-label-list))
+            (dolist (address (bbdb-record-address record))
+              (bbdb-pushnew (bbdb-address-label address) bbdb-address-label-list)
+              (mapc (lambda (street) (bbdb-pushnewt street bbdb-street-list))
+                    (bbdb-address-streets 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))
+              (bbdb-pushnewq (car xfield) bbdb-xfield-label-list))
+            (dolist (organization (bbdb-record-organization record))
+              (bbdb-pushnew organization bbdb-organization-list))
+
+            (let ((name (bbdb-concat 'name-first-last
+                                     (bbdb-record-firstname record)
+                                     (bbdb-record-lastname record))))
+              (when (and (not bbdb-allow-duplicates)
+                         (bbdb-gethash name '(fl-name aka)))
+                ;; This does not check for duplicate mail fields.
+                ;; Yet under normal circumstances, this should really
+                ;; not be necessary each time BBDB is loaded as BBDB checks
+                ;; whether creating a new record or modifying an existing one
+                ;; results in duplicates.
+                ;; Alternatively, you can use `bbdb-search-duplicates'.
+                (message "Duplicate BBDB record encountered: %s" name)
+                (sit-for 1)))
+
+            ;; If `bbdb-allow-duplicates' is non-nil, we allow that two records
+            ;; (with different uuids) refer to the same person (same name etc.).
+            ;; Such duplicate records are always hashed.
+            ;; Otherwise, an unhashed record would not be available for things
+            ;; like completion (and we would not know which record to keeep
+            ;; and which one to hide).  We trust the user she knows what
+            ;; she wants if she keeps duplicate records in the database though
+            ;; `bbdb-allow-duplicates' is nil.
+            (bbdb-hash-record record))
+
+          ;; Note that `bbdb-xfield-label-list' serves two purposes:
+          ;;  - check whether an xfield is new to BBDB
+          ;;  - list of known xfields for minibuffer completion
+          ;; Only in the latter case, we might want to exclude
+          ;; those xfields that are handled automatically.
+          ;; So the following is not a satisfactory solution.
+
+          ;; (dolist (label (bbdb-layout-get-option 'multi-line 'omit))
+          ;;   (setq bbdb-xfield-label-list (delq label bbdb-xfield-label-list)))
+
+          ;; `bbdb-end-marker' allows to put comments at the end of `bbdb-file'
+          ;; that are ignored.
+          (setq bbdb-end-marker (point-marker))
+
+          (when migrate
+            (dolist (record bbdb-records)
+              (bbdb-overwrite-record-internal record))
+            ;; update file format
+            (goto-char (point-min))
+            (if (re-search-forward (format "^;;; file-\\(version\\|format\\): %d$"
+                                           file-format) nil t)
+                (replace-match (format ";;; file-format: %d" bbdb-file-format))))
 
-  (unless bbdb-silent (message "Parsing BBDB...done")))
+          (unless bbdb-silent (message "Parsing BBDB file `%s'...done" file))
+          bbdb-records)))))
 
 (defun bbdb-before-save ()
   "Run before saving `bbdb-file' as buffer-local part of `before-save-hook'."
@@ -3319,52 +3465,102 @@ 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.
-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."
+(defun bbdb-change-record (record &rest ignored)
+  "Update the database after a change of RECORD.
+Return RECORD if RECORD got changed compared with the database,
+return nil otherwise.
+Hash RECORD if it is new.  If RECORD is not new, it is the the caller's
+responsibility to update the hashtables for RECORD.  (Up-to-date hashtables are
+ensured if the fields are modified by calling `bbdb-record-set-field'.)
+Redisplay RECORD if it is not new.
+
+Args IGNORED are ignored and their use is discouraged.
+They are present only for backward compatibility."
+  (when (and ignored (get 'bbdb-change-record 'bbdb-outdated))
+    (put 'bbdb-change-record 'bbdb-outdated t)
+    (message "Outdated usage of `bbdb-change-record'")
+    (sit-for 2))
+
   (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)
+  ;; no longer refers to a record in `bbdb-records'.  RECORD will then
+  ;; be treated as new, when we try to merge it with the known record.
+  (let ((tail (memq record (bbdb-records))))
+    (if 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))))))
+          (bbdb-record-set-timestamp
+           record (format-time-string bbdb-time-stamp-format nil t))
+          (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 tables here.
+              ;; We assume they 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)
+
+      ;; Record is new and not yet in BBDB.
+      (unless (bbdb-record-cache record)
+        (bbdb-record-set-cache record (make-vector bbdb-cache-length nil)))
+      (unless (bbdb-record-uuid record)
+        (bbdb-record-set-uuid record (bbdb-uuid)))
+      (unless (bbdb-record-creation-date record)
+        (bbdb-record-set-creation-date
+         record (format-time-string bbdb-time-stamp-format nil t))
+        (run-hook-with-args 'bbdb-create-hook record))
+
+      (let ((old-record (gethash (bbdb-record-uuid record) bbdb-uuid-table)))
+        (if old-record
+            ;; RECORD is really OLD-RECORD.  Merge and return OLD-RECORD.
+            (if bbdb-merge-records-function
+                (funcall bbdb-merge-records-function record old-record)
+              (bbdb-merge-records record old-record))
+
+          ;; RECORD is really new.
+          (bbdb-record-set-timestamp
+           record (format-time-string bbdb-time-stamp-format nil t))
+          (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)))))
 
 (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
+    (barf-if-buffer-read-only)
     (let ((tail (memq record bbdb-records))
           (inhibit-quit t))
       (unless tail (error "BBDB record absent: %s" record))
@@ -3381,23 +3577,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 +3586,7 @@ 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)
+    (barf-if-buffer-read-only)
     ;; splice record into `bbdb-records'
     (bbdb-debug (if (memq record bbdb-records)
                     (error "BBDB record not unique: - %s" record)))
@@ -3449,6 +3627,7 @@ that calls the hooks, too."
 Do not call this function directly, call instead `bbdb-change-record'
 that calls the hooks, too."
   (bbdb-with-db-buffer
+    (barf-if-buffer-read-only)
     (let* ((tail (memq record bbdb-records))
            (_ (unless tail (error "BBDB record absent: %s" record)))
            (cache (bbdb-record-cache record))
@@ -3498,7 +3677,7 @@ that calls the hooks, too."
 This is done by comparing the postcode to `bbdb-continental-postcode-regexp'.
 
 This is a possible identifying function for
-`bbdb-address-format-list' and `bbdb-print-address-format-list'."
+`bbdb-address-format-list' and `bbdb-tex-address-format-list'."
   (string-match bbdb-continental-postcode-regexp
                 (bbdb-address-postcode address)))
 
@@ -3593,7 +3772,7 @@ If TERMINATOR is non-nil use it to termi
 If FACE is non-nil use it as FACE for inserted text.
 If INDENT and `bbdb-wrap-column' are integers, insert line breaks in between
 elements of LIST if otherwise inserted text exceeds `bbdb-wrap-column'."
-  ;; `truncate-lines' is fine for one-line layout.  But it is  annyoing
+  ;; `truncate-lines' is fine for one-line layout.  But it is annyoing
   ;; for records that are displayed with multi-line layout.
   ;; Non-nil `word-wrap' would be much nicer.  How can we switch between
   ;; non-nil `truncate-lines' and non-nil `word-wrap' on a per-record basis?
@@ -3717,15 +3896,34 @@ FIELD-LIST is the list of actually displ
              (let ((aka (bbdb-record-aka record)))
                (if aka
                    (bbdb-display-list aka 'aka "; "))))
+            ;; uuid
+            ((eq field 'uuid)
+             (let ((uuid (bbdb-record-uuid record)))
+               (bbdb-display-text (format "%s; " uuid) `(uuid ,uuid))))
+            ;; creation-date
+            ((eq field 'creation-date)
+             (let ((creation-date (bbdb-record-creation-date record)))
+               (bbdb-display-text (format "%s; " creation-date) `(creation-date ,creation-date))))
+            ;; timestamp
+            ((eq field 'timestamp)
+             (let ((timestamp (bbdb-record-timestamp record)))
+               (bbdb-display-text (format "%s; " timestamp) `(timestamp ,timestamp))))
             ;; 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 +3937,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))
@@ -3783,15 +3981,43 @@ FIELD-LIST is the list of actually displ
                  (bbdb-display-text (format fmt "AKA") '(aka nil field-label)
                                     'bbdb-field-name)
                  (bbdb-display-list aka 'aka "\n"))))
+            ;; uuid
+            ((eq field 'uuid)
+             (let ((uuid (bbdb-record-uuid record)))
+               (bbdb-display-text (format fmt "uuid") `(uuid ,uuid field-label)
+                                  'bbdb-field-name)
+               (bbdb-display-text (format "%s\n" uuid) `(uuid ,uuid))))
+            ;; creation-date
+            ((eq field 'creation-date)
+             (let ((creation-date (bbdb-record-creation-date record)))
+               (bbdb-display-text (format fmt "creation-date") `(creation-date ,creation-date field-label)
+                                  'bbdb-field-name)
+               (bbdb-display-text (format "%s\n" creation-date) `(creation-date ,creation-date))))
+            ;; timestamp
+            ((eq field 'timestamp)
+             (let ((timestamp (bbdb-record-timestamp record)))
+               (bbdb-display-text (format fmt "timestamp") `(timestamp ,timestamp field-label)
+                                  'bbdb-field-name)
+               (bbdb-display-text (format "%s\n" timestamp) `(timestamp ,timestamp))))
             ;; 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")))
 
@@ -3814,7 +4040,8 @@ Move point to the end of the inserted re
         (omit-list  (bbdb-layout-get-option layout 'omit)) ; omitted fields
         (order-list (bbdb-layout-get-option layout 'order)); requested field order
         (all-fields (append '(phone address mail aka) ; default field order
-                             (mapcar 'car (bbdb-record-xfields record))))
+                            (mapcar 'car (bbdb-record-xfields record))
+                            '(uuid creation-date timestamp)))
         (beg (point))
         format-function field-list)
     (when (or (not display-p)
@@ -3863,7 +4090,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 +4139,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 +4156,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 +4175,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 +4215,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
@@ -4141,10 +4379,9 @@ current record.
 \\[bbdb-do-all-records]\\[bbdb-mail]\t Compose mail \
 to everyone whose record is displayed.
 \\[bbdb-save]\t Save the BBDB file to disk.
-\\[bbdb-print]\t Create a TeX file containing a pretty-printed version \
-of all the\n\t records in the database.
-\\[bbdb-do-all-records]\\[bbdb-print]\t Do that for the \
-displayed records only.
+\\[bbdb-tex]\t Create a TeX listing of the current record.
+\\[bbdb-do-all-records]\\[bbdb-tex]\t Do that for all \
+displayed record.
 \\[other-window]\t Move to another window.
 \\[bbdb-info]\t Read the Info documentation for BBDB.
 \\[bbdb-help]\t Display a one line command summary in the echo area.
@@ -4152,7 +4389,7 @@ displayed records only.
 record.
 
 For address completion using the names and mail addresses in the database:
-\t in Sendmail mode, type \\<mail-mode-map>\\[bbdb-complete-mail].
+\t in Mail mode, type \\<mail-mode-map>\\[bbdb-complete-mail].
 \t in Message mode, type \\<message-mode-map>\\[bbdb-complete-mail].
 
 Important variables:
@@ -4193,7 +4430,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 +4647,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 +4664,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 +4680,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 +4714,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-2017 Roland Winkler <winkler@gnu.org>
 # 
 # This file is part of the Insidious Big Brother Database (aka BBDB),
 # 
@@ -43,33 +43,48 @@ 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 \
+SRCS =	bbdb.el bbdb-site.el bbdb-com.el bbdb-tex.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
-ELC =	bbdb.elc bbdb-site.elc bbdb-com.elc bbdb-print.elc bbdb-anniv.elc \
+ELC =	bbdb.elc bbdb-site.elc bbdb-com.elc bbdb-tex.elc bbdb-anniv.elc \
 	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)
+bbdb-tex.elc: bbdb-tex.el bbdb-com.elc
+	$(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-2017 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-2017 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-2017 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-2017 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-2017 Roland Winkler <winkler@gnu.org>
 # 
 # This file is part of the Insidious Big Brother Database (aka BBDB),
 # 
@@ -19,6 +19,4 @@
 # along with BBDB.  If not, see <http://www.gnu.org/licenses/>.
 
 dist_pkgdata_DATA = 				\
-	bbdb-cols.tex 				\
-	bbdb-print-brief.tex 			\
-	bbdb-print.tex
+	bbdb.sty
--- /dev/null
+++ bbdb3-3.1.2/tex/bbdb.sty
@@ -0,0 +1,89 @@
+% bbdb.sty --- basic LaTeX style for TeXing BBDB
+%
+% Copyright (C) 2017 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 defines a basic LaTeX style for TeXing BBDB.
+
+\def\bbdb@name#1#2{\textbf{#2, #1}}
+\def\bbdb@organization#1{#1}
+\def\bbdb@affix#1{\emph{affix:} #1}
+\def\bbdb@aka#1{\emph{aka:} #1}
+\def\bbdb@phone#1#2{\emph{#1:} #2}
+\def\bbdb@mail#1#2{\ifx\href\undefined
+    \texttt{#2}%
+  \else
+    \href{mailto:#1}{\texttt{#2}}%
+  \fi}
+\def\bbdb@address#1#2{\emph{#1:} #2}
+\def\bbdb@xfield#1#2{\emph{#1:} #2}
+
+% \def\bbdb@separator#1{\hline}
+\def\bbdb@separator#1{\\\hline
+\multicolumn{\LT@cols}{@{}c@{}}{\hrulefill\ #1\rule{0pt}{2.2ex}\ \hrulefill}\\}
+
+\RequirePackage{longtable}
+\newenvironment{bbdb}[1]{%
+\let\name\bbdb@name
+\let\organization\bbdb@organization
+\let\affix\bbdb@affix
+\let\aka\bbdb@aka
+\let\phone\bbdb@phone
+\let\mail\bbdb@mail
+\let\address\bbdb@address
+\let\xfield\bbdb@xfield
+\let\bbdbseparator\bbdb@separator
+\begin{longtable}[l]{@{}#1@{}}}%
+{\\ \hline \multicolumn{\LT@cols}{c}{Printed \today}\\ \hline\end{longtable}}
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+\def\bbdbrecord@name#1#2{{\raggedright\textbf{#2, #1}\dotfill\par}}
+\def\bbdbrecord@organization#1{#1\par}
+\def\bbdbrecord@affix#1{\bbdbrecord@par{\emph{affix:} #1}}
+\def\bbdbrecord@aka#1{\bbdbrecord@par{\emph{aka:} #1}}
+\def\bbdbrecord@phone#1#2{\hspace*{\fill}\emph{#1:} #2\par}
+\def\bbdbrecord@mail#1#2{\ifx\href\undefined
+    \texttt{#2}%
+  \else
+    \href{mailto:#1}{\texttt{#2}}%
+  \fi\par}
+\def\bbdbrecord@par#1{{\leftskip 1em\parindent -\leftskip#1\par}}
+\def\bbdbrecord@address#1#2{\bbdbrecord@par{\emph{#1:} #2}}
+\def\bbdbrecord@xfield#1#2{\bbdbrecord@par{\emph{#1:} #2}}
+
+\newenvironment{bbdbrecord}{%
+\smallbreak
+\parskip 0pt
+\parindent 0pt
+\let\name\bbdbrecord@name
+\let\organization\bbdbrecord@organization
+\let\affix\bbdbrecord@affix
+\let\aka\bbdbrecord@aka
+\let\phone\bbdbrecord@phone
+\let\mail\bbdbrecord@mail
+\let\address\bbdbrecord@address
+\let\xfield\bbdbrecord@xfield}{\medbreak}
+
+\newcommand*{\bbdbseparator}[1]{\vspace{3ex}\noindent
+  \fbox{\parbox{\dimexpr\linewidth-2\fboxrule-2\fboxsep}%
+               {\centering\textbf{#1}}}%
+  \vspace{1ex}}
+
+% \endinput % Fails when inlining this file.
