« ^ »

Emacsで既存のバッファを避けて現時点で新しく使用可能と思われるバッファ名を返す

所要時間: 約 2分

同じような実装はどこかにありそうだが、探すのが面倒だったので実装した。

get-new-buffer-name.el
;;; get-new-buffer-name --- Find non-conflicting buffer names. -*- lexical-binding: t -*-

;; Copyright (C) 2023 TakesxiSximada

;; Author: TakesxiSximada
;; Maintainer: TakesxiSximada
;; Version: 1
;; Package-Version: 20231008.0000
;; Package-Requires: ((emacs "29.1") (dotenv))
;; Date: 2023-10-08

;; This file is part of get-new-buffer-name.

;; This software is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Affero General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.

;; This software is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;; Affero General Public License for more details.

;; You should have received a copy of the GNU Affero General Public
;; License along with this program.  If not, see
;; <https://www.gnu.org/licenses/>.

;;; Code:

(defun get-new-buffer-name (prefix &optional number)
  "既存のバッファを避けて現時点で新しく使用可能と思われるバッファ名を返す。

=prefix= に =number= を付与した文字列を作成し、その文字列と同じバッファ名を持つ
バッファが存在するかを調べる。バッファが存在しない場合、そのバッファ名は使用可能
と判断しその文字列を返す。バッファが存在する場合、そのバッファ名は使用中と判断し、
numberをインクリメントして関数を再帰呼び出しする。ただし無限に探索する訳にもいか
ないので、上限を30とする。"
  (let ((num (or number 0)))
    (if (> num 30)
	;; これはリテラルにしない方が良いかもしれないが、現時点でこれを変更したい
	;; ニーズはないためリテラルとする。
	(error "too many buffer")
      (let* ((buffer-name-candidate (format "%s:%d" prefix num)))
	(if (not (get-buffer buffer-name-candidate))
	    buffer-name-candidate
	  (get-new-buffer-name prefix (+ num 1)))))))

(provide 'get-new-buffer-name)
;;; get-new-buffer-name.el ends here

get-new-buffer-name.el