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