Function: rename-buffer

rename-buffer is an interactive function defined in buffer.c.

Signature

(rename-buffer NEWNAME &optional UNIQUE)

Documentation

Change current buffer's name to NEWNAME (a string).

If second arg UNIQUE is nil or omitted, it is an error if a buffer named NEWNAME already exists. If UNIQUE is non-nil, come up with a new name using generate-new-buffer-name. Interactively, you can set UNIQUE with a prefix argument. We return the name we actually gave the buffer. This does not change the name of the visited file (if any).

View in manual

Probably introduced at or before Emacs version 1.10.

Key Bindings

Source Code

// Defined in /usr/src/emacs/src/buffer.c
{
  register Lisp_Object tem, buf;
  Lisp_Object oldname = BVAR (current_buffer, name);
  Lisp_Object requestedname = newname;

  CHECK_STRING (newname);

  if (SCHARS (newname) == 0)
    error ("Empty string is invalid as a buffer name");

  tem = Fget_buffer (newname);
  if (!NILP (tem))
    {
      /* Don't short-circuit if UNIQUE is t.  That is a useful way to
	 rename the buffer automatically so you can create another
	 with the original name.  It makes UNIQUE equivalent to
	 (rename-buffer (generate-new-buffer-name NEWNAME)).  */
      if (NILP (unique) && XBUFFER (tem) == current_buffer)
	return BVAR (current_buffer, name);
      if (!NILP (unique))
	newname = Fgenerate_new_buffer_name (newname, oldname);
      else
	error ("Buffer name `%s' is in use", SDATA (newname));
    }

  bset_last_name (current_buffer, oldname);
  bset_name (current_buffer, newname);

  /* Catch redisplay's attention.  Unless we do this, the mode lines for
     any windows displaying current_buffer will stay unchanged.  */
  bset_update_mode_line (current_buffer);

  XSETBUFFER (buf, current_buffer);
  Fsetcar (Frassq (buf, Vbuffer_alist), newname);
  if (NILP (BVAR (current_buffer, filename))
      && !NILP (BVAR (current_buffer, auto_save_file_name)))
    call0 (Qrename_auto_save_file);

  run_buffer_list_update_hook (current_buffer);

  call2 (Quniquify__rename_buffer_advice,
         requestedname, unique);

  /* Refetch since that last call may have done GC.  */
  return BVAR (current_buffer, name);
}