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 ;;; Advanced usage / notes:
51 ;; Tested to work with thunderbird, gmail, linkedin, outlook.com/hotmail.com. For
52 ;; those programs, if it's exporter has an option of what kind of csv format,
53 ;; choose it's own native format if available, if not, choose an outlook
54 ;; compatible format. If you're exporting from some other program and its csv
55 ;; exporter claims outlook compatibility, there is a good chance it will work
58 ;; Duplicate contacts (according to email address) are skipped if
59 ;; bbdb-allow-duplicates is nil (default). Any duplicates found are echoed at
60 ;; the end of the import.
62 ;; If things don't work, you can probably fix it with a custom field mapping
63 ;; variable. It should not be too hard. Use the existing tables as an
64 ;; example. By default, we use a combination of most predefined mappings, and
65 ;; look for all of their fields, but it is probably best to avoid that kind of
66 ;; table when setting up your own as it is an unnecessary complexity in that
67 ;; case. If you have a problem with data from a supported export program, start
68 ;; by testing its specific mapping table instead of the combined one. Here is a
69 ;; handy template to set each of the predefined mapping tables if you would
70 ;; rather avoid the configure interface:
72 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-combined)
73 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-thunderbird)
74 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-gmail)
75 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-gmail-typed-email)
76 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-linkedin)
77 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-outlook-web)
78 ;; (setq bbdb-csv-import-mapping-table bbdb-csv-import-outlook-typed-email)
80 ;; In addition to the examples, the doc string for `bbdb-create-internal' may
81 ;; also be useful. Please send any new mapping tables to the maintainer listed
82 ;; in this file. The maintainer should be able to help with any issues and may
83 ;; create a new mapping table given sample data.
85 ;;; Misc tips/troubleshooting:
87 ;; - ASynK looks promising for syncing bbdb/google/outlook.
88 ;; - The git repo contains a test folder with exactly tested version info and working
90 ;; - bbdb doesn't work if you delete the bbdb database file in
91 ;; the middle of an emacs session. If you want to empty the current bbdb database,
92 ;; do M-x bbdb then .* then C-u * d on the beginning of a record.
93 ;; - After changing a mapping table variable, don't forget to re-execute
94 ;; (setq bbdb-csv-import-mapping-table ...) so that it propagates.
96 ;;; Bugs, patches, discussion, feedback
98 ;; Patches and bugs are very welcome via https://gitlab.com/iankelling/bbdb-csv-import
100 ;; Questions, feedback, etc are very welcome via email to Ian Kelling
101 ;; <ian@iankelling.org>. I will add any useful questions, answers, etc. to this
102 ;; file. The scope/userbase of this project doesn't justify a mailing list, but if
103 ;; it ever did I would start a mailman or discourse to act as a mailing list
111 (eval-when-compile (require 'cl))
114 (defconst bbdb-csv-import-thunderbird
115 '((:namelist "First Name" "Last Name")
116 (:name "Display Name")
118 (:mail "Primary Email" "Secondary Email")
119 (:phone "Work Phone" "Home Phone" "Fax Number" "Pager Number" "Mobile Number")
122 (("Home Address" "Home Address 2")
123 "Home City" "Home State"
124 "Home ZipCode" "Home Country"))
126 (("Work Address" "Work Address 2")
127 "Work City" "Work State"
128 "Work ZipCode" "Work Country"))))
129 (:organization "Organization")
130 (:xfields "Web Page 1" "Web Page 2" "Birth Year" "Birth Month"
131 "Birth Day" "Department" "Custom 1" "Custom 2" "Custom 3"
132 "Custom 4" "Notes" "Job Title"))
133 "Thunderbird csv format")
135 (defconst bbdb-csv-import-linkedin
136 '((:namelist "First Name" "Middle Name" "Last Name")
138 (:mail "E-mail Address" "E-mail 2 Address" "E-mail 3 Address")
140 "Assistant's Phone" "Business Fax" "Business Phone"
141 "Business Phone 2" "Callback" "Car Phone"
142 "Company Main Phone" "Home Fax" "Home Phone"
143 "Home Phone 2" "ISDN" "Mobile Phone"
144 "Other Fax" "Other Phone" "Pager"
145 "Primary Phone" "Radio Phone" "TTY/TDD Phone" "Telex")
148 (("Business Street" "Business Street 2" "Business Street 3")
149 "Business City" "Business State"
150 "Business Postal Code" "Business Country"))
152 (("Home Street" "Home Street 2" "Home Street 3")
153 "Home City" "Home State"
154 "Home Postal Code" "Home Country"))
156 (("Other Street" "Other Street 2" "Other Street 3")
157 "Other City" "Other State"
158 "Other Postal Code" "Other Country"))))
159 (:organization "Company")
161 "Department" "Job Title" "Assistant's Name"
162 "Birthday" "Manager's Name" "Notes" "Other Address PO Box"
163 "Spouse" "Web Page" "Personal Web Page"))
164 "Linkedin export in the Outlook csv format.")
167 (defconst bbdb-csv-import-gmail
168 '((:namelist "Given Name" "Family Name")
170 (:affix "Name Prefix" "Name Suffix")
172 (:mail (repeat "E-mail 1 - Value"))
173 (:phone (repeat ("Phone 1 - Type" "Phone 1 - Value")))
175 (repeat (("Address 1 - Type")
176 (("Address 1 - Street" "Address 1 - PO Box" "Address 1 - Extended Address")
177 "Address 1 - City" "Address 1 - Region"
178 "Address 1 - Postal Code" "Address 1 - Country"))))
179 (:organization (repeat "Organization 1 - Name"))
181 "Additional Name" "Yomi Name" "Given Name Yomi"
182 "Additional Name Yomi" "Family Name Yomi"
183 "Initials" "Short Name" "Maiden Name" "Birthday"
184 "Gender" "Location" "Billing Information"
185 "Directory Server" "Mileage" "Occupation"
186 "Hobby" "Sensitivity" "Priority"
187 "Subject" "Notes" "Group Membership"
188 ;; Gmail wouldn't let me add more than 1 organization in its web interface,
189 ;; but no harm in looking for multiple since the field name implies the
192 "Organization 1 - Type" "Organization 1 - Yomi Name"
193 "Organization 1 - Title" "Organization 1 - Department"
194 "Organization 1 - Symbol" "Organization 1 - Location"
195 "Organization 1 - Job Description")
196 (repeat ("Relation 1 - Type" "Relation 1 - Value"))
197 (repeat ("Website 1 - Type" "Website 1 - Value"))
198 (repeat ("Event 1 - Type" "Event 1 - Value"))
199 (repeat ("Custom Field 1 - Type" "Custom Field 1 - Value"))))
200 "Gmail csv export format. Note some fields don't map perfectly,
201 feel free to modify them as you wish. \"PO Box\" and \"Extended
202 Address\" are added as additional address street lines if they
203 exist. Some special name fields are made custom instead of put in
204 name, which gets a single string. We map Gmail's \"Name Prefix\"
205 and \"Name Suffix\" to bbdb's affix (a list of strings). We lose
206 the prefix/suffix label, but those are usually obvious.")
209 (defconst bbdb-csv-import-gmail-typed-email
210 (append (car (last bbdb-csv-import-gmail)) '((repeat "E-mail 1 - Type")))
211 "Like the first Gmail mapping, but use custom fields to store
212 Gmail's email labels. This is separate because I assume most
213 people don't use those labels and using the default labels
214 would create useless custom fields.")
216 (defconst bbdb-csv-import-outlook-web
217 '((:namelist "First Name" "Middle Name" "Last Name")
218 (:mail "E-mail Address" "E-mail 2 Address" "E-mail 3 Address")
221 "Assistant's Phone" "Business Fax" "Business Phone"
222 "Business Phone 2" "Callback" "Car Phone"
223 "Company Main Phone" "Home Fax" "Home Phone"
224 "Home Phone 2" "ISDN" "Mobile Phone"
225 "Other Fax" "Other Phone" "Pager"
226 "Primary Phone" "Radio Phone" "TTY/TDD Phone" "Telex")
230 "Business City" "Business State"
231 "Business Postal Code" "Business Country"))
234 "Home City" "Home State"
235 "Home Postal Code" "Home Country"))
238 "Other City" "Other State"
239 "Other Postal Code" "Other Country"))))
240 (:organization "Company")
242 "Anniversary" "Family Name Yomi" "Given Name Yomi"
243 "Department" "Job Title" "Birthday" "Manager's Name" "Notes"
244 "Spouse" "Web Page"))
245 "Hotmail.com, outlook.com, live.com, etc.
246 Based on 'Export for outlook.com and other services',
247 not the export for Outlook 2010 and 2013.")
249 (defconst bbdb-csv-import-outlook-typed-email
250 (append (car (last bbdb-csv-import-outlook-web)) '((repeat "E-mail 1 - Type")))
251 "Like bbdb-csv-import-gmail-typed-email, but for outlook-web.
252 Adds email labels as custom fields.")
255 (defun bbdb-csv-import-flatten1 (list)
256 "Flatten LIST by 1 level."
257 (--reduce-from (if (consp it)
263 (defun bbdb-csv-import-merge-map (root)
264 "Combine two root mappings for making a combined mapping."
265 (bbdb-csv-import-flatten1
269 (cdr (assoc root bbdb-csv-import-thunderbird))
270 (cdr (assoc root bbdb-csv-import-linkedin))
271 (cdr (assoc root bbdb-csv-import-gmail))
272 (cdr (assoc root bbdb-csv-import-outlook-web)))))))
275 (defconst bbdb-csv-import-combined
277 ;; manually combined for proper ordering
278 '(:namelist "First Name" "Given Name" "Middle Name" "Last Name" "Family Name")
279 (bbdb-csv-import-merge-map :name)
280 (bbdb-csv-import-merge-map :affix)
281 (bbdb-csv-import-merge-map :aka)
282 (bbdb-csv-import-merge-map :mail)
283 (bbdb-csv-import-merge-map :phone)
284 ;; manually combined the addresses. Because it was easier.
286 (repeat (("Address 1 - Type")
287 (("Address 1 - Street" "Address 1 - PO Box" "Address 1 - Extended Address")
288 "Address 1 - City" "Address 1 - Region"
289 "Address 1 - Postal Code" "Address 1 - Country")))
291 (("Business Street" "Business Street 2" "Business Street 3")
292 "Business City" "Business State"
293 "Business Postal Code" "Business Country"))
295 (("Home Street" "Home Street 2" "Home Street 3"
296 "Home Address" "Home Address 2")
297 "Home City" "Home State"
298 "Home Postal Code" "Home ZipCode" "Home Country"))
300 (("Work Address" "Work Address 2")
301 "Work City" "Work State"
302 "Work ZipCode" "Work Country"))
304 (("Other Street" "Other Street 2" "Other Street 3")
305 "Other City" "Other State"
306 "Other Postal Code" "Other Country"))))
307 (bbdb-csv-import-merge-map :organization)
308 (bbdb-csv-import-merge-map :xfields)))
310 (defcustom bbdb-csv-import-mapping-table bbdb-csv-import-combined
311 "The table which maps bbdb fields to csv fields. The default should work for most cases.
312 See the commentary section of this file for more details."
313 :group 'bbdb-csv-import
317 (defun bbdb-csv-import-expand-repeats (csv-fields list)
318 "Return new list where elements from LIST in form (repeat elem1 ...)
319 become ((elem1 ...) [(elem2 ...)] ...) for as many repeating
320 numbered fields exist in the csv fields. elem can be a string or
321 a tree (a list with lists inside it)"
322 (cl-flet ((replace-num (num string)
323 ;; in STRING, replace all groups of numbers with NUM
324 (replace-regexp-in-string "[0-9]+"
325 (number-to-string num)
328 (if (not (and (consp it) (eq (car it) 'repeat)))
332 (first-field (car (-flatten it))))
333 (setq acc (cons it acc))
334 ;; use first-field to test if there is another repetition.
336 (replace-num (setq i (1+ i)) first-field)
338 (cl-labels ((fun (cell)
341 (replace-num i cell))))
342 (setq acc (cons (fun it) acc))))
346 (defun bbdb-csv-import-map-bbdb (csv-fields root)
347 "ROOT is a root element from bbdb-csv-import-mapping-table. Get
348 the csv-fields for root in the mapping format, including variably
349 repeated ones. Flatten by one because repeated fields are put in
350 sub-lists, but after expanding them, that extra depth is no
351 longer useful. Small trade off: address mappings without 'repeat need
352 to be grouped in a list because they contain sublists that we
353 don't want flattened."
354 (bbdb-csv-import-flatten1
355 (bbdb-csv-import-expand-repeats
357 (cdr (assoc root bbdb-csv-import-mapping-table)))))
360 (defun bbdb-csv-import-file (filename)
361 "Parse and import csv file FILENAME to bbdb."
362 (interactive "fCSV file containg contact data: ")
363 (bbdb-csv-import-buffer (find-file-noselect filename)))
366 (defun bbdb-csv-import-buffer (&optional buffer-or-name)
367 "Parse and import csv BUFFER-OR-NAME to bbdb.
368 Argument is a buffer or name of a buffer.
369 Defaults to current buffer."
370 (interactive "bBuffer containing CSV contact data: ")
371 (when (null bbdb-csv-import-mapping-table)
372 (error "error: `bbdb-csv-import-mapping-table' is nil. Please set it and rerun."))
373 (let* ((csv-data (pcsv-parse-buffer (get-buffer (or buffer-or-name (current-buffer)))))
374 (csv-fields (car csv-data))
375 (csv-data (cdr csv-data))
376 (allow-dupes bbdb-allow-duplicates)
377 csv-record rd assoc-plus map-bbdb dupes)
378 ;; convenient function names
379 (fset 'rd 'bbdb-csv-import-rd)
380 (fset 'assoc-plus 'bbdb-csv-import-assoc-plus)
381 (fset 'map-bbdb (-partial 'bbdb-csv-import-map-bbdb csv-fields))
382 ;; we handle duplicates ourselves
383 (setq bbdb-allow-duplicates t)
384 ;; loop over the csv records
385 (while (setq csv-record (map 'list 'cons csv-fields (pop csv-data)))
387 ((ca (key list) (cdr (assoc key list))) ;; utility function
389 ;; given ROOT, return a list of data, ignoring empty fields
390 (rd (lambda (elem) (assoc-plus elem csv-record)) (map-bbdb root)))
392 ;; E = data-field-name | (field-name-field data-field)
393 ;; get data from the csv-record and return (field-name data) or nil.
394 (let ((data-name (if (consp e) (ca (car e) csv-record) e))
395 (data (assoc-plus (if (consp e) (cadr e) e) csv-record)))
396 (if data (list data-name data)))))
397 ;; set the arguments to bbdb-create-internal, then call it, the end.
398 (let ((name (let ((name (rd-assoc :namelist)))
399 ;; prioritize any combination of first middle last over :name
400 (if (>= (length name) 2)
401 (mapconcat 'identity name " ")
402 (car (rd-assoc :name)))))
403 (affix (rd-assoc :affix))
404 (aka (rd-assoc :aka))
405 (organization (rd-assoc :organization))
406 (mail (rd-assoc :mail))
407 (phone (rd 'vconcat (rd #'assoc-expand (map-bbdb :phone))))
408 (address (rd (lambda (e)
410 (let ((al (rd (lambda (elem) ;; al = address lines
411 (assoc-plus elem csv-record))
413 ;; to use bbdb-csv-import-combined, we can't mapcar
414 (address-data (--reduce-from (if (member it csv-fields)
415 (cons (ca it csv-record) acc)
419 (setq al (nreverse al))
420 (setq address-data (nreverse address-data))
421 ;; make it a list of at least 2 elements
423 (-repeat (- 2 (length al)) "")))
424 (when (consp elem-name)
425 (setq elem-name (ca (car elem-name) csv-record)))
427 ;; determine if non-nil and put together the minimum set
428 (when (or (not (--all? (zerop (length it)) address-data))
429 (not (--all? (zerop (length it)) al)))
430 (when (> 2 (length al))
431 (setcdr (max 2 (nthcdr (--find-last-index (not (null it))
434 (vconcat (list elem-name) (list al) address-data))))
435 (map-bbdb :address)))
436 (xfields (rd (lambda (list)
437 (let ((e (car list)))
438 (while (string-match "-" e)
439 (setq e (replace-match "" nil nil e)))
440 (while (string-match " +" e)
441 (setq e (replace-match "-" nil nil e)))
442 (setq e (make-symbol (downcase e)))
443 (cons e (cadr list)))) ;; change from (a b) to (a . b)
444 (rd #'assoc-expand (map-bbdb :xfields)))))
445 ;; we copy and subvert bbdb's duplicate detection instead of catching
446 ;; errors so that we don't interfere with other errors, and can print
447 ;; them nicely at the end.
450 (when (bbdb-gethash elt '(mail))
452 (setq found-dupe t)))
453 (when (or allow-dupes (not found-dupe))
454 (bbdb-create-internal name affix aka organization mail phone address xfields t))))))
455 (when dupes (if allow-dupes
456 (message "Warning, contacts with duplicate email addresses were imported:\n%s" dupes)
457 (message "Skipped contacts with duplicate email addresses:\n%s" dupes)))
458 (setq bbdb-allow-duplicates allow-dupes)))
460 (defun bbdb-csv-import-rd (func list)
461 "like mapcar but don't build nil results into the resulting list"
462 (--reduce-from (let ((funcreturn (funcall func it)))
464 (cons funcreturn acc)
468 (defun bbdb-csv-import-assoc-plus (key list)
469 "Like (cdr assoc ...) but turn an empty string result to nil."
470 (let ((result (cdr (assoc key list))))
471 (when (not (string= "" result))
474 (provide 'bbdb-csv-import)
476 ;;; bbdb-csv-import.el ends here