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