Created
March 3, 2017 20:51
-
-
Save Fuco1/72451629d89b835143ff26b9c9c48d22 to your computer and use it in GitHub Desktop.
Automatically save write-protected files with SUDO TRAMP method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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)))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No more fuss editing
/etc
! It is also reasonably safe and warns you before you do something stupid.