Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get emacs to write to read-only files automatically?

Tags:

emacs

elisp

I am finding myself editing a lot of files that are read-only. I usually hit C-x C-q to call toggle-read-only. Then I hit C-x C-s to save and get,

File foo.txt is write-protected; try to save anyway? (y or n)

After hitting y, the file is saved and the permissions on the file remain read-only.

Is there a way to shorten this process and make it so that simply saving a file with C-x C-s does the whole thing without prompting? Should I look into inserting chmod in before-save-hook and after-save-hook or is there a better way?

like image 504
sigjuice Avatar asked Feb 27 '23 19:02

sigjuice


1 Answers

Adding a call to chmod in before-save-hook would be clean way to accomplish this. There isn't any setting you can change to avoid the permissions check.

Based on the follow-up question, it sounds like you'd like the files to be changed to writable by you automatically upon opening. This code does the trick:

(defun change-file-permissions-to-writable ()
  "to be run from find-file-hook, change write permissions"
  (when (not (file-writable-p buffer-file-name))
    (chmod buffer-file-name (file-modes-symbolic-to-number "u+w" (nth 8 (file-attributes buffer-file-name))))
    (if (not (file-writable-p buffer-file-name))
        (message "Unable to make file writable."))))

(add-hook 'find-file-hook 'change-file-permissions-to-writable)

Note: When I tested it on my Windows machine, the file permissions didn't show up until I tried to save the buffer, but it worked as expected. I personally feel uneasy about this customization, but it's your Emacs. :)

like image 191
Trey Jackson Avatar answered Mar 23 '23 21:03

Trey Jackson