Make eshell-for obsolete (replaced by dolist)
[bpt/emacs.git] / lisp / eshell / em-dirs.el
1 ;;; em-dirs.el --- directory navigation commands
2
3 ;; Copyright (C) 1999-2011 Free Software Foundation, Inc.
4
5 ;; Author: John Wiegley <johnw@gnu.org>
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23
24 ;; The only special feature that Eshell offers in the last-dir-ring.
25 ;; To view the ring, enter:
26 ;;
27 ;; cd =
28 ;;
29 ;; Changing to an index within the ring is done using:
30 ;;
31 ;; cd - ; same as cd -0
32 ;; cd -4
33 ;;
34 ;; Or, it is possible to change the first member in the ring which
35 ;; matches a regexp:
36 ;;
37 ;; cd =bcc ; change to the last directory visited containing "bcc"
38 ;;
39 ;; This ring is maintained automatically, and is persisted across
40 ;; Eshell sessions. It is a separate mechanism from `pushd' and
41 ;; `popd', and the two may be used at the same time.
42
43 ;;; Code:
44
45 (require 'eshell)
46 (require 'ring)
47 (require 'esh-opt)
48
49 ;;;###autoload
50 (eshell-defgroup eshell-dirs nil
51 "Directory navigation involves changing directories, examining the
52 current directory, maintaining a directory stack, and also keeping
53 track of a history of the last directory locations the user was in.
54 Emacs does provide standard Lisp definitions of `pwd' and `cd', but
55 they lack somewhat in feel from the typical shell equivalents."
56 :tag "Directory navigation"
57 :group 'eshell-module)
58
59 ;;; User Variables:
60
61 (defcustom eshell-dirs-load-hook '(eshell-dirs-initialize)
62 "A hook that gets run when `eshell-dirs' is loaded."
63 :type 'hook
64 :group 'eshell-dirs)
65
66 (defcustom eshell-pwd-convert-function (if (eshell-under-windows-p)
67 'expand-file-name
68 'identity)
69 "The function used to normalize the value of Eshell's `pwd'.
70 The value returned by `pwd' is also used when recording the
71 last-visited directory in the last-dir-ring, so it will affect the
72 form of the list used by 'cd ='."
73 :type '(radio (function-item file-truename)
74 (function-item expand-file-name)
75 (function-item identity)
76 (function :tag "Other"))
77 :group 'eshell-dirs)
78
79 (defcustom eshell-ask-to-save-last-dir 'always
80 "Determine if the last-dir-ring should be automatically saved.
81 The last-dir-ring is always preserved when exiting an Eshell buffer.
82 However, when Emacs is being shut down, this variable determines
83 whether to prompt the user, or just save the ring.
84 If set to nil, it means never ask whether to save the last-dir-ring.
85 If set to t, always ask if any Eshell buffers are open at exit time.
86 If set to `always', the list-dir-ring will always be saved, silently."
87 :type '(choice (const :tag "Never" nil)
88 (const :tag "Ask" t)
89 (const :tag "Always save" always))
90 :group 'eshell-dirs)
91
92 (defcustom eshell-cd-shows-directory nil
93 "If non-nil, using `cd' will report the directory it changes to."
94 :type 'boolean
95 :group 'eshell-dirs)
96
97 (defcustom eshell-cd-on-directory t
98 "If non-nil, do a cd if a directory is in command position."
99 :type 'boolean
100 :group 'eshell-dirs)
101
102 (defcustom eshell-directory-change-hook nil
103 "A hook to run when the current directory changes."
104 :type 'hook
105 :group 'eshell-dirs)
106
107 (defcustom eshell-list-files-after-cd nil
108 "If non-nil, call \"ls\" with any remaining args after doing a cd.
109 This is provided for convenience, since the same effect is easily
110 achieved by adding a function to `eshell-directory-change-hook' that
111 calls \"ls\" and references `eshell-last-arguments'."
112 :type 'boolean
113 :group 'eshell-dirs)
114
115 (defcustom eshell-pushd-tohome nil
116 "If non-nil, make pushd with no arg behave as 'pushd ~' (like `cd').
117 This mirrors the optional behavior of tcsh."
118 :type 'boolean
119 :group 'eshell-dirs)
120
121 (defcustom eshell-pushd-dextract nil
122 "If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
123 This mirrors the optional behavior of tcsh."
124 :type 'boolean
125 :group 'eshell-dirs)
126
127 (defcustom eshell-pushd-dunique nil
128 "If non-nil, make pushd only add unique directories to the stack.
129 This mirrors the optional behavior of tcsh."
130 :type 'boolean
131 :group 'eshell-dirs)
132
133 (defcustom eshell-dirtrack-verbose t
134 "If non-nil, show the directory stack following directory change.
135 This is effective only if directory tracking is enabled."
136 :type 'boolean
137 :group 'eshell-dirs)
138
139 (defcustom eshell-last-dir-ring-file-name
140 (expand-file-name "lastdir" eshell-directory-name)
141 "If non-nil, name of the file to read/write the last-dir-ring.
142 See also `eshell-read-last-dir-ring' and `eshell-write-last-dir-ring'.
143 If it is nil, the last-dir-ring will not be written to disk."
144 :type 'file
145 :group 'eshell-dirs)
146
147 (defcustom eshell-last-dir-ring-size 32
148 "If non-nil, the size of the directory history ring.
149 This ring is added to every time `cd' or `pushd' is used. It simply
150 stores the most recent directory locations Eshell has been in. To
151 return to the most recent entry, use 'cd -' (equivalent to 'cd -0').
152 To return to an older entry, use 'cd -N', where N is an integer less
153 than `eshell-last-dir-ring-size'. To return to the last directory
154 matching a particular regexp, use 'cd =REGEXP'. To display the
155 directory history list, use 'cd ='.
156
157 This mechanism is very similar to that provided by `pushd', except
158 it's far more automatic. `pushd' allows the user to decide which
159 directories gets pushed, and its size is unlimited.
160
161 `eshell-last-dir-ring' is meant for users who don't use `pushd'
162 explicity very much, but every once in a while would like to return to
163 a previously visited directory without having to type in the whole
164 thing again."
165 :type 'integer
166 :group 'eshell-dirs)
167
168 (defcustom eshell-last-dir-unique t
169 "If non-nil, `eshell-last-dir-ring' contains only unique entries."
170 :type 'boolean
171 :group 'eshell-dirs)
172
173 ;;; Internal Variables:
174
175 (defvar eshell-dirstack nil
176 "List of directories saved by pushd in the Eshell buffer.
177 Thus, this does not include the current directory.")
178
179 (defvar eshell-last-dir-ring nil
180 "The last directory that Eshell was in.")
181
182 ;;; Functions:
183
184 (defun eshell-dirs-initialize ()
185 "Initialize the builtin functions for Eshell."
186 (make-local-variable 'eshell-variable-aliases-list)
187 (setq eshell-variable-aliases-list
188 (append
189 eshell-variable-aliases-list
190 '(("-" (lambda (indices)
191 (if (not indices)
192 (unless (ring-empty-p eshell-last-dir-ring)
193 (expand-file-name
194 (ring-ref eshell-last-dir-ring 0)))
195 (expand-file-name
196 (eshell-apply-indices eshell-last-dir-ring indices)))))
197 ("+" "PWD")
198 ("PWD" (lambda (indices)
199 (expand-file-name (eshell/pwd))) t)
200 ("OLDPWD" (lambda (indices)
201 (unless (ring-empty-p eshell-last-dir-ring)
202 (expand-file-name
203 (ring-ref eshell-last-dir-ring 0)))) t))))
204
205 (when eshell-cd-on-directory
206 (make-local-variable 'eshell-interpreter-alist)
207 (setq eshell-interpreter-alist
208 (cons (cons 'eshell-lone-directory-p
209 'eshell-dirs-substitute-cd)
210 eshell-interpreter-alist)))
211
212 (add-hook 'eshell-parse-argument-hook
213 'eshell-parse-user-reference nil t)
214 (if (eshell-under-windows-p)
215 (add-hook 'eshell-parse-argument-hook
216 'eshell-parse-drive-letter nil t))
217
218 (when (eshell-using-module 'eshell-cmpl)
219 (add-hook 'pcomplete-try-first-hook
220 'eshell-complete-user-reference nil t))
221
222 (make-local-variable 'eshell-dirstack)
223 (make-local-variable 'eshell-last-dir-ring)
224
225 (if eshell-last-dir-ring-file-name
226 (eshell-read-last-dir-ring))
227 (unless eshell-last-dir-ring
228 (setq eshell-last-dir-ring (make-ring eshell-last-dir-ring-size)))
229
230 (add-hook 'eshell-exit-hook 'eshell-write-last-dir-ring nil t)
231
232 (add-hook 'kill-emacs-hook 'eshell-save-some-last-dir))
233
234 (defun eshell-save-some-last-dir ()
235 "Save the list-dir-ring for any open Eshell buffers."
236 (dolist (buf (buffer-list))
237 (if (buffer-live-p buf)
238 (with-current-buffer buf
239 (if (and eshell-mode
240 eshell-ask-to-save-last-dir
241 (or (eq eshell-ask-to-save-last-dir 'always)
242 (y-or-n-p
243 (format "Save last dir ring for Eshell buffer `%s'? "
244 (buffer-name buf)))))
245 (eshell-write-last-dir-ring))))))
246
247 (defun eshell-lone-directory-p (file)
248 "Test whether FILE is just a directory name, and not a command name."
249 (and (file-directory-p file)
250 (or (file-name-directory file)
251 (not (eshell-search-path file)))))
252
253 (defun eshell-dirs-substitute-cd (&rest args)
254 "Substitute the given command for a call to `cd' on that name."
255 (if (> (length args) 1)
256 (error "%s: command not found" (car args))
257 (throw 'eshell-replace-command
258 (eshell-parse-command "cd" (eshell-flatten-list args)))))
259
260 (defun eshell-parse-user-reference ()
261 "An argument beginning with ~ is a filename to be expanded."
262 (when (and (not eshell-current-argument)
263 (eq (char-after) ?~))
264 (add-to-list 'eshell-current-modifiers 'expand-file-name)
265 (forward-char)
266 (char-to-string (char-before))))
267
268 (defun eshell-parse-drive-letter ()
269 "An argument beginning with X:[^/] is a drive letter reference."
270 (when (and (not eshell-current-argument)
271 (looking-at "\\([A-Za-z]:\\)\\([^/\\\\]\\|\\'\\)"))
272 (goto-char (match-end 1))
273 (let* ((letter (match-string 1))
274 (regexp (concat "\\`" letter))
275 (path (eshell-find-previous-directory regexp)))
276 (concat (or path letter) "/"))))
277
278 (defvar pcomplete-stub)
279 (defvar pcomplete-last-completion-raw)
280 (declare-function pcomplete-actual-arg "pcomplete")
281 (declare-function pcomplete-uniqify-list "pcomplete")
282
283 (defun eshell-complete-user-reference ()
284 "If there is a user reference, complete it."
285 (let ((arg (pcomplete-actual-arg)))
286 (when (string-match "\\`~[a-z]*\\'" arg)
287 (setq pcomplete-stub (substring arg 1)
288 pcomplete-last-completion-raw t)
289 (throw 'pcomplete-completions
290 (progn
291 (eshell-read-user-names)
292 (pcomplete-uniqify-list
293 (mapcar
294 (function
295 (lambda (user)
296 (file-name-as-directory (cdr user))))
297 eshell-user-names)))))))
298
299 (defun eshell/pwd (&rest args)
300 "Change output from `pwd` to be cleaner."
301 (let* ((path default-directory)
302 (len (length path)))
303 (if (and (> len 1)
304 (eq (aref path (1- len)) ?/)
305 (not (and (eshell-under-windows-p)
306 (string-match "\\`[A-Za-z]:[\\\\/]\\'" path))))
307 (setq path (substring path 0 (1- (length path)))))
308 (if eshell-pwd-convert-function
309 (funcall eshell-pwd-convert-function path)
310 path)))
311
312 (defun eshell-expand-multiple-dots (path)
313 "Convert '...' to '../..', '....' to '../../..', etc..
314
315 With the following piece of advice, you can make this functionality
316 available in most of Emacs, with the exception of filename completion
317 in the minibuffer:
318
319 (defadvice expand-file-name
320 (before translate-multiple-dots
321 (filename &optional directory) activate)
322 (setq filename (eshell-expand-multiple-dots filename)))"
323 (while (string-match "\\(?:^\\|/\\)\\.\\.\\(\\.+\\)\\(?:$\\|/\\)" path)
324 (let* ((extra-dots (match-string 1 path))
325 (len (length extra-dots))
326 replace-text)
327 (while (> len 0)
328 (setq replace-text (concat replace-text "/..")
329 len (1- len)))
330 (setq path
331 (replace-match replace-text t t path 1))))
332 path)
333
334 (defun eshell-find-previous-directory (regexp)
335 "Find the most recent last-dir matching REGEXP."
336 (let ((index 0)
337 (len (ring-length eshell-last-dir-ring))
338 oldpath)
339 (if (> (length regexp) 0)
340 (while (< index len)
341 (setq oldpath (ring-ref eshell-last-dir-ring index))
342 (if (string-match regexp oldpath)
343 (setq index len)
344 (setq oldpath nil
345 index (1+ index)))))
346 oldpath))
347
348 (defvar dired-directory)
349
350 (defun eshell/cd (&rest args) ; all but first ignored
351 "Alias to extend the behavior of `cd'."
352 (setq args (eshell-flatten-list args))
353 (let ((path (car args))
354 (subpath (car (cdr args)))
355 (case-fold-search (eshell-under-windows-p))
356 handled)
357 (if (numberp path)
358 (setq path (number-to-string path)))
359 (if (numberp subpath)
360 (setq subpath (number-to-string subpath)))
361 (cond
362 (subpath
363 (let ((curdir (eshell/pwd)))
364 (if (string-match path curdir)
365 (setq path (replace-match subpath nil nil curdir))
366 (error "Path substring '%s' not found" path))))
367 ((and path (string-match "^-\\([0-9]*\\)$" path))
368 (let ((index (match-string 1 path)))
369 (setq path
370 (ring-remove eshell-last-dir-ring
371 (if index
372 (string-to-number index)
373 0)))))
374 ((and path (string-match "^=\\(.*\\)$" path))
375 (let ((oldpath (eshell-find-previous-directory
376 (match-string 1 path))))
377 (if oldpath
378 (setq path oldpath)
379 (let ((len (ring-length eshell-last-dir-ring))
380 (index 0))
381 (if (= len 0)
382 (error "Directory ring empty"))
383 (eshell-init-print-buffer)
384 (while (< index len)
385 (eshell-buffered-print
386 (concat (number-to-string index) ": "
387 (ring-ref eshell-last-dir-ring index) "\n"))
388 (setq index (1+ index)))
389 (eshell-flush)
390 (setq handled t)))))
391 (path
392 (setq path (eshell-expand-multiple-dots path))))
393 (unless handled
394 (setq dired-directory (or path "~"))
395 (let ((curdir (eshell/pwd)))
396 (unless (equal curdir dired-directory)
397 (eshell-add-to-dir-ring curdir))
398 (let ((result (cd dired-directory)))
399 (and eshell-cd-shows-directory
400 (eshell-printn result)))
401 (run-hooks 'eshell-directory-change-hook)
402 (if eshell-list-files-after-cd
403 ;; Let-bind eshell-last-command around this?
404 (eshell-plain-command "ls" (cdr args)))
405 nil))))
406
407 (put 'eshell/cd 'eshell-no-numeric-conversions t)
408
409 (defun eshell-add-to-dir-ring (path)
410 "Add PATH to the last-dir-ring, if applicable."
411 (unless (and (not (ring-empty-p eshell-last-dir-ring))
412 (equal path (ring-ref eshell-last-dir-ring 0)))
413 (if eshell-last-dir-unique
414 (let ((index 0)
415 (len (ring-length eshell-last-dir-ring)))
416 (while (< index len)
417 (if (equal (ring-ref eshell-last-dir-ring index) path)
418 (ring-remove eshell-last-dir-ring index)
419 (setq index (1+ index))))))
420 (ring-insert eshell-last-dir-ring path)))
421
422 ;;; pushd [+n | dir]
423 (defun eshell/pushd (&rest args) ; all but first ignored
424 "Implementation of pushd in Lisp."
425 (let ((path (car args)))
426 (cond
427 ((null path)
428 ;; no arg -- swap pwd and car of stack unless eshell-pushd-tohome
429 (cond (eshell-pushd-tohome
430 (eshell/pushd "~"))
431 (eshell-dirstack
432 (let ((old (eshell/pwd)))
433 (eshell/cd (car eshell-dirstack))
434 (setq eshell-dirstack (cons old (cdr eshell-dirstack)))
435 (eshell/dirs t)))
436 (t
437 (error "pushd: No other directory"))))
438 ((string-match "^\\+\\([0-9]\\)" path)
439 ;; pushd +n
440 (setq path (string-to-number (match-string 1 path)))
441 (cond ((> path (length eshell-dirstack))
442 (error "Directory stack not that deep"))
443 ((= path 0)
444 (error "Couldn't cd"))
445 (eshell-pushd-dextract
446 (let ((dir (nth (1- path) eshell-dirstack)))
447 (eshell/popd path)
448 (eshell/pushd (eshell/pwd))
449 (eshell/cd dir)
450 (eshell/dirs t)))
451 (t
452 (let* ((ds (cons (eshell/pwd) eshell-dirstack))
453 (dslen (length ds))
454 (front (nthcdr path ds))
455 (back (nreverse (nthcdr (- dslen path) (reverse ds))))
456 (new-ds (append front back)))
457 (eshell/cd (car new-ds))
458 (setq eshell-dirstack (cdr new-ds))
459 (eshell/dirs t)))))
460 (t
461 ;; pushd <dir>
462 (let ((old-wd (eshell/pwd)))
463 (eshell/cd path)
464 (if (or (null eshell-pushd-dunique)
465 (not (member old-wd eshell-dirstack)))
466 (setq eshell-dirstack (cons old-wd eshell-dirstack)))
467 (eshell/dirs t)))))
468 nil)
469
470 (put 'eshell/pushd 'eshell-no-numeric-conversions t)
471
472 ;;; popd [+n]
473 (defun eshell/popd (&rest args)
474 "Implementation of popd in Lisp."
475 (let ((ref (or (car args) "+0")))
476 (unless (and (stringp ref)
477 (string-match "\\`\\([+-][0-9]+\\)\\'" ref))
478 (error "popd: bad arg `%s'" ref))
479 (setq ref (string-to-number (match-string 1 ref)))
480 (cond ((= ref 0)
481 (unless eshell-dirstack
482 (error "popd: Directory stack empty"))
483 (eshell/cd (car eshell-dirstack))
484 (setq eshell-dirstack (cdr eshell-dirstack))
485 (eshell/dirs t))
486 ((<= (abs ref) (length eshell-dirstack))
487 (let* ((ds (cons nil eshell-dirstack))
488 (cell (nthcdr (if (> ref 0)
489 (1- ref)
490 (+ (length eshell-dirstack) ref)) ds))
491 (dir (cadr cell)))
492 (eshell/cd dir)
493 (setcdr cell (cdr (cdr cell)))
494 (setq eshell-dirstack (cdr ds))
495 (eshell/dirs t)))
496 (t
497 (error "Couldn't popd"))))
498 nil)
499
500 (put 'eshell/popd 'eshell-no-numeric-conversions t)
501
502 (defun eshell/dirs (&optional if-verbose)
503 "Implementation of dirs in Lisp."
504 (when (or (not if-verbose) eshell-dirtrack-verbose)
505 (let* ((msg "")
506 (ds (cons (eshell/pwd) eshell-dirstack))
507 (home (expand-file-name "~/"))
508 (homelen (length home)))
509 (while ds
510 (let ((dir (car ds)))
511 (and (>= (length dir) homelen)
512 (string= home (substring dir 0 homelen))
513 (setq dir (concat "~/" (substring dir homelen))))
514 (setq msg (concat msg (directory-file-name dir) " "))
515 (setq ds (cdr ds))))
516 msg)))
517
518 (defun eshell-read-last-dir-ring ()
519 "Set the buffer's `eshell-last-dir-ring' from a history file."
520 (let ((file eshell-last-dir-ring-file-name))
521 (cond
522 ((or (null file)
523 (equal file "")
524 (not (file-readable-p file)))
525 nil)
526 (t
527 (let* ((count 0)
528 (size eshell-last-dir-ring-size)
529 (ring (make-ring size)))
530 (with-temp-buffer
531 (insert-file-contents file)
532 ;; Save restriction in case file is already visited...
533 ;; Watch for those date stamps in history files!
534 (goto-char (point-max))
535 (while (and (< count size)
536 (re-search-backward "^\\([^\n].*\\)$" nil t))
537 (ring-insert-at-beginning ring (match-string 1))
538 (setq count (1+ count)))
539 ;; never allow the top element to equal the current
540 ;; directory
541 (while (and (not (ring-empty-p ring))
542 (equal (ring-ref ring 0) (eshell/pwd)))
543 (ring-remove ring 0)))
544 (setq eshell-last-dir-ring ring))))))
545
546 (defun eshell-write-last-dir-ring ()
547 "Write the buffer's `eshell-last-dir-ring' to a history file."
548 (let ((file eshell-last-dir-ring-file-name))
549 (cond
550 ((or (null file)
551 (equal file "")
552 (null eshell-last-dir-ring)
553 (ring-empty-p eshell-last-dir-ring))
554 nil)
555 ((not (file-writable-p file))
556 (message "Cannot write last-dir-ring file %s" file))
557 (t
558 (let* ((ring eshell-last-dir-ring)
559 (index (ring-length ring)))
560 (with-temp-buffer
561 (while (> index 0)
562 (setq index (1- index))
563 (insert (ring-ref ring index) ?\n))
564 (insert (eshell/pwd) ?\n)
565 (eshell-with-private-file-modes
566 (write-region (point-min) (point-max) file nil
567 'no-message))))))))
568
569 (provide 'em-dirs)
570
571 ;; Local Variables:
572 ;; generated-autoload-file: "esh-groups.el"
573 ;; End:
574
575 ;;; em-dirs.el ends here