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?

Drew
  • 75,699
  • 9
  • 109
  • 225
Ugur
  • 139
  • 1
  • 6

2 Answers2

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.

Drew
  • 75,699
  • 9
  • 109
  • 225
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")
Ugur
  • 139
  • 1
  • 6