GNU bug report logs - #48294
Use 'with-current-buffer' byte-compiler warning seems wrong

Previous Next

Package: emacs;

Reported by: rswgnu <at> gmail.com

Date: Sat, 8 May 2021 20:15:01 UTC

Severity: normal

Tags: notabug

Done: Lars Ingebrigtsen <larsi <at> gnus.org>

Bug is archived. No further changes may be made.

Full log


Message #8 received at 48294 <at> debbugs.gnu.org (full text, mbox):

From: Eli Zaretskii <eliz <at> gnu.org>
To: rswgnu <at> gmail.com
Cc: 48294 <at> debbugs.gnu.org
Subject: Re: bug#48294: Use 'with-current-buffer' byte-compiler warning seems
 wrong
Date: Sun, 09 May 2021 11:05:47 +0300
tags 48294 notabug
thanks

> From: Robert Weiner <rsw <at> gnu.org>
> Date: Sat, 8 May 2021 16:14:09 -0400
> 
> I get a lot of these byte-compile warnings in my Elisp code:
> 
> hbut.el:683:26:Warning: Use ‘with-current-buffer’ rather than
>     save-excursion+set-buffer
> 
> but since with-current-buffer does not save the value of point, it is
> not a valid substitute for save-excursion and should not be suggested.
> Evaluate the two samples below and you will see that they are not
> equivalent.  If I am correct, I'd like this suggestion disabled.  Thanks.  -- rsw
> 
> (save-excursion
>   (set-buffer (current-buffer))
>   (forward-char 20))
> 
> (with-current-buffer (current-buffer)
>   (forward-char 20))

The ELisp manual says about this:

     Because ‘save-excursion’ only saves point for the buffer that was
  current at the start of the excursion, any changes made to point in
  other buffers, during the excursion, will remain in effect afterward.
  This frequently leads to unintended consequences, so the byte compiler
  warns if you call ‘set-buffer’ during an excursion:

       Warning: Use ‘with-current-buffer’ rather than
		save-excursion+set-buffer

  To avoid such problems, you should call ‘save-excursion’ only after
  setting the desired current buffer, as in the following example:

       (defun append-string-to-buffer (string buffer)
	 "Append STRING to the end of BUFFER."
	 (with-current-buffer buffer
	   (save-excursion
	     (goto-char (point-max))
	     (insert string))))

I believe this example shows how to solve your problem.




This bug report was last modified 4 years and 70 days ago.

Previous Next


GNU bug tracking system
Copyright (C) 1999 Darren O. Benham, 1997,2003 nCipher Corporation Ltd, 1994-97 Ian Jackson.