ls-lisp.el 29 KB

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