1 ;;; bbdb-csv-import.el --- import csv to bbdb version 3+
3 ;; Copyright (C) 2014 by Ian Kelling
5 ;; Maintainer: Ian Kelling <ian@iankelling.org>
6 ;; Author: Ian Kelling <ian@iankelling.org>
9 ;; Package-Requires: ((pcsv "1.3.3") (dash "2.5.0") (bbdb "20140412.1949"))
10 ;; Keywords: csv, util, bbdb
11 ;; Homepage: https://gitlab.com/iankelling/bbdb-csv-import
13 ;; This program is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
28 ;; Importer of csv (comma separated value) text into Emacs’s bbdb database,
29 ;; version 3+. Works out of the box with csv exported from Thunderbird, Gmail,
30 ;; Linkedin, Outlook.com/hotmail, and probably others.
31 ;; Easily extensible to handle new formats.
35 ;; If you installed this file with a package manager, just
37 ;; (require 'bbdb-csv-import)
39 ;; Else, note the min versions of dependencies above in "Package-Requires:",
40 ;; and load this file. The exact minimum bbdb version is unknown, something 3+.
44 ;; Back up bbdb by copying `bbdb-file' in case things go wrong.
46 ;; Simply M-x `bbdb-csv-import-buffer' or `bbdb-csv-import-file'.
47 ;; When called interactively, they prompt for file or buffer arguments.
49 ;; Then view your bbdb records: M-x bbdb .* RET
50 ;; If the import looks good save the bbdb database: C-x s (bbdb-save)
52 ;;; Advanced usage / notes:
54 ;; Tested to work with thunderbird, gmail, linkedin,
55 ;; outlook.com/hotmail.com. For those programs, if it's exporter has an option
56 ;; of what kind of csv format, choose it's own native format if available, if
57 ;; not, choose an outlook compatible format. If you're exporting from some other
58 ;; program and its csv exporter claims outlook compatibility, there is a good
59 ;; chance it will work out of the box. If it doesn't, you can try to fix it as
60 ;; described below, or the maintainer will be happy to help, just anonymize your
61 ;; csv data using the M-x bbdb-csv-anonymize-current-buffer (make sure csv
62 ;; buffer is the current one) and attach it to an email.
64 ;; Duplicate contacts (according to email address) are skipped if
65 ;; bbdb-allow-duplicates is nil (default). Any duplicates found are echoed at
66 ;; the end of the import.
68 ;;; Custom mapping of csv fields
70 ;; If a field is handled wrong or you want to extend the program to handle a new
71 ;; kind of csv format, you need to setup a custom field mapping variable. Use
72 ;; the existing tables as an example. By default, we use a combination of most
73 ;; predefined mappings, and look for all of their fields, but it is probably
74 ;; best to avoid that kind of table when setting up your own as it is an
75 ;; unnecessary complexity in that case. If you have a problem with data from a
76 ;; supported export program, start by testing its specific mapping table instead
77 ;; of the combined one. Here is a handy template to set each of the predefined
78 ;; mapping tables if you would rather avoid the configure interface:
80 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-combined)
81 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-thunderbird)
82 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-gmail)
83 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-gmail-typed-email)
84 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-linkedin)
85 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-outlook-web)
86 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-outlook-typed-email)
88 ;; The doc string for `bbdb-create-internal' may also be useful when creating a
89 ;; mapping table. Please send any new tables to the maintainer listed in this
90 ;; file. The maintainer should be able to help with any issues and may create a
91 ;; new mapping table given sample data.
93 ;; Mapping table tips: For field names or sets of field names which go together,
94 ;; and are numbered, 1, 2, 3, the repeat keyword can be used to expand as many
95 ;; as are in your csv data.
97 ;;; Misc tips/troubleshooting:
99 ;; - ASynK looks promising for syncing bbdb/google/outlook.
100 ;; - The git repo contains a test folder with exactly tested version info and working
101 ;; test data. Software, and especially online services are prone to changing how they
102 ;; export. Please send feedback if you run into problems.
103 ;; - bbdb doesn't work if you delete the bbdb database file in
104 ;; the middle of an emacs session. If you want to empty the current bbdb database,
105 ;; do M-x bbdb then .* then C-u * d on the beginning of a record.
106 ;; - After changing a mapping table variable, don't forget to re-execute
107 ;; (setq bbdb-csv-import-mapping-table ...) so that it propagates.
109 ;;; Bugs, patches, discussion, feedback
111 ;; Patches and bugs are very welcome via https://gitlab.com/iankelling/bbdb-csv-import
113 ;; Questions, feedback, or anything is very welcome at to the bbdb-csv-import mailing list
114 ;; https://lists.iankelling.org/listinfo/bbdb-csv-import, no subscription needed to post via
115 ;; bbdb-csv-import@lists.iankelling.org
123 (eval-when-compile (require 'cl))
126 (defconst bbdb-csv-import-thunderbird
127 '((:namelist "First Name" "Last Name")
128 (:name "Display Name")
130 (:mail "Primary Email" "Secondary Email")
131 (:phone "Work Phone" "Home Phone" "Fax Number" "Pager Number" "Mobile Number")
134 (("Home Address" "Home Address 2")
135 "Home City" "Home State"
136 "Home ZipCode" "Home Country"))
138 (("Work Address" "Work Address 2")
139 "Work City" "Work State"
140 "Work ZipCode" "Work Country"))))
141 (:organization "Organization")
142 (:xfields "Web Page 1" "Web Page 2" "Birth Year" "Birth Month"
143 "Birth Day" "Department" "Custom 1" "Custom 2" "Custom 3"
144 "Custom 4" "Notes" "Job Title"))
145 "Thunderbird csv format")
147 (defconst bbdb-csv-import-linkedin
148 '((:namelist "First Name" "Middle Name" "Last Name")
150 (:mail "E-mail Address" "E-mail 2 Address" "E-mail 3 Address")
152 "Assistant's Phone" "Business Fax" "Business Phone"
153 "Business Phone 2" "Callback" "Car Phone"
154 "Company Main Phone" "Home Fax" "Home Phone"
155 "Home Phone 2" "ISDN" "Mobile Phone"
156 "Other Fax" "Other Phone" "Pager"
157 "Primary Phone" "Radio Phone" "TTY/TDD Phone" "Telex")
160 (("Business Street" "Business Street 2" "Business Street 3")
161 "Business City" "Business State"
162 "Business Postal Code" "Business Country"))
164 (("Home Street" "Home Street 2" "Home Street 3")
165 "Home City" "Home State"
166 "Home Postal Code" "Home Country"))
168 (("Other Street" "Other Street 2" "Other Street 3")
169 "Other City" "Other State"
170 "Other Postal Code" "Other Country"))))
171 (:organization "Company")
173 "Department" "Job Title" "Assistant's Name"
174 "Birthday" "Manager's Name" "Notes" "Other Address PO Box"
175 "Spouse" "Web Page" "Personal Web Page"))
176 "Linkedin export in the Outlook csv format.")
179 (defconst bbdb-csv-import-gmail
180 '((:namelist "Given Name" "Family Name")
182 (:affix "Name Prefix" "Name Suffix")
184 (:mail (repeat "E-mail 1 - Value"))
185 (:phone (repeat ("Phone 1 - Type" "Phone 1 - Value")))
187 (repeat (("Address 1 - Type")
188 (("Address 1 - Street" "Address 1 - PO Box" "Address 1 - Extended Address")
189 "Address 1 - City" "Address 1 - Region"
190 "Address 1 - Postal Code" "Address 1 - Country"))))
191 (:organization (repeat "Organization 1 - Name"))
193 "Additional Name" "Yomi Name" "Given Name Yomi"
194 "Additional Name Yomi" "Family Name Yomi"
195 "Initials" "Short Name" "Maiden Name" "Birthday"
196 "Gender" "Location" "Billing Information"
197 "Directory Server" "Mileage" "Occupation"
198 "Hobby" "Sensitivity" "Priority"
199 "Subject" "Notes" "Group Membership"
200 ;; Gmail wouldn't let me add more than 1 organization in its web interface,
201 ;; but no harm in looking for multiple since the field name implies the
204 "Organization 1 - Type" "Organization 1 - Yomi Name"
205 "Organization 1 - Title" "Organization 1 - Department"
206 "Organization 1 - Symbol" "Organization 1 - Location"
207 "Organization 1 - Job Description")
208 (repeat ("Relation 1 - Type" "Relation 1 - Value"))
209 (repeat ("Website 1 - Type" "Website 1 - Value"))
210 (repeat ("Event 1 - Type" "Event 1 - Value"))
211 (repeat ("Custom Field 1 - Type" "Custom Field 1 - Value"))))
212 "Gmail csv export format. Note some fields don't map perfectly,
213 feel free to modify them as you wish. \"PO Box\" and \"Extended
214 Address\" are added as additional address street lines if they
215 exist. Some special name fields are made custom instead of put in
216 name, which gets a single string. We map Gmail's \"Name Prefix\"
217 and \"Name Suffix\" to bbdb's affix (a list of strings). We lose
218 the prefix/suffix label, but those are usually obvious.")
221 (defconst bbdb-csv-import-gmail-typed-email
222 (append (car (last bbdb-csv-import-gmail)) '((repeat "E-mail 1 - Type")))
223 "Like the first Gmail mapping, but use custom fields to store
224 Gmail's email labels. This is separate because I assume most
225 people don't use those labels and using the default labels
226 would create useless custom fields.")
228 (defconst bbdb-csv-import-outlook-web
229 '((:namelist "First Name" "Middle Name" "Last Name")
230 (:mail "E-mail Address" "E-mail 2 Address" "E-mail 3 Address")
233 "Assistant's Phone" "Business Fax" "Business Phone"
234 "Business Phone 2" "Callback" "Car Phone"
235 "Company Main Phone" "Home Fax" "Home Phone"
236 "Home Phone 2" "ISDN" "Mobile Phone"
237 "Other Fax" "Other Phone" "Pager"
238 "Primary Phone" "Radio Phone" "TTY/TDD Phone" "Telex")
242 "Business City" "Business State"
243 "Business Postal Code" "Business Country"))
246 "Home City" "Home State"
247 "Home Postal Code" "Home Country"))
250 "Other City" "Other State"
251 "Other Postal Code" "Other Country"))))
252 (:organization "Company")
254 "Anniversary" "Family Name Yomi" "Given Name Yomi"
255 "Department" "Job Title" "Birthday" "Manager's Name" "Notes"
256 "Spouse" "Web Page"))
257 "Hotmail.com, outlook.com, live.com, etc.
258 Based on 'Export for outlook.com and other services',
259 not the export for Outlook 2010 and 2013.")
261 (defconst bbdb-csv-import-outlook-typed-email
262 (append (car (last bbdb-csv-import-outlook-web)) '((repeat "E-mail 1 - Type")))
263 "Like bbdb-csv-import-gmail-typed-email, but for outlook-web.
264 Adds email labels as custom fields.")
267 (defun bbdb-csv-import-flatten1 (list)
268 "Flatten LIST by 1 level."
269 (--reduce-from (if (consp it)
275 (defun bbdb-csv-import-merge-map (root)
276 "Combine two root mappings for making a combined mapping."
277 (bbdb-csv-import-flatten1
281 (cdr (assoc root bbdb-csv-import-thunderbird))
282 (cdr (assoc root bbdb-csv-import-linkedin))
283 (cdr (assoc root bbdb-csv-import-gmail))
284 (cdr (assoc root bbdb-csv-import-outlook-web)))))))
287 (defconst bbdb-csv-import-combined
289 ;; manually combined for proper ordering
290 '(:namelist "First Name" "Given Name" "Middle Name" "Last Name" "Family Name")
291 (bbdb-csv-import-merge-map :name)
292 (bbdb-csv-import-merge-map :affix)
293 (bbdb-csv-import-merge-map :aka)
294 (bbdb-csv-import-merge-map :mail)
295 (bbdb-csv-import-merge-map :phone)
296 ;; manually combined the addresses. Because it was easier.
298 (repeat (("Address 1 - Type")
299 (("Address 1 - Street" "Address 1 - PO Box" "Address 1 - Extended Address")
300 "Address 1 - City" "Address 1 - Region"
301 "Address 1 - Postal Code" "Address 1 - Country")))
303 (("Business Street" "Business Street 2" "Business Street 3")
304 "Business City" "Business State"
305 "Business Postal Code" "Business Country"))
307 (("Home Street" "Home Street 2" "Home Street 3"
308 "Home Address" "Home Address 2")
309 "Home City" "Home State"
310 "Home Postal Code" "Home ZipCode" "Home Country"))
312 (("Work Address" "Work Address 2")
313 "Work City" "Work State"
314 "Work ZipCode" "Work Country"))
316 (("Other Street" "Other Street 2" "Other Street 3")
317 "Other City" "Other State"
318 "Other Postal Code" "Other Country"))))
319 (bbdb-csv-import-merge-map :organization)
320 (bbdb-csv-import-merge-map :xfields)))
322 (defcustom bbdb-csv-import-mapping-table bbdb-csv-import-combined
323 "The table which maps bbdb fields to csv fields. The default should work for most cases.
324 See the commentary section of this file for more details."
325 :group 'bbdb-csv-import
329 (defun bbdb-csv-import-expand-repeats (csv-fields list)
330 "Return new list where elements from LIST in form (repeat elem1
331 ...) become ((elem1 ...) [(elem2 ...)] ...) for as many fields
332 exist in the csv fields. elem can be a string or a tree (a list
333 with lists inside it). We use the first element as a template,
334 and increase its number by one, and check if it exists, and then
335 increment any other elements from the repeat list which have
337 (cl-flet ((replace-num (num string)
338 ;; in STRING, replace all groups of numbers with NUM
339 (replace-regexp-in-string "[0-9]+"
340 (number-to-string num)
343 (if (not (and (consp it) (eq (car it) 'repeat)))
347 (first-field (car (-flatten it))))
348 (setq acc (cons it acc))
349 ;; use first-field to test if there is another repetition.
351 (replace-num (setq i (1+ i)) first-field)
353 (cl-labels ((fun (cell)
356 (replace-num i cell))))
357 (setq acc (cons (fun it) acc))))
361 (defun bbdb-csv-import-map-bbdb (csv-fields root)
362 "ROOT is a root element from bbdb-csv-import-mapping-table. Get
363 the csv-fields for root in the mapping format, including variably
364 repeated ones. Flatten by one because repeated fields are put in
365 sub-lists, but after expanding them, that extra depth is no
366 longer useful. Small trade off: address mappings without 'repeat need
367 to be grouped in a list because they contain sublists that we
368 don't want flattened."
369 (bbdb-csv-import-flatten1
370 (bbdb-csv-import-expand-repeats
372 (cdr (assoc root bbdb-csv-import-mapping-table)))))
375 (defun bbdb-csv-import-file (filename)
376 "Parse and import csv file FILENAME to bbdb.
377 The file will be saved to disk with blank lines and aberrant characters removed."
378 (interactive "fCSV file containg contact data: ")
379 (bbdb-csv-import-buffer (find-file-noselect filename)))
382 (defun bbdb-csv-import-buffer (&optional buffer-or-name)
383 "Parse and import csv buffer to bbdb. Interactively, it prompts for a buffer.
384 The buffer will be saved to disk with blank lines and aberrant characters removed.
385 BUFFER-OR-NAME is a buffer or name of a buffer, or the current buffer if nil."
386 (interactive "bBuffer containing CSV contact data: ")
387 (when (null bbdb-csv-import-mapping-table)
388 (error "error: `bbdb-csv-import-mapping-table' is nil. Please set it and rerun."))
389 (let* ((csv-buffer (get-buffer (or buffer-or-name (current-buffer))))
390 (csv-data (save-excursion
391 (set-buffer csv-buffer)
392 ;; deal with blank lines and ^M from linkedin
393 (flush-lines "^\\s-*$")
394 (goto-char (point-min))
395 ;; remove ^M aka ret characters
396 (while (re-search-forward (char-to-string 13) nil t)
399 (pcsv-parse-file buffer-file-name)))
400 (csv-fields (car csv-data))
401 (csv-data (cdr csv-data))
402 (allow-dupes bbdb-allow-duplicates)
403 csv-record rd assoc-plus map-bbdb dupes)
404 ;; convenient function names
405 (fset 'rd 'bbdb-csv-import-rd)
406 (fset 'assoc-plus 'bbdb-csv-import-assoc-plus)
407 (fset 'map-bbdb (-partial 'bbdb-csv-import-map-bbdb csv-fields))
408 ;; we handle duplicates ourselves
409 (setq bbdb-allow-duplicates t)
410 ;; loop over the csv records
411 (while (setq csv-record (map 'list 'cons csv-fields (pop csv-data)))
413 ((ca (key list) (cdr (assoc key list))) ;; utility function
415 ;; given ROOT, return a list of data, ignoring empty fields
416 (rd (lambda (elem) (assoc-plus elem csv-record)) (map-bbdb root)))
418 ;; E = data-field-name | (field-name-field data-field)
419 ;; get data from the csv-record and return (field-name data) or nil.
420 (let ((data-name (if (consp e) (ca (car e) csv-record) e))
421 (data (assoc-plus (if (consp e) (cadr e) e) csv-record)))
422 (if data (list data-name data)))))
423 ;; set the arguments to bbdb-create-internal, then call it, the end.
424 (let ((name (let ((name (rd-assoc :namelist)))
425 ;; prioritize any combination of first middle last over :name
426 (if (>= (length name) 2)
427 (mapconcat 'identity name " ")
428 (car (rd-assoc :name)))))
429 (affix (rd-assoc :affix))
430 (aka (rd-assoc :aka))
431 (organization (rd-assoc :organization))
432 (mail (rd-assoc :mail))
433 (phone (rd 'vconcat (rd #'assoc-expand (map-bbdb :phone))))
434 (address (rd (lambda (e)
436 (let ((al (rd (lambda (elem) ;; al = address lines
437 (assoc-plus elem csv-record))
439 ;; to use bbdb-csv-import-combined, we can't mapcar
440 (address-data (--reduce-from (if (member it csv-fields)
441 (cons (ca it csv-record) acc)
445 (setq al (nreverse al))
446 (setq address-data (nreverse address-data))
447 ;; make it a list of at least 2 elements
449 (-repeat (- 2 (length al)) "")))
450 (when (consp elem-name)
451 (setq elem-name (ca (car elem-name) csv-record)))
453 ;; determine if non-nil and put together the minimum set
454 (when (or (not (--all? (zerop (length it)) address-data))
455 (not (--all? (zerop (length it)) al)))
456 (when (> 2 (length al))
457 (setcdr (max 2 (nthcdr (--find-last-index (not (null it))
460 (vconcat (list elem-name) (list al) address-data))))
461 (map-bbdb :address)))
462 (xfields (rd (lambda (list)
463 (let ((e (car list)))
464 (while (string-match "-" e)
465 (setq e (replace-match "" nil nil e)))
466 (while (string-match " +" e)
467 (setq e (replace-match "-" nil nil e)))
468 (setq e (make-symbol (downcase e)))
469 (cons e (cadr list)))) ;; change from (a b) to (a . b)
470 (rd #'assoc-expand (map-bbdb :xfields)))))
471 ;; we copy and subvert bbdb's duplicate detection instead of catching
472 ;; errors so that we don't interfere with other errors, and can print
473 ;; them nicely at the end.
476 (when (bbdb-gethash elt '(mail))
478 (setq found-dupe t)))
479 (when (or allow-dupes (not found-dupe))
480 (bbdb-create-internal name affix aka organization mail phone address xfields t))))))
481 (when dupes (if allow-dupes
482 (message "Warning, contacts with duplicate email addresses were imported:\n%s" dupes)
483 (message "Skipped contacts with duplicate email addresses:\n%s" dupes)))
484 (setq bbdb-allow-duplicates allow-dupes)))
486 (defun bbdb-csv-import-rd (func list)
487 "like mapcar but don't build nil results into the resulting list"
488 (--reduce-from (let ((funcreturn (funcall func it)))
490 (cons funcreturn acc)
494 (defun bbdb-csv-import-assoc-plus (key list)
495 "Like (cdr assoc ...) but turn an empty string result to nil."
496 (let ((result (cdr (assoc key list))))
497 (when (not (string= "" result))
500 (defun bbdb-csv-anonymize-current-buffer ()
502 "Anonymize the current buffer which contains csv data.
503 The first line should contain header names."
505 (while (re-search-forward "\\w")
507 (insert (number-to-string (random 9)))))
510 (provide 'bbdb-csv-import)
512 ;;; bbdb-csv-import.el ends here