Skip to content

Instantly share code, notes, and snippets.

@osmatsuda
Last active April 17, 2017 11:25
Show Gist options
  • Save osmatsuda/d88addb6f4796caf7adeaa1f352401b1 to your computer and use it in GitHub Desktop.
Save osmatsuda/d88addb6f4796caf7adeaa1f352401b1 to your computer and use it in GitHub Desktop.
(defvar auto-view-mode-alist nil
"Alist of elements (MAJOR-MODE . DIRECTORIES) to use for enabling View mode
when a buffer's mode is MAJOR-MODE and children of the DIRECTORIES.")
(defun auto-view-mode--major-mode-hook (mode)
(intern (concat (downcase (symbol-name mode))
"-hook")))
(defun update-auto-view-mode-alist (mode directory)
(unless (symbolp mode)
(error "MODE should be a symbol."))
(unless (file-exists-p directory)
(error "%s dosen't exists." directory))
(setq directory (directory-file-name (expand-file-name directory)))
(and (if (assoc mode auto-view-mode-alist)
(let* ((old-dirs (cdr (assoc mode auto-view-mode-alist)))
(new-dirs (if (equal directory old-dirs)
old-dirs
(if (consp old-dirs)
(if (member directory old-dirs)
old-dirs
(cons directory old-dirs))
(list directory old-dirs)))))
(unless (eq new-dirs old-dirs)
(setq auto-view-mode-alist
(cons (cons mode new-dirs)
(rassq-delete-all old-dirs auto-view-mode-alist)))))
(setq auto-view-mode-alist
(cons (cons mode directory) auto-view-mode-alist)))
(mapc #'(lambda (asc)
(add-hook (auto-view-mode--major-mode-hook (car asc))
'view-mode-with-auto-view-mode-alist))
auto-view-mode-alist)))
(defun disable-auto-view-mode-alist (&optional target)
(setq auto-view-mode-alist
(cond ((null target)
(mapc #'(lambda (asc)
(remove-hook (auto-view-mode--major-mode-hook (car asc))
'view-mode-with-auto-view-mode-alist))
auto-view-mode-alist)
nil)
((symbolp target)
(remove-hook (auto-view-mode--major-mode-hook mode)
'view-mode-with-auto-view-mode-alist)
(assq-delete-all mode auto-view-mode-alist))
((stringp target)
(setq target (expand-file-name target))
(nreverse
(cl-reduce #'(lambda (acc asset)
(if (consp (cdr asset))
(cons (if (member target (cdr asset))
(cons (car asset)
(remove target (cdr asset)))
asset)
acc)
(if (equal target (cdr asset))
acc
(cons asset acc))))
auto-view-mode-alist :initial-value nil)))
(t (signal 'wrong-type-argument '(symbolp mode))))))
(defun view-mode-with-auto-view-mode-alist ()
(let ((dirs (cdr (assoc major-mode auto-view-mode-alist)))
(file (buffer-file-name)))
(and file
(string-match (if (consp dirs)
(setq dirs (regexp-opt dirs))
dirs)
file)
(and (eq (match-beginning 0) 0)
(view-mode)))))
(provide 'auto-view-mode)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment