Skip to content

Instantly share code, notes, and snippets.

@Fuco1
Created March 3, 2017 20:51
Show Gist options
  • Save Fuco1/72451629d89b835143ff26b9c9c48d22 to your computer and use it in GitHub Desktop.
Save Fuco1/72451629d89b835143ff26b9c9c48d22 to your computer and use it in GitHub Desktop.
Automatically save write-protected files with SUDO TRAMP method
;; TODO: package this?
(defadvice basic-save-buffer-2 (around fix-unwritable-save-with-sudo activate)
"When we save a buffer which is write-protected, try to sudo-save it.
When the buffer is write-protected it is usually opened in
read-only mode. Use \\[read-only-mode] to toggle
`read-only-mode', make your changes and \\[save-buffer] to save.
Emacs will warn you that the buffer is write-protected and asks
you to confirm if you really want to save. If you answer yes,
Emacs will use sudo tramp method to save the file and then
reverts it, making it read-only again. The buffer stays
associated with the original non-sudo filename."
(condition-case err
(progn
ad-do-it)
(file-error
(when (string-prefix-p
"Doing chmod: operation not permitted"
(error-message-string err))
(let ((old-buffer-file-name buffer-file-name)
(success nil))
(unwind-protect
(progn
(setq buffer-file-name (concat "/sudo::" buffer-file-name))
(save-buffer)
(setq success t))
(setq buffer-file-name old-buffer-file-name)
(when success
(revert-buffer t t))))))))
@Fuco1
Copy link
Author

Fuco1 commented Mar 3, 2017

No more fuss editing /etc! It is also reasonably safe and warns you before you do something stupid.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment