I edit my address book in Emacs --- it's a text file, I can grep it, I
can isearch it, I keep it in CVS --- and I prefer keeping things
consistent in it.  So here's a little utility I wrote to reformat
phone numbers into a consistent style.

;;; still doesn't handle the formats 4154975513 and 415 4975513
(defun reformat-us-phone-number ()
  "Reformat a phone number in a US format into my normal phone number format."
  (interactive)
  (save-excursion
    ; XXX these regexen break at end of buffer
    (if (looking-at "[0-9]\\{3\\}[-. ][0-9]\\{3\\}[-. ][0-9]\\{4\\}[^0-9]")
        (progn
          (insert "+1 ")
          (forward-char 3)
          (delete-char 1)
          (insert " ")
          (forward-char 3)
          (delete-char 1)
          (insert " ")
          t)
      (if (looking-at
           "([0-9]\\{3\\})[-. ]?[0-9]\\{3\\}[-. ][0-9]\\{4\\}[^0-9]")
          (progn 
            (insert "+1 ")
            (delete-char 1)
            (forward-char 3)
            (delete-char 1)
            (if (looking-at "[-. ]") (delete-char 1))
            (insert " ")
            (forward-char 3)
            (delete-char 1)
            (insert " ")
            t)
        nil))))

(defun magic-reformat-us-phone-number ()
  "Reformat a US phone number somewhere in the vicinity."
  (interactive)
  (or (reformat-us-phone-number)
      (save-excursion (forward-char 1) (reformat-us-phone-number))
      (save-excursion (backward-char 1) (reformat-us-phone-number))
      (and (looking-at "1-[0-9]\\{3\\}")
           (progn (delete-char 2) (reformat-us-phone-number)))
      (save-excursion (backward-char 12) (reformat-us-phone-number))
      (save-excursion (backward-char 13) (reformat-us-phone-number))
      (save-excursion (backward-char 14) (reformat-us-phone-number))))
(global-set-key [C-M-tab] 'magic-reformat-us-phone-number)

Reply via email to