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

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?

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

I agree with Trey that universally doing a chmod on write is risky -- read-only files are read-only for a reason, IMHO. Here's a way to specifically override things on a per-buffer basis. It's not ideal in that it overrides file-writable-p for the life of the buffer (or at least until you toggle my-override-mode-on-save back to nil), but it makes you make a conscious decision on a file-by-file basis (sort-of; it's really a buffer-by-buffer basis, which is fairly similar). Of course since you're looking to automatically toggle the read-only flag when the file is visited, you might not be interested in this distinction. Still, here it is; enjoy it or ignore it as you will.
(make-variable-buffer-local
(defvar my-override-mode-on-save nil
"Can be set to automatically ignore read-only mode of a file when saving."))
(defadvice file-writable-p (around my-overide-file-writeable-p act)
"override file-writable-p if `my-override-mode-on-save' is set."
(setq ad-return-value (or
my-override-mode-on-save
ad-do-it)))
(defun my-override-toggle-read-only ()
"Toggle buffer's read-only status, keeping `my-override-mode-on-save' in sync."
(interactive)
(setq my-override-mode-on-save (not my-override-mode-on-save))
(toggle-read-only))
P.S. Thanks to Trey for the ad-return-value pointer in the other SO question.

Since I find it useful to be constantly reminded that I am about to edit a file I do not have permissions to, when I open a file in a buffer I want to force myself to proactively make the buffer writable wit C-x q. Opening it with tramp by hand however is quite tedious so I advise save-buffer to prompt me for password if it fails to write. I totally recommend you put this snippet in your .emacs
(defadvice save-buffer (around save-buffer-as-root-around activate)
"Use sudo to save the current buffer."
(interactive "p")
(if (and (buffer-file-name) (not (file-writable-p (buffer-file-name))))
(let ((buffer-file-name (format "/sudo::%s" buffer-file-name)))
ad-do-it)
ad-do-it))

For a reason I could no determine the Trey Jackson solution does not work on my gnu emacs 25.2 under windows: the file-modes-rights-to-number called from file-modes-rights-to-number fails.
If someone is stuck with the same problem he could use a less elegant but working solution replace block :
(chmod buffer-file-name (file-modes-symbolic-to-number "u+w" (nth 8 (file-attributes buffer-file-name))))
with block :
(cond ((or (eq system-type 'ms-dos) (eq system-type 'windows-nt))
(progn
(shell-command-to-string (concat "attrib -R " (buffer-file-name (current-buffer))))
(message "Setting file and buffer to writeable (%s style)" system-type)
))
((eq system-type 'gnu/linux)
(progn
(shell-command-to-string (concat "chmod u+w " (buffer-file-name (current-buffer))))
(message "Setting file and buffer to writeable (%s style)" system-type)
))
(t (message "file permission change not handle for OS %s" system-type))
)

Related

Persistent Undos in Emacs [duplicate]

Is there any way to have EMACS save your undo history between sessions?
I'm aware of the savehist lib, the saveplace lib, the desktop lib, and the windows lib, these all provide some session control but none seem to save the undo history.
From version 0.4 onwards, undo-tree supports persistent storage of undo-tree data between sessions "out of the box". (Note that there are significant bug-fixes related to this feature in more recent versions; the latest version at the time of writing is 0.6.3.)
Simply enable the undo-tree-auto-save-history customization option to automatically save and load undo history in undo-tree buffers. Or use the undo-tree-save/load-history commands to save and load undo history manually.
You need at least Emacs version 24.3 for this to work reliably, but with a recent enough Emacs it works very well.
Add the following to your .emacs file :
(global-undo-tree-mode)
(setq undo-tree-auto-save-history t)
(setq undo-tree-history-directory-alist '(("." . "~/.emacs.d/undo")))
Explanation
(global-undo-tree-mode) enables undo tree.
(setq undo-tree-auto-save-history t) enables auto save of undo history.
(setq undo-tree-history-directory-alist '(("." . "~/.emacs.d/undo"))) so that your project does not get littered with undo-history savefiles.
Here's some code I wrote which seems to do the trick. It isn't bullet-proof, as in, it doesn't handle all the file handling intricacies that Emacs does (e.g. overriding where auto-save files are put, symlink handling, etc.). But, it seemed to do the trick for some simple text files I manipulated.
(defun save-undo-filename (orig-name)
"given a filename return the file name in which to save the undo list"
(concat (file-name-directory orig-name)
"."
(file-name-nondirectory orig-name)
".undo"))
(defun save-undo-list ()
"Save the undo list to a file"
(save-excursion
(ignore-errors
(let ((undo-to-save `(setq buffer-undo-list ',buffer-undo-list))
(undo-file-name (save-undo-filename (buffer-file-name))))
(find-file undo-file-name)
(erase-buffer)
(let (print-level
print-length)
(print undo-to-save (current-buffer)))
(let ((write-file-hooks (remove 'save-undo-list write-file-hooks)))
(save-buffer))
(kill-buffer))))
nil)
(defvar handling-undo-saving nil)
(defun load-undo-list ()
"load the undo list if appropriate"
(ignore-errors
(when (and
(not handling-undo-saving)
(null buffer-undo-list)
(file-exists-p (save-undo-filename (buffer-file-name))))
(let* ((handling-undo-saving t)
(undo-buffer-to-eval (find-file-noselect (save-undo-filename (buffer-file-name)))))
(eval (read undo-buffer-to-eval))))))
(add-hook 'write-file-hooks 'save-undo-list)
(add-hook 'find-file-hook 'load-undo-list)
desktop-save-mode does not save buffer-undo-list by default. You just have to tell him!
(add-to-list 'desktop-locals-to-save 'buffer-undo-list)
Emacs Session appears to support this:
(add-to-list 'session-locals-include 'buffer-undo-list)
I have managed to get the undo history working by using the information provided here: http://emacs.stackexchange.com/q/3725/2287
Instead of patching the original file desktop.el.gz I created an advice that temporarily overrides (buffer-local-variables) then I use it together with the function that gathers information about the buffer.
(defun +append-buffer-undo-list-to-buffer-local-variables-advice (orig-fn &rest args)
"Override `buffer-local-variables' and call ORIG-FN with ARGS.
There is a bug in Emacs where the `buffer-undo-list' data is
missing from the output of `buffer-local-variables'. This
advice temporarily overrides the function and appends the
missing data."
(let ((orig-buffer-local-variables-fn (symbol-function 'buffer-local-variables)))
(cl-letf (((symbol-function 'buffer-local-variables)
#'(lambda () (append (funcall orig-buffer-local-variables-fn)
`(,(cons 'buffer-undo-list buffer-undo-list))))))
(apply orig-fn args))))
(advice-add #'desktop-buffer-info :around #'+append-buffer-undo-list-to-buffer-local-variables-advice)
(push 'buffer-undo-list desktop-locals-to-save)
(desktop-save-mode 1)
I hope this helps someone else.

Is there a way to retain the undo list in Emacs after reverting a buffer from file?

How can I make Emacs retain its undo history for my buffer after doing revert-buffer or using auto-revert-mode?
In Vim, if a file that is open in a buffer is changed on disc, Vim prompts me to reload the file. I can then simply click 'u' to undo the reload if I so wish and even go back further from then. Emacs seems to trash all the undo information the moment I revert the buffer.
Emacs allows you to set revert-buffer-function to override the behaviour. Here's a revert-buffer implementation that keeps the history.
;; emacs doesn't actually save undo history with revert-buffer
;; see http://lists.gnu.org/archive/html/bug-gnu-emacs/2011-04/msg00151.html
;; fix that.
(defun revert-buffer-keep-history (&optional IGNORE-AUTO NOCONFIRM PRESERVE-MODES)
(interactive)
;; tell Emacs the modtime is fine, so we can edit the buffer
(clear-visited-file-modtime)
;; insert the current contents of the file on disk
(widen)
(delete-region (point-min) (point-max))
(insert-file-contents (buffer-file-name))
;; mark the buffer as not modified
(not-modified)
(set-visited-file-modtime))
(setq revert-buffer-function 'revert-buffer-keep-history)
You could use the before-hook to save the previous buffer-content to the kill-ring:
(add-hook 'before-revert-hook (lambda () (kill-ring-save (point-min) (point-max))))
The upcoming Emacs-24.4 does what you want by default.
I guess the obvious approach would be a function which kills the current buffer content, and then calls insert-file to read in the current content from the file.
If the changes to the file included changes to the character encoding, there might be problems? I haven't tested that.
Here's my current attempt. It's a little hairy IMO, but it works okay.
;; Allow buffer reverts to be undone
(defun my-revert-buffer (&optional ignore-auto noconfirm preserve-modes)
"Revert buffer from file in an undo-able manner."
(interactive)
(when (buffer-file-name)
;; Based upon `delphi-save-state':
;; Ensure that any buffer modifications do not have any side
;; effects beyond the actual content changes.
(let ((buffer-read-only nil)
(inhibit-read-only t)
(before-change-functions nil)
(after-change-functions nil))
(unwind-protect
(progn
;; Prevent triggering `ask-user-about-supersession-threat'
(set-visited-file-modtime)
;; Kill buffer contents and insert from associated file.
(widen)
(kill-region (point-min) (point-max))
(insert-file-contents (buffer-file-name))
;; Mark buffer as unmodified.
(set-buffer-modified-p nil))))))
(defadvice ask-user-about-supersession-threat
(around my-supersession-revert-buffer)
"Use my-revert-buffer in place of revert-buffer."
(let ((real-revert-buffer (symbol-function 'revert-buffer)))
(fset 'revert-buffer 'my-revert-buffer)
;; Note that `ask-user-about-supersession-threat' calls
;; (signal 'file-supersession ...), so we need to handle
;; the error in order to restore revert-buffer.
(unwind-protect
ad-do-it
(fset 'revert-buffer real-revert-buffer))))
(ad-activate 'ask-user-about-supersession-threat)
Annoyingly, I've only just noticed all the relevant-looking information in the revert-buffer docs, so there's probably a much simpler way to do this.
If the value of revert-buffer-function is non-nil, it is called to
do all the work for this command. Otherwise, the hooks
before-revert-hook and after-revert-hook are run at the beginning
and the end, and if revert-buffer-insert-file-contents-function is
non-nil, it is called instead of rereading visited file contents.

Is there any way to have Emacs save your undo history between sessions?

Is there any way to have EMACS save your undo history between sessions?
I'm aware of the savehist lib, the saveplace lib, the desktop lib, and the windows lib, these all provide some session control but none seem to save the undo history.
From version 0.4 onwards, undo-tree supports persistent storage of undo-tree data between sessions "out of the box". (Note that there are significant bug-fixes related to this feature in more recent versions; the latest version at the time of writing is 0.6.3.)
Simply enable the undo-tree-auto-save-history customization option to automatically save and load undo history in undo-tree buffers. Or use the undo-tree-save/load-history commands to save and load undo history manually.
You need at least Emacs version 24.3 for this to work reliably, but with a recent enough Emacs it works very well.
Add the following to your .emacs file :
(global-undo-tree-mode)
(setq undo-tree-auto-save-history t)
(setq undo-tree-history-directory-alist '(("." . "~/.emacs.d/undo")))
Explanation
(global-undo-tree-mode) enables undo tree.
(setq undo-tree-auto-save-history t) enables auto save of undo history.
(setq undo-tree-history-directory-alist '(("." . "~/.emacs.d/undo"))) so that your project does not get littered with undo-history savefiles.
Here's some code I wrote which seems to do the trick. It isn't bullet-proof, as in, it doesn't handle all the file handling intricacies that Emacs does (e.g. overriding where auto-save files are put, symlink handling, etc.). But, it seemed to do the trick for some simple text files I manipulated.
(defun save-undo-filename (orig-name)
"given a filename return the file name in which to save the undo list"
(concat (file-name-directory orig-name)
"."
(file-name-nondirectory orig-name)
".undo"))
(defun save-undo-list ()
"Save the undo list to a file"
(save-excursion
(ignore-errors
(let ((undo-to-save `(setq buffer-undo-list ',buffer-undo-list))
(undo-file-name (save-undo-filename (buffer-file-name))))
(find-file undo-file-name)
(erase-buffer)
(let (print-level
print-length)
(print undo-to-save (current-buffer)))
(let ((write-file-hooks (remove 'save-undo-list write-file-hooks)))
(save-buffer))
(kill-buffer))))
nil)
(defvar handling-undo-saving nil)
(defun load-undo-list ()
"load the undo list if appropriate"
(ignore-errors
(when (and
(not handling-undo-saving)
(null buffer-undo-list)
(file-exists-p (save-undo-filename (buffer-file-name))))
(let* ((handling-undo-saving t)
(undo-buffer-to-eval (find-file-noselect (save-undo-filename (buffer-file-name)))))
(eval (read undo-buffer-to-eval))))))
(add-hook 'write-file-hooks 'save-undo-list)
(add-hook 'find-file-hook 'load-undo-list)
desktop-save-mode does not save buffer-undo-list by default. You just have to tell him!
(add-to-list 'desktop-locals-to-save 'buffer-undo-list)
Emacs Session appears to support this:
(add-to-list 'session-locals-include 'buffer-undo-list)
I have managed to get the undo history working by using the information provided here: http://emacs.stackexchange.com/q/3725/2287
Instead of patching the original file desktop.el.gz I created an advice that temporarily overrides (buffer-local-variables) then I use it together with the function that gathers information about the buffer.
(defun +append-buffer-undo-list-to-buffer-local-variables-advice (orig-fn &rest args)
"Override `buffer-local-variables' and call ORIG-FN with ARGS.
There is a bug in Emacs where the `buffer-undo-list' data is
missing from the output of `buffer-local-variables'. This
advice temporarily overrides the function and appends the
missing data."
(let ((orig-buffer-local-variables-fn (symbol-function 'buffer-local-variables)))
(cl-letf (((symbol-function 'buffer-local-variables)
#'(lambda () (append (funcall orig-buffer-local-variables-fn)
`(,(cons 'buffer-undo-list buffer-undo-list))))))
(apply orig-fn args))))
(advice-add #'desktop-buffer-info :around #'+append-buffer-undo-list-to-buffer-local-variables-advice)
(push 'buffer-undo-list desktop-locals-to-save)
(desktop-save-mode 1)
I hope this helps someone else.

How do I change read/write mode for a file using Emacs?

If a file is set to read only mode, how do I change it to write mode and vice versa from within Emacs?
M-x read-only-mode
in very old versions of Emacs, the command was:
M-x toggle-read-only
On my Windows box, that amounts to Alt-x to bring up the meta prompt and typing "read-only-mode" to call the correct elisp function.
If you are using the default keyboard bindings,
C-x C-q
(which you read aloud as "Control-X Control-Q") will have the same effect. Remember, however, given that emacs is essentially infinitely re-configurable, your mileage may vary.
Following up from the commentary: you should note that the writeable status of the buffer does not change the writeable permission of the file. If you try to write out to a read only file, you'll see a confirmation message. However, if you own the file, you can write out your changes without changing the permissions on the file.
This is very convenient if you'd like to make a quick change to a file without having to go through the multiple steps of add write permission, write out changes, remove write permission. I tend to forget that last step, leaving potentially critical files open for accidental changes later on.
Be sure you're not confusing 'file' with 'buffer'. You can set buffers to read-only and back again with C-x C-q (toggle-read-only). If you have permission to read, but not write, a file, the buffer you get when you visit the file (C-x C-f or find-file) will be put in read-only mode automatically. If you want to change the permissions on a file in the file system, perhaps start with dired on the directory that contains the file. Documentation for dired can be found in info; C-h i (emacs)dired RET.
What I found is M-x set-file-modes filename mode
It worked at my Windows Vista box.
For example: M-x set-file-modes <RET> ReadOnlyFile.txt <RET> 0666
As mentioned up there by somebody else: M-x toggle-read-only would work.
However, this is now deprecated and M-x read-only-mode is the current way to do it, that it is set to C-x C-q keybinding.
CTRL + X + CTRL + Q
If only the buffer (and not the file) is read-only, you can use toggle-read-only, which is usually bound to C-x C-q.
If the file itself is read-only, however, you may find the following function useful:
(defun set-buffer-file-writable ()
"Make the file shown in the current buffer writable.
Make the buffer writable as well."
(interactive)
(unix-output "chmod" "+w" (buffer-file-name))
(toggle-read-only nil)
(message (trim-right '(?\n) (unix-output "ls" "-l" (buffer-file-name)))))
The function depends on unix-output and trim-right:
(defun unix-output (command &rest args)
"Run a unix command and, if it returns 0, return the output as a string.
Otherwise, signal an error. The error message is the first line of the output."
(let ((output-buffer (generate-new-buffer "*stdout*")))
(unwind-protect
(let ((return-value (apply 'call-process command nil
output-buffer nil args)))
(set-buffer output-buffer)
(save-excursion
(unless (= return-value 0)
(goto-char (point-min))
(end-of-line)
(if (= (point-min) (point))
(error "Command failed: %s%s" command
(with-output-to-string
(dolist (arg args)
(princ " ")
(princ arg))))
(error "%s" (buffer-substring-no-properties (point-min)
(point)))))
(buffer-substring-no-properties (point-min) (point-max))))
(kill-buffer output-buffer))))
(defun trim-right (bag string &optional start end)
(setq bag (if (eq bag t) '(?\ ?\n ?\t ?\v ?\r ?\f) bag)
start (or start 0)
end (or end (length string)))
(while (and (> end 0)
(member (aref string (1- end)) bag))
(decf end))
(substring string start end))
Place the functions in your ~/.emacs.el, evaluate them (or restart emacs). You can then make the file in the current buffer writable with M-x set-buffer-file-writable.
If you are looking at a directory of files (dired), then you can use Shift + M on a filename and enter the modespec, the same attributes used in the chmod command.
M modespec <RET>
See the other useful commands on files in a directory listing at
http://www.gnu.org/s/libtool/manual/emacs/Operating-on-Files.html
I tried out Vebjorn Ljosa's solution, and it turned out that at least in my Emacs (22.3.1) there isn't such function as 'trim-right', which is used for removing an useless newline at the end of chmod output.
Removing the call to 'trim-right' helped, but made the status row "bounce" because of the extra newline.
C-x C-q is useless. Because your also need the permission to save a file.
I use Spacemacs. It gives me a convenient function to solve this question. The code is following.
(defun spacemacs/sudo-edit (&optional arg)
(interactive "p")
(if (or arg (not buffer-file-name))
(find-file (concat "/sudo:root#localhost:" (ido-read-file-name "File: ")))
(find-alternate-file (concat "/sudo:root#localhost:" buffer-file-name))))
I call spacemacs/sudo-edit to open a file in emacs and input my password, I can change the file without read-only mode.
You can write a new function like spacemacs/sudo-edit.

How to get equivalent of Vim's :Texplore in Emacs?

I know about M-x dire, but would like to customize it. I would like to hit one key (for example F2) and get dire buffer open. When I navigate across the directory hierarchy it shouldn't open new buffers.
And when I finally open the file it also shouldn't open new buffer for it (not strictly necessary, but strongly preferred).
Of course this behavior can be global, i.e. for all dire buffers/invocations.
Check out dired-single, which pretty much does what you want (except that last bit, where it reuses the dired buffer for the newly visted file).
Caveat Lector: I wrote it, so I'm biased towards its usefulness.
Some alternatives - EmacsWiki: DiredReuseDirectoryBuffer, and this short snippet from an awkwardly-formatted blog-entry.
caveat: haven't tried them, myself.
I know this is very old but All you have to do is press 'a' on a dir or file to get this functionality. It's already there.
Here's what I finally used:
(require 'dired)
(global-set-key [(f2)] 'my-dired)
(defun my-dired ()
(interactive)
(dired (file-name-directory (buffer-file-name))))
(defadvice dired-advertised-find-file (around dired-subst-directory activate)
"Replace current buffer if file is a directory."
(interactive)
(let ((orig (current-buffer)) (filename (dired-get-filename :no-error-if-not-filep t)))
ad-do-it
(when (not (eq (current-buffer) orig)) (kill-buffer orig))))