[Top][All Lists]

[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: Fri, 20 Dec 2019 11:00:40 -0500
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/27.0.50 (gnu/linux)

> (setq myText "<item>bla</item>")
> (setq myMarker "<!-- place new items before this comment -->")
> (setq myFile "/path/to/test.xml")

Being at top-level these aren't just setting the vars but defining them,
so should use `defvar` or `defconst`.

> (defun myInsert (myText myMarker myFile)
>   (save-current-buffer
>     (set-buffer (find-file-noselect myFile))

`with-current-buffer` does the same, but shorter ;-)

>     (goto-char (point-min))
>     (goto-char (- (search-forward myMarker) (length myMarker)))

If the search fails, this will signal a "low-level" error, and it's
often useful to replace it with some other behavior (e.g. an error
message which the user is more likely to understand, or some other
behavior), so it's more idiomatic to do something like:

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

> Are there things I can do to make that code more idiomatic?

Can't think of anything else.


reply via email to

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