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