diff --git a/lisp/files.el b/lisp/files.el index 62e1702fdf..18a54b3ec7 100644 --- a/lisp/files.el +++ b/lisp/files.el @@ -4889,6 +4889,20 @@ extension, the value is \"\"." (if period ""))))) +(defun file-name-set-extension (filename extension) + "Change the extension of a FILENAME to EXTENSION. +Sanitizes the input to consolidate leading/trailing dots. + +Returns `nil' if either of the FILENAME or EXTENSION are `nil' +before sanitizing, or empty afterwards." + (when (and filename extension) + (let* ((patt "[ \t\n\r.]+") ; Inspired by `string-trim'. + (filename (string-trim-right filename patt)) + (extension (string-trim-left extension patt))) + (unless (or (string-empty-p filename) + (string-empty-p extension)) + (concat (file-name-sans-extension filename) "." extension))))) + (defun file-name-base (&optional filename) "Return the base name of the FILENAME: no directory, no extension." (declare (advertised-calling-convention (filename) "27.1"))