Emacs: fix 'changed on disk'/'Reread from disk' when file has not changed [duplicate] - emacs

How to disable Emacs from checking the buffer file was changed outside the editor?

Emacs is really trying to help you here. Read the info page on Protection against Simultaneous Editing.
But, if you still want to avoid that message/prompt, you can redefine the function that is doing the prompting:
(defun ask-user-about-supersession-threat (fn)
"blatantly ignore files that changed on disk"
)
(defun ask-user-about-lock (file opponent)
"always grab lock"
t)
The second function there is for when two people are using Emacs to edit the same file, and would provide a similar prompt (but not the one you seemed to refer to in the question).
I'd advise against overriding the two routines, but it's there if you want.
On the off chance global-auto-revert-mode is on, you could disable that. Add this to your .emacs:
(global-auto-revert-mode -1)
You can tell if the mode is on by looking at the variable of the same name:
C-h v global-auto-revert-mode RET
If the value is t, then the mode is on, otherwise it is off.

I have the following in my .emacs. It makes Emacs only ask about really changed files. If a file remains the same bytewise, just its timestamp is updated, as often happens when you switch branches in VCS, this "change" is ignored by Emacs.
;; Ignore modification-time-only changes in files, i.e. ones that
;; don't really change the contents. This happens often with
;; switching between different VC buffers.
(defun update-buffer-modtime-if-byte-identical ()
(let* ((size (buffer-size))
(byte-size (position-bytes size))
(filename buffer-file-name))
(when (and byte-size (<= size 1000000))
(let* ((attributes (file-attributes filename))
(file-size (nth 7 attributes)))
(when (and file-size
(= file-size byte-size)
(string= (buffer-substring-no-properties 1 (1+ size))
(with-temp-buffer
(insert-file-contents filename)
(buffer-string))))
(set-visited-file-modtime (nth 5 attributes))
t)))))
(defun verify-visited-file-modtime--ignore-byte-identical (original &optional buffer)
(or (funcall original buffer)
(with-current-buffer buffer
(update-buffer-modtime-if-byte-identical))))
(advice-add 'verify-visited-file-modtime :around #'verify-visited-file-modtime--ignore-byte-identical)
(defun ask-user-about-supersession-threat--ignore-byte-identical (original &rest arguments)
(unless (update-buffer-modtime-if-byte-identical)
(apply original arguments)))
(advice-add 'ask-user-about-supersession-threat :around #'ask-user-about-supersession-threat--ignore-byte-identical)

In my case I wanted:
(setq revert-without-query '(".*"))
Documentation for revert-without-query:
Specify which files should be reverted without query.
The value is a list of regular expressions.
If the file name matches one of these regular expressions,
then ‘revert-buffer’ reverts the file without querying
if the file has changed on disk and you have not edited the buffer.

I had annoyance with this because every time I switched branches in git, emacs thought all my files had changed.
Revbuffs helps you cope with the symptoms of this. It allows you to cause all your buffers to be reloaded.
You can also try (global-auto-revert-mode) which will automatically revert your files to what's on disk.

Related

How to make `C-x b RET` switch to previous buffer even if it's already shown in another frame?

Edit: What the poster calls a "window", Emacs calls a "frame". I fixed the title.
Concisely, the question is: in a window, how do I switch quickly to a buffer previously visited in that window, even if it's already opened in another window?
A more detailed description follows.
Normally, in order to switch window to previous buffer one just types C-x b RET. That is, the default argument to switch-to-buffer (or ido-switch-buffer) is the previous buffer.
This is not, however, the case when that (previous) buffer is already shown in another window. That's exactly what bugs me.
Let's consider an example. Suppose I have three buffers (A, B and C) and two windows showing buffers A and B (C is not visible at this point).
Then I open buffer A in the second window, too. So, now I have buffer A shown in both windows. Then I switch (C-x b RET) to B again. After that, C-x b RET will bring me not to A, but to C because A is already shown in the other window.
How do I make C-x b RET behave more consistently?
Update
After this problem had been solved, I realized I needed more: namely, for point position to be remembered per-window, not per buffer. Luckily, there're ready-made solutions:
winpoint
per-window-point
They're quite similar; for a discussion of differences see here.
I've found a fix for switch-to-buffer. It eventually calls
(other-buffer (current-buffer))
while in order to fix your problem, the call needs to look like this:
(other-buffer (current-buffer) t)
i.e. the visible-ok argument needs to be t.
Here's an advice to have it always at t. Hopefully it won't break other stuff that uses other-buffer:
(defadvice other-buffer (around fix-switch-to-buffer
(&optional buffer visible-ok frame) activate)
(setq visible-ok t)
ad-do-it)
Note that ido-switch-to-buffer uses a different machinery, so a different method is needed to fix it.
update: fix for ido-switch-to-buffer
I needed to re-define ido-make-buffer-list:
(defun ido-make-buffer-list (default)
(let* ((ido-current-buffers (list (buffer-name (current-buffer))))
(ido-temp-list (ido-make-buffer-list-1 (selected-frame) ido-current-buffers)))
(if ido-temp-list
(nconc ido-temp-list ido-current-buffers)
(setq ido-temp-list ido-current-buffers))
(if default
(setq ido-temp-list
(cons default (delete default ido-temp-list))))
(if (bound-and-true-p ido-enable-virtual-buffers)
(ido-add-virtual-buffers-to-list))
(run-hooks 'ido-make-buffer-list-hook)
ido-temp-list))
The diff is just one line, but it's too messy to advice it.
update: use new advice system for other-buffer
The old stuff should still work for quite a while, but here's the new approach:
(defun other-buffer-advice (orig-fun &optional buffer visible-ok frame)
(funcall orig-fun buffer t frame))
(advice-add 'other-buffer :around #'other-buffer-advice)
;; (advice-remove 'other-buffer :around #'other-buffer-advice)
Instead of advising the built-in function other-buffer, you can pre-select visible buffers using a package.
1 Using Ivy
If you're using Ivy, you can use abo-abo's approach to override the lower-use function ivy-switch-buffer.
(defun user/ivy-switch-buffer ()
"Switch to another buffer with visible-ok preselection."
(interactive)
(ivy-read "Switch to buffer: " #'internal-complete-buffer
:keymap ivy-switch-buffer-map
:preselect (buffer-name (other-buffer (current-buffer) t))
:action #'ivy--switch-buffer-action
:matcher #'ivy--switch-buffer-matcher
:caller 'ivy-switch-buffer))
(advice-add 'ivy-switch-buffer :override #'user/ivy-switch-buffer)
2 Using Ido mode
2.1 Switching to a buffer shown in another frame
If by "window" you really mean "frame" (i.e., you'd like to ido-switch-buffer to a buffer that is currently shown in another frame), then ido-mode gives you the behavior you're looking for when you change ido-default-buffer-method from its default value of raise-frame to selected-window:
(setq ido-default-buffer-method 'selected-window)
Emacs constructs an independent buffer list for each frame, so the only thing you have to do is to configure Ido to avoid jumping to another frame when you switch buffers.
2.2 Switching to a buffer that is shown in another window inside the same frame
To get this behavior across windows within the same frame, you should hook a function that reorders the buffer list onto ido-make-buffer-list-hook.
From ido.el:
;; Changing the list of files
;; --------------------------
;; By default, the list of current files is most recent first,
;; oldest last, with the exception that the files visible in the
;; current frame are put at the end of the list. A hook exists to
;; allow other functions to order the list. For example, if you add:
;;
;; (add-hook 'ido-make-buffer-list-hook 'ido-summary-buffers-to-end)
;;
;; then all files matching "Summary" are moved to the end of the
;; list. (I find this handy for keeping the INBOX Summary and so on
;; out of the way.) It also moves files matching "output\*$" to the
;; end of the list (these are created by AUCTeX when compiling.)
;; Other functions could be made available which alter the list of
;; matching files (either deleting or rearranging elements.)

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.

How to automatically save files on lose focus in Emacs

Is it possible to configure Emacs, so that it saves all files when the emacs window loses
focus?
I added focus hooks to Gnu Emacs 24.4.
They are called focus-in-hook and focus-out-hook.
You can add
(defun save-all ()
(interactive)
(save-some-buffers t))
(add-hook 'focus-out-hook 'save-all)
to your .emacs file and it should save all files on loss of focus.
I use this, it will only work if emacs is running under X (like it probably would in something like ubuntu).
(when
(and (featurep 'x) window-system)
(defvar on-blur--saved-window-id 0 "Last known focused window.")
(defvar on-blur--timer nil "Timer refreshing known focused window.")
(defun on-blur--refresh ()
"Runs on-blur-hook if emacs has lost focus."
(let* ((active-window (x-window-property
"_NET_ACTIVE_WINDOW" nil "WINDOW" 0 nil t))
(active-window-id (if (numberp active-window)
active-window
(string-to-number
(format "%x00%x"
(car active-window)
(cdr active-window)) 16)))
(emacs-window-id (string-to-number
(frame-parameter nil 'outer-window-id))))
(when (and
(= emacs-window-id on-blur--saved-window-id)
(not (= active-window-id on-blur--saved-window-id)))
(run-hooks 'on-blur-hook))
(setq on-blur--saved-window-id active-window-id)
(run-with-timer 1 nil 'on-blur--refresh)))
(add-hook 'on-blur-hook #'(lambda () (save-some-buffers t)))
(on-blur--refresh))
Not sure if this is what you want.
(defun dld-deselect-frame-hook ()
(save-some-buffers 1))
(add-hook 'deselect-frame-hook 'dld-deselect-frame-hook)
From: http://www.dribin.org/dave/blog/archives/2003/09/10/emacs/
EDIT: It only seems to work in XEmacs
[…] the feature I am talking about is from
Scribes. It is very convient when
editing html and the like, you don't
have to press C-x C-s anymore, you
just change the window and check your
browser.
In that case, instead of switching to the browser application, order Emacs to load the browser application (C-c C-v or M-x browse-url-of-buffer). With this method, you can write your own function that saves the buffer and then brings the browser up, like:
(defun my-browse-url-of-buffer ()
"Save current buffer and view its content in browser."
(interactive)
(save-buffer)
(browse-url-of-buffer))
And hook it to a convenient binding.
Or you can still use the html-autoview-mode that each time you saves the buffer, automatically loads the file into your favorite browser.
You can use `auto-save-interval' to save every n characters you type. Mine is set to 100. So about every 2-3 lines of code, maybe?
auto-save-interval is a variable
defined in `C source code'. Its value
is 100
Documentation:
*Number of input events between auto-saves. Zero means disable
autosaving due to number of characters
typed.
You can customize this variable.
This doesn't answer your original question; it's just a way to achieve something similar.

Emacs: reopen buffers from last session on startup?

Every day I start up emacs and open the exact same files I had open the day before. Is there something I can add to init.el file so it will reopen all the buffers I was using when I last quit emacs?
You can use the Emacs Desktop library:
You can save the desktop manually with
the command M-x desktop-save. You can
also enable automatic saving of the
desktop when you exit Emacs, and
automatic restoration of the last
saved desktop when Emacs starts: use
the Customization buffer (see Easy
Customization) to set
desktop-save-mode to t for future
sessions, or add this line in your
~/.emacs file:
(desktop-save-mode 1)
Although I suspect the question was looking for the emacs "desktop" functionality (see above answer), Lewap's approach can be useful if the set of files one uses really is the exact same file set. In fact, one can go a step further and define 'profiles' if one has different sets of regularly used files... Quickie example:
(let ((profile
(read-from-minibuffer "Choose a profile (acad,dist,lisp,comp,rpg): ")
))
(cond
((string-match "acad" profile)
(dired "/home/thomp/acad")
(dired "/home/thomp/acad/papers")
)
((string-match "lisp" profile)
(setup-slime)
(lisp-miscellany)
(open-lisp-dirs)
)
((string-match "rpg" profile)
(find-file "/home/thomp/comp/lisp/rp-geneval/README")
(dired "/home/thomp/comp/lisp/rp-geneval/rp-geneval")
... etc.
If you find that you regularly switch back and forth between different sets of regularly-used files as you work, consider using perspectives and populating each perspective with the desired set of regularly-used files.
For storing/restoring the buffers/tabs (specifically elscreen tabs): I use elscreen and the way I manage storing/restoring the desktop session and the elscreen tab configuration is the following code in my .emacs file (the names used are self-explanatory and if the storing/restoring functions should not be executed every time emacs starts just comment out the lines with "(push #'elscreen-store kill-emacs-hook)" and "(elscreen-restore)"):
(defvar emacs-configuration-directory
"~/.emacs.d/"
"The directory where the emacs configuration files are stored.")
(defvar elscreen-tab-configuration-store-filename
(concat emacs-configuration-directory ".elscreen")
"The file where the elscreen tab configuration is stored.")
(defun elscreen-store ()
"Store the elscreen tab configuration."
(interactive)
(if (desktop-save emacs-configuration-directory)
(with-temp-file elscreen-tab-configuration-store-filename
(insert (prin1-to-string (elscreen-get-screen-to-name-alist))))))
(push #'elscreen-store kill-emacs-hook)
(defun elscreen-restore ()
"Restore the elscreen tab configuration."
(interactive)
(if (desktop-read)
(let ((screens (reverse
(read
(with-temp-buffer
(insert-file-contents elscreen-tab-configuration-store-filename)
(buffer-string))))))
(while screens
(setq screen (car (car screens)))
(setq buffers (split-string (cdr (car screens)) ":"))
(if (eq screen 0)
(switch-to-buffer (car buffers))
(elscreen-find-and-goto-by-buffer (car buffers) t t))
(while (cdr buffers)
(switch-to-buffer-other-window (car (cdr buffers)))
(setq buffers (cdr buffers)))
(setq screens (cdr screens))))))
(elscreen-restore)
There are useful enhancements you can make to the basic desktop feature. Particular handy (IMO) are methods of auto-saving the desktop during the session, as otherwise if your system crashes you will be stuck with the desktop file you had started that session with -- pretty annoying if you tend to keep Emacs running for many days at a time.
http://www.emacswiki.org/emacs/DeskTop
The wiki also has useful information about persisting data between sessions in general:
http://www.emacswiki.org/emacs/SessionManagement
For desktops specifically, I thought that Desktop Recover looked particularly promising, however I've not yet tried it out.
(find-file-noselect "/my/file") will open it silently, ie w/o raising the buffer. Just saying.
EDIT This command is not interactive ; To test it you have to evaluate the expression, for example by positioning the cursor after the last parenthesis and hitting C-x C-e
Downvoting this is not cool ; this command definitely works and is in the scope of the question.

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