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