1

Is there a function that allows to prepend text to a list of files / buffers?

I tried this:

(defun prepend-to-org-files (text)
  (let* ((path "~/Dropbox/org/database")
         (regex "org$")
         (org-files (directory-files-recursively path regex)))
    (dolist (org-file org-files)
      (prepend-to-buffer org-file text))))

But I am missing a function like prepend-to-buffer. Is there something like this?

  • Do you want the text to be added once at the beggining of the buffer? Or in front of every line? – NickD Aug 29 at 16:49
  • Once at the beginning of the buffer. But I think I might have solved it. Please see below. – Ugur Aug 29 at 16:53
  • This is sometimes called a file header. – Drew Aug 29 at 18:10
1

Try library header2.el, or one of the other such solutions described on Emacs Wiki page Automatic File Headers. (They can actually be added automatically or on-demand.)

header2.el lets you define file headers for different types of file (C, shell, Emacs Lisp, and so on). You can automatically insert a header when you open a new file buffer, by putting code like this in your init file:

(add-hook 'emacs-lisp-mode-hook 'auto-make-header)

A header can have parts that are associated with updating functions, so that whenever the file is saved (or some other event occurs), those parts are updated in specific ways. How a given file header looks is under your control.

| improve this answer | |
0

Solved:

;;; ugt / helper functions
(defun prepend-to-file (text fname)
  "Prepend `TEXT' to file `FNAME'"
  (with-temp-buffer
    ;; first: insert `text' into temp buffer
    (insert text)
    ;; next: insert contents of `fname' into temp buffer
    (insert-file-contents fname)
    ;; finally: write whole buffer to `fname'
    (write-region (point-min) (point-max) fname)))

(defun prepend-to-files (text search-in-path &optional file-regex)
  "Prepend `TEXT' to every file in path `SEARCH-FILES-IN-PATH'.
   If `FILE-REGEX' is nil, it will be set to `org$'"
  (let* ((path search-in-path) ;; "~/Dropbox/org/database"
         ;; if `file-regex' is given, then use that, else use "org$"
         (regex (or file-regex "org$"))
         ;; find files recursively
         (file-list
          (directory-files-recursively path regex)))
    ;; iterate over files
    (dolist (filepath file-list)
      (prepend-to-file text filepath))))
                   

Example usage

(prepend-to-files (concat "#+TITLE: " "\n" "#+AUTHOR: Ugur" "\n")
                  "~/dropbox/org/database")
| improve this answer | |

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.