[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: safe way to add contents to a file ?
From: |
Óscar Fuentes |
Subject: |
Re: safe way to add contents to a file ? |
Date: |
Sun, 22 Dec 2019 15:37:32 +0100 |
User-agent: |
Gnus/5.13 (Gnus v5.13) Emacs/27.0.50 (gnu/linux) |
Jean-Christophe Helary <jean.christophe.helary@traduction-libre.org>
writes:
> Here is my latest version...
>
>
> (defun myInsert4 (myText myMarker myFile)
> (save-current-buffer
> (set-buffer (find-file-noselect myFile))
> (goto-char (point-min))
> (if (not (search-forward myMarker nil t))
> (progn
> (user-error (format "%s was not found" myMarker))
> (kill-buffer))
> (progn
> (goto-char (point-min))
> (goto-char (- (search-forward myMarker) (length myMarker)))
> (insert myText)
> (indent-region (point-min) (point-max))
> (save-buffer)))
> (kill-buffer)))
>
> Really not sure if I'm going in the right direction. Plus, for some
> reason, the buffer is not killed even after an error...
`user-error' (which is a variant of `error') stops the execution, so
`kill-buffer' is never executed. Either put `kill-buffer' before
`user-error' or do not use `user-error', like this:
(defun myInsert4 (myText myMarker myFile)
(save-current-buffer (find-file-noselect myFile))
(goto-char (point-min))
(if (not (search-forward myMarker nil t))
(message "%s was not found" myMarker)
(progn
(goto-char (point-min))
(goto-char (- (search-forward myMarker) (length myMarker)))
(insert myText)
(indent-region (point-min) (point-max))
(save-buffer)))
(kill-buffer))
You can also cache the result of `search-forward', thus avoiding
repeating it:
(defun myInsert4 (myText myMarker myFile)
(save-current-buffer (find-file-noselect myFile))
(goto-char (point-min))
(setq p (search-forward myMarker nil t))
(if (not p)
(message "%s was not found" myMarker)
(progn
(goto-char (- p (length myMarker)))
(insert myText)
(indent-region (point-min) (point-max))
(save-buffer)))
(kill-buffer))
A `let' would be nicer than a `setq'. Fixing that is left as an exercise
for the reader.
- safe way to add contents to a file ?, Jean-Christophe Helary, 2019/12/17
- Re: safe way to add contents to a file ?, Óscar Fuentes, 2019/12/17
- Re: safe way to add contents to a file ?, Jean-Christophe Helary, 2019/12/17
- Re: safe way to add contents to a file ?, Jean-Christophe Helary, 2019/12/20
- Re: safe way to add contents to a file ?, Stefan Monnier, 2019/12/20
- Re: safe way to add contents to a file ?, Jean-Christophe Helary, 2019/12/21
- Re: safe way to add contents to a file ?, Jean-Christophe Helary, 2019/12/21
- Re: safe way to add contents to a file ?,
Óscar Fuentes <=
- Re: safe way to add contents to a file ?, Jean-Christophe Helary, 2019/12/22
- Re: safe way to add contents to a file ?, Óscar Fuentes, 2019/12/22
- Re: safe way to add contents to a file ?, Stefan Monnier, 2019/12/22
Re: safe way to add contents to a file ?, Stefan Monnier, 2019/12/17