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
Asked
Active
Viewed 964 times
7
-
2See `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 05 '18 at 03:11
2 Answers
8
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))

glucas
- 20,175
- 1
- 51
- 83
-
5You 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 https://www.emacswiki.org/emacs/DirectoryVariables (and of course the manual) for more. – phils Feb 05 '18 at 23:28
0
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)

Heikki
- 2,961
- 11
- 18