I have written a function that extracts a portion of text from current file and writes it in another one:

(defun foobar ()

  ;; re-search "beg" point
  ;; re-search "end" point

  ;; define markers
  (let* ((beg (copy-marker ...))
         (end (copy-marker ...)))

    (write-region beg end filename t)))

Now I would like that all the text between beg and end is added at the beginning of filename. How can I do this?

1 Answer 1


The doc string of write-region says:

Optional fourth argument APPEND if non-nil means append to existing file contents (if any). If it is a number, seek to that offset in the file before writing.

So call it like this:

(write-region beg end filename 0)

but as you found out that overwrites the beginning of the file with the contents of the region. To insert the contents of the region, you can do something like this:

   (let ((s (buffer-substring beg end)))
    (with-current-buffer (find-file-noselect filename)
      (goto-char (point-min))
      (insert s)
  • @NiclD I had not understand the meaning of "seek to that offset" in the doc string of write-region. However, with your code, whole contents of filename is replace by all text between beg and end. I need that whole original contents of filename is preserved. Dec 7, 2020 at 16:48
  • Try it now and let me know if there are any problems - thanks!
    – NickD
    Dec 7, 2020 at 18:12
  • Ok, now it works! Thank you very much! Dec 7, 2020 at 18:56
  • 1
    (point-min) is 1, not 0 (though 0, -1 etc works the same as 1 since goto-char does not check bounds), or simply use (goto-char (point-min)).
    – xuchunyang
    Dec 7, 2020 at 19:34
  • Thanks! Corrected it.
    – NickD
    Dec 7, 2020 at 20:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.