2

I am trying to write a function that prints the name of the current buffer to the file in the current buffer in its first line. For example, if the file is called "test.el", when invoking such function, the result should be:

test.el
; rest of file

However, I am stuck with the following non-working function:

(defun my-heading ()
  "Write the name of the present file on the first line."
  (append-to-file (point-min)   ; start: beginning of buffer
                  200           ; end: I don't know when to stop
                  (buffer-name) ; filename
))

Moreover, in the manual page for the function append-to-file, it is written:

Don’t use these functions [append-to-fileand write-region] to write to files that are being visited; that could cause confusion in the mechanisms for visiting.

So, how can I write a function that appends text to the beginning of my current file?

7

The insert function will do what you want. Below is a simple function that takes care of some housekeeping and inserts the buffer's name at the beginning of the buffer:

(defun do-my-thing ()
  "Insert the name of the buffer at the beginning of the buffer."
  (save-excursion
    (save-restriction
      (widen)
      (goto-char (point-min))
      (insert (concat (buffer-name) "\n")))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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