Assume that I am working with a file whose name contains a unique version number for example myfile_03.tex or 03jhcjh.tex and so on. Currently I create a new version of the file by C-x C-w and incrementing the number manually.

To be precise I would like to maintain the number length if possible, i.e. 027 → 028 instead of 28, but 9 → 10.

Is there a function in emacs which automatizes this procedure? Other solutions are welcomed.


The following elisp code should define a function write-file-increment doing what you want, except for the "preserving length" part.

If the file name does not contain a number, it adds "-1". Apart from that case, the position of the number in the filename shouldn't matter.

(defun tv/increment-number-in-file-name (name)
    (insert name)
    (search-backward "." nil t)
    (re-search-backward "[0-9]+" nil t)
    ;(skip-chars-forward "0") ;; Would preserve 0s
    (if (looking-at "[0123456789]+")
        (replace-match (number-to-string (1+ (string-to-number (match-string 0)))))
      (insert "-1"))

(defun write-file-increment ()
  (write-file (tv/increment-number-in-file-name (buffer-file-name))))

Preserving prefixed 0s can be done by uncommenting the commented line, but it would also replace 09 with 010, probably not what you want.

  • I suggest to add (re-search-backward "[0-9]+" nil t) before (skip-chars-backward "0123456789") otherwise 31_file.tex becomes 31_file-1.tex.
    – Name
    Oct 16 '16 at 10:26
  • @Name Indeed that's a possibility. I tend to think this kind of numbering is best placed at the end of the name, for sorting purposes, but one of the examples of the question does have the numbering at the start. Thanks for the fix!
    – T. Verron
    Oct 16 '16 at 11:53
  • Btw aaa31bbb22.txt will still become aaa31bbb23.txt, there's not much I can suggest short of creating an ad-hoc function for this usecase if you want to increment 31 instead.
    – T. Verron
    Oct 16 '16 at 12:11
  • In my question, I have assumed that there is a unique identifiable number in the file name. Sorry if I have worded it badly.
    – Name
    Oct 16 '16 at 12:22
  • hi. i get this error when i try to run the function progn: Search failed: "."Invalid face reference: quote. any clue? also can one also stick current date in the generated file name?
    – zeltak
    Oct 17 '16 at 10:19

C-x C-f <your directory> wdired-change-to-wdired-mode query-replace-regexp

Using query-replace-regexp with \# should do.

  • 1
    Your answer would be clearer if you elaborated a bit, such as showing a step-by-step example, addressing the example(s) used in the question.
    – Drew
    Oct 16 '16 at 14:28

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.