9ffbd2ccf5627ffde9700dc1bb3e5bbf84cd0adc
[bpt/emacs.git] / lisp / ls-lisp.el
1 ;;; ls-lisp.el --- emulate insert-directory completely in Emacs Lisp
2
3 ;; Copyright (C) 1992, 1994, 2000-2013 Free Software Foundation, Inc.
4
5 ;; Author: Sebastian Kremer <sk@thp.uni-koeln.de>
6 ;; Modified by: Francis J. Wright <F.J.Wright@maths.qmw.ac.uk>
7 ;; Maintainer: FSF
8 ;; Keywords: unix, dired
9 ;; Package: emacs
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;; OVERVIEW ==========================================================
29
30 ;; This file redefines the function `insert-directory' to implement it
31 ;; directly from Emacs lisp, without running ls in a subprocess. It
32 ;; is useful if you cannot afford to fork Emacs on a real memory UNIX,
33 ;; or other non-UNIX platforms if you don't have the ls
34 ;; program, or if you want a different format from what ls offers.
35
36 ;; This function can use regexps instead of shell wildcards. If you
37 ;; enter regexps remember to double each $ sign. For example, to
38 ;; include files *.el, enter `.*\.el$$', resulting in the regexp
39 ;; `.*\.el$'.
40
41 ;; RESTRICTIONS ======================================================
42
43 ;; * A few obscure ls switches are still ignored: see the docstring of
44 ;; `insert-directory'.
45
46 ;; TO DO =============================================================
47
48 ;; Complete handling of F switch (if/when possible).
49
50 ;; FJW: May be able to sort much faster by consing the sort key onto
51 ;; the front of each list element, sorting and then stripping the key
52 ;; off again!
53
54 ;;; History:
55
56 ;; Written originally by Sebastian Kremer <sk@thp.uni-koeln.de>
57 ;; Revised by Andrew Innes and Geoff Volker (and maybe others).
58
59 ;; Modified by Francis J. Wright <F.J.Wright@maths.qmw.ac.uk>, mainly
60 ;; to support many more ls options, "platform emulation" and more
61 ;; robust sorting.
62
63 ;;; Code:
64
65 (defgroup ls-lisp nil
66 "Emulate the ls program completely in Emacs Lisp."
67 :version "21.1"
68 :group 'dired)
69
70 (defun ls-lisp-set-options ()
71 "Reset the ls-lisp options that depend on `ls-lisp-emulation'."
72 (mapc 'custom-reevaluate-setting
73 '(ls-lisp-ignore-case ls-lisp-dirs-first ls-lisp-verbosity)))
74
75 (defcustom ls-lisp-emulation
76 (cond ;; ((eq system-type 'windows-nt) 'MS-Windows)
77 ((memq system-type '(hpux usg-unix-v irix berkeley-unix))
78 'UNIX)) ; very similar to GNU
79 ;; Anything else defaults to nil, meaning GNU.
80 "Platform to emulate: GNU (default), MacOS, MS-Windows, UNIX.
81 Corresponding value is one of: nil, `MacOS', `MS-Windows', `UNIX'.
82 Set this to your preferred value; it need not match the actual platform
83 you are using.
84
85 This variable does not affect the behavior of ls-lisp directly.
86 Rather, it controls the default values for some variables that do:
87 `ls-lisp-ignore-case', `ls-lisp-dirs-first', and `ls-lisp-verbosity'.
88
89 If you change this variable directly (without using customize)
90 after loading `ls-lisp', you should use `ls-lisp-set-options' to
91 update the dependent variables."
92 :type '(choice (const :tag "GNU" nil)
93 (const MacOS)
94 (const MS-Windows)
95 (const UNIX))
96 :initialize 'custom-initialize-default
97 :set (lambda (symbol value)
98 (unless (equal value (eval symbol))
99 (custom-set-default symbol value)
100 (ls-lisp-set-options)))
101 :group 'ls-lisp)
102
103 ;; Only made an obsolete alias in 23.3. Before that, the initial
104 ;; value was set according to:
105 ;; (or (memq ls-lisp-emulation '(MS-Windows MacOS))
106 ;; (and (boundp 'ls-lisp-dired-ignore-case) ls-lisp-dired-ignore-case))
107 ;; Which isn't the right thing to do.
108 (define-obsolete-variable-alias 'ls-lisp-dired-ignore-case
109 'ls-lisp-ignore-case "21.1")
110
111 (defcustom ls-lisp-ignore-case
112 (memq ls-lisp-emulation '(MS-Windows MacOS))
113 "Non-nil causes ls-lisp alphabetic sorting to ignore case."
114 :set-after '(ls-lisp-emulation)
115 :type 'boolean
116 :group 'ls-lisp)
117
118 (defcustom ls-lisp-dirs-first (eq ls-lisp-emulation 'MS-Windows)
119 "Non-nil causes ls-lisp to sort directories first in any ordering.
120 \(Or last if it is reversed.) Follows Microsoft Windows Explorer."
121 ;; Functionality suggested by Chris McMahan <cmcmahan@one.net>
122 :set-after '(ls-lisp-emulation)
123 :type 'boolean
124 :group 'ls-lisp)
125
126 (defcustom ls-lisp-verbosity
127 (cond ((eq ls-lisp-emulation 'MacOS) nil)
128 ((eq ls-lisp-emulation 'MS-Windows)
129 (if (and (fboundp 'w32-using-nt) (w32-using-nt))
130 '(links))) ; distinguish NT/2K from 9x
131 ((eq ls-lisp-emulation 'UNIX) '(links uid)) ; UNIX ls
132 (t '(links uid gid))) ; GNU ls
133 "A list of optional file attributes that ls-lisp should display.
134 It should contain none or more of the symbols: links, uid, gid.
135 A value of nil (or an empty list) means display none of them.
136
137 Concepts come from UNIX: `links' means count of names associated with
138 the file; `uid' means user (owner) identifier; `gid' means group
139 identifier.
140
141 If emulation is MacOS then default is nil;
142 if emulation is MS-Windows then default is `(links)' if platform is
143 Windows NT/2K, nil otherwise;
144 if emulation is UNIX then default is `(links uid)';
145 if emulation is GNU then default is `(links uid gid)'."
146 :set-after '(ls-lisp-emulation)
147 ;; Functionality suggested by Howard Melman <howard@silverstream.com>
148 :type '(set (const :tag "Show Link Count" links)
149 (const :tag "Show User" uid)
150 (const :tag "Show Group" gid))
151 :group 'ls-lisp)
152
153 (defcustom ls-lisp-use-insert-directory-program
154 (not (memq system-type '(ms-dos windows-nt)))
155 "Non-nil causes ls-lisp to revert back to using `insert-directory-program'.
156 This is useful on platforms where ls-lisp is dumped into Emacs, such as
157 Microsoft Windows, but you would still like to use a program to list
158 the contents of a directory."
159 :type 'boolean
160 :group 'ls-lisp)
161
162 ;;; Autoloaded because it is let-bound in `recover-session', `mail-recover-1'.
163 ;;;###autoload
164 (defcustom ls-lisp-support-shell-wildcards t
165 "Non-nil means ls-lisp treats file patterns as shell wildcards.
166 Otherwise they are treated as Emacs regexps (for backward compatibility)."
167 :type 'boolean
168 :group 'ls-lisp)
169
170 (defcustom ls-lisp-format-time-list
171 '("%b %e %H:%M"
172 "%b %e %Y")
173 "List of `format-time-string' specs to display file time stamps.
174 These specs are used ONLY if a valid locale can not be determined.
175
176 If `ls-lisp-use-localized-time-format' is non-nil, these specs are used
177 regardless of whether the locale can be determined.
178
179 Syntax: (EARLY-TIME-FORMAT OLD-TIME-FORMAT)
180
181 The EARLY-TIME-FORMAT is used if file has been modified within the
182 current year. The OLD-TIME-FORMAT is used for older files. To use ISO
183 8601 dates, you could set:
184
185 \(setq ls-lisp-format-time-list
186 '(\"%Y-%m-%d %H:%M\"
187 \"%Y-%m-%d \"))"
188 :type '(list (string :tag "Early time format")
189 (string :tag "Old time format"))
190 :group 'ls-lisp)
191
192 (defcustom ls-lisp-use-localized-time-format nil
193 "Non-nil means to always use `ls-lisp-format-time-list' for time stamps.
194 This applies even if a valid locale is specified.
195
196 WARNING: Using localized date/time format might cause Dired columns
197 to fail to line up, e.g. if month names are not all of the same length."
198 :type 'boolean
199 :group 'ls-lisp)
200
201 (defvar ls-lisp-uid-d-fmt "-%d"
202 "Format to display integer UIDs.")
203 (defvar ls-lisp-uid-s-fmt "-%s"
204 "Format to display user names.")
205 (defvar ls-lisp-gid-d-fmt "-%d"
206 "Format to display integer GIDs.")
207 (defvar ls-lisp-gid-s-fmt "-%s"
208 "Format to display user group names.")
209 (defvar ls-lisp-filesize-d-fmt "%d"
210 "Format to display integer file sizes.")
211 (defvar ls-lisp-filesize-f-fmt "%.0f"
212 "Format to display float file sizes.")
213 \f
214 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
215
216 (defun ls-lisp--insert-directory (orig-fun file switches &optional wildcard full-directory-p)
217 "Insert directory listing for FILE, formatted according to SWITCHES.
218 Leaves point after the inserted text.
219 SWITCHES may be a string of options, or a list of strings.
220 Optional third arg WILDCARD means treat FILE as shell wildcard.
221 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
222 switches do not contain `d', so that a full listing is expected.
223
224 This version of the function comes from `ls-lisp.el'.
225 If the value of `ls-lisp-use-insert-directory-program' is non-nil then
226 this advice just delegates the work to ORIG-FUN (the normal `insert-directory'
227 function from `files.el').
228 But if the value of `ls-lisp-use-insert-directory-program' is nil
229 then it runs a Lisp emulation.
230
231 The Lisp emulation does not run any external programs or shells. It
232 supports ordinary shell wildcards if `ls-lisp-support-shell-wildcards'
233 is non-nil; otherwise, it interprets wildcards as regular expressions
234 to match file names. It does not support all `ls' switches -- those
235 that work are: A a B C c F G g h i n R r S s t U u X. The l switch
236 is assumed to be always present and cannot be turned off."
237 (if ls-lisp-use-insert-directory-program
238 (funcall orig-fun
239 file switches wildcard full-directory-p)
240 ;; We need the directory in order to find the right handler.
241 (let ((handler (find-file-name-handler (expand-file-name file)
242 'insert-directory))
243 (orig-file file)
244 wildcard-regexp)
245 (if handler
246 (funcall handler 'insert-directory file switches
247 wildcard full-directory-p)
248 ;; Remove --dired switch
249 (if (string-match "--dired " switches)
250 (setq switches (replace-match "" nil nil switches)))
251 ;; Convert SWITCHES to a list of characters.
252 (setq switches (delete ?\ (delete ?- (append switches nil))))
253 ;; Sometimes we get ".../foo*/" as FILE. While the shell and
254 ;; `ls' don't mind, we certainly do, because it makes us think
255 ;; there is no wildcard, only a directory name.
256 (if (and ls-lisp-support-shell-wildcards
257 (string-match "[[?*]" file)
258 ;; Prefer an existing file to wildcards, like
259 ;; dired-noselect does.
260 (not (file-exists-p file)))
261 (progn
262 (or (not (eq (aref file (1- (length file))) ?/))
263 (setq file (substring file 0 (1- (length file)))))
264 (setq wildcard t)))
265 (if wildcard
266 (setq wildcard-regexp
267 (if ls-lisp-support-shell-wildcards
268 (wildcard-to-regexp (file-name-nondirectory file))
269 (file-name-nondirectory file))
270 file (file-name-directory file))
271 (if (memq ?B switches) (setq wildcard-regexp "[^~]\\'")))
272 (condition-case err
273 (ls-lisp-insert-directory
274 file switches (ls-lisp-time-index switches)
275 wildcard-regexp full-directory-p)
276 (invalid-regexp
277 ;; Maybe they wanted a literal file that just happens to
278 ;; use characters special to shell wildcards.
279 (if (equal (cadr err) "Unmatched [ or [^")
280 (progn
281 (setq wildcard-regexp (if (memq ?B switches) "[^~]\\'")
282 file (file-relative-name orig-file))
283 (ls-lisp-insert-directory
284 file switches (ls-lisp-time-index switches)
285 nil full-directory-p))
286 (signal (car err) (cdr err)))))
287 ;; Try to insert the amount of free space.
288 (save-excursion
289 (goto-char (point-min))
290 ;; First find the line to put it on.
291 (when (re-search-forward "^total" nil t)
292 (let ((available (get-free-disk-space ".")))
293 (when available
294 ;; Replace "total" with "total used", to avoid confusion.
295 (replace-match "total used in directory")
296 (end-of-line)
297 (insert " available " available)))))))))
298 (advice-add 'insert-directory :around #'ls-lisp--insert-directory)
299
300 (defun ls-lisp-insert-directory
301 (file switches time-index wildcard-regexp full-directory-p)
302 "Insert directory listing for FILE, formatted according to SWITCHES.
303 Leaves point after the inserted text. This is an internal function
304 optionally called by the `ls-lisp.el' version of `insert-directory'.
305 It is called recursively if the -R switch is used.
306 SWITCHES is a *list* of characters. TIME-INDEX is the time index into
307 file-attributes according to SWITCHES. WILDCARD-REGEXP is nil or an *Emacs
308 regexp*. FULL-DIRECTORY-P means file is a directory and SWITCHES does
309 not contain `d', so that a full listing is expected."
310 (if (or wildcard-regexp full-directory-p)
311 (let* ((dir (file-name-as-directory file))
312 (default-directory dir) ; so that file-attributes works
313 (file-alist
314 (directory-files-and-attributes dir nil wildcard-regexp t
315 (if (memq ?n switches)
316 'integer
317 'string)))
318 (sum 0)
319 (max-uid-len 0)
320 (max-gid-len 0)
321 (max-file-size 0)
322 ;; do all bindings here for speed
323 total-line files elt short file-size attr
324 fuid fgid uid-len gid-len)
325 (setq file-alist (ls-lisp-sanitize file-alist))
326 (cond ((memq ?A switches)
327 (setq file-alist
328 (ls-lisp-delete-matching "^\\.\\.?$" file-alist)))
329 ((not (memq ?a switches))
330 ;; if neither -A nor -a, flush . files
331 (setq file-alist
332 (ls-lisp-delete-matching "^\\." file-alist))))
333 (setq file-alist
334 (ls-lisp-handle-switches file-alist switches))
335 (if (memq ?C switches) ; column (-C) format
336 (ls-lisp-column-format file-alist)
337 (setq total-line (cons (point) (car-safe file-alist)))
338 ;; Find the appropriate format for displaying uid, gid, and
339 ;; file size, by finding the longest strings among all the
340 ;; files we are about to display.
341 (dolist (elt file-alist)
342 (setq attr (cdr elt)
343 fuid (nth 2 attr)
344 uid-len (if (stringp fuid) (string-width fuid)
345 (length (format "%d" fuid)))
346 fgid (nth 3 attr)
347 gid-len (if (stringp fgid) (string-width fgid)
348 (length (format "%d" fgid)))
349 file-size (nth 7 attr))
350 (if (> uid-len max-uid-len)
351 (setq max-uid-len uid-len))
352 (if (> gid-len max-gid-len)
353 (setq max-gid-len gid-len))
354 (if (> file-size max-file-size)
355 (setq max-file-size file-size)))
356 (setq ls-lisp-uid-d-fmt (format " %%-%dd" max-uid-len))
357 (setq ls-lisp-uid-s-fmt (format " %%-%ds" max-uid-len))
358 (setq ls-lisp-gid-d-fmt (format " %%-%dd" max-gid-len))
359 (setq ls-lisp-gid-s-fmt (format " %%-%ds" max-gid-len))
360 (setq ls-lisp-filesize-d-fmt
361 (format " %%%dd"
362 (if (memq ?s switches)
363 (length (format "%.0f"
364 (fceiling (/ max-file-size 1024.0))))
365 (length (format "%.0f" max-file-size)))))
366 (setq ls-lisp-filesize-f-fmt
367 (format " %%%d.0f"
368 (if (memq ?s switches)
369 (length (format "%.0f"
370 (fceiling (/ max-file-size 1024.0))))
371 (length (format "%.0f" max-file-size)))))
372 (setq files file-alist)
373 (while files ; long (-l) format
374 (setq elt (car files)
375 files (cdr files)
376 short (car elt)
377 attr (cdr elt)
378 file-size (nth 7 attr))
379 (and attr
380 (setq sum (+ file-size
381 ;; Even if neither SUM nor file's size
382 ;; overflow, their sum could.
383 (if (or (< sum (- 134217727 file-size))
384 (floatp sum)
385 (floatp file-size))
386 sum
387 (float sum))))
388 (insert (ls-lisp-format short attr file-size
389 switches time-index))))
390 ;; Insert total size of all files:
391 (save-excursion
392 (goto-char (car total-line))
393 (or (cdr total-line)
394 ;; Shell says ``No match'' if no files match
395 ;; the wildcard; let's say something similar.
396 (insert "(No match)\n"))
397 (insert (format "total %.0f\n" (fceiling (/ sum 1024.0))))))
398 ;; dired-insert-directory expects to find point after the
399 ;; text. But if the listing is empty, as e.g. in empty
400 ;; directories with -a removed from switches, point will be
401 ;; before the inserted text, and dired-insert-directory will
402 ;; not indent the listing correctly. Going to the end of the
403 ;; buffer fixes that.
404 (unless files (goto-char (point-max)))
405 (if (memq ?R switches)
406 ;; List the contents of all directories recursively.
407 ;; cadr of each element of `file-alist' is t for
408 ;; directory, string (name linked to) for symbolic
409 ;; link, or nil.
410 (while file-alist
411 (setq elt (car file-alist)
412 file-alist (cdr file-alist))
413 (when (and (eq (cadr elt) t) ; directory
414 ;; Under -F, we have already decorated all
415 ;; directories, including "." and "..", with
416 ;; a /, so allow for that as well.
417 (not (string-match "\\`\\.\\.?/?\\'" (car elt))))
418 (setq elt (expand-file-name (car elt) dir))
419 (insert "\n" elt ":\n")
420 (ls-lisp-insert-directory
421 elt switches time-index wildcard-regexp full-directory-p)))))
422 ;; If not full-directory-p, FILE *must not* end in /, as
423 ;; file-attributes will not recognize a symlink to a directory,
424 ;; so must make it a relative filename as ls does:
425 (if (file-name-absolute-p file) (setq file (expand-file-name file)))
426 (if (eq (aref file (1- (length file))) ?/)
427 (setq file (substring file 0 -1)))
428 (let ((fattr (file-attributes file 'string)))
429 (if fattr
430 (insert (ls-lisp-format
431 (if (memq ?F switches)
432 (ls-lisp-classify-file file fattr)
433 file)
434 fattr (nth 7 fattr)
435 switches time-index))
436 (message "%s: doesn't exist or is inaccessible" file)
437 (ding) (sit-for 2))))) ; to show user the message!
438
439 (defun ls-lisp-sanitize (file-alist)
440 "Sanitize the elements in FILE-ALIST.
441 Fixes any elements in the alist for directory entries whose file
442 attributes are nil (meaning that `file-attributes' failed for
443 them). This is known to happen for some network shares, in
444 particular for the \"..\" directory entry.
445
446 If the \"..\" directory entry has nil attributes, the attributes
447 are copied from the \".\" entry, if they are non-nil. Otherwise,
448 the offending element is removed from the list, as are any
449 elements for other directory entries with nil attributes."
450 (if (and (null (cdr (assoc ".." file-alist)))
451 (cdr (assoc "." file-alist)))
452 (setcdr (assoc ".." file-alist) (cdr (assoc "." file-alist))))
453 (rassq-delete-all nil file-alist))
454
455 (defun ls-lisp-column-format (file-alist)
456 "Insert the file names (only) in FILE-ALIST into the current buffer.
457 Format in columns, sorted vertically, following GNU ls -C.
458 Responds to the window width as ls should but may not!"
459 (let (files fmt ncols collen (nfiles 0) (colwid 0))
460 ;; Count number of files as `nfiles', build list of filenames as
461 ;; `files', and find maximum filename length as `colwid':
462 (let (file len)
463 (while file-alist
464 (setq nfiles (1+ nfiles)
465 file (caar file-alist)
466 files (cons file files)
467 file-alist (cdr file-alist)
468 len (length file))
469 (if (> len colwid) (setq colwid len))))
470 (setq files (nreverse files)
471 colwid (+ 2 colwid) ; 2 character column gap
472 fmt (format "%%-%ds" colwid) ; print format
473 ncols (/ (window-width) colwid) ; no of columns
474 collen (/ nfiles ncols)) ; floor of column length
475 (if (> nfiles (* collen ncols)) (setq collen (1+ collen)))
476 ;; Output the file names in columns, sorted vertically:
477 (let ((i 0) j)
478 (while (< i collen)
479 (setq j i)
480 (while (< j nfiles)
481 (insert (format fmt (nth j files)))
482 (setq j (+ j collen)))
483 ;; FJW: This is completely unnecessary, but I don't like
484 ;; trailing white space...
485 (delete-region (point) (progn (skip-chars-backward " \t") (point)))
486 (insert ?\n)
487 (setq i (1+ i))))))
488
489 (defun ls-lisp-delete-matching (regexp list)
490 "Delete all elements matching REGEXP from LIST, return new list."
491 ;; Should perhaps use setcdr for efficiency.
492 (let (result)
493 (while list
494 (or (string-match regexp (caar list))
495 (setq result (cons (car list) result)))
496 (setq list (cdr list)))
497 result))
498
499 (defsubst ls-lisp-string-lessp (s1 s2)
500 "Return t if string S1 is less than string S2 in lexicographic order.
501 Case is significant if `ls-lisp-ignore-case' is nil.
502 Unibyte strings are converted to multibyte for comparison."
503 (let ((u (compare-strings s1 0 nil s2 0 nil ls-lisp-ignore-case)))
504 (and (numberp u) (< u 0))))
505
506 (defun ls-lisp-handle-switches (file-alist switches)
507 "Return new FILE-ALIST sorted according to SWITCHES.
508 SWITCHES is a list of characters. Default sorting is alphabetic."
509 ;; FILE-ALIST's elements are (FILE . FILE-ATTRIBUTES).
510 (or (memq ?U switches) ; unsorted
511 ;; Catch and ignore unexpected sorting errors
512 (condition-case err
513 (setq file-alist
514 (let (index)
515 ;; Copy file-alist in case of error
516 (sort (copy-sequence file-alist) ; modifies its argument!
517 (cond ((memq ?S switches)
518 (lambda (x y) ; sorted on size
519 ;; 7th file attribute is file size
520 ;; Make largest file come first
521 (< (nth 7 (cdr y))
522 (nth 7 (cdr x)))))
523 ((setq index (ls-lisp-time-index switches))
524 (lambda (x y) ; sorted on time
525 (time-less-p (nth index (cdr y))
526 (nth index (cdr x)))))
527 ((memq ?X switches)
528 (lambda (x y) ; sorted on extension
529 (ls-lisp-string-lessp
530 (ls-lisp-extension (car x))
531 (ls-lisp-extension (car y)))))
532 (t
533 (lambda (x y) ; sorted alphabetically
534 (ls-lisp-string-lessp (car x) (car y))))))))
535 (error (message "Unsorted (ls-lisp sorting error) - %s"
536 (error-message-string err))
537 (ding) (sit-for 2)))) ; to show user the message!
538 (if (memq ?F switches) ; classify switch
539 (setq file-alist (mapcar 'ls-lisp-classify file-alist)))
540 (if ls-lisp-dirs-first
541 ;; Re-sort directories first, without otherwise changing the
542 ;; ordering, and reverse whole list. cadr of each element of
543 ;; `file-alist' is t for directory, string (name linked to) for
544 ;; symbolic link, or nil.
545 (let (el dirs files)
546 (while file-alist
547 (if (or (eq (cadr (setq el (car file-alist))) t) ; directory
548 (and (stringp (cadr el))
549 (file-directory-p (cadr el)))) ; symlink to a directory
550 (setq dirs (cons el dirs))
551 (setq files (cons el files)))
552 (setq file-alist (cdr file-alist)))
553 (setq file-alist
554 (if (memq ?U switches) ; unsorted order is reversed
555 (nconc dirs files)
556 (nconc files dirs)
557 ))))
558 ;; Finally reverse file alist if necessary.
559 ;; (eq below MUST compare `(not (memq ...))' to force comparison of
560 ;; `t' or `nil', rather than list tails!)
561 (if (eq (eq (not (memq ?U switches)) ; unsorted order is reversed
562 (not (memq ?r switches))) ; reversed sort order requested
563 ls-lisp-dirs-first) ; already reversed
564 (nreverse file-alist)
565 file-alist))
566
567 (defun ls-lisp-classify-file (filename fattr)
568 "Append a character to FILENAME indicating the file type.
569
570 FATTR is the file attributes returned by `file-attributes' for the file.
571 The file type indicators are `/' for directories, `@' for symbolic
572 links, `|' for FIFOs, `=' for sockets, `*' for regular files that
573 are executable, and nothing for other types of files."
574 (let* ((type (car fattr))
575 (modestr (nth 8 fattr))
576 (typestr (substring modestr 0 1)))
577 (cond
578 (type
579 (concat filename (if (eq type t) "/" "@")))
580 ((string-match "x" modestr)
581 (concat filename "*"))
582 ((string= "p" typestr)
583 (concat filename "|"))
584 ((string= "s" typestr)
585 (concat filename "="))
586 (t filename))))
587
588 (defun ls-lisp-classify (filedata)
589 "Append a character to file name in FILEDATA indicating the file type.
590
591 FILEDATA has the form (FILENAME . ATTRIBUTES), where ATTRIBUTES is the
592 structure returned by `file-attributes' for that file.
593
594 The file type indicators are `/' for directories, `@' for symbolic
595 links, `|' for FIFOs, `=' for sockets, `*' for regular files that
596 are executable, and nothing for other types of files."
597 (let ((file-name (car filedata))
598 (fattr (cdr filedata)))
599 (setq file-name (propertize file-name 'dired-filename t))
600 (cons (ls-lisp-classify-file file-name fattr) fattr)))
601
602 (defun ls-lisp-extension (filename)
603 "Return extension of FILENAME (ignoring any version extension)
604 FOLLOWED by null and full filename, SOLELY for full alpha sort."
605 ;; Force extension sort order: `no ext' then `null ext' then `ext'
606 ;; to agree with GNU ls.
607 (concat
608 (let* ((i (length filename)) end)
609 (if (= (aref filename (1- i)) ?.) ; null extension
610 "\0"
611 (while (and (>= (setq i (1- i)) 0)
612 (/= (aref filename i) ?.)))
613 (if (< i 0) "\0\0" ; no extension
614 (if (/= (aref filename (1+ i)) ?~)
615 (substring filename (1+ i))
616 ;; version extension found -- ignore it
617 (setq end i)
618 (while (and (>= (setq i (1- i)) 0)
619 (/= (aref filename i) ?.)))
620 (if (< i 0) "\0\0" ; no extension
621 (substring filename (1+ i) end))))
622 )) "\0" filename))
623
624 (defun ls-lisp-format (file-name file-attr file-size switches time-index)
625 "Format one line of long ls output for file FILE-NAME.
626 FILE-ATTR and FILE-SIZE give the file's attributes and size.
627 SWITCHES and TIME-INDEX give the full switch list and time data."
628 (let ((file-type (nth 0 file-attr))
629 ;; t for directory, string (name linked to)
630 ;; for symbolic link, or nil.
631 (drwxrwxrwx (nth 8 file-attr))) ; attribute string ("drwxrwxrwx")
632 (concat (if (memq ?i switches) ; inode number
633 (let ((inode (nth 10 file-attr)))
634 (if (consp inode)
635 (if (consp (cdr inode))
636 ;; 2^(24+16) = 1099511627776.0, but
637 ;; multiplying by it and then adding the
638 ;; other members of the cons cell in one go
639 ;; loses precision, since a double does not
640 ;; have enough significant digits to hold a
641 ;; full 64-bit value. So below we split
642 ;; 1099511627776 into high 13 and low 5
643 ;; digits and compute in two parts.
644 (let ((p1 (* (car inode) 10995116.0))
645 (p2 (+ (* (car inode) 27776.0)
646 (* (cadr inode) 65536.0)
647 (cddr inode))))
648 (format " %13.0f%05.0f "
649 ;; Use floor to emulate integer
650 ;; division.
651 (+ p1 (floor p2 100000.0))
652 (mod p2 100000.0)))
653 (format " %18.0f "
654 (+ (* (car inode) 65536.0)
655 (cdr inode))))
656 (format " %18d " inode))))
657 ;; nil is treated like "" in concat
658 (if (memq ?s switches) ; size in K
659 (format ls-lisp-filesize-f-fmt
660 (fceiling (/ file-size 1024.0))))
661 drwxrwxrwx ; attribute string
662 (if (memq 'links ls-lisp-verbosity)
663 (format "%3d" (nth 1 file-attr))) ; link count
664 ;; Numeric uid/gid are more confusing than helpful;
665 ;; Emacs should be able to make strings of them.
666 ;; They tend to be bogus on non-UNIX platforms anyway so
667 ;; optionally hide them.
668 (if (memq 'uid ls-lisp-verbosity)
669 ;; uid can be a string or an integer
670 (let ((uid (nth 2 file-attr)))
671 (format (if (stringp uid)
672 ls-lisp-uid-s-fmt
673 ls-lisp-uid-d-fmt)
674 uid)))
675 (if (not (memq ?G switches)) ; GNU ls -- shows group by default
676 (if (or (memq ?g switches) ; UNIX ls -- no group by default
677 (memq 'gid ls-lisp-verbosity))
678 (let ((gid (nth 3 file-attr)))
679 (format (if (stringp gid)
680 ls-lisp-gid-s-fmt
681 ls-lisp-gid-d-fmt)
682 gid))))
683 (ls-lisp-format-file-size file-size (memq ?h switches))
684 " "
685 (ls-lisp-format-time file-attr time-index)
686 " "
687 (if (not (memq ?F switches)) ; ls-lisp-classify already did that
688 (propertize file-name 'dired-filename t)
689 file-name)
690 (if (stringp file-type) ; is a symbolic link
691 (concat " -> " file-type))
692 "\n"
693 )))
694
695 (defun ls-lisp-time-index (switches)
696 "Return time index into file-attributes according to ls SWITCHES list.
697 Return nil if no time switch found."
698 ;; FJW: Default of nil is IMPORTANT and used in `ls-lisp-handle-switches'!
699 (cond ((memq ?c switches) 6) ; last mode change
700 ((memq ?t switches) 5) ; last modtime
701 ((memq ?u switches) 4))) ; last access
702
703 (defun ls-lisp-format-time (file-attr time-index)
704 "Format time for file with attributes FILE-ATTR according to TIME-INDEX.
705 Use the same method as ls to decide whether to show time-of-day or year,
706 depending on distance between file date and the current time.
707 All ls time options, namely c, t and u, are handled."
708 (let* ((time (nth (or time-index 5) file-attr)) ; default is last modtime
709 (diff (- (float-time time) (float-time)))
710 ;; Consider a time to be recent if it is within the past six
711 ;; months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
712 ;; 31556952 seconds on the average, and half of that is 15778476.
713 ;; Write the constant explicitly to avoid roundoff error.
714 (past-cutoff -15778476)) ; half a Gregorian year
715 (condition-case nil
716 ;; Use traditional time format in the C or POSIX locale,
717 ;; ISO-style time format otherwise, so columns line up.
718 (let ((locale system-time-locale))
719 (if (not locale)
720 (let ((vars '("LC_ALL" "LC_TIME" "LANG")))
721 (while (and vars (not (setq locale (getenv (car vars)))))
722 (setq vars (cdr vars)))))
723 (if (member locale '("C" "POSIX"))
724 (setq locale nil))
725 (format-time-string
726 (if (and (<= past-cutoff diff) (<= diff 0))
727 (if (and locale (not ls-lisp-use-localized-time-format))
728 "%m-%d %H:%M"
729 (nth 0 ls-lisp-format-time-list))
730 (if (and locale (not ls-lisp-use-localized-time-format))
731 "%Y-%m-%d "
732 (nth 1 ls-lisp-format-time-list)))
733 time))
734 (error "Unk 0 0000"))))
735
736 (defun ls-lisp-format-file-size (file-size human-readable)
737 (if (not human-readable)
738 (format (if (floatp file-size)
739 ls-lisp-filesize-f-fmt
740 ls-lisp-filesize-d-fmt)
741 file-size)
742 (format " %7s" (file-size-human-readable file-size))))
743
744 (provide 'ls-lisp)
745
746 ;;; ls-lisp.el ends here