I am looking for a way to open all files from $MYPATH (for instance) as read-only buffer by default. And all rest of the files should be opened as normal buffer (I mean, not read-only buffer). Does anyone know how to do this? Cheers. - A still naive EMACS lover

  • 2
    See find-file-hook. After the file is visited in a buffer, check (e.g. against a list of yours) whether the buffer should be read-only, and if so, make it read-only.
    – Drew
    Feb 5, 2018 at 3:11

2 Answers 2


You can also do this using using dir locals and associating one or more directories with a directory class. For example:

;; Define a read-only directory class
(dir-locals-set-class-variables 'read-only
 '((nil . ((buffer-read-only . t)))))

;; Associate directories with the read-only class
(dolist (dir (list "/some/dir" "/some/other/dir"))
  (dir-locals-set-directory-class (file-truename dir) 'read-only))
  • 5
    You can alternatively put that ((nil . ((buffer-read-only . t)))) into a file named .dir-locals.el in the /some/dir and /some/other/dir directories. See emacswiki.org/emacs/DirectoryVariables (and of course the manual) for more.
    – phils
    Feb 5, 2018 at 23:28

The following code does what Drew suggested. It implements only one directory under which all files are opened as read-only -- like you asked. The newly opened buffer is set read-only if 1) it has file associated with it 2) the directory string matches and 3) the file is not already read-only. If a filesystem permission already restricts file to be read-only, nothing needs to be done.

;; home dir needs to be spelled out, no '~'
(setq my-read-only-dir-re "^/Users/heikki/tmp")

(defun my-open-buffer-as-read-only ()
    "All buffers opened from directory my-read-only-dir-re are set read-only."
    (if (and buffer-file-name  ;; buffer is associated with a file
             ;; directory name matches
             (string-match my-read-only-dir-re buffer-file-name)
             (not buffer-read-only))  ;; buffer is writable
      (read-only-mode 1)))

(add-hook 'find-file-hook  #'my-open-buffer-as-read-only)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.