1 ;;; ls-lisp.el --- emulate insert-directory completely in Emacs Lisp
3 ;; Copyright (C) 1992, 1994, 2000 Free Software Foundation, Inc.
5 ;; Author: Sebastian Kremer <sk@thp.uni-koeln.de>
6 ;; Modified by: Francis J. Wright <F.J.Wright@maths.qmw.ac.uk>
8 ;; Keywords: unix, dired
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
29 ;; OVERVIEW ==========================================================
31 ;; This file redefines the function `insert-directory' to implement it
32 ;; directly from Emacs lisp, without running ls in a subprocess. It
33 ;; is useful if you cannot afford to fork Emacs on a real memory UNIX,
34 ;; under VMS or other non-UNIX platforms if you don't have the ls
35 ;; program, or if you want a different format from what ls offers.
37 ;; This function can use regexps instead of shell wildcards. If you
38 ;; enter regexps remember to double each $ sign. For example, to
39 ;; include files *.el, enter `.*\.el$$', resulting in the regexp
42 ;; RESTRICTIONS ======================================================
44 ;; * A few obscure ls switches are still ignored: see the docstring of
45 ;; `insert-directory'.
47 ;; * Generally only numeric uid/gid.
49 ;; TO DO =============================================================
51 ;; Complete handling of F switch (if/when possible).
53 ;; FJW: May be able to sort much faster by consing the sort key onto
54 ;; the front of each list element, sorting and then stripping the key
59 ;; Written originally by Sebastian Kremer <sk@thp.uni-koeln.de>
60 ;; Revised by Andrew Innes and Geoff Volker (and maybe others).
62 ;; Modified by Francis J. Wright <F.J.Wright@maths.qmw.ac.uk>, mainly
63 ;; to support many more ls options, "platform emulation", hooks for
64 ;; external symbolic link support and more robust sorting.
70 "Emulate the ls program completely in Emacs Lisp."
74 (defcustom ls-lisp-emulation
75 (cond ((eq system-type
'macos
) 'MacOS
)
76 ;; ((eq system-type 'windows-nt) 'MS-Windows)
78 '(hpux dgux usg-unix-v unisoft-unix rtu irix berkeley-unix
))
79 'UNIX
)) ; very similar to GNU
80 ;; Anything else defaults to nil, meaning GNU.
81 "*Platform to emulate: GNU (default), MacOS, MS-Windows, UNIX.
82 Corresponding value is one of the atoms: nil, MacOS, MS-Windows, UNIX.
83 Sets default values for: `ls-lisp-ignore-case', `ls-lisp-dirs-first',
84 `ls-lisp-verbosity'. Need not match actual platform. Changing this
85 option will have no effect until you restart Emacs."
86 :type
'(choice (const :tag
"GNU" nil
)
92 (defcustom ls-lisp-ignore-case
93 ;; Name change for consistency with other option names.
94 (or (memq ls-lisp-emulation
'(MS-Windows MacOS
))
95 (and (boundp 'ls-lisp-dired-ignore-case
) ls-lisp-dired-ignore-case
))
96 "*Non-nil causes ls-lisp alphabetic sorting to ignore case."
100 (defcustom ls-lisp-dirs-first
(eq ls-lisp-emulation
'MS-Windows
)
101 "*Non-nil causes ls-lisp to sort directories first in any ordering.
102 \(Or last if it is reversed.) Follows Microsoft Windows Explorer."
103 ;; Functionality suggested by Chris McMahan <cmcmahan@one.net>
107 (defcustom ls-lisp-verbosity
108 (cond ((eq ls-lisp-emulation
'MacOS
) nil
)
109 ((eq ls-lisp-emulation
'MS-Windows
)
110 (if (and (fboundp 'w32-using-nt
) (w32-using-nt))
111 '(links))) ; distinguish NT/2K from 9x
112 ((eq ls-lisp-emulation
'UNIX
) '(links uid
)) ; UNIX ls
113 (t '(links uid gid
))) ; GNU ls
114 "*A list of optional file attributes that ls-lisp should display.
115 It should contain none or more of the symbols: links, uid, gid.
116 nil (or an empty list) means display none of them.
118 Concepts come from UNIX: `links' means count of names associated with
119 the file\; `uid' means user (owner) identifier\; `gid' means group
122 If emulation is MacOS then default is nil\;
123 if emulation is MS-Windows then default is `(links)' if platform is
124 Windows NT/2K, nil otherwise\;
125 if emulation is UNIX then default is `(links uid)'\;
126 if emulation is GNU then default is `(links uid gid)'."
127 ;; Functionality suggested by Howard Melman <howard@silverstream.com>
128 :type
'(set (const :tag
"Show Link Count" links
)
129 (const :tag
"Show User" uid
)
130 (const :tag
"Show Group" gid
))
133 (defcustom ls-lisp-use-insert-directory-program nil
134 "*Non-nil causes ls-lisp to revert back to using `insert-directory-program'.
135 This is useful on platforms where ls-lisp is dumped into Emacs, such as
136 Microsoft Windows, but you would still like to use a program to list
137 the contents of a directory."
141 (defcustom ls-lisp-support-shell-wildcards t
142 "*Non-nil means ls-lisp treats file patterns as shell wildcards.
143 Otherwise they are treated as Emacs regexps (for backward compatibility)."
147 (defcustom ls-lisp-format-time-list
150 "*List of `format-time-string' specs to display file time stamps.
151 They are used whenever a locale is not specified to use instead.
153 Syntax: (EARLY-TIME-FORMAT OLD-TIME-FORMAT)
155 The EARLY-TIME-FORMAT is used if file has been modified within the
156 current year. The OLD-TIME-FORMAT is used for older files. To use ISO
157 8601 dates, you could set:
159 \(setq ls-lisp-format-time-list
165 ;; Remember the original insert-directory function
166 (or (featurep 'ls-lisp
) ; FJW: unless this file is being reloaded!
167 (fset 'original-insert-directory
(symbol-function 'insert-directory
)))
169 ;; This stub is to allow ls-lisp to parse symbolic links via another
170 ;; library such as w32-symlinks.el from
171 ;; http://centaur.qmw.ac.uk/Emacs/:
172 (defun ls-lisp-parse-symlink (file-name)
173 "This stub may be redefined to parse FILE-NAME as a symlink.
174 It should return nil or the link target as a string."
178 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
180 (defun insert-directory (file switches
&optional wildcard full-directory-p
)
181 "Insert directory listing for FILE, formatted according to SWITCHES.
182 Leaves point after the inserted text.
183 SWITCHES may be a string of options, or a list of strings.
184 Optional third arg WILDCARD means treat FILE as shell wildcard.
185 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
186 switches do not contain `d', so that a full listing is expected.
188 This version of the function comes from `ls-lisp.el'.
189 If the value of `ls-lisp-use-insert-directory-program' is non-nil then
190 it works exactly like the version from `files.el' and runs a directory
191 listing program whose name is in the variable
192 `insert-directory-program'; if also WILDCARD is non-nil then it runs
193 the shell specified by `shell-file-name'. If the value of
194 `ls-lisp-use-insert-directory-program' is nil then it runs a Lisp
197 The Lisp emulation does not run any external programs or shells. It
198 supports ordinary shell wildcards if `ls-lisp-support-shell-wildcards'
199 is non-nil; otherwise, it interprets wildcards as regular expressions
200 to match file names. It does not support all `ls' switches -- those
201 that work are: A a c i r S s t u U X g G B C R and F partly."
202 (if ls-lisp-use-insert-directory-program
203 (original-insert-directory file switches wildcard full-directory-p
)
204 ;; We need the directory in order to find the right handler.
205 (let ((handler (find-file-name-handler (expand-file-name file
)
208 (funcall handler
'insert-directory file switches
209 wildcard full-directory-p
)
210 ;; Convert SWITCHES to a list of characters.
211 (setq switches
(delete ?-
(append switches nil
)))
214 (if ls-lisp-support-shell-wildcards
215 (wildcard-to-regexp (file-name-nondirectory file
))
216 (file-name-nondirectory file
))
217 file
(file-name-directory file
))
218 (if (memq ?B switches
) (setq wildcard
"[^~]\\'")))
219 (ls-lisp-insert-directory
220 file switches
(ls-lisp-time-index switches
)
221 wildcard full-directory-p
)
222 ;; Try to insert the amount of free space.
224 (goto-char (point-min))
225 ;; First find the line to put it on.
226 (when (re-search-forward "^total" nil t
)
227 (let ((available (get-free-disk-space ".")))
229 ;; Replace "total" with "total used", to avoid confusion.
230 (replace-match "total used in directory")
232 (insert " available " available
)))))))))
234 (defun ls-lisp-insert-directory
235 (file switches time-index wildcard full-directory-p
)
236 "Insert directory listing for FILE, formatted according to SWITCHES.
237 Leaves point after the inserted text. This is an internal function
238 optionally called by the `ls-lisp.el' version of `insert-directory'.
239 It is called recursively if the -R switch is used.
240 SWITCHES is a *list* of characters. TIME-INDEX is the time index into
241 file-attributes according to SWITCHES. WILDCARD is nil or an *Emacs
242 regexp*. FULL-DIRECTORY-P means file is a directory and SWITCHES does
243 not contain `d', so that a full listing is expected."
244 ;; Sometimes we get ".../foo*/" as FILE. While the shell and
245 ;; `ls' don't mind, we certainly do, because it makes us think
246 ;; there is no wildcard, only a directory name.
247 (if (and ls-lisp-support-shell-wildcards
248 (string-match "[[?*]" file
))
250 (or (not (eq (aref file
(1- (length file
))) ?
/))
251 (setq file
(substring file
0 (1- (length file
)))))
253 (if (or wildcard full-directory-p
)
254 (let* ((dir (file-name-as-directory file
))
255 (default-directory dir
) ; so that file-attributes works
257 (directory-files-and-attributes dir nil wildcard t
))
260 ;; do all bindings here for speed
261 total-line files elt short file-size fil attr
)
262 (cond ((memq ?A switches
)
264 (ls-lisp-delete-matching "^\\.\\.?$" file-alist
)))
265 ((not (memq ?a switches
))
266 ;; if neither -A nor -a, flush . files
268 (ls-lisp-delete-matching "^\\." file-alist
))))
270 (ls-lisp-handle-switches file-alist switches
))
271 (if (memq ?C switches
) ; column (-C) format
272 (ls-lisp-column-format file-alist
)
273 (setq total-line
(cons (point) (car-safe file-alist
)))
274 (setq files file-alist
)
275 (while files
; long (-l) format
276 (setq elt
(car files
)
280 file-size
(nth 7 attr
))
282 (setq sum
(+ file-size
283 ;; Even if neither SUM nor file's size
284 ;; overflow, their sum could.
285 (if (or (< sum
(- 134217727 file-size
))
290 (insert (ls-lisp-format short attr file-size
291 switches time-index now
))))
292 ;; Insert total size of all files:
294 (goto-char (car total-line
))
296 ;; Shell says ``No match'' if no files match
297 ;; the wildcard; let's say something similar.
298 (insert "(No match)\n"))
299 (insert (format "total %.0f\n" (fceiling (/ sum
1024.0))))))
300 (if (memq ?R switches
)
301 ;; List the contents of all directories recursively.
302 ;; cadr of each element of `file-alist' is t for
303 ;; directory, string (name linked to) for symbolic
306 (setq elt
(car file-alist
)
307 file-alist
(cdr file-alist
))
308 (when (and (eq (cadr elt
) t
) ; directory
309 (not (string-match "\\`\\.\\.?\\'" (car elt
))))
310 (setq elt
(expand-file-name (car elt
) dir
))
311 (insert "\n" elt
":\n")
312 (ls-lisp-insert-directory
313 elt switches time-index wildcard full-directory-p
)))))
314 ;; If not full-directory-p, FILE *must not* end in /, as
315 ;; file-attributes will not recognize a symlink to a directory,
316 ;; so must make it a relative filename as ls does:
317 (if (eq (aref file
(1- (length file
))) ?
/)
318 (setq file
(substring file
0 -
1)))
319 (let ((fattr (file-attributes file
)))
321 (insert (ls-lisp-format file fattr
(nth 7 fattr
)
322 switches time-index
(current-time)))
323 (message "%s: doesn't exist or is inaccessible" file
)
324 (ding) (sit-for 2))))) ; to show user the message!
326 (defun ls-lisp-column-format (file-alist)
327 "Insert the file names (only) in FILE-ALIST into the current buffer.
328 Format in columns, sorted vertically, following GNU ls -C.
329 Responds to the window width as ls should but may not!"
330 (let (files fmt ncols collen
(nfiles 0) (colwid 0))
331 ;; Count number of files as `nfiles', build list of filenames as
332 ;; `files', and find maximum filename length as `colwid':
335 (setq nfiles
(1+ nfiles
)
336 file
(caar file-alist
)
337 files
(cons file files
)
338 file-alist
(cdr file-alist
)
340 (if (> len colwid
) (setq colwid len
))))
341 (setq files
(nreverse files
)
342 colwid
(+ 2 colwid
) ; 2 character column gap
343 fmt
(format "%%-%ds" colwid
) ; print format
344 ncols
(/ (window-width) colwid
) ; no of columns
345 collen
(/ nfiles ncols
)) ; floor of column length
346 (if (> nfiles
(* collen ncols
)) (setq collen
(1+ collen
)))
347 ;; Output the file names in columns, sorted vertically:
352 (insert (format fmt
(nth j files
)))
353 (setq j
(+ j collen
)))
354 ;; FJW: This is completely unnecessary, but I don't like
355 ;; trailing white space...
356 (delete-region (point) (progn (skip-chars-backward " \t") (point)))
360 (defun ls-lisp-delete-matching (regexp list
)
361 "Delete all elements matching REGEXP from LIST, return new list."
362 ;; Should perhaps use setcdr for efficiency.
365 (or (string-match regexp
(caar list
))
366 (setq result
(cons (car list
) result
)))
367 (setq list
(cdr list
)))
370 (defsubst ls-lisp-string-lessp
(s1 s2
)
371 "Return t if string S1 is less than string S2 in lexicographic order.
372 Case is significant if `ls-lisp-ignore-case' is nil.
373 Unibyte strings are converted to multibyte for comparison."
374 (let ((u (compare-strings s1
0 nil s2
0 nil ls-lisp-ignore-case
)))
375 (and (numberp u
) (< u
0))))
377 (defun ls-lisp-handle-switches (file-alist switches
)
378 "Return new FILE-ALIST sorted according to SWITCHES.
379 SWITCHES is a list of characters. Default sorting is alphabetic."
380 ;; FILE-ALIST's elements are (FILE . FILE-ATTRIBUTES).
381 (or (memq ?U switches
) ; unsorted
382 ;; Catch and ignore unexpected sorting errors
386 ;; Copy file-alist in case of error
387 (sort (copy-sequence file-alist
) ; modifies its argument!
388 (cond ((memq ?S switches
)
389 (lambda (x y
) ; sorted on size
390 ;; 7th file attribute is file size
391 ;; Make largest file come first
394 ((setq index
(ls-lisp-time-index switches
))
395 (lambda (x y
) ; sorted on time
396 (ls-lisp-time-lessp (nth index
(cdr y
))
397 (nth index
(cdr x
)))))
399 (lambda (x y
) ; sorted on extension
400 (ls-lisp-string-lessp
401 (ls-lisp-extension (car x
))
402 (ls-lisp-extension (car y
)))))
404 (lambda (x y
) ; sorted alphabetically
405 (ls-lisp-string-lessp (car x
) (car y
))))))))
406 (error (message "Unsorted (ls-lisp sorting error) - %s"
407 (error-message-string err
))
408 (ding) (sit-for 2)))) ; to show user the message!
409 (if (memq ?F switches
) ; classify switch
410 (setq file-alist
(mapcar 'ls-lisp-classify file-alist
)))
411 (if ls-lisp-dirs-first
412 ;; Re-sort directories first, without otherwise changing the
413 ;; ordering, and reverse whole list. cadr of each element of
414 ;; `file-alist' is t for directory, string (name linked to) for
415 ;; symbolic link, or nil.
418 (if (eq (cadr (setq el
(car file-alist
))) t
) ; directory
419 (setq dirs
(cons el dirs
))
420 (setq files
(cons el files
)))
421 (setq file-alist
(cdr file-alist
)))
423 (if (memq ?U switches
) ; unsorted order is reversed
427 ;; Finally reverse file alist if necessary.
428 ;; (eq below MUST compare `(not (memq ...))' to force comparison of
429 ;; `t' or `nil', rather than list tails!)
430 (if (eq (eq (not (memq ?U switches
)) ; unsorted order is reversed
431 (not (memq ?r switches
))) ; reversed sort order requested
432 ls-lisp-dirs-first
) ; already reversed
433 (nreverse file-alist
)
436 (defun ls-lisp-classify (filedata)
437 "Append a character to each file name indicating the file type.
438 Also, for regular files that are executable, append `*'.
439 The file type indicators are `/' for directories, `@' for symbolic
440 links, `|' for FIFOs, `=' for sockets, and nothing for regular files.
441 \[But FIFOs and sockets are not recognised.]
442 FILEDATA has the form (filename . `file-attributes'). Its `cadr' is t
443 for directory, string (name linked to) for symbolic link, or nil."
444 (let ((dir (cadr filedata
)) (file-name (car filedata
)))
446 ;; Parsing .lnk files here is perhaps overkill!
447 (setq dir
(ls-lisp-parse-symlink file-name
)))
449 (concat file-name
(if (eq dir t
) "/" "@"))
451 ((string-match "x" (nth 9 filedata
))
453 (concat file-name
"*")
457 (defun ls-lisp-extension (filename)
458 "Return extension of FILENAME (ignoring any version extension)
459 FOLLOWED by null and full filename, SOLELY for full alpha sort."
460 ;; Force extension sort order: `no ext' then `null ext' then `ext'
461 ;; to agree with GNU ls.
463 (let* ((i (length filename
)) end
)
464 (if (= (aref filename
(1- i
)) ?.
) ; null extension
466 (while (and (>= (setq i
(1- i
)) 0)
467 (/= (aref filename i
) ?.
)))
468 (if (< i
0) "\0\0" ; no extension
469 (if (/= (aref filename
(1+ i
)) ?~
)
470 (substring filename
(1+ i
))
471 ;; version extension found -- ignore it
473 (while (and (>= (setq i
(1- i
)) 0)
474 (/= (aref filename i
) ?.
)))
475 (if (< i
0) "\0\0" ; no extension
476 (substring filename
(1+ i
) end
))))
479 ;; From Roland McGrath. Can use this to sort on time.
480 (defun ls-lisp-time-lessp (time0 time1
)
481 "Return t if time TIME0 is earlier than time TIME1."
482 (let ((hi0 (car time0
)) (hi1 (car time1
)))
485 (< (cadr time0
) (cadr time1
))))))
487 (defun ls-lisp-format (file-name file-attr file-size switches time-index now
)
488 "Format one line of long ls output for file FILE-NAME.
489 FILE-ATTR and FILE-SIZE give the file's attributes and size.
490 SWITCHES, TIME-INDEX and NOW give the full switch list and time data."
491 (let ((file-type (nth 0 file-attr
))
492 ;; t for directory, string (name linked to)
493 ;; for symbolic link, or nil.
494 (drwxrwxrwx (nth 8 file-attr
))) ; attribute string ("drwxrwxrwx")
495 (and (null file-type
)
496 ;; Maybe no kernel support for symlinks, so...
497 (setq file-type
(ls-lisp-parse-symlink file-name
))
498 (aset drwxrwxrwx
0 ?l
)) ; symbolic link - update attribute string
499 (concat (if (memq ?i switches
) ; inode number
500 (format " %6d" (nth 10 file-attr
)))
501 ;; nil is treated like "" in concat
502 (if (memq ?s switches
) ; size in K
503 (format " %4.0f" (fceiling (/ file-size
1024.0))))
504 drwxrwxrwx
; attribute string
505 (if (memq 'links ls-lisp-verbosity
)
506 (format " %3d" (nth 1 file-attr
))) ; link count
507 ;; Numeric uid/gid are more confusing than helpful;
508 ;; Emacs should be able to make strings of them.
509 ;; They tend to be bogus on non-UNIX platforms anyway so
510 ;; optionally hide them.
511 (if (memq 'uid ls-lisp-verbosity
)
512 ;; (user-login-name uid) works on Windows NT but not
513 ;; on 9x and maybe not on some other platforms, so...
514 (let ((uid (nth 2 file-attr
)))
515 (if (= uid
(user-uid))
516 (format " %-8s" (user-login-name))
517 (format " %-8d" uid
))))
518 (if (not (memq ?G switches
)) ; GNU ls -- shows group by default
519 (if (or (memq ?g switches
) ; UNIX ls -- no group by default
520 (memq 'gid ls-lisp-verbosity
))
521 (if (memq system-type
'(macos windows-nt ms-dos
))
522 ;; No useful concept of group...
524 (let* ((gid (nth 3 file-attr
))
525 (group (user-login-name gid
)))
527 (format " %-8s" group
)
528 (format " %-8d" gid
))))))
529 (format (if (floatp file-size
) " %8.0f" " %8d") file-size
)
531 (ls-lisp-format-time file-attr time-index now
)
534 (if (stringp file-type
) ; is a symbolic link
535 (concat " -> " file-type
))
539 (defun ls-lisp-time-index (switches)
540 "Return time index into file-attributes according to ls SWITCHES list.
541 Return nil if no time switch found."
542 ;; FJW: Default of nil is IMPORTANT and used in `ls-lisp-handle-switches'!
543 (cond ((memq ?c switches
) 6) ; last mode change
544 ((memq ?t switches
) 5) ; last modtime
545 ((memq ?u switches
) 4))) ; last access
547 (defun ls-lisp-time-to-seconds (time)
548 "Convert TIME to a floating point number."
549 (+ (* (car time
) 65536.0)
551 (/ (or (nth 2 time
) 0) 1000000.0)))
553 (defun ls-lisp-format-time (file-attr time-index now
)
554 "Format time for file with attributes FILE-ATTR according to TIME-INDEX.
555 Use the same method as ls to decide whether to show time-of-day or year,
556 depending on distance between file date and NOW.
557 All ls time options, namely c, t and u, are handled."
558 (let* ((time (nth (or time-index
5) file-attr
)) ; default is last modtime
559 (diff (- (ls-lisp-time-to-seconds time
)
560 (ls-lisp-time-to-seconds now
)))
561 ;; Consider a time to be recent if it is within the past six
562 ;; months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
563 ;; 31556952 seconds on the average, and half of that is 15778476.
564 ;; Write the constant explicitly to avoid roundoff error.
565 (past-cutoff -
15778476)) ; half a Gregorian year
567 ;; Use traditional time format in the C or POSIX locale,
568 ;; ISO-style time format otherwise, so columns line up.
569 (let ((locale system-time-locale
))
571 (let ((vars '("LC_ALL" "LC_TIME" "LANG")))
572 (while (and vars
(not (setq locale
(getenv (car vars
)))))
573 (setq vars
(cdr vars
)))))
574 (if (member locale
'("C" "POSIX"))
577 (if (and (<= past-cutoff diff
) (<= diff
0))
578 (if locale
"%m-%d %H:%M" (nth 0 ls-lisp-format-time-list
))
579 (if locale
"%Y-%m-%d " (nth 1 ls-lisp-format-time-list
)))
581 (error "Unk 0 0000"))))
585 ;;; ls-lisp.el ends here