Function: add-name-to-file

add-name-to-file is an interactive function defined in fileio.c.

Signature

(add-name-to-file FILE NEWNAME &optional OK-IF-ALREADY-EXISTS)

Documentation

Give FILE additional name NEWNAME. Both args must be strings.

If NEWNAME is a directory name, give FILE a like-named new name under NEWNAME.

Signal a file-already-exists error if a file NEWNAME already exists unless optional third argument OK-IF-ALREADY-EXISTS is non-nil. An integer third arg means request confirmation if NEWNAME already exists. This is what happens in interactive use with M-x.

Other relevant functions are documented in the file group.

Probably introduced at or before Emacs version 18.

Key Bindings

Shortdoc

;; file
(add-name-to-file "/tmp/foo" "/tmp/bar")

Source Code

// Defined in /usr/src/emacs/src/fileio.c
{
  Lisp_Object handler;
  Lisp_Object encoded_file, encoded_newname;

  file = Fexpand_file_name (file, Qnil);
  newname = expand_cp_target (file, newname);

  /* If the file name has special constructs in it,
     call the corresponding file name handler.  */
  handler = Ffind_file_name_handler (file, Qadd_name_to_file);
  if (!NILP (handler))
    return call4 (handler, Qadd_name_to_file, file,
		  newname, ok_if_already_exists);

  /* If the new name has special constructs in it,
     call the corresponding file name handler.  */
  handler = Ffind_file_name_handler (newname, Qadd_name_to_file);
  if (!NILP (handler))
    return call4 (handler, Qadd_name_to_file, file,
		  newname, ok_if_already_exists);

  encoded_file = ENCODE_FILE (file);
  encoded_newname = ENCODE_FILE (newname);

  if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
    return Qnil;

  if (errno == EEXIST)
    {
      if (NILP (ok_if_already_exists)
	  || FIXNUMP (ok_if_already_exists))
	barf_or_query_if_file_exists (newname, true, "make it a new name",
				      FIXNUMP (ok_if_already_exists), false);
      unlink (SSDATA (newname));
      if (link (SSDATA (encoded_file), SSDATA (encoded_newname)) == 0)
	return Qnil;
    }

  report_file_error ("Adding new name", list2 (file, newname));
}