;;; obfemail-mode.el --- minor mode for editing files with obfuscated emails

;; Authors: 2009 Sergey Poznyakoff
;; Version: 1.0
;; Keywords: Mailfromd, Email, Caesar, Rot13

;; This file is part of Mailfromd
;; Copyright (C) 2009-2022 Sergey Poznyakoff
 
;; Mailfromd 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.
 
;; Mailfromd 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 Mailfromd.  If not, see <http://www.gnu.org/licenses/>.

;;; Code:

(eval-when-compile
  ;; We use functions from these modules
  (mapcar 'require '(rot13)))

(defun obfemail-region (beg end)
  (interactive "*r")
  (save-excursion
    (goto-char beg)
    (while (search-forward-regexp "<\\([^>@]+@[a-zA-Z0-9._+-]+\\)>" end t)
      (rot13 (current-buffer) (match-beginning 1) (match-end 1)))))

(defun obfemail-current-buffer ()
  (obfemail-region 0 (point-max)))

(defun obfemail-current-buffer-nomod ()
  (let ((mod (buffer-modified-p)))
    (obfemail-current-buffer)
    (set-buffer-modified-p mod)))

(defun obfemail-install ()
  (add-hook 'write-contents-hooks 'obfemail-current-buffer)
  (make-local-variable 'after-save-hook)
  (add-hook 'after-save-hook 'obfemail-current-buffer-nomod)
  (obfemail-current-buffer-nomod))

(defun obfemail-installed-p ()
  (member 'obfemail-current-buffer-nomod after-save-hook))

(defun obfemail-uninstall ()
  (remove-hook 'write-contents-hooks 'obfemail-current-buffer t)
  (remove-hook 'after-save-hook 'obfemail-current-buffer-nomod t)
  (obfemail-current-buffer-nomod))

(and (obfemail-installed-p)
     (obfemail-uninstall))

;;;###autoload
(define-minor-mode obfemail-mode 
  "Minor mode for displaying files containig email addresses encrypted using
Caesar cipher."
  :init-value nil :lighter "-ObfE" 
  (let ((installed (obfemail-installed-p))
	(flag obfemail-mode))
    (cond
     ((and flag installed) t)               ; ok, already installed
     ((and (not flag) (not installed)) nil) ; ok, nothing to do
     (flag (obfemail-install))              ; install the mode
     (t (obfemail-uninstall)))))

(provide 'obfemail-mode)
;;; obfemail-mode ends
