Re: save-excursion defeated by set-buffer - what does this mean?

David Engster <[email protected]> Tue, 23 Feb 2010 09:19:33 +0100
Newsgroups gmane.emacs.code-browser
Message-ID <[email protected]>
(Don't know if this is still an issue for you - my first mail was lost due to
the Gmane outage over the weekend.)

Klaus Berndl <[email protected]> writes:
> when byte-compiling ECB with forthcoming Emacs 23.2 then i get myriads of this Warning:
> save-excursion' defeated by set-buffer.
>
> Can anybody tell me what does this mean?

This has been discussed intensely on emacs-devel:

http://thread.gmane.org/gmane.emacs.devel/118710

The main point is this (quoted from Stefan Monnier):

>> save-excursion only saves point in the current buffer, so
>>
>>   (save-excursion (set-buffer foo) (goto-char (point-min)))
>>
>> will move point in foo and the point-saving done by save-excursion is
>> useless.  So either you want to use
>>
>>   (save-current-buffer (set-buffer foo) (goto-char (point-min)))
>> aka
>>   (with-current-buffer foo (goto-char (point-min)))
>>
>> if moving point in foo is what you wanted, or
>>
>>   (with-current-buffer foo (save-excursion (goto-char (point-min))))
>>
>> if you didn't want to move point in foo.

and further:

>> The experience so far is that when replacing
>>
>>   (save-excursion (set-buffer FOO) ...)
>> with
>>   (with-current-buffer FOO ...)
>>
>> either the behavior is unchanged (i.e. the set-buffer makes the
>> point-saving part of save-excursion useless), or a bug shows up which
>> can be fixed with the use of
>>
>>  (with-current-buffer FOO (save-excursion ...))
>>
>> I.e. the original code only worked right when the set-buffer was a noop
>> (which for such code is typically the most common case, obviously,
>> otherwise the bug would have surfaced earlier).

> And maybe how to prevent Emacs from nagging this?

AFAIK you can't, at least not without suppressing other warnings.

-David


------------------------------------------------------------------------------
Download Intel&#174; Parallel Studio Eval
Try the new software tools for yourself. Speed compiling, find bugs
proactively, and fine-tune applications for parallel performance.
See why Intel Parallel Studio got high marks during beta.
http://p.sf.net/sfu/intel-sw-dev