help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: safe way to add contents to a file ?


From: Stefan Monnier
Subject: Re: safe way to add contents to a file ?
Date: Sun, 22 Dec 2019 13:23:29 -0500
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/27.0.50 (gnu/linux)

> How is it supposed to be shorter ?
[...]
> (defun myInsert2 (myText myMarker myFile)
>   (with-current-buffer
>       (set-buffer (find-file-noselect myFile))

This `set-buffer` is redundant:

    (defun myInsert2 (myText myMarker myFile)
      (with-current-buffer (find-file-noselect myFile)

>>    (goto-char (point-min))
>>    (if (not (search-forward myMarker nil t))
>>        (user-error "Can't find foo bar in your fine file")
>>      (goto-char (match-beginning 0))
>
> But here, the code would go on inserting the text in a position that's not 
> correct, right ?

No (for 2 reasons: the insertion would only in the `else` part of the
`if` and the `user-error` immediately terminates the execution of this 
function).

> And if I put the kill-buffer inside the progn, then I'm left with an
>  open buffer that's not relevant anymore...

Cleanup code like this `kill-buffer` should be placed in an
`unwind-protect`, so it's executed both for normal exits and for
non-local exits:

    (with-current-buffer (find-file-noselect myFile)
      (unwind-protect
          (progn
            ... do the insertion and stuff)
        (kill-buffer)))

Tho I'd change that code to pass the buffer explicitly to `kill-buffer`,
just to make sure there's no risk of killing some unrelated buffer in
fringe circumstances:

    (with-current-buffer (find-file-noselect myFile)
      (let ((buf (current-buffer)))
        (unwind-protect
            (progn
              ... do the insertion and stuff)
          (kill-buffer buf))))


-- Stefan




reply via email to

[Prev in Thread] Current Thread [Next in Thread]