uniquify.el 17.9 KB
Newer Older
Karl Heuer's avatar
Karl Heuer committed
1
;;; uniquify.el --- unique buffer names dependent on file name
Karl Heuer's avatar
Karl Heuer committed
2

3
;; Copyright (c) 1989, 1995, 1996, 1997 Free Software Foundation, Inc.
Karl Heuer's avatar
Karl Heuer committed
4 5

;; Author: Dick King <king@reasoning.com>
6
;; Maintainer: Michael Ernst <mernst@alum.mit.edu>
Karl Heuer's avatar
Karl Heuer committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
;; Created: 15 May 86

;; This file is part of GNU Emacs.

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

;; GNU Emacs 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 General Public License for more details.

;; You should have received a copy of the GNU General Public License
Erik Naggum's avatar
Erik Naggum committed
22 23 24
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
Karl Heuer's avatar
Karl Heuer committed
25 26 27 28 29 30

;;; Commentary:

;; Emacs's standard method for making buffer names unique adds <2>, <3>,
;; etc. to the end of (all but one of) the buffers.  This file replaces
;; that behavior, for buffers visiting files and dired buffers, with a
Karl Heuer's avatar
Karl Heuer committed
31
;; uniquification that adds parts of the file name until the buffer names
Karl Heuer's avatar
Karl Heuer committed
32 33 34 35 36
;; are unique.  For instance, buffers visiting /u/mernst/tmp/Makefile and
;; /usr/projects/zaphod/Makefile would be named Makefile|tmp and
;; Makefile|zaphod, respectively (instead of Makefile and Makefile<2>).
;; Other buffer name styles are also available.

37 38 39
;; To use this file, do (require 'uniquify)
;; and set uniquify-buffer-name-style to one of its non-nil alternative values.

Karl Heuer's avatar
Karl Heuer committed
40 41
;; For other options, see "User-visible variables", below.

42 43
;; A version of uniquify.el that works under Emacs 18, Emacs 19, XEmacs,
;; and InfoDock is available from the maintainer.
Karl Heuer's avatar
Karl Heuer committed
44

45 46 47 48 49
;; Doesn't work under NT when backslash is used as a path separator (forward
;;   slash path separator works fine).  To fix, check system-type against
;;   'windows-nt, write a routine that breaks paths down into components.
;;   (Surprisingly, there isn't one built in.)

Karl Heuer's avatar
Karl Heuer committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
;;; Change Log:

;; Originally by Dick King <king@reasoning.com> 15 May 86
;; Converted for Emacs 18 by Stephen Gildea <gildea@lcs.mit.edu>
;; Make uniquify-min-dir-content 0 truly non-invasive.  gildea 23 May 89
;; Some cleanup.  uniquify-min-dir-content default 0.  gildea 01 Jun 89
;; Don't rename to "".  Michael Ernst <mernst@theory.lcs.mit.edu> 15 Jun 94
;; Add kill-buffer-hook.  Kenneth Manheimer <ken.manheimer@nist.gov> 09 May 95
;; Add advice for rename-buffer and create-file-buffer, handle dired buffers,
;;  kill-buffer-rationalize-buffer-names-p, documentation.  mernst 24 May 95
;; Remove free variables, fix typos.  mernst 5 Jun 95
;; Efficiently support Emacs 19.27 & earlier.  ken.manheimer, mernst 10 Jun 95
;; Rename user options to "uniquify-...", add uniquify-reverse-dir-content-p,
;;  add uniquify-ask-about-buffer-names-p.  king, mernst 13 Jun 95
;; Prefix functions by "uniquify-..."; rename mnemonic-buffer-names to
;;  uniquify-buffer-name-style; add 'forward and 'post-forward-angle-brackets
;;  styles; remove uniquify-reverse-dir-content-p; add
;;  uniquify-trailing-separator-p.  mernst 4 Aug 95
68 69 70
;; Don't call expand-file-name on nil.  mernst 7 Jan 96
;; Check whether list-buffers-directory is bound.  mernst 11 Oct 96
;; Ignore non-file non-dired buffers. Colin Rafferty <craffert@ml.com> 3 Mar 97
71 72
;; Use last component, not "", for file name of directories.  mernst 27 Jun 97
;; Use directory-file-name; code cleanup.  mernst 6 Sep 97
73 74
;; Add uniquify-ignore-buffers-re.
;;  Andre Srinivasan <andre@visigenic.com> 9 Sep 97
75 76
;; Add uniquify-list-buffers-directory-modes
;;   Stefan Monnier <monnier@cs.yale.edu> 17 Nov 2000
Karl Heuer's avatar
Karl Heuer committed
77 78 79 80 81 82

;; Valuable feedback was provided by
;; Paul Smith <psmith@baynetworks.com>,
;; Alastair Burt <burt@dfki.uni-kl.de>,
;; Bob Weiner <weiner@footloose.sps.mot.com>,
;; Albert L. Ting <alt@vlibs.com>,
83 84
;; gyro@reasoning.com,
;; Bryan O'Sullivan <bos@eng.sun.com>.
Karl Heuer's avatar
Karl Heuer committed
85 86 87 88 89


;;; Code:

(provide 'uniquify)
90
(eval-when-compile (require 'cl))
Karl Heuer's avatar
Karl Heuer committed
91 92 93

;;; User-visible variables

94 95 96 97 98
(defgroup uniquify nil
  "Unique buffer names dependent on file name"
  :group 'applications)


99
(defcustom uniquify-buffer-name-style nil
Karl Heuer's avatar
Karl Heuer committed
100
  "*If non-nil, buffer names are uniquified with parts of directory name.
Karl Heuer's avatar
Karl Heuer committed
101 102 103 104
The value determines the buffer name style and is one of `forward',
`reverse', `post-forward' (the default), or `post-forward-angle-brackets'.
For example, files `/foo/bar/mumble/name' and `/baz/quux/mumble/name'
would have the following buffer names in the various styles:
Karl Heuer's avatar
Karl Heuer committed
105 106 107 108
  forward        bar/mumble/name  quux/mumble/name
  reverse        name\\mumble\\bar  name\\mumble\\quux
  post-forward   name|bar/mumble  name|quux/mumble
  post-forward-angle-brackets   name<bar/mumble>  name<quux/mumble>
109 110 111 112
  nil            name  name<2>"
  :type '(radio (const forward)
		(const reverse)
		(const post-forward)
113
		(const post-forward-angle-brackets)
114
		(const :tag "standard Emacs behavior (nil)" nil))
115
  :require 'uniquify
116 117 118
  :group 'uniquify)

(defcustom uniquify-after-kill-buffer-p nil
Karl Heuer's avatar
Karl Heuer committed
119 120
  "*If non-nil, rerationalize buffer names after a buffer has been killed.
This can be dangerous if Emacs Lisp code is keeping track of buffers by their
121 122 123
names (rather than keeping pointers to the buffers themselves)."
  :type 'boolean
  :group 'uniquify)
Karl Heuer's avatar
Karl Heuer committed
124

125
(defcustom uniquify-ask-about-buffer-names-p nil
Karl Heuer's avatar
Karl Heuer committed
126 127
  "*If non-nil, permit user to choose names for buffers with same base file.
If the user chooses to name a buffer, uniquification is preempted and no
128 129 130
other buffer names are changed."
  :type 'boolean
  :group 'uniquify)
Karl Heuer's avatar
Karl Heuer committed
131

132
(defcustom uniquify-ignore-buffers-re nil
133
  "*Regular expression matching buffer names that should not be uniquified.
134 135 136
For instance, set this to \"^draft-[0-9]+$\" to avoid having uniquify rename
draft buffers even if `uniquify-after-kill-buffer-p' is non-nil and the
visited file name isn't the same as that of the buffer."
137
  :type '(choice (const :tag "Uniquify all buffers" nil) regexp)
138 139
  :group 'uniquify)

140
(defcustom uniquify-min-dir-content 0
141
  "*Minimum number of directory name components included in buffer name."
142 143
  :type 'integer
  :group 'uniquify)
Karl Heuer's avatar
Karl Heuer committed
144

145
(defcustom uniquify-separator nil
Karl Heuer's avatar
Karl Heuer committed
146
  "*String separator for buffer name components.
Karl Heuer's avatar
Karl Heuer committed
147
When `uniquify-buffer-name-style' is `post-forward', separates
Karl Heuer's avatar
Karl Heuer committed
148
base file name from directory part in buffer names (default \"|\").
Karl Heuer's avatar
Karl Heuer committed
149
When `uniquify-buffer-name-style' is `reverse', separates all
150 151 152
file name components (default \"\\\")."
  :type '(choice (const nil) string)
  :group 'uniquify)
Karl Heuer's avatar
Karl Heuer committed
153

154
(defcustom uniquify-trailing-separator-p nil
Karl Heuer's avatar
Karl Heuer committed
155 156 157
  "*If non-nil, add a file name separator to dired buffer names.
If `uniquify-buffer-name-style' is `forward', add the separator at the end;
if it is `reverse', add the separator at the beginning; otherwise, this
158 159 160
variable is ignored."
  :type 'boolean
  :group 'uniquify)
Karl Heuer's avatar
Karl Heuer committed
161

162 163 164 165
(defvar uniquify-list-buffers-directory-modes '(dired-mode cvs-mode)
  "List of modes for which uniquify should obey `list-buffers-directory'.
That means that when `buffer-file-name' is set to nil, `list-buffers-directory'
contains the name of the directory which the buffer is visiting.")
Karl Heuer's avatar
Karl Heuer committed
166 167 168

;;; Utilities

169 170 171
;; For directories, return the last component, not the empty string.
(defun uniquify-file-name-nondirectory (file-name)
  (file-name-nondirectory (directory-file-name file-name)))
Karl Heuer's avatar
Karl Heuer committed
172

173 174
;; uniquify-fix-list data structure
(defmacro uniquify-fix-item-base (a)
Gerd Moellmann's avatar
Gerd Moellmann committed
175
  `(car ,a))
176
(defmacro uniquify-fix-item-filename (a)
Gerd Moellmann's avatar
Gerd Moellmann committed
177
  `(car (cdr ,a)))
178
(defmacro uniquify-fix-item-buffer (a)
Gerd Moellmann's avatar
Gerd Moellmann committed
179
  `(car (cdr (cdr ,a))))
180 181 182
;; Not a macro: passed to mapcar.
(defun uniquify-fix-item-unrationalized-buffer (item)
  (or (car (cdr (cdr (cdr item)))) nil))	;maybe better in the future
Karl Heuer's avatar
Karl Heuer committed
183

184 185 186
(defun uniquify-fix-item-filename-lessp (fixlist1 fixlist2)
  (uniquify-filename-lessp (uniquify-fix-item-filename fixlist1)
			   (uniquify-fix-item-filename fixlist2)))
Karl Heuer's avatar
Karl Heuer committed
187 188 189 190 191 192 193 194

;; Internal variables used free
(defvar uniquify-non-file-buffer-names nil)
(defvar uniquify-possibly-resolvable nil)

;;; Main entry point.

(defun uniquify-rationalize-file-buffer-names (&optional newbuffile newbuf)
195
  "Make file buffer names unique by adding segments from file name.
Karl Heuer's avatar
Karl Heuer committed
196
If `uniquify-min-dir-content' > 0, always pulls that many
Karl Heuer's avatar
Karl Heuer committed
197
file name elements.  Arguments cause only a subset of buffers to be renamed."
Karl Heuer's avatar
Karl Heuer committed
198 199
  (interactive)
  (let (fix-list
200
	uniquify-non-file-buffer-names)
Karl Heuer's avatar
Karl Heuer committed
201 202 203 204
    (let ((buffers (buffer-list)))
      (while buffers
	(let* ((buffer (car buffers))
	       (bfn (if (eq buffer newbuf)
205 206 207 208 209
                        (and newbuffile
			     (expand-file-name
			      (if (file-directory-p newbuffile)
				  (directory-file-name newbuffile)
			       newbuffile)))
Karl Heuer's avatar
Karl Heuer committed
210
		      (uniquify-buffer-file-name buffer)))
211
	       (rawname (and bfn (uniquify-file-name-nondirectory bfn)))
Karl Heuer's avatar
Karl Heuer committed
212
	       (deserving (and rawname
213 214 215
			       (not (and uniquify-ignore-buffers-re
					 (string-match uniquify-ignore-buffers-re
						       (buffer-name buffer))))
Karl Heuer's avatar
Karl Heuer committed
216 217
			       (or (not newbuffile)
				   (equal rawname
218
					  (uniquify-file-name-nondirectory newbuffile))))))
Karl Heuer's avatar
Karl Heuer committed
219
	  (if deserving
220 221 222
	      (push (list rawname bfn buffer nil) fix-list)
	    (push (list (buffer-name buffer))
		  uniquify-non-file-buffer-names)))
Karl Heuer's avatar
Karl Heuer committed
223 224 225 226
	(setq buffers (cdr buffers))))
    ;; selects buffers whose names may need changing, and others that
    ;; may conflict.
    (setq fix-list
227
	  (sort fix-list 'uniquify-fix-item-filename-lessp))
Karl Heuer's avatar
Karl Heuer committed
228
    ;; bringing conflicting names together
229 230
    (uniquify-rationalize-a-list fix-list uniquify-min-dir-content)
    (mapcar 'uniquify-fix-item-unrationalized-buffer fix-list)))
Karl Heuer's avatar
Karl Heuer committed
231

232
;; uniquify's version of buffer-file-name; result never contains trailing slash
Karl Heuer's avatar
Karl Heuer committed
233 234
(defun uniquify-buffer-file-name (buffer)
  "Return name of file BUFFER is visiting, or nil if none.
235 236
Works on ordinary file-visiting buffers and buffers whose mode is mentioned
in `uniquify-list-buffers-directory-modes', otherwise returns nil."
Karl Heuer's avatar
Karl Heuer committed
237
  (or (buffer-file-name buffer)
238
      (with-current-buffer buffer
239
	(and
240
	 (memq major-mode uniquify-list-buffers-directory-modes)
241 242 243 244 245 246 247 248 249
	 (if (boundp 'list-buffers-directory) ; XEmacs mightn't define this
	     (and list-buffers-directory
		  (directory-file-name list-buffers-directory))
	   ;; don't use default-directory if dired-directory is nil
	   (and dired-directory
		(expand-file-name
		 (directory-file-name
		  (if (consp dired-directory)
		      (car dired-directory)
250
		    dired-directory)))))))))
Karl Heuer's avatar
Karl Heuer committed
251

252
;; This examines the filename components in reverse order.
Karl Heuer's avatar
Karl Heuer committed
253
(defun uniquify-filename-lessp (s1 s2)
254 255
  (let ((s1f (uniquify-file-name-nondirectory s1))
	(s2f (uniquify-file-name-nondirectory s2)))
Karl Heuer's avatar
Karl Heuer committed
256 257 258 259 260 261 262 263 264 265 266 267
    (and (not (equal s2f ""))
	 (or (string-lessp s1f s2f)
	     (and (equal s1f s2f)
		  (let ((s1d (file-name-directory s1))
			(s2d (file-name-directory s2)))
		    (and (not (<= (length s2d) 1))
			 (or (<= (length s1d) 1)
			     (uniquify-filename-lessp
			      (substring s1d 0 -1)
			      (substring s2d 0 -1))))))))))

(defun uniquify-rationalize-a-list (fix-list depth)
268
  (let (conflicting-sublist	; all elements have the same proposed name
Karl Heuer's avatar
Karl Heuer committed
269 270 271 272 273 274 275 276 277 278
	(old-name "")
	proposed-name uniquify-possibly-resolvable)
    (while fix-list
      (let ((item (car fix-list)))
	(setq proposed-name (uniquify-get-proposed-name item depth))
	(if (not (equal proposed-name old-name))
	    (progn
	      (uniquify-rationalize-conflicting-sublist
	       conflicting-sublist old-name depth)
	      (setq conflicting-sublist nil)))
279
	(push item conflicting-sublist)
Karl Heuer's avatar
Karl Heuer committed
280 281 282 283 284 285 286 287 288
	(setq old-name proposed-name))
      (setq fix-list (cdr fix-list)))
    (uniquify-rationalize-conflicting-sublist
     conflicting-sublist old-name depth)))

(defun uniquify-get-proposed-name (item depth)
  (let (index
	(extra-string "")
	(n depth)
289 290
	(base (uniquify-fix-item-base item))
	(fn (uniquify-fix-item-filename item)))
Karl Heuer's avatar
Karl Heuer committed
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
    (while (and (> n 0)
		(setq index (string-match
			     (concat "\\(^\\|/[^/]*\\)/"
				     (regexp-quote extra-string)
				     (regexp-quote base)
				     "\\'")
			     fn)))
      (setq extra-string (substring fn
				    (if (zerop index) 0 (1+ index))
				    ;; (- (length base)) fails for base = "".
				    ;; Equivalently, we could have used
				    ;; (apply 'substring ...
				    ;;        (and (not (string= "" base))
				    ;;             (list (- (length base)))))
				    (- (length fn) (length base)))
	    n (1- n)))
    (if (zerop n) (setq uniquify-possibly-resolvable t))


    ;; Distinguish directories by adding extra separator.
    (if (and uniquify-trailing-separator-p
	     (file-directory-p fn)
	     (not (string-equal base "")))
	(cond ((eq uniquify-buffer-name-style 'forward)
	       (setq base (concat base "/")))
	      ((eq uniquify-buffer-name-style 'reverse)
	       (setq base (concat (or uniquify-separator "\\") base)))))

    ;; Trim trailing separator on directory part
    (if (and (not (string-equal extra-string ""))
	     (or (eq uniquify-buffer-name-style 'post-forward)
		 (eq uniquify-buffer-name-style 'post-forward-angle-brackets)))
	(setq extra-string (substring extra-string 0
				      (- (length extra-string) 1))))

    (cond ((string-equal extra-string "")
	   base)
	  ((string-equal base "")
	   extra-string)
	  ((eq uniquify-buffer-name-style 'forward)
	   (concat extra-string base))
	  ((eq uniquify-buffer-name-style 'reverse)
	   (concat base (uniquify-reverse-components extra-string)))
	  ((eq uniquify-buffer-name-style 'post-forward)
	   (concat base (or uniquify-separator "|") extra-string))
	  ((eq uniquify-buffer-name-style 'post-forward-angle-brackets)
	   (concat base "<" extra-string ">"))
	  (t (error "Bad value for uniquify-buffer-name-style: %s"
		    uniquify-buffer-name-style)))))


342 343
;; Deal with conflicting-sublist, all of whose elements have identical
;; "base" components.
Karl Heuer's avatar
Karl Heuer committed
344 345 346 347 348 349 350 351 352 353 354
(defun uniquify-rationalize-conflicting-sublist (conflicting-sublist old-name depth)
  (or (null conflicting-sublist)
      (and (null (cdr conflicting-sublist))
	   (not (assoc old-name uniquify-non-file-buffer-names))
	   (or (and (not (string= old-name ""))
		    (uniquify-rename-buffer (car conflicting-sublist) old-name))
	       t))
      (if uniquify-possibly-resolvable
	  (uniquify-rationalize-a-list conflicting-sublist (1+ depth)))))

(defun uniquify-rename-buffer (item newname)
355
  (let ((buffer (uniquify-fix-item-buffer item)))
Karl Heuer's avatar
Karl Heuer committed
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
    (if (not (equal newname (buffer-name buffer)))
	(let ((unset (current-buffer))
	      ;; avoid hooks on rename-buffer
	      (uniquify-buffer-name-style nil))
	  (set-buffer buffer)
	  (rename-buffer newname)
	  (set-buffer unset))))
  (rplaca (nthcdr 3 item) t))

(defun uniquify-reverse-components (instring)
  (let ((sofar '())
	(cursor 0)
	(len (length instring))
	(sep (or uniquify-separator "\\")))
    (while (< cursor len)
      (if (= (aref instring cursor) ?/)
          (setq sofar (cons sep sofar)
                cursor (1+ cursor))
        (let ((first-slash (or (string-match "/" instring cursor) len)))
          (setq sofar (cons (substring instring cursor first-slash) sofar)
                cursor first-slash))))
    (apply (function concat) sofar)))


;;; Hooks from the rest of Emacs

;; The logical place to put all this code is in generate-new-buffer-name.
;; It's written in C, so we would add a generate-new-buffer-name-function
;; which, if non-nil, would be called instead of the C.  One problem with
;; that is that generate-new-buffer-name takes a potential buffer name as
;; its argument -- not other information, such as what file the buffer will
;; visit.

;; The below solution works because generate-new-buffer-name is called
;; only by rename-buffer (which, as of 19.29, is never called from C) and
;; generate-new-buffer, which is called only by Lisp functions
;; create-file-buffer and rename-uniquely.  Rename-uniquely generally
;; isn't used for buffers visiting files, so it's sufficient to hook
;; rename-buffer and create-file-buffer.  (Setting find-file-hooks isn't
;; sufficient.)

(defadvice rename-buffer (after rename-buffer-uniquify activate)
  "Uniquify buffer names with parts of directory name."
  (if (and uniquify-buffer-name-style
	   ;; UNIQUE argument
	   (ad-get-arg 1))
      (progn
	(if uniquify-after-kill-buffer-p
	    ;; call with no argument; rationalize vs. old name as well as new
	    (uniquify-rationalize-file-buffer-names)
	  ;; call with argument: rationalize vs. new name only
	  (uniquify-rationalize-file-buffer-names
	   (uniquify-buffer-file-name (current-buffer)) (current-buffer)))
	(setq ad-return-value (buffer-name (current-buffer))))))

(defadvice create-file-buffer (after create-file-buffer-uniquify activate)
  "Uniquify buffer names with parts of directory name."
  (if uniquify-buffer-name-style
      (uniquify-rationalize-file-buffer-names (ad-get-arg 0) ad-return-value)))

;; Buffer deletion
;; Rerationalize after a buffer is killed, to reduce coinciding buffer names.
;; This mechanism uses `kill-buffer-hook', which runs *before* deletion.
;; That means that the kill-buffer-hook function cannot just delete the
;; buffer -- it has to set something to do the rationalization *later*.
;; It actually puts another function on `post-command-hook'.  This other
;; function runs the rationalization and then removes itself from the hook.
;; Is there a better way to accomplish this?
;; (This ought to set some global variables so the work is done only for
;; buffers with names similar to the deleted buffer.  -MDE)

(defun delay-uniquify-rationalize-file-buffer-names ()
  "Add `delayed-uniquify-rationalize-file-buffer-names' to `post-command-hook'.
For use on, eg, `kill-buffer-hook', to rationalize *after* buffer deletion."
  (if (and uniquify-buffer-name-style
	   uniquify-after-kill-buffer-p)
      (add-hook 'post-command-hook
433
		'delayed-uniquify-rationalize-file-buffer-names)))
Karl Heuer's avatar
Karl Heuer committed
434 435 436 437 438 439 440 441 442 443 444

(defun delayed-uniquify-rationalize-file-buffer-names ()
  "Rerationalize buffer names and remove self from `post-command-hook'.
See also `delay-rationalize-file-buffer-names' for hook setter."
  (uniquify-rationalize-file-buffer-names)
  (remove-hook 'post-command-hook
	       'delayed-uniquify-rationalize-file-buffer-names))

(add-hook 'kill-buffer-hook 'delay-uniquify-rationalize-file-buffer-names)

;;; uniquify.el ends here