Function: generate-new-buffer-name

generate-new-buffer-name is a function defined in buffer.c.

Signature

(generate-new-buffer-name NAME &optional IGNORE)

Documentation

Return a string that is the name of no existing buffer based on NAME.

If there is no live buffer named NAME, then return NAME. Otherwise modify name by appending <NUMBER>, incrementing NUMBER
(starting at 2) until an unused name is found, and then return that name.
Optional second argument IGNORE specifies a name that is okay to use (if it is in the sequence to be tried) even if a buffer with that name exists.

If NAME begins with a space (i.e., a buffer that is not normally visible to users), then if buffer NAME already exists a random number is first appended to NAME, to speed up finding a non-existent buffer.

View in manual

Source Code

// Defined in /usr/src/emacs/src/buffer.c
{
  Lisp_Object genbase;

  CHECK_STRING (name);

  if ((!NILP (ignore) && !NILP (Fstring_equal (name, ignore)))
      || NILP (Fget_buffer (name)))
    return name;

  if (SREF (name, 0) != ' ') /* See bug#1229.  */
    genbase = name;
  else
    {
      enum { bug_57211 = true };  /* https://bugs.gnu.org/57211 */
      char number[bug_57211 ? INT_BUFSIZE_BOUND (int) + 1 : sizeof "-999999"];
      EMACS_INT r = get_random ();
      eassume (0 <= r);
      int i = r % 1000000;
      AUTO_STRING_WITH_LEN (lnumber, number, sprintf (number, "-%d", i));
      genbase = concat2 (name, lnumber);
      if (NILP (Fget_buffer (genbase)))
	return genbase;
    }

  for (ptrdiff_t count = 2; ; count++)
    {
      char number[INT_BUFSIZE_BOUND (ptrdiff_t) + sizeof "<>"];
      AUTO_STRING_WITH_LEN (lnumber, number,
			    sprintf (number, "<%"pD"d>", count));
      Lisp_Object gentemp = concat2 (genbase, lnumber);
      if (!NILP (Fstring_equal (gentemp, ignore))
	  || NILP (Fget_buffer (gentemp)))
	return gentemp;
    }
}