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