0

Suppose I create a file in dir1/file1.txt. As soon as I write the file for the first time, I want to create another file in dir2/file1_friend.txt. But when I create a file dir1/file2.txt, I want the new file created be dir2/file2_friend.txt.

0

You can use a before-save-hook for this. Note this runs on every buffer save, so we have some checks to make sure we have a buffer file name, that it ends with the right string, and that your new file doesn't already exist. then, if all that is ok, we make the file.

(require 'f)
(require 's)

(defun custom-save ()
  (let ((bf (buffer-file-name))
        (bff "my_file_abc_friend.txt"))
    (when (and bf
           (s-ends-with? "dir1/my_file_abc.txt" bf)
           (not (file-exists-p bff)))
      ;; I think this means you are in dir1 so we can just make the desired file      
      (with-temp-file bff
    ;; add contents here if you want
    ))))

(add-hook 'before-save-hook 'custom-save)
| improve this answer | |
  • The point of "abc" was that if the file that is originally saved is "gfh", then the other file should be gfh_friend etc. – Prikshet Sharma Feb 15 at 20:34
  • 1
    you probably have to be a lot more specific about your regex, or you will get _friend.txt files for every kind of text file. What is the real pattern you are looking for? Is it just dir1/*.txt? – John Kitchin Feb 15 at 20:39
0

Here the "need a friend" suffix is _blah.txt.You'd probably want to make it a defvar and maybe include some directory path. But .... it works.

  (defun friend-file-root-name(f)
    (string-match  "\\(.*\\)\\(_blah.txt\\)" f)
    (match-string 1 f)
    )

  (defun custom-save-create-friend-file ()
    (message "in custom save")
    (when (friend-file-root-name (buffer-file-name))
      (let ((friend-file (concat (friend-file-root-name (buffer-file-name)) "_friend.txt")))
        (message "potential friend file is: %s" friend-file)
        (unless (file-exists-p friend-file)
          (with-temp-file friend-file
            (message "need to create %s" friend-file)
            (save-buffer)
            )))))

  (add-hook 'after-save-hook 'custom-save-create-friend-file)
| improve this answer | |
  • Would you please explain how to use this code? – Prikshet Sharma Feb 16 at 20:55
  • The custom save hook looks to match a "spec" for your - file see the (string-match ..) call. Then if there is a match it replaces the "_blah.txt" with "friend.txt" and creates that file if it doesnt already exist. You should be able to work from that and change accordingly. – RichieHH Feb 16 at 21:39

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.