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