Search code examples
emacselisp

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


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?


Solution

  • 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. :)