Improve format-time-string doc
[emacs.git] / lisp / ls-lisp.el
blob280e7f4bc3e295bcaf1c72956a1d22d6527dc740
1 ;;; ls-lisp.el --- emulate insert-directory completely in Emacs Lisp -*- lexical-binding: t -*-
3 ;; Copyright (C) 1992, 1994, 2000-2017 Free Software Foundation, Inc.
5 ;; Author: Sebastian Kremer <sk@thp.uni-koeln.de>
6 ;; Modified by: Francis J. Wright <F.J.Wright@maths.qmw.ac.uk>
7 ;; Maintainer: emacs-devel@gnu.org
8 ;; Keywords: unix, dired
9 ;; Package: emacs
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 <https://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; OVERVIEW ==========================================================
30 ;; This file advises the function `insert-directory' to implement it
31 ;; directly from Emacs lisp, without running ls in a subprocess.
32 ;; This is useful if you don't have ls installed (ie, on MS Windows).
34 ;; This function can use regexps instead of shell wildcards. If you
35 ;; enter regexps remember to double each $ sign. For example, to
36 ;; include files *.el, enter `.*\.el$$', resulting in the regexp
37 ;; `.*\.el$'.
39 ;; RESTRICTIONS ======================================================
41 ;; * A few obscure ls switches are still ignored: see the docstring of
42 ;; `insert-directory'.
44 ;; TO DO =============================================================
46 ;; Complete handling of F switch (if/when possible).
48 ;; FJW: May be able to sort much faster by consing the sort key onto
49 ;; the front of each list element, sorting and then stripping the key
50 ;; off again!
52 ;;; History:
54 ;; Written originally by Sebastian Kremer <sk@thp.uni-koeln.de>
55 ;; Revised by Andrew Innes and Geoff Volker (and maybe others).
57 ;; Modified by Francis J. Wright <F.J.Wright@maths.qmw.ac.uk>, mainly
58 ;; to support many more ls options, "platform emulation" and more
59 ;; robust sorting.
61 ;;; Code:
65 (defgroup ls-lisp nil
66 "Emulate the ls program completely in Emacs Lisp."
67 :version "21.1"
68 :group 'dired)
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)))
75 (defcustom ls-lisp-emulation
76 (cond ;; ((eq system-type 'windows-nt) 'MS-Windows)
77 ((memq system-type '(hpux usg-unix-v berkeley-unix))
78 'UNIX)) ; very similar to GNU
79 ;; Anything else defaults to nil, meaning GNU.
80 "Platform to emulate: GNU (default), macOS, MS-Windows, UNIX.
81 Corresponding value is one of: nil, `MacOS', `MS-Windows', `UNIX'.
82 Set this to your preferred value; it need not match the actual platform
83 you are using.
85 This variable does not affect the behavior of ls-lisp directly.
86 Rather, it controls the default values for some variables that do:
87 `ls-lisp-ignore-case', `ls-lisp-dirs-first', and `ls-lisp-verbosity'.
89 If you change this variable directly (without using customize)
90 after loading `ls-lisp', you should use `ls-lisp-set-options' to
91 update the dependent variables."
92 :type '(choice (const :tag "GNU" nil)
93 (const MacOS)
94 (const MS-Windows)
95 (const UNIX))
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)))
101 :group 'ls-lisp)
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")
111 (defcustom ls-lisp-ignore-case
112 (memq ls-lisp-emulation '(MS-Windows MacOS))
113 "Non-nil causes ls-lisp alphabetic sorting to ignore case."
114 :set-after '(ls-lisp-emulation)
115 :type 'boolean
116 :group 'ls-lisp)
118 (defcustom ls-lisp-use-string-collate
119 (cond ((memq ls-lisp-emulation '(MacOS UNIX)) nil)
120 (t t)) ; GNU/Linux or MS-Windows emulate GNU ls
121 "Non-nil causes ls-lisp to sort files in locale-dependent collation order.
123 A value of nil means use ordinary string comparison (see `compare-strings')
124 for sorting files. A non-nil value uses `string-collate-lessp' instead,
125 which more closely emulates what GNU `ls' does.
127 On GNU/Linux systems, if the locale's codeset specifies UTF-8, as
128 in \"en_US.UTF-8\", the collation order follows the Unicode
129 Collation Algorithm (UCA), which places together file names that
130 differ only in punctuation characters. On MS-Windows, customize
131 the option `ls-lisp-UCA-like-collation' to a non-nil value to get
132 similar behavior."
133 :version "25.1"
134 :set-after '(ls-lisp-emulation)
135 :type 'boolean
136 :group 'ls-lisp)
138 (defcustom ls-lisp-UCA-like-collation t
139 "Non-nil means force ls-lisp use a collation order compatible with UCA.
141 UCA is the Unicode Collation Algorithm. GNU/Linux systems automatically
142 follow it in their string-collation routines if the locale specifies
143 UTF-8 as its codeset. On MS-Windows, customize this option to a non-nil
144 value to get similar behavior.
146 When this option is non-nil, and `ls-lisp-use-string-collate' is also
147 non-nil, the collation order produced on MS-Windows will ignore
148 punctuation and symbol characters, which will, for example, place
149 `.foo' near `foo'. See the documentation of `string-collate-lessp'
150 and `w32-collate-ignore-punctuation' for more details.
152 This option is ignored on platforms other than MS-Windows; to
153 control the collation ordering of the file names on those other
154 systems, set your locale instead."
155 :version "25.1"
156 :type 'boolean
157 :group 'ls-lisp)
159 (defcustom ls-lisp-dirs-first (eq ls-lisp-emulation 'MS-Windows)
160 "Non-nil causes ls-lisp to sort directories first in any ordering.
161 \(Or last if it is reversed.) Follows Microsoft Windows Explorer."
162 ;; Functionality suggested by Chris McMahan <cmcmahan@one.net>
163 :set-after '(ls-lisp-emulation)
164 :type 'boolean
165 :group 'ls-lisp)
167 (defcustom ls-lisp-verbosity
168 (cond ((eq ls-lisp-emulation 'MacOS) nil)
169 ((eq ls-lisp-emulation 'MS-Windows)
170 (if (and (fboundp 'w32-using-nt) (w32-using-nt))
171 '(links))) ; distinguish NT/2K from 9x
172 ((eq ls-lisp-emulation 'UNIX) '(links uid)) ; UNIX ls
173 (t '(links uid gid))) ; GNU ls
174 "A list of optional file attributes that ls-lisp should display.
175 It should contain none or more of the symbols: links, uid, gid.
176 A value of nil (or an empty list) means display none of them.
178 Concepts come from UNIX: `links' means count of names associated with
179 the file; `uid' means user (owner) identifier; `gid' means group
180 identifier.
182 If emulation is MacOS then default is nil;
183 if emulation is MS-Windows then default is `(links)' if platform is
184 Windows NT/2K, nil otherwise;
185 if emulation is UNIX then default is `(links uid)';
186 if emulation is GNU then default is `(links uid gid)'."
187 :set-after '(ls-lisp-emulation)
188 ;; Functionality suggested by Howard Melman <howard@silverstream.com>
189 :type '(set (const :tag "Show Link Count" links)
190 (const :tag "Show User" uid)
191 (const :tag "Show Group" gid))
192 :group 'ls-lisp)
194 (defcustom ls-lisp-use-insert-directory-program
195 (not (memq system-type '(ms-dos windows-nt)))
196 "Non-nil causes ls-lisp to revert back to using `insert-directory-program'.
197 This is useful on platforms where ls-lisp is dumped into Emacs, such as
198 Microsoft Windows, but you would still like to use a program to list
199 the contents of a directory."
200 :type 'boolean
201 :group 'ls-lisp)
203 ;;; Autoloaded because it is let-bound in `recover-session', `mail-recover-1'.
204 ;;;###autoload
205 (defcustom ls-lisp-support-shell-wildcards t
206 "Non-nil means ls-lisp treats file patterns as shell wildcards.
207 Otherwise they are treated as Emacs regexps (for backward compatibility)."
208 :type 'boolean
209 :group 'ls-lisp)
211 (defcustom ls-lisp-format-time-list
212 '("%b %e %H:%M"
213 "%b %e %Y")
214 "List of `format-time-string' specs to display file time stamps.
215 These specs are used ONLY if a valid locale can not be determined.
217 If `ls-lisp-use-localized-time-format' is non-nil, these specs are used
218 regardless of whether the locale can be determined.
220 Syntax: (EARLY-TIME-FORMAT OLD-TIME-FORMAT)
222 The EARLY-TIME-FORMAT is used if file has been modified within the
223 current year. The OLD-TIME-FORMAT is used for older files. To use ISO
224 8601 dates, you could set:
226 \(setq ls-lisp-format-time-list
227 \\='(\"%Y-%m-%d %H:%M\"
228 \"%Y-%m-%d \"))"
229 :type '(list (string :tag "Early time format")
230 (string :tag "Old time format"))
231 :group 'ls-lisp)
233 (defcustom ls-lisp-use-localized-time-format nil
234 "Non-nil means to always use `ls-lisp-format-time-list' for time stamps.
235 This applies even if a valid locale is specified.
237 WARNING: Using localized date/time format might cause Dired columns
238 to fail to line up, e.g. if month names are not all of the same length."
239 :type 'boolean
240 :group 'ls-lisp)
242 (defvar ls-lisp-uid-d-fmt " %d"
243 "Format to display integer UIDs.")
244 (defvar ls-lisp-uid-s-fmt " %s"
245 "Format to display user names.")
246 (defvar ls-lisp-gid-d-fmt " %d"
247 "Format to display integer GIDs.")
248 (defvar ls-lisp-gid-s-fmt " %s"
249 "Format to display user group names.")
250 (defvar ls-lisp-filesize-d-fmt " %d"
251 "Format to display integer file sizes.")
252 (defvar ls-lisp-filesize-f-fmt " %.0f"
253 "Format to display float file sizes.")
254 (defvar ls-lisp-filesize-b-fmt " %.0f"
255 "Format to display file sizes in blocks (for the -s switch).")
257 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
259 (defun ls-lisp--insert-directory (orig-fun file switches &optional wildcard full-directory-p)
260 "Insert directory listing for FILE, formatted according to SWITCHES.
261 Leaves point after the inserted text.
262 SWITCHES may be a string of options, or a list of strings.
263 Optional third arg WILDCARD means treat FILE as shell wildcard.
264 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
265 switches do not contain `d', so that a full listing is expected.
267 This version of the function comes from `ls-lisp.el'.
268 If the value of `ls-lisp-use-insert-directory-program' is non-nil then
269 this advice just delegates the work to ORIG-FUN (the normal `insert-directory'
270 function from `files.el').
271 But if the value of `ls-lisp-use-insert-directory-program' is nil
272 then it runs a Lisp emulation.
274 The Lisp emulation does not run any external programs or shells. It
275 supports ordinary shell wildcards if `ls-lisp-support-shell-wildcards'
276 is non-nil; otherwise, it interprets wildcards as regular expressions
277 to match file names. It does not support all `ls' switches -- those
278 that work are: A a B C c F G g h i n R r S s t U u v X. The l switch
279 is assumed to be always present and cannot be turned off."
280 (if ls-lisp-use-insert-directory-program
281 (funcall orig-fun
282 file switches wildcard full-directory-p)
283 ;; We need the directory in order to find the right handler.
284 (let ((handler (find-file-name-handler (expand-file-name file)
285 'insert-directory))
286 (orig-file file)
287 wildcard-regexp)
288 (if handler
289 (funcall handler 'insert-directory file switches
290 wildcard full-directory-p)
291 ;; Remove --dired switch
292 (if (string-match "--dired " switches)
293 (setq switches (replace-match "" nil nil switches)))
294 ;; Convert SWITCHES to a list of characters.
295 (setq switches (delete ?\ (delete ?- (append switches nil))))
296 ;; Sometimes we get ".../foo*/" as FILE. While the shell and
297 ;; `ls' don't mind, we certainly do, because it makes us think
298 ;; there is no wildcard, only a directory name.
299 (if (and ls-lisp-support-shell-wildcards
300 (string-match "[[?*]" file)
301 ;; Prefer an existing file to wildcards, like
302 ;; dired-noselect does.
303 (not (file-exists-p file)))
304 (progn
305 (or (not (eq (aref file (1- (length file))) ?/))
306 (setq file (substring file 0 (1- (length file)))))
307 (setq wildcard t)))
308 (if wildcard
309 (setq wildcard-regexp
310 (if ls-lisp-support-shell-wildcards
311 (wildcard-to-regexp (file-name-nondirectory file))
312 (file-name-nondirectory file))
313 file (file-name-directory file))
314 (if (memq ?B switches) (setq wildcard-regexp "[^~]\\'")))
315 (condition-case err
316 (ls-lisp-insert-directory
317 file switches (ls-lisp-time-index switches)
318 wildcard-regexp full-directory-p)
319 (invalid-regexp
320 ;; Maybe they wanted a literal file that just happens to
321 ;; use characters special to shell wildcards.
322 (if (equal (cadr err) "Unmatched [ or [^")
323 (progn
324 (setq wildcard-regexp (if (memq ?B switches) "[^~]\\'")
325 file (file-relative-name orig-file))
326 (ls-lisp-insert-directory
327 file switches (ls-lisp-time-index switches)
328 nil full-directory-p))
329 (signal (car err) (cdr err)))))
330 ;; Try to insert the amount of free space.
331 (save-excursion
332 (goto-char (point-min))
333 ;; First find the line to put it on.
334 (when (re-search-forward "^total" nil t)
335 (let ((available (get-free-disk-space ".")))
336 (when available
337 ;; Replace "total" with "total used", to avoid confusion.
338 (replace-match "total used in directory")
339 (end-of-line)
340 (insert " available " available)))))))))
341 (advice-add 'insert-directory :around #'ls-lisp--insert-directory)
343 (defun ls-lisp-insert-directory
344 (file switches time-index wildcard-regexp full-directory-p)
345 "Insert directory listing for FILE, formatted according to SWITCHES.
346 Leaves point after the inserted text. This is an internal function
347 optionally called by the `ls-lisp.el' version of `insert-directory'.
348 It is called recursively if the -R switch is used.
349 SWITCHES is a *list* of characters. TIME-INDEX is the time index into
350 file-attributes according to SWITCHES. WILDCARD-REGEXP is nil or an *Emacs
351 regexp*. FULL-DIRECTORY-P means file is a directory and SWITCHES does
352 not contain `d', so that a full listing is expected."
353 (if (or (and wildcard-regexp
354 (not (string= "[^~]\\'" wildcard-regexp))) ; Switch -B pseudo-wildcard regexp
355 full-directory-p)
356 (let* ((dir (file-name-as-directory file))
357 (default-directory dir) ; so that file-attributes works
358 (file-alist
359 (directory-files-and-attributes dir nil wildcard-regexp t
360 (if (memq ?n switches)
361 'integer
362 'string)))
363 (sum 0)
364 (max-uid-len 0)
365 (max-gid-len 0)
366 (max-file-size 0)
367 ;; do all bindings here for speed
368 total-line files elt short file-size attr
369 fuid fgid uid-len gid-len)
370 (setq file-alist (ls-lisp-sanitize file-alist))
371 (cond ((memq ?A switches)
372 (setq file-alist
373 (ls-lisp-delete-matching "^\\.\\.?$" file-alist)))
374 ((not (memq ?a switches))
375 ;; if neither -A nor -a, flush . files
376 (setq file-alist
377 (ls-lisp-delete-matching "^\\." file-alist))))
378 (setq file-alist
379 (ls-lisp-handle-switches file-alist switches))
380 (if (memq ?C switches) ; column (-C) format
381 (ls-lisp-column-format file-alist)
382 (setq total-line (cons (point) (car-safe file-alist)))
383 ;; Find the appropriate format for displaying uid, gid, and
384 ;; file size, by finding the longest strings among all the
385 ;; files we are about to display.
386 (dolist (elt file-alist)
387 (setq attr (cdr elt)
388 fuid (nth 2 attr)
389 uid-len (if (stringp fuid) (string-width fuid)
390 (length (format "%d" fuid)))
391 fgid (nth 3 attr)
392 gid-len (if (stringp fgid) (string-width fgid)
393 (length (format "%d" fgid)))
394 file-size (nth 7 attr))
395 (if (> uid-len max-uid-len)
396 (setq max-uid-len uid-len))
397 (if (> gid-len max-gid-len)
398 (setq max-gid-len gid-len))
399 (if (> file-size max-file-size)
400 (setq max-file-size file-size)))
401 (setq ls-lisp-uid-d-fmt (format " %%-%dd" max-uid-len))
402 (setq ls-lisp-uid-s-fmt (format " %%-%ds" max-uid-len))
403 (setq ls-lisp-gid-d-fmt (format " %%-%dd" max-gid-len))
404 (setq ls-lisp-gid-s-fmt (format " %%-%ds" max-gid-len))
405 (setq ls-lisp-filesize-d-fmt
406 (format " %%%dd" (length (format "%.0f" max-file-size))))
407 (setq ls-lisp-filesize-f-fmt
408 (format " %%%d.0f" (length (format "%.0f" max-file-size))))
409 (if (memq ?s switches)
410 (setq ls-lisp-filesize-b-fmt
411 (format "%%%d.0f "
412 (length (format "%.0f"
413 (fceiling
414 (/ max-file-size 1024.0)))))))
415 (setq files file-alist)
416 (while files ; long (-l) format
417 (setq elt (car files)
418 files (cdr files)
419 short (car elt)
420 attr (cdr elt)
421 file-size (nth 7 attr))
422 (and attr
423 (setq sum (+ file-size
424 ;; Even if neither SUM nor file's size
425 ;; overflow, their sum could.
426 (if (or (< sum (- 134217727 file-size))
427 (floatp sum)
428 (floatp file-size))
430 (float sum))))
431 (insert (ls-lisp-format short attr file-size
432 switches time-index))))
433 ;; Insert total size of all files:
434 (save-excursion
435 (goto-char (car total-line))
436 (or (cdr total-line)
437 ;; Shell says ``No match'' if no files match
438 ;; the wildcard; let's say something similar.
439 (insert "(No match)\n"))
440 (insert (format "total %.0f\n" (fceiling (/ sum 1024.0))))))
441 ;; dired-insert-directory expects to find point after the
442 ;; text. But if the listing is empty, as e.g. in empty
443 ;; directories with -a removed from switches, point will be
444 ;; before the inserted text, and dired-insert-directory will
445 ;; not indent the listing correctly. Going to the end of the
446 ;; buffer fixes that.
447 (unless files (goto-char (point-max)))
448 (if (memq ?R switches)
449 ;; List the contents of all directories recursively.
450 ;; cadr of each element of `file-alist' is t for
451 ;; directory, string (name linked to) for symbolic
452 ;; link, or nil.
453 (while file-alist
454 (setq elt (car file-alist)
455 file-alist (cdr file-alist))
456 (when (and (eq (cadr elt) t) ; directory
457 ;; Under -F, we have already decorated all
458 ;; directories, including "." and "..", with
459 ;; a /, so allow for that as well.
460 (not (string-match "\\`\\.\\.?/?\\'" (car elt))))
461 (setq elt (expand-file-name (car elt) dir))
462 (insert "\n" elt ":\n")
463 (ls-lisp-insert-directory
464 elt switches time-index wildcard-regexp full-directory-p)))))
465 ;; If not full-directory-p, FILE *must not* end in /, as
466 ;; file-attributes will not recognize a symlink to a directory,
467 ;; so must make it a relative filename as ls does:
468 (if (file-name-absolute-p file) (setq file (expand-file-name file)))
469 (if (eq (aref file (1- (length file))) ?/)
470 (setq file (substring file 0 -1)))
471 (let ((fattr (file-attributes file 'string)))
472 (if fattr
473 (insert (ls-lisp-format
474 (if (memq ?F switches)
475 (ls-lisp-classify-file file fattr)
476 file)
477 fattr (nth 7 fattr)
478 switches time-index))
479 (message "%s: doesn't exist or is inaccessible" file)
480 (ding) (sit-for 2))))) ; to show user the message!
482 (declare-function dired-read-dir-and-switches "dired" (str))
483 (declare-function dired-goto-next-file "dired" ())
485 (defun ls-lisp--dired (orig-fun dir-or-list &optional switches)
486 (interactive (dired-read-dir-and-switches ""))
487 (if (consp dir-or-list)
488 (funcall orig-fun dir-or-list switches)
489 (let ((dir-wildcard (insert-directory-wildcard-in-dir-p
490 (expand-file-name dir-or-list))))
491 (if (not dir-wildcard)
492 (funcall orig-fun dir-or-list switches)
493 (let* ((default-directory (car dir-wildcard))
494 (files (file-expand-wildcards (cdr dir-wildcard)))
495 (dir (car dir-wildcard)))
496 (if files
497 (let ((inhibit-read-only t)
498 (buf
499 (apply orig-fun (nconc (list dir) files) (and switches (list switches)))))
500 (with-current-buffer buf
501 (save-excursion
502 (goto-char (point-min))
503 (dired-goto-next-file)
504 (forward-line 0)
505 (insert " wildcard " (cdr dir-wildcard) "\n"))))
506 (user-error "No files matching regexp")))))))
508 (advice-add 'dired :around #'ls-lisp--dired)
510 (defun ls-lisp-sanitize (file-alist)
511 "Sanitize the elements in FILE-ALIST.
512 Fixes any elements in the alist for directory entries whose file
513 attributes are nil (meaning that `file-attributes' failed for
514 them). This is known to happen for some network shares, in
515 particular for the \"..\" directory entry.
517 If the \"..\" directory entry has nil attributes, the attributes
518 are copied from the \".\" entry, if they are non-nil. Otherwise,
519 the offending element is removed from the list, as are any
520 elements for other directory entries with nil attributes."
521 (if (and (null (cdr (assoc ".." file-alist)))
522 (cdr (assoc "." file-alist)))
523 (setcdr (assoc ".." file-alist) (cdr (assoc "." file-alist))))
524 (rassq-delete-all nil file-alist))
526 (defun ls-lisp-column-format (file-alist)
527 "Insert the file names (only) in FILE-ALIST into the current buffer.
528 Format in columns, sorted vertically, following GNU ls -C.
529 Responds to the window width as ls should but may not!"
530 (let (files fmt ncols collen (nfiles 0) (colwid 0))
531 ;; Count number of files as `nfiles', build list of filenames as
532 ;; `files', and find maximum filename length as `colwid':
533 (let (file len)
534 (while file-alist
535 (setq nfiles (1+ nfiles)
536 file (caar file-alist)
537 files (cons file files)
538 file-alist (cdr file-alist)
539 len (length file))
540 (if (> len colwid) (setq colwid len))))
541 (setq files (nreverse files)
542 colwid (+ 2 colwid) ; 2 character column gap
543 fmt (format "%%-%ds" colwid) ; print format
544 ncols (/ (window-width) colwid) ; no of columns
545 collen (/ nfiles ncols)) ; floor of column length
546 (if (> nfiles (* collen ncols)) (setq collen (1+ collen)))
547 ;; Output the file names in columns, sorted vertically:
548 (let ((i 0) j)
549 (while (< i collen)
550 (setq j i)
551 (while (< j nfiles)
552 (insert (format fmt (nth j files)))
553 (setq j (+ j collen)))
554 ;; FJW: This is completely unnecessary, but I don't like
555 ;; trailing white space...
556 (delete-region (point) (progn (skip-chars-backward " \t") (point)))
557 (insert ?\n)
558 (setq i (1+ i))))))
560 (defun ls-lisp-delete-matching (regexp list)
561 "Delete all elements matching REGEXP from LIST, return new list."
562 ;; Should perhaps use setcdr for efficiency.
563 (let (result)
564 (while list
565 (or (string-match regexp (caar list))
566 (setq result (cons (car list) result)))
567 (setq list (cdr list)))
568 result))
570 (defsubst ls-lisp-string-lessp (s1 s2)
571 "Return t if string S1 should sort before string S2.
572 Case is significant if `ls-lisp-ignore-case' is nil.
573 Uses `string-collate-lessp' if `ls-lisp-use-string-collate' is non-nil,
574 `compare-strings' otherwise.
575 On GNU/Linux systems, if the locale specifies UTF-8 as the codeset,
576 the sorting order will place together file names that differ only
577 by punctuation characters, like `.emacs' and `emacs'. To have a
578 similar behavior on MS-Windows, customize `ls-lisp-UCA-like-collation'
579 to a non-nil value."
580 (let ((w32-collate-ignore-punctuation ls-lisp-UCA-like-collation))
581 (if ls-lisp-use-string-collate
582 (string-collate-lessp s1 s2 nil ls-lisp-ignore-case)
583 (let ((u (compare-strings s1 0 nil s2 0 nil ls-lisp-ignore-case)))
584 (and (numberp u) (< u 0))))))
586 (defun ls-lisp-version-lessp (s1 s2)
587 "Return t if versioned string S1 should sort before versioned string S2.
589 Case is significant if `ls-lisp-ignore-case' is nil.
590 This is the same as string-lessp (with the exception of case
591 insensitivity), but sequences of digits are compared numerically,
592 as a whole, in the same manner as the `strverscmp' function available
593 in some standard C libraries does."
594 (let ((i1 0)
595 (i2 0)
596 (len1 (length s1))
597 (len2 (length s2))
598 (val 0)
599 ni1 ni2 e1 e2 found-2-numbers-p)
600 (while (and (< i1 len1) (< i2 len2) (zerop val))
601 (unless found-2-numbers-p
602 (setq ni1 (string-match "[0-9]+" s1 i1)
603 e1 (match-end 0))
604 (setq ni2 (string-match "[0-9]+" s2 i2)
605 e2 (match-end 0)))
606 (cond
607 ((and ni1 ni2)
608 (cond
609 ((and (> ni1 i1) (> ni2 i2))
610 ;; Compare non-numerical part as strings.
611 (setq val (compare-strings s1 i1 ni1 s2 i2 ni2 ls-lisp-ignore-case)
612 i1 ni1
613 i2 ni2
614 found-2-numbers-p t))
615 ((and (= ni1 i1) (= ni2 i2))
616 (setq found-2-numbers-p nil)
617 ;; Compare numerical parts as integral and/or fractional parts.
618 (let* ((sub1 (substring s1 ni1 e1))
619 (sub2 (substring s2 ni2 e2))
620 ;; "Fraction" is a numerical sequence with leading zeros.
621 (fr1 (string-match "\\`0+" sub1))
622 (fr2 (string-match "\\`0+" sub2)))
623 (cond
624 ((and fr1 fr2) ; two fractions, the shortest wins
625 (setq val (- val (- (length sub1) (length sub2)))))
626 (fr1 ; a fraction is always less than an integral
627 (setq val (- ni1)))
628 (fr2
629 (setq val ni2)))
630 (if (zerop val) ; fall back on numerical comparison
631 (setq val (- (string-to-number sub1)
632 (string-to-number sub2))))
633 (setq i1 e1
634 i2 e2)))
636 (setq val (compare-strings s1 i1 nil s2 i2 nil ls-lisp-ignore-case)
637 i1 len1
638 i2 len2))))
639 (t (setq val (compare-strings s1 i1 nil s2 i2 nil ls-lisp-ignore-case)
640 i1 len1
641 i2 len2)))
642 (and (eq val t) (setq val 0)))
643 (if (zerop val)
644 (setq val (- len1 len2)))
645 (< val 0)))
647 (defun ls-lisp-handle-switches (file-alist switches)
648 "Return new FILE-ALIST sorted according to SWITCHES.
649 SWITCHES is a list of characters. Default sorting is alphabetic."
650 ;; FILE-ALIST's elements are (FILE . FILE-ATTRIBUTES).
651 (or (memq ?U switches) ; unsorted
652 ;; Catch and ignore unexpected sorting errors
653 (condition-case err
654 (setq file-alist
655 (let (index)
656 ;; Copy file-alist in case of error
657 (sort (copy-sequence file-alist) ; modifies its argument!
658 (cond ((memq ?S switches)
659 (lambda (x y) ; sorted on size
660 ;; 7th file attribute is file size
661 ;; Make largest file come first
662 (< (nth 7 (cdr y))
663 (nth 7 (cdr x)))))
664 ((setq index (ls-lisp-time-index switches))
665 (lambda (x y) ; sorted on time
666 (time-less-p (nth index (cdr y))
667 (nth index (cdr x)))))
668 ((memq ?X switches)
669 (lambda (x y) ; sorted on extension
670 (ls-lisp-string-lessp
671 (ls-lisp-extension (car x))
672 (ls-lisp-extension (car y)))))
673 ((memq ?v switches)
674 (lambda (x y) ; sorted by version number
675 (ls-lisp-version-lessp (car x) (car y))))
677 (lambda (x y) ; sorted alphabetically
678 (ls-lisp-string-lessp (car x) (car y))))))))
679 (error (message "Unsorted (ls-lisp sorting error) - %s"
680 (error-message-string err))
681 (ding) (sit-for 2)))) ; to show user the message!
682 (if (memq ?F switches) ; classify switch
683 (setq file-alist (mapcar 'ls-lisp-classify file-alist)))
684 (if ls-lisp-dirs-first
685 ;; Re-sort directories first, without otherwise changing the
686 ;; ordering, and reverse whole list. cadr of each element of
687 ;; `file-alist' is t for directory, string (name linked to) for
688 ;; symbolic link, or nil.
689 (let (el dirs files)
690 (while file-alist
691 (if (or (eq (cadr (setq el (car file-alist))) t) ; directory
692 (and (stringp (cadr el))
693 (file-directory-p (cadr el)))) ; symlink to a directory
694 (setq dirs (cons el dirs))
695 (setq files (cons el files)))
696 (setq file-alist (cdr file-alist)))
697 (setq file-alist
698 (if (memq ?U switches) ; unsorted order is reversed
699 (nconc dirs files)
700 (nconc files dirs)
701 ))))
702 ;; Finally reverse file alist if necessary.
703 ;; (eq below MUST compare `(not (memq ...))' to force comparison of
704 ;; t or nil, rather than list tails!)
705 (if (eq (eq (not (memq ?U switches)) ; unsorted order is reversed
706 (not (memq ?r switches))) ; reversed sort order requested
707 ls-lisp-dirs-first) ; already reversed
708 (nreverse file-alist)
709 file-alist))
711 (defun ls-lisp-classify-file (filename fattr)
712 "Append a character to FILENAME indicating the file type.
714 FATTR is the file attributes returned by `file-attributes' for the file.
715 The file type indicators are `/' for directories, `@' for symbolic
716 links, `|' for FIFOs, `=' for sockets, `*' for regular files that
717 are executable, and nothing for other types of files."
718 (let* ((type (car fattr))
719 (modestr (nth 8 fattr))
720 (typestr (substring modestr 0 1)))
721 (cond
722 (type
723 (concat filename (if (eq type t) "/" "@")))
724 ((string-match "x" modestr)
725 (concat filename "*"))
726 ((string= "p" typestr)
727 (concat filename "|"))
728 ((string= "s" typestr)
729 (concat filename "="))
730 (t filename))))
732 (defun ls-lisp-classify (filedata)
733 "Append a character to file name in FILEDATA indicating the file type.
735 FILEDATA has the form (FILENAME . ATTRIBUTES), where ATTRIBUTES is the
736 structure returned by `file-attributes' for that file.
738 The file type indicators are `/' for directories, `@' for symbolic
739 links, `|' for FIFOs, `=' for sockets, `*' for regular files that
740 are executable, and nothing for other types of files."
741 (let ((file-name (car filedata))
742 (fattr (cdr filedata)))
743 (setq file-name (propertize file-name 'dired-filename t))
744 (cons (ls-lisp-classify-file file-name fattr) fattr)))
746 (defun ls-lisp-extension (filename)
747 "Return extension of FILENAME (ignoring any version extension)
748 FOLLOWED by null and full filename, SOLELY for full alpha sort."
749 ;; Force extension sort order: `no ext' then `null ext' then `ext'
750 ;; to agree with GNU ls.
751 (concat
752 (let* ((i (length filename)) end)
753 (if (= (aref filename (1- i)) ?.) ; null extension
754 "\0"
755 (while (and (>= (setq i (1- i)) 0)
756 (/= (aref filename i) ?.)))
757 (if (< i 0) "\0\0" ; no extension
758 (if (/= (aref filename (1+ i)) ?~)
759 (substring filename (1+ i))
760 ;; version extension found -- ignore it
761 (setq end i)
762 (while (and (>= (setq i (1- i)) 0)
763 (/= (aref filename i) ?.)))
764 (if (< i 0) "\0\0" ; no extension
765 (substring filename (1+ i) end))))
766 )) "\0" filename))
768 (defun ls-lisp-format (file-name file-attr file-size switches time-index)
769 "Format one line of long ls output for file FILE-NAME.
770 FILE-ATTR and FILE-SIZE give the file's attributes and size.
771 SWITCHES and TIME-INDEX give the full switch list and time data."
772 (let ((file-type (nth 0 file-attr))
773 ;; t for directory, string (name linked to)
774 ;; for symbolic link, or nil.
775 (drwxrwxrwx (nth 8 file-attr))) ; attribute string ("drwxrwxrwx")
776 (concat (if (memq ?i switches) ; inode number
777 (let ((inode (nth 10 file-attr)))
778 (if (consp inode)
779 (if (consp (cdr inode))
780 ;; 2^(24+16) = 1099511627776.0, but
781 ;; multiplying by it and then adding the
782 ;; other members of the cons cell in one go
783 ;; loses precision, since a double does not
784 ;; have enough significant digits to hold a
785 ;; full 64-bit value. So below we split
786 ;; 1099511627776 into high 13 and low 5
787 ;; digits and compute in two parts.
788 (let ((p1 (* (car inode) 10995116.0))
789 (p2 (+ (* (car inode) 27776.0)
790 (* (cadr inode) 65536.0)
791 (cddr inode))))
792 (format " %13.0f%05.0f "
793 ;; Use floor to emulate integer
794 ;; division.
795 (+ p1 (floor p2 100000.0))
796 (mod p2 100000.0)))
797 (format " %18.0f "
798 (+ (* (car inode) 65536.0)
799 (cdr inode))))
800 (format " %18d " inode))))
801 ;; nil is treated like "" in concat
802 (if (memq ?s switches) ; size in K, rounded up
803 ;; In GNU ls, -h affects the size in blocks, displayed
804 ;; by -s, as well.
805 (if (memq ?h switches)
806 (format "%6s "
807 (file-size-human-readable
808 ;; We use 1K as "block size", although
809 ;; most Windows volumes use 4KB to 8KB
810 ;; clusters, and exFAT will usually have
811 ;; clusters of 32KB or even 128KB. See
812 ;; KB article 140365 for the details.
813 (* 1024.0 (fceiling (/ file-size 1024.0)))))
814 (format ls-lisp-filesize-b-fmt
815 (fceiling (/ file-size 1024.0)))))
816 drwxrwxrwx ; attribute string
817 (if (memq 'links ls-lisp-verbosity)
818 (format "%3d" (nth 1 file-attr))) ; link count
819 ;; Numeric uid/gid are more confusing than helpful;
820 ;; Emacs should be able to make strings of them.
821 ;; They tend to be bogus on non-UNIX platforms anyway so
822 ;; optionally hide them.
823 (if (memq 'uid ls-lisp-verbosity)
824 ;; uid can be a string or an integer
825 (let ((uid (nth 2 file-attr)))
826 (format (if (stringp uid)
827 ls-lisp-uid-s-fmt
828 ls-lisp-uid-d-fmt)
829 uid)))
830 (if (not (memq ?G switches)) ; GNU ls -- shows group by default
831 (if (or (memq ?g switches) ; UNIX ls -- no group by default
832 (memq 'gid ls-lisp-verbosity))
833 (let ((gid (nth 3 file-attr)))
834 (format (if (stringp gid)
835 ls-lisp-gid-s-fmt
836 ls-lisp-gid-d-fmt)
837 gid))))
838 (ls-lisp-format-file-size file-size (memq ?h switches))
840 (ls-lisp-format-time file-attr time-index)
842 (if (not (memq ?F switches)) ; ls-lisp-classify already did that
843 (propertize file-name 'dired-filename t)
844 file-name)
845 (if (stringp file-type) ; is a symbolic link
846 (concat " -> " file-type))
847 "\n"
850 (defun ls-lisp-time-index (switches)
851 "Return time index into file-attributes according to ls SWITCHES list.
852 Return nil if no time switch found."
853 ;; FJW: Default of nil is IMPORTANT and used in `ls-lisp-handle-switches'!
854 (cond ((memq ?c switches) 6) ; last mode change
855 ((memq ?t switches) 5) ; last modtime
856 ((memq ?u switches) 4))) ; last access
858 (defun ls-lisp-format-time (file-attr time-index)
859 "Format time for file with attributes FILE-ATTR according to TIME-INDEX.
860 Use the same method as ls to decide whether to show time-of-day or year,
861 depending on distance between file date and the current time.
862 All ls time options, namely c, t and u, are handled."
863 (let* ((time (nth (or time-index 5) file-attr)) ; default is last modtime
864 (diff (- (float-time time) (float-time)))
865 ;; Consider a time to be recent if it is within the past six
866 ;; months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
867 ;; 31556952 seconds on the average, and half of that is 15778476.
868 ;; Write the constant explicitly to avoid roundoff error.
869 (past-cutoff -15778476)) ; half a Gregorian year
870 (condition-case nil
871 ;; Use traditional time format in the C or POSIX locale,
872 ;; ISO-style time format otherwise, so columns line up.
873 (let ((locale system-time-locale))
874 (if (not locale)
875 (let ((vars '("LC_ALL" "LC_TIME" "LANG")))
876 (while (and vars (not (setq locale (getenv (car vars)))))
877 (setq vars (cdr vars)))))
878 (if (member locale '("C" "POSIX"))
879 (setq locale nil))
880 (format-time-string
881 (if (and (<= past-cutoff diff) (<= diff 0))
882 (if (and locale (not ls-lisp-use-localized-time-format))
883 "%m-%d %H:%M"
884 (nth 0 ls-lisp-format-time-list))
885 (if (and locale (not ls-lisp-use-localized-time-format))
886 "%Y-%m-%d "
887 (nth 1 ls-lisp-format-time-list)))
888 time))
889 (error "Unk 0 0000"))))
891 (defun ls-lisp-format-file-size (file-size human-readable)
892 (if (not human-readable)
893 (format (if (floatp file-size)
894 ls-lisp-filesize-f-fmt
895 ls-lisp-filesize-d-fmt)
896 file-size)
897 (format " %6s" (file-size-human-readable file-size))))
899 (defun ls-lisp-unload-function ()
900 "Unload ls-lisp library."
901 (advice-remove 'insert-directory #'ls-lisp--insert-directory)
902 (advice-remove 'dired #'ls-lisp--dired)
903 ;; Continue standard unloading.
904 nil)
906 (provide 'ls-lisp)
908 ;;; ls-lisp.el ends here