1;;; arc-mode.el --- simple editing of archives
2
3;; Copyright (C) 1995, 1997-1998, 2001-2021 Free Software Foundation,
4;; Inc.
5
6;; Author: Morten Welinder <terra@gnu.org>
7;; Keywords: files archives ms-dos editing major-mode
8;; Favorite-brand-of-beer: None, I hate beer.
9
10;; This file is part of GNU Emacs.
11
12;; GNU Emacs is free software: you can redistribute it and/or modify
13;; it under the terms of the GNU General Public License as published by
14;; the Free Software Foundation, either version 3 of the License, or
15;; (at your option) any later version.
16
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20;; GNU General Public License for more details.
21
22;; You should have received a copy of the GNU General Public License
23;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
24
25;;; Commentary:
26
27;; NAMING: "arc" is short for "archive" and does not refer specifically
28;; to files whose name end in ".arc"
29;;
30;; This code does not decode any files internally, although it does
31;; understand the directory level of the archives.  For this reason,
32;; you should expect this code to need more fiddling than tar-mode.el
33;; (although it at present has fewer bugs :-)  In particular, I have
34;; not tested this under MS-DOS myself.
35;; -------------------------------------
36;; INTERACTION: arc-mode.el should play together with
37;;
38;; * ange-ftp.el: Remote archives (i.e., ones that ange-ftp has brought
39;;                to you) are handled by doing all updates on a local
40;;                copy.  When you make changes to a remote file the
41;;                changes will first take effect when the archive buffer
42;;                is saved.  You will be warned about this.
43;;
44;; * dos-fns.el:  (Part of Emacs 19).  You get automatic ^M^J <--> ^J
45;;                conversion.
46;;
47;; arc-mode.el does not work well with crypt++.el; for the archives as
48;; such this could be fixed (but wouldn't be useful) by declaring such
49;; archives to be "remote".  For the members this is a general Emacs
50;; problem that 19.29's file formats may fix.
51;; -------------------------------------
52;; ARCHIVE TYPES: Currently only the archives below are handled, but the
53;; structure for handling just about anything is in place.
54;;
55;;			Arc	Lzh	Zip	Zoo	Rar	7z
56;;			--------------------------------------------
57;; View listing		Intern	Intern	Intern	Intern	Y	Y
58;; Extract member	Y	Y	Y	Y	Y	Y
59;; Save changed member	Y	Y	Y	Y	N	Y
60;; Add new member	N	N	N	N	N	N
61;; Delete member	Y	Y	Y	Y	N	Y
62;; Rename member	Y	Y	N	N	N	N
63;; Chmod		-	Y	Y	-	N	N
64;; Chown		-	Y	-	-	N	N
65;; Chgrp		-	Y	-	-	N	N
66;;
67;; Special thanks to Bill Brodie <wbrodie@panix.com> for very useful tips
68;; on the first released version of this package.
69;;
70;; This code is partly based on tar-mode.el from Emacs.
71;; -------------------------------------
72;; ARCHIVE STRUCTURES:
73;; (This is mostly for myself.)
74;;
75;; ARC         A series of (header,file).  No interactions among members.
76;;
77;; LZH         A series of (header,file).  Headers are checksummed.  No
78;;             interaction among members.
79;;             Headers come in three flavors called level 0, 1 and 2 headers.
80;;             Level 2 header is free of DOS specific restrictions and most
81;;             commonly used.  Also level 1 and 2 headers consist of base
82;;             and extension headers.  For more details see
83;;             http://homepage1.nifty.com/dangan/en/Content/Program/Java/jLHA/Notes/Notes.html
84;;             http://www.osirusoft.com/joejared/lzhformat.html
85;;
86;; ZIP         A series of (lheader,fil) followed by a "central directory"
87;;             which is a series of (cheader) followed by an end-of-
88;;             central-dir record possibly followed by junk.  The e-o-c-d
89;;             links to c-d.  cheaders link to lheaders which are basically
90;;             cut-down versions of the cheaders.
91;;
92;; ZOO         An archive header followed by a series of (header,file).
93;;             Each member header points to the next.  The archive is
94;;             terminated by a bogus header with a zero next link.
95;; -------------------------------------
96;; HOOKS: `foo' means one of the supported archive types.
97;;
98;; archive-mode-hook
99;; archive-foo-mode-hook
100;; archive-extract-hook
101
102;;; Code:
103
104;; -------------------------------------------------------------------------
105;;; Section: Configuration.
106
107(defgroup archive nil
108  "Simple editing of archives."
109  :group 'data)
110
111(defgroup archive-arc nil
112  "ARC-specific options to archive."
113  :group 'archive)
114
115(defgroup archive-lzh nil
116  "LZH-specific options to archive."
117  :group 'archive)
118
119(defgroup archive-zip nil
120  "ZIP-specific options to archive."
121  :group 'archive)
122
123(defgroup archive-zoo nil
124  "ZOO-specific options to archive."
125  :group 'archive)
126
127(defcustom archive-tmpdir
128  ;; make-temp-name is safe here because we use this name
129  ;; to create a directory.
130  (make-temp-name
131   (expand-file-name (if (eq system-type 'ms-dos) "ar" "archive.tmp")
132		     temporary-file-directory))
133  "Directory for temporary files made by `arc-mode.el'."
134  :type 'directory
135  :group 'archive)
136
137(defcustom archive-remote-regexp "^/[^/:]*[^/:.]:"
138  "Regexp recognizing archive files names that are not local.
139A non-local file is one whose file name is not proper outside Emacs.
140A local copy of the archive will be used when updating."
141  :type 'regexp
142  :group 'archive)
143
144(define-obsolete-variable-alias 'archive-extract-hooks
145  'archive-extract-hook "24.3")
146(defcustom archive-extract-hook nil
147  "Hook run when an archive member has been extracted."
148  :type 'hook
149  :group 'archive)
150
151(defcustom archive-visit-single-files nil
152  "If non-nil, opening an archive with a single file visits that file.
153If nil, visiting such an archive displays the archive summary."
154  :version "25.1"
155  :type '(choice (const :tag "Visit the single file" t)
156                 (const :tag "Show the archive summary" nil))
157  :group 'archive)
158;; ------------------------------
159;; Arc archive configuration
160
161;; We always go via a local file since there seems to be no reliable way
162;; to extract to stdout without junk getting added.
163(defcustom archive-arc-extract
164  '("arc" "x")
165  "Program and its options to run in order to extract an arc file member.
166Extraction should happen to the current directory.  Archive and member
167name will be added."
168  :type '(list (string :tag "Program")
169		(repeat :tag "Options"
170			:inline t
171			(string :format "%v")))
172  :group 'archive-arc)
173
174(defcustom archive-arc-expunge
175  '("arc" "d")
176  "Program and its options to run in order to delete arc file members.
177Archive and member names will be added."
178  :type '(list (string :tag "Program")
179		(repeat :tag "Options"
180			:inline t
181			(string :format "%v")))
182  :group 'archive-arc)
183
184(defcustom archive-arc-write-file-member
185  '("arc" "u")
186  "Program and its options to run in order to update an arc file member.
187Archive and member name will be added."
188  :type '(list (string :tag "Program")
189		(repeat :tag "Options"
190			:inline t
191			(string :format "%v")))
192  :group 'archive-arc)
193;; ------------------------------
194;; Lzh archive configuration
195
196(defcustom archive-lzh-extract
197  '("lha" "pq")
198  "Program and its options to run in order to extract an lzh file member.
199Extraction should happen to standard output.  Archive and member name will
200be added."
201  :type '(list (string :tag "Program")
202		(repeat :tag "Options"
203			:inline t
204			(string :format "%v")))
205  :group 'archive-lzh)
206
207(defcustom archive-lzh-expunge
208  '("lha" "d")
209  "Program and its options to run in order to delete lzh file members.
210Archive and member names will be added."
211  :type '(list (string :tag "Program")
212		(repeat :tag "Options"
213			:inline t
214			(string :format "%v")))
215  :group 'archive-lzh)
216
217(defcustom archive-lzh-write-file-member
218  '("lha" "a")
219  "Program and its options to run in order to update an lzh file member.
220Archive and member name will be added."
221  :type '(list (string :tag "Program")
222		(repeat :tag "Options"
223			:inline t
224			(string :format "%v")))
225  :group 'archive-lzh)
226;; ------------------------------
227;; Zip archive configuration
228
229(defvar archive-7z-program (let ((7z (or (executable-find "7z")
230                                         (executable-find "7za"))))
231                             (when 7z
232                               (file-name-nondirectory 7z))))
233
234(defcustom archive-zip-extract
235  (cond ((executable-find "unzip")   '("unzip" "-qq" "-c"))
236	(archive-7z-program          `(,archive-7z-program "x" "-so"))
237	((executable-find "pkunzip") '("pkunzip" "-e" "-o-"))
238	(t                           '("unzip" "-qq" "-c")))
239  "Program and its options to run in order to extract a zip file member.
240Extraction should happen to standard output.  Archive and member name will
241be added."
242  :type '(list (string :tag "Program")
243	       (repeat :tag "Options"
244		       :inline t
245		       (string :format "%v")))
246  :group 'archive-zip)
247
248;; For several reasons the latter behavior is not desirable in general.
249;; (1) It uses more disk space.  (2) Error checking is worse or non-
250;; existent.  (3) It tends to do funny things with other systems' file
251;; names.
252
253(defcustom archive-zip-expunge
254  (cond ((executable-find "zip")     '("zip" "-d" "-q"))
255	(archive-7z-program          `(,archive-7z-program "d"))
256	((executable-find "pkzip")   '("pkzip" "-d"))
257	(t                           '("zip" "-d" "-q")))
258  "Program and its options to run in order to delete zip file members.
259Archive and member names will be added."
260  :type '(list (string :tag "Program")
261	       (repeat :tag "Options"
262		       :inline t
263		       (string :format "%v")))
264  :group 'archive-zip)
265
266(defcustom archive-zip-update
267  (cond ((executable-find "zip")     '("zip" "-q"))
268	(archive-7z-program          `(,archive-7z-program "u"))
269	((executable-find "pkzip")   '("pkzip" "-u" "-P"))
270	(t                           '("zip" "-q")))
271  "Program and its options to run in order to update a zip file member.
272Options should ensure that specified directory will be put into the zip
273file.  Archive and member name will be added."
274  :type '(list (string :tag "Program")
275	       (repeat :tag "Options"
276		       :inline t
277		       (string :format "%v")))
278  :group 'archive-zip)
279
280(defcustom archive-zip-update-case
281  (cond ((executable-find "zip")     '("zip" "-q" "-k"))
282	(archive-7z-program          `(,archive-7z-program "u"))
283	((executable-find "pkzip")   '("pkzip" "-u" "-P"))
284	(t                           '("zip" "-q" "-k")))
285  "Program and its options to run in order to update a case fiddled zip member.
286Options should ensure that specified directory will be put into the zip file.
287Archive and member name will be added."
288  :type '(list (string :tag "Program")
289	       (repeat :tag "Options"
290		       :inline t
291		       (string :format "%v")))
292  :group 'archive-zip)
293
294(declare-function msdos-long-file-names "msdos.c")
295(defcustom archive-zip-case-fiddle (and (eq system-type 'ms-dos)
296                                        (not (msdos-long-file-names)))
297  "If non-nil, then all-caps names of zip file members will be down-cased.
298This case fiddling will only happen for members created by a system
299that uses caseless file names.
300In addition, this flag forces members added/updated in the zip archive
301to be truncated to DOS 8+3 file-name restrictions."
302  :type 'boolean
303  :version "27.1"
304  :group 'archive-zip)
305;; ------------------------------
306;; Zoo archive configuration
307
308(defcustom archive-zoo-extract
309  '("zoo" "xpq")
310  "Program and its options to run in order to extract a zoo file member.
311Extraction should happen to standard output.  Archive and member name will
312be added."
313  :type '(list (string :tag "Program")
314		(repeat :tag "Options"
315			:inline t
316			(string :format "%v")))
317  :group 'archive-zoo)
318
319(defcustom archive-zoo-expunge
320  '("zoo" "DqPP")
321  "Program and its options to run in order to delete zoo file members.
322Archive and member names will be added."
323  :type '(list (string :tag "Program")
324		(repeat :tag "Options"
325			:inline t
326			(string :format "%v")))
327  :group 'archive-zoo)
328
329(defcustom archive-zoo-write-file-member
330  '("zoo" "a")
331  "Program and its options to run in order to update a zoo file member.
332Archive and member name will be added."
333  :type '(list (string :tag "Program")
334		(repeat :tag "Options"
335			:inline t
336			(string :format "%v")))
337  :group 'archive-zoo)
338;; ------------------------------
339;; 7z archive configuration
340
341(defcustom archive-7z-extract
342  `(,(or archive-7z-program "7z") "x" "-so")
343  "Program and its options to run in order to extract a 7z file member.
344Extraction should happen to standard output.  Archive and member name will
345be added."
346  :version "24.1"
347  :type '(list (string :tag "Program")
348	       (repeat :tag "Options"
349		       :inline t
350		       (string :format "%v")))
351  :group 'archive-7z)
352
353(defcustom archive-7z-expunge
354  `(,(or archive-7z-program "7z") "d")
355  "Program and its options to run in order to delete 7z file members.
356Archive and member names will be added."
357  :version "24.1"
358  :type '(list (string :tag "Program")
359	       (repeat :tag "Options"
360		       :inline t
361		       (string :format "%v")))
362  :group 'archive-7z)
363
364(defcustom archive-7z-update
365  `(,(or archive-7z-program "7z") "u")
366  "Program and its options to run in order to update a 7z file member.
367Options should ensure that specified directory will be put into the 7z
368file.  Archive and member name will be added."
369  :version "24.1"
370  :type '(list (string :tag "Program")
371	       (repeat :tag "Options"
372		       :inline t
373		       (string :format "%v")))
374  :group 'archive-7z)
375
376;; -------------------------------------------------------------------------
377;;; Section: Variables
378
379(defvar archive-subtype nil "Symbol describing archive type.")
380(defvar archive-file-list-start nil "Position of first contents line.")
381(defvar archive-file-list-end nil "Position just after last contents line.")
382(defvar archive-proper-file-start nil "Position of real archive's start.")
383(defvar archive-read-only nil "Non-nil if the archive is read-only on disk.")
384(defvar archive-local-name nil "Name of local copy of remote archive.")
385(defvar archive-mode-map
386  (let ((map (make-keymap)))
387    (set-keymap-parent map special-mode-map)
388    (define-key map " " 'archive-next-line)
389    (define-key map "a" 'archive-alternate-display)
390    ;;(define-key map "c" 'archive-copy)
391    (define-key map "d" 'archive-flag-deleted)
392    (define-key map "\C-d" 'archive-flag-deleted)
393    (define-key map "e" 'archive-extract)
394    (define-key map "f" 'archive-extract)
395    (define-key map "\C-m" 'archive-extract)
396    (define-key map "m" 'archive-mark)
397    (define-key map "n" 'archive-next-line)
398    (define-key map "\C-n" 'archive-next-line)
399    (define-key map [down] 'archive-next-line)
400    (define-key map "o" 'archive-extract-other-window)
401    (define-key map "p" 'archive-previous-line)
402    (define-key map "\C-p" 'archive-previous-line)
403    (define-key map [?\S-\ ] 'archive-previous-line)
404    (define-key map [up] 'archive-previous-line)
405    (define-key map "r" 'archive-rename-entry)
406    (define-key map "u" 'archive-unflag)
407    (define-key map "\M-\C-?" 'archive-unmark-all-files)
408    (define-key map "v" 'archive-view)
409    (define-key map "x" 'archive-expunge)
410    (define-key map "\177" 'archive-unflag-backwards)
411    (define-key map "E" 'archive-extract-other-window)
412    (define-key map "M" 'archive-chmod-entry)
413    (define-key map "G" 'archive-chgrp-entry)
414    (define-key map "O" 'archive-chown-entry)
415    ;; Let mouse-1 follow the link.
416    (define-key map [follow-link] 'mouse-face)
417
418    (if (fboundp 'command-remapping)
419        (progn
420          (define-key map [remap advertised-undo] 'archive-undo)
421          (define-key map [remap undo] 'archive-undo))
422      (substitute-key-definition 'advertised-undo 'archive-undo map global-map)
423      (substitute-key-definition 'undo 'archive-undo map global-map))
424
425    (define-key map [mouse-2] 'archive-extract)
426
427    (define-key map [menu-bar immediate]
428      (cons "Immediate" (make-sparse-keymap "Immediate")))
429    (define-key map [menu-bar immediate alternate]
430      '(menu-item "Alternate Display" archive-alternate-display
431                  :enable (boundp (archive-name "alternate-display"))
432                  :help "Toggle alternate file info display"))
433    (define-key map [menu-bar immediate view]
434      '(menu-item "View This File" archive-view
435                  :help "Display file at cursor in View Mode"))
436    (define-key map [menu-bar immediate display]
437      '(menu-item "Display in Other Window" archive-display-other-window
438                  :help "Display file at cursor in another window"))
439    (define-key map [menu-bar immediate find-file-other-window]
440      '(menu-item "Find in Other Window" archive-extract-other-window
441                  :help "Edit file at cursor in another window"))
442    (define-key map [menu-bar immediate find-file]
443      '(menu-item "Find This File" archive-extract
444                  :help "Extract file at cursor and edit it"))
445
446    (define-key map [menu-bar mark]
447      (cons "Mark" (make-sparse-keymap "Mark")))
448    (define-key map [menu-bar mark unmark-all]
449      '(menu-item "Unmark All" archive-unmark-all-files
450                  :help "Unmark all marked files"))
451    (define-key map [menu-bar mark deletion]
452      '(menu-item "Flag" archive-flag-deleted
453                  :help "Flag file at cursor for deletion"))
454    (define-key map [menu-bar mark unmark]
455      '(menu-item "Unflag" archive-unflag
456                  :help "Unmark file at cursor"))
457    (define-key map [menu-bar mark mark]
458      '(menu-item "Mark" archive-mark
459                  :help "Mark file at cursor"))
460
461    (define-key map [menu-bar operate]
462      (cons "Operate" (make-sparse-keymap "Operate")))
463    (define-key map [menu-bar operate chown]
464      '(menu-item "Change Owner..." archive-chown-entry
465                  :enable (fboundp (archive-name "chown-entry"))
466                  :help "Change owner of marked files"))
467    (define-key map [menu-bar operate chgrp]
468      '(menu-item "Change Group..." archive-chgrp-entry
469                  :enable (fboundp (archive-name "chgrp-entry"))
470                  :help "Change group ownership of marked files"))
471    (define-key map [menu-bar operate chmod]
472      '(menu-item "Change Mode..." archive-chmod-entry
473                  :enable (fboundp (archive-name "chmod-entry"))
474                  :help "Change mode (permissions) of marked files"))
475    (define-key map [menu-bar operate rename]
476      '(menu-item "Rename to..." archive-rename-entry
477                  :enable (fboundp (archive-name "rename-entry"))
478                  :help "Rename marked files"))
479    ;;(define-key map [menu-bar operate copy]
480    ;;  '(menu-item "Copy to..." archive-copy))
481    (define-key map [menu-bar operate expunge]
482      '(menu-item "Expunge Marked Files" archive-expunge
483                  :help "Delete all flagged files from archive"))
484    map)
485  "Local keymap for archive mode listings.")
486(defvar archive-file-name-indent nil "Column where file names start.")
487
488(defvar archive-remote nil "Non-nil if the archive is outside file system.")
489(make-variable-buffer-local 'archive-remote)
490(put 'archive-remote 'permanent-local t)
491
492(defvar archive-member-coding-system nil "Coding-system of archive member.")
493(make-variable-buffer-local 'archive-member-coding-system)
494
495(defvar archive-alternate-display nil
496  "Non-nil when alternate information is shown.")
497(make-variable-buffer-local 'archive-alternate-display)
498(put 'archive-alternate-display 'permanent-local t)
499
500(defvar archive-superior-buffer nil "In archive members, points to archive.")
501(put 'archive-superior-buffer 'permanent-local t)
502
503(defvar archive-subfile-mode nil "Non-nil in archive member buffers.")
504(make-variable-buffer-local 'archive-subfile-mode)
505(put 'archive-subfile-mode 'permanent-local t)
506
507(defvar archive-file-name-coding-system nil)
508(make-variable-buffer-local 'archive-file-name-coding-system)
509(put 'archive-file-name-coding-system 'permanent-local t)
510
511(defvar archive-files nil
512  "Vector of file descriptors.
513Each descriptor is a vector of the form
514 [EXT-FILE-NAME INT-FILE-NAME CASE-FIDDLED MODE ...]")
515(make-variable-buffer-local 'archive-files)
516
517;; -------------------------------------------------------------------------
518;;; Section: Support functions.
519
520(defun arc-insert-unibyte (&rest args)
521  "Like insert but don't make unibyte string and eight-bit char multibyte."
522  (dolist (elt args)
523    (if (integerp elt)
524	(insert (if (< elt 128) elt (decode-char 'eight-bit elt)))
525      (insert elt))))
526
527(defsubst archive-name (suffix)
528  (intern (concat "archive-" (symbol-name archive-subtype) "-" suffix)))
529
530(defun archive-l-e (str &optional len)
531  "Convert little endian string/vector STR to integer.
532Alternatively, STR may be a buffer position in the current buffer
533in which case a second argument, length LEN, should be supplied."
534  (if (stringp str)
535      (setq len (length str))
536    (setq str (buffer-substring str (+ str len))))
537  (if (multibyte-string-p str)
538      (setq str (encode-coding-string str 'utf-8-emacs-unix)))
539  (let ((result 0)
540        (i 0))
541    (while (< i len)
542      (setq i (1+ i)
543            result (+ (ash result 8)
544		      (aref str (- len i)))))
545    result))
546
547(defun archive-int-to-mode (mode)
548  "Turn an integer like 0700 (i.e., 448) into a mode string like -rwx------."
549  ;; FIXME: merge with tar-grind-file-mode.
550  (string
551    (if (zerop (logand  8192 mode))
552	(if (zerop (logand 16384 mode)) ?- ?d)
553      ?c) ; completeness
554    (if (zerop (logand   256 mode)) ?- ?r)
555    (if (zerop (logand   128 mode)) ?- ?w)
556    (if (zerop (logand    64 mode))
557	(if (zerop (logand  2048 mode)) ?- ?S)
558      (if (zerop (logand  2048 mode)) ?x ?s))
559    (if (zerop (logand    32 mode)) ?- ?r)
560    (if (zerop (logand    16 mode)) ?- ?w)
561    (if (zerop (logand     8 mode))
562	(if (zerop (logand  1024 mode)) ?- ?S)
563      (if (zerop (logand  1024 mode)) ?x ?s))
564    (if (zerop (logand     4 mode)) ?- ?r)
565    (if (zerop (logand     2 mode)) ?- ?w)
566    (if (zerop (logand     1 mode)) ?- ?x)))
567
568(defun archive-calc-mode (oldmode newmode &optional error)
569  "From the integer OLDMODE and the string NEWMODE calculate a new file mode.
570NEWMODE may be an octal number including a leading zero in which case it
571will become the new mode.\n
572NEWMODE may also be a relative specification like \"og-rwx\" in which case
573OLDMODE will be modified accordingly just like chmod(2) would have done.\n
574If optional third argument ERROR is non-nil an error will be signaled if
575the mode is invalid.  If ERROR is nil then nil will be returned."
576  (cond ((string-match "^0[0-7]*$" newmode)
577	 (let ((result 0)
578	       (len (length newmode))
579	       (i 1))
580	   (while (< i len)
581	     (setq result (+ (ash result 3) (aref newmode i) (- ?0))
582		   i (1+ i)))
583	   (logior (logand oldmode 65024) result)))
584	((string-match "^\\([agou]+\\)\\([---+=]\\)\\([rwxst]+\\)$" newmode)
585	 (let ((who 0)
586	       (result oldmode)
587	       (op (aref newmode (match-beginning 2)))
588	       (bits 0)
589	       (i (match-beginning 3)))
590	   (while (< i (match-end 3))
591	     (let ((rwx (aref newmode i)))
592	       (setq bits (logior bits (cond ((= rwx ?r)  292)
593					     ((= rwx ?w)  146)
594					     ((= rwx ?x)   73)
595					     ((= rwx ?s) 3072)
596					     ((= rwx ?t)  512)))
597		     i (1+ i))))
598	   (while (< who (match-end 1))
599	     (let* ((whoc (aref newmode who))
600		    (whomask (cond ((= whoc ?a) 4095)
601				   ((= whoc ?u) 1472)
602				   ((= whoc ?g) 2104)
603				   ((= whoc ?o)    7))))
604	       (if (= op ?=)
605		   (setq result (logand result (lognot whomask))))
606	       (if (= op ?-)
607		   (setq result (logand result (lognot (logand whomask bits))))
608		 (setq result (logior result (logand whomask bits)))))
609	     (setq who (1+ who)))
610	   result))
611	(t
612	 (if error
613	     (error "Invalid mode specification: %s" newmode)))))
614
615(defun archive-dosdate (date)
616  "Stringify dos packed DATE record."
617  (let ((year (+ 1980 (logand (ash date -9) 127)))
618        (month (logand (ash date -5) 15))
619        (day (logand date 31)))
620    (if (or (> month 12) (< month 1))
621        ""
622      (format "%2d-%s-%d"
623              day
624              (aref ["Jan" "Feb" "Mar" "Apr" "May" "Jun"
625                     "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"] (1- month))
626              year))))
627
628(defun archive-dostime (time)
629  "Stringify dos packed TIME record."
630  (let ((hour (logand (ash time -11) 31))
631        (minute (logand (ash time -5) 63))
632        (second (* 2 (logand time 31)))) ; 2 seconds resolution
633    (format "%02d:%02d:%02d" hour minute second)))
634
635(defun archive-unixdate (low high)
636  "Stringify Unix (LOW HIGH) date."
637  (let* ((time (list high low))
638	 (str (current-time-string time)))
639    (format "%s-%s-%s"
640	    (substring str 8 10)
641	    (substring str 4 7)
642	    (format-time-string "%Y" time))))
643
644(defun archive-unixtime (low high)
645  "Stringify Unix (LOW HIGH) time."
646  (format-time-string "%H:%M:%S" (list high low)))
647
648(defun archive-get-lineno ()
649  (if (>= (point) archive-file-list-start)
650      (count-lines archive-file-list-start
651		   (line-beginning-position))
652    0))
653
654(defun archive-get-descr (&optional noerror)
655  "Return the descriptor vector for file at point.
656Does not signal an error if optional argument NOERROR is non-nil."
657  (let ((no (archive-get-lineno)))
658    (if (and (>= (point) archive-file-list-start)
659             (< no (length archive-files)))
660	(let ((item (aref archive-files no)))
661	  (if (vectorp item)
662	      item
663	    (if (not noerror)
664		(error "Entry is not a regular member of the archive"))))
665      (if (not noerror)
666          (error "Line does not describe a member of the archive")))))
667;; -------------------------------------------------------------------------
668;;; Section: the mode definition
669
670;;;###autoload
671(defun archive-mode (&optional force)
672  "Major mode for viewing an archive file in a dired-like way.
673You can move around using the usual cursor motion commands.
674Letters no longer insert themselves.
675Type `e' to pull a file out of the archive and into its own buffer;
676or click mouse-2 on the file's line in the archive mode buffer.
677
678If you edit a sub-file of this archive (as with the `e' command) and
679save it, the contents of that buffer will be saved back into the
680archive.
681
682\\{archive-mode-map}"
683  ;; This is not interactive because you shouldn't be turning this
684  ;; mode on and off.  You can corrupt things that way.
685  (if (zerop (buffer-size))
686      ;; At present we cannot create archives from scratch
687      (funcall (or (default-value 'major-mode) 'fundamental-mode))
688    (if (and (not force) archive-files) nil
689      (kill-all-local-variables)
690      (let* ((type (archive-find-type))
691	     (typename (capitalize (symbol-name type))))
692	(make-local-variable 'archive-subtype)
693	(setq archive-subtype type)
694
695	;; Buffer contains treated image of file before the file contents
696	(make-local-variable 'revert-buffer-function)
697	(setq revert-buffer-function 'archive-mode-revert)
698	(auto-save-mode 0)
699
700	(add-hook 'write-contents-functions 'archive-write-file nil t)
701
702	(make-local-variable 'require-final-newline)
703	(setq require-final-newline nil)
704	(make-local-variable 'local-enable-local-variables)
705	(setq local-enable-local-variables nil)
706
707	;; Prevent loss of data when saving the file.
708	(make-local-variable 'file-precious-flag)
709	(setq file-precious-flag t)
710
711	(make-local-variable 'archive-read-only)
712	;; Archives which are inside other archives and whose
713	;; names are invalid for this OS, can't be written.
714	(setq archive-read-only
715	      (or (not (file-writable-p (buffer-file-name)))
716		  (and archive-subfile-mode
717		       (string-match file-name-invalid-regexp
718				     (aref archive-subfile-mode 0)))))
719
720	;; Should we use a local copy when accessing from outside Emacs?
721	(make-local-variable 'archive-local-name)
722
723	;; An archive can contain another archive whose name is invalid
724	;; on local filesystem.  Treat such archives as remote.
725	(or archive-remote
726	    (setq archive-remote
727		  (or (string-match archive-remote-regexp (buffer-file-name))
728		      (string-match file-name-invalid-regexp
729				    (buffer-file-name)))))
730
731	(setq major-mode 'archive-mode)
732	(setq mode-name (concat typename "-Archive"))
733	;; Run archive-foo-mode-hook and archive-mode-hook
734	(run-mode-hooks (archive-name "mode-hook") 'archive-mode-hook)
735	(use-local-map archive-mode-map))
736
737      (make-local-variable 'archive-proper-file-start)
738      (make-local-variable 'archive-file-list-start)
739      (make-local-variable 'archive-file-list-end)
740      (make-local-variable 'archive-file-name-indent)
741      (setq archive-file-name-coding-system
742	    (or file-name-coding-system
743		default-file-name-coding-system
744		locale-coding-system))
745      (set-buffer-multibyte 'to)
746      (archive-summarize nil)
747      (setq buffer-read-only t)
748      (when (and archive-visit-single-files
749                 auto-compression-mode
750                 (= (length archive-files) 1))
751        (rename-buffer (concat " " (buffer-name)))
752        (archive-extract)))))
753
754;; Archive mode is suitable only for specially formatted data.
755(put 'archive-mode 'mode-class 'special)
756
757(let ((item1 '(archive-subfile-mode " Archive")))
758  (or (member item1 minor-mode-alist)
759      (setq minor-mode-alist (cons item1 minor-mode-alist))))
760;; -------------------------------------------------------------------------
761(defun archive-find-type ()
762  (widen)
763  (goto-char (point-min))
764  ;; The funny [] here make it unlikely that the .elc file will be treated
765  ;; as an archive by other software.
766  (let (case-fold-search)
767    (cond ((looking-at "\\(PK00\\)?[P]K\003\004") 'zip)
768	  ((looking-at "..-l[hz][0-9ds]-") 'lzh)
769	  ((looking-at "....................[\334]\247\304\375") 'zoo)
770	  ((and (looking-at "\C-z")	; signature too simple, IMHO
771		(string-match "\\.[aA][rR][cC]\\'"
772			      (or buffer-file-name (buffer-name))))
773	   'arc)
774          ;; This pattern modeled on the BSD/GNU+Linux `file' command.
775          ;; Have seen capital "LHA's", and file has lower case "LHa's" too.
776          ;; Note this regexp is also in archive-exe-p.
777          ((looking-at "MZ\\(.\\|\n\\)\\{34\\}LH[aA]'s SFX ") 'lzh-exe)
778          ((looking-at "Rar!") 'rar)
779          ((looking-at "!<arch>\n") 'ar)
780          ((and (looking-at "MZ")
781                (re-search-forward "Rar!" (+ (point) 100000) t))
782           'rar-exe)
783	  ((looking-at "7z\274\257\047\034") '7z)
784	  (t (error "Buffer format not recognized")))))
785;; -------------------------------------------------------------------------
786
787(defun archive-desummarize ()
788  (let ((inhibit-read-only t)
789        (modified (buffer-modified-p)))
790    (widen)
791    (delete-region (point-min) archive-proper-file-start)
792    (restore-buffer-modified-p modified)))
793
794
795(defun archive-summarize (&optional shut-up)
796  "Parse the contents of the archive file in the current buffer.
797Place a dired-like listing on the front;
798then narrow to it, so that only that listing
799is visible (and the real data of the buffer is hidden).
800Optional argument SHUT-UP, if non-nil, means don't print messages
801when parsing the archive."
802  (widen)
803  (let ((create-lockfiles nil) ; avoid changing dir mtime by lock_file
804	(inhibit-read-only t))
805    (setq archive-proper-file-start (copy-marker (point-min) t))
806    (set (make-local-variable 'change-major-mode-hook) 'archive-desummarize)
807    (or shut-up
808	(message "Parsing archive file..."))
809    (buffer-disable-undo (current-buffer))
810    (setq archive-files (funcall (archive-name "summarize")))
811    (or shut-up
812	(message "Parsing archive file...done."))
813    (setq archive-proper-file-start (point-marker))
814    (narrow-to-region (point-min) (point))
815    (set-buffer-modified-p nil)
816    (buffer-enable-undo))
817  (goto-char archive-file-list-start)
818  (archive-next-line 0))
819
820(defun archive-resummarize ()
821  "Recreate the contents listing of an archive."
822  (let ((no (archive-get-lineno)))
823    (archive-desummarize)
824    (archive-summarize t)
825    (goto-char archive-file-list-start)
826    (archive-next-line no)))
827
828(defun archive-summarize-files (files)
829  "Insert a description of a list of files annotated with proper mouse face."
830  (setq archive-file-list-start (point-marker))
831  (setq archive-file-name-indent (if files (aref (car files) 1) 0))
832  ;; We don't want to do an insert for each element since that takes too
833  ;; long when the archive -- which has to be moved in memory -- is large.
834  (insert
835   (apply
836    #'concat
837    (mapcar
838     (lambda (fil)
839       ;; Using `concat' here copies the text also, so we can add
840       ;; properties without problems.
841       (let ((text (concat (aref fil 0) "\n")))
842         (add-text-properties
843          (aref fil 1) (aref fil 2)
844          '(mouse-face highlight
845                       help-echo "mouse-2: extract this file into a buffer")
846          text)
847         text))
848     files)))
849  (setq archive-file-list-end (point-marker)))
850
851(defun archive-alternate-display ()
852  "Toggle alternative display.
853To avoid very long lines archive mode does not show all information.
854This function changes the set of information shown for each files."
855  (interactive)
856  (setq archive-alternate-display (not archive-alternate-display))
857  (archive-resummarize))
858;; -------------------------------------------------------------------------
859;;; Section: Local archive copy handling
860
861(defun archive-unique-fname (fname dir)
862  "Make sure a file FNAME can be created uniquely in directory DIR.
863
864If FNAME can be uniquely created in DIR, it is returned unaltered.
865If FNAME is something our underlying filesystem can't grok, or if another
866file by that name already exists in DIR, a unique new name is generated
867using `make-temp-file', and the generated name is returned."
868  (let ((fullname (expand-file-name fname dir))
869	(alien (string-match file-name-invalid-regexp fname))
870	(tmpfile
871	 (expand-file-name
872	  (if (if (fboundp 'msdos-long-file-names)
873		  (not (msdos-long-file-names)))
874	      "am"
875	    "arc-mode.")
876	  dir)))
877    (if (or alien (file-exists-p fullname))
878	(progn
879	  ;; Make sure all the leading directories in
880	  ;; archive-local-name exist under archive-tmpdir, so that
881	  ;; the directory structure recorded in the archive is
882	  ;; reconstructed in the temporary directory.
883	  (make-directory (file-name-directory tmpfile) t)
884	  (make-temp-file tmpfile))
885      ;; Make sure all the leading directories in `fullname' exist
886      ;; under archive-tmpdir.  This is necessary for nested archives
887      ;; (`archive-extract' sets `archive-remote' to t in case
888      ;; an archive occurs inside another archive).
889      (make-directory (file-name-directory fullname) t)
890      fullname)))
891
892(defun archive-maybe-copy (archive)
893  (let ((coding-system-for-write 'no-conversion))
894    (if archive-remote
895	(let ((start (point-max))
896	      ;; Sometimes ARCHIVE is invalid while its actual name, as
897	      ;; recorded in its parent archive, is not.  For example, an
898	      ;; archive bar.zip inside another archive foo.zip gets a name
899	      ;; "foo.zip:bar.zip", which is invalid on DOS/Windows.
900	      ;; So use the actual name if available.
901	      (archive-name
902	       (or (and archive-subfile-mode (aref archive-subfile-mode 0))
903		   archive)))
904	  (setq archive-local-name
905		(archive-unique-fname archive-name archive-tmpdir))
906	  (save-restriction
907	    (widen)
908	    (write-region start (point-max) archive-local-name nil 'nomessage))
909	  archive-local-name)
910      (if (buffer-modified-p) (save-buffer))
911      archive)))
912
913(defun archive-maybe-update (unchanged)
914  (if archive-remote
915      (let ((name archive-local-name)
916	    (modified (buffer-modified-p))
917	    (coding-system-for-read 'no-conversion)
918	    (lno (archive-get-lineno))
919	    (inhibit-read-only t))
920	(if unchanged nil
921	  (setq archive-files nil)
922	  (erase-buffer)
923	  (insert-file-contents name)
924	  (archive-mode t)
925	  (goto-char archive-file-list-start)
926	  (archive-next-line lno))
927	(archive-delete-local name)
928	(if (not unchanged)
929	    (message
930	     "Buffer `%s' must be saved for changes to take effect"
931	     (buffer-name (current-buffer))))
932	(set-buffer-modified-p (or modified (not unchanged))))))
933
934(defun archive-delete-local (name)
935  "Delete file NAME and its parents up to and including `archive-tmpdir'."
936  (let ((again t)
937	(top (directory-file-name (file-name-as-directory archive-tmpdir))))
938    (condition-case nil
939	(delete-file name)
940      (error nil))
941    (while again
942      (setq name (directory-file-name (file-name-directory name)))
943      (condition-case nil
944	  (delete-directory name)
945	(error nil))
946      (if (string= name top) (setq again nil)))))
947;; -------------------------------------------------------------------------
948;;; Section: Member extraction
949
950(defun archive-try-jka-compr ()
951  (when (and auto-compression-mode
952             (jka-compr-get-compression-info buffer-file-name))
953    (let* ((basename (file-name-nondirectory buffer-file-name))
954           (tmpname (if (string-match ":\\([^:]+\\)\\'" basename)
955                        (match-string 1 basename) basename))
956           (tmpfile (make-temp-file (file-name-sans-extension tmpname)
957                                    nil
958                                    (file-name-extension tmpname 'period))))
959      (unwind-protect
960          (progn
961            (let ((coding-system-for-write 'no-conversion)
962                  ;; Don't re-compress this data just before decompressing it.
963                  (jka-compr-inhibit t))
964              (write-region (point-min) (point-max) tmpfile nil 'quiet))
965            (erase-buffer)
966            (set-buffer-multibyte t)
967            (insert-file-contents tmpfile))
968        (delete-file tmpfile)))))
969
970(defun archive-file-name-handler (op &rest args)
971  (or (eq op 'file-exists-p)
972      (let ((file-name-handler-alist nil))
973	(apply op args))))
974
975(defun archive-set-buffer-as-visiting-file (filename)
976  "Set the current buffer as if it were visiting FILENAME."
977  (save-excursion
978    (goto-char (point-min))
979    (let ((buffer-undo-list t)
980	  (coding
981	   (or coding-system-for-read
982	       (and set-auto-coding-function
983		    (save-excursion
984		      (funcall set-auto-coding-function
985			       filename (- (point-max) (point-min)))))
986	       ;; The following let-binding of file-name-handler-alist forces
987	       ;; find-file-not-found-set-buffer-file-coding-system to ignore
988	       ;; the file's name (see dos-w32.el).
989	       (let ((file-name-handler-alist
990		      '(("" . archive-file-name-handler))))
991		 (car (find-operation-coding-system
992		       'insert-file-contents
993		       (cons filename (current-buffer)) t))))))
994      (unless (or coding-system-for-read
995                  enable-multibyte-characters)
996        (setq coding
997              (coding-system-change-text-conversion coding 'raw-text)))
998      (unless (memq coding '(nil no-conversion))
999        (decode-coding-region (point-min) (point-max) coding)
1000	(setq last-coding-system-used coding))
1001      (set-buffer-modified-p nil)
1002      (kill-local-variable 'buffer-file-coding-system)
1003      (after-insert-file-set-coding (- (point-max) (point-min))))))
1004
1005(defun archive-extract (&optional other-window-p event)
1006  "In archive mode, extract this entry of the archive into its own buffer."
1007  (interactive (list nil last-input-event))
1008  (if event (posn-set-point (event-end event)))
1009  (let* ((view-p (eq other-window-p 'view))
1010	 (descr (archive-get-descr))
1011         (ename (aref descr 0))
1012         (iname (aref descr 1))
1013         (archive-buffer (current-buffer))
1014         (arcdir default-directory)
1015         (archive (buffer-file-name))
1016         (arcname (file-name-nondirectory archive))
1017         (bufname (concat (file-name-nondirectory iname) " (" arcname ")"))
1018         (extractor (archive-name "extract"))
1019	 ;; Members with file names which aren't valid for the
1020	 ;; underlying filesystem, are treated as read-only.
1021         (read-only-p (or archive-read-only
1022			  view-p
1023			  (string-match file-name-invalid-regexp ename)))
1024	 (arcfilename (expand-file-name (concat arcname ":" iname)))
1025         (buffer (get-buffer bufname))
1026         (just-created nil)
1027	 (file-name-coding archive-file-name-coding-system))
1028      (if (and buffer
1029	       (string= (buffer-file-name buffer) arcfilename))
1030          nil
1031	(setq archive (archive-maybe-copy archive))
1032	(setq bufname (generate-new-buffer-name bufname))
1033        (setq buffer (get-buffer-create bufname))
1034        (setq just-created t)
1035        (with-current-buffer buffer
1036          (setq buffer-file-name arcfilename)
1037          (setq buffer-file-truename
1038                (abbreviate-file-name buffer-file-name))
1039          ;; Set the default-directory to the dir of the superior buffer.
1040          (setq default-directory arcdir)
1041          (make-local-variable 'archive-superior-buffer)
1042          (setq archive-superior-buffer archive-buffer)
1043          (add-hook 'write-file-functions #'archive-write-file-member nil t)
1044          (setq archive-subfile-mode descr)
1045	  (setq archive-file-name-coding-system file-name-coding)
1046	  (if (and
1047	       (null
1048		(let (;; We may have to encode the file name argument for
1049		      ;; external programs.
1050		      (coding-system-for-write
1051		       (and enable-multibyte-characters
1052			    archive-file-name-coding-system))
1053		      ;; We read an archive member by no-conversion at
1054		      ;; first, then decode appropriately by calling
1055		      ;; archive-set-buffer-as-visiting-file later.
1056		      (coding-system-for-read 'no-conversion)
1057		      ;; Avoid changing dir mtime by lock_file
1058		      (create-lockfiles nil))
1059		  (condition-case err
1060		      (if (fboundp extractor)
1061			  (funcall extractor archive ename)
1062			(archive-*-extract archive ename
1063					   (symbol-value extractor)))
1064		    (error
1065		     (ding (message "%s" (error-message-string err)))
1066		     nil))))
1067	       just-created)
1068	      (progn
1069		(set-buffer-modified-p nil)
1070		(kill-buffer buffer))
1071            (archive-try-jka-compr)     ;Pretty ugly hack :-(
1072	    (archive-set-buffer-as-visiting-file ename)
1073	    (goto-char (point-min))
1074	    (rename-buffer bufname)
1075	    (setq buffer-read-only read-only-p)
1076	    (setq buffer-undo-list nil)
1077	    (set-buffer-modified-p nil)
1078	    (setq buffer-saved-size (buffer-size))
1079	    (normal-mode)
1080	    ;; Just in case an archive occurs inside another archive.
1081	    (when (derived-mode-p 'archive-mode)
1082              (setq archive-remote t)
1083              (if read-only-p (setq archive-read-only t))
1084              ;; We will write out the archive ourselves if it is
1085              ;; part of another archive.
1086              (remove-hook 'write-contents-functions #'archive-write-file t))
1087            (run-hooks 'archive-extract-hook)
1088	    (if archive-read-only
1089		(message "Note: altering this archive is not implemented."))))
1090	(archive-maybe-update t))
1091      (or (not (buffer-name buffer))
1092          (cond
1093           (view-p
1094	    (view-buffer buffer (and just-created 'kill-buffer-if-not-modified)))
1095           ((eq other-window-p 'display) (display-buffer buffer))
1096           (other-window-p (switch-to-buffer-other-window buffer))
1097           (t (switch-to-buffer buffer))))))
1098
1099(defun archive-*-extract (archive name command)
1100  (let* ((default-directory (file-name-as-directory archive-tmpdir))
1101	 (tmpfile (expand-file-name (file-name-nondirectory name)
1102				    default-directory))
1103	 exit-status success)
1104    (make-directory (directory-file-name default-directory) t)
1105    (setq exit-status
1106	  (apply #'call-process
1107		 (car command)
1108		 nil
1109		 nil
1110		 nil
1111		 (append (cdr command) (list archive name))))
1112    (cond ((and (numberp exit-status) (zerop exit-status))
1113	   (if (not (file-exists-p tmpfile))
1114	       (ding (message "`%s': no such file or directory" tmpfile))
1115	     (insert-file-contents tmpfile)
1116	     (setq success t)))
1117	  ((numberp exit-status)
1118	   (ding
1119	    (message "`%s' exited with status %d" (car command) exit-status)))
1120	  ((stringp exit-status)
1121	   (ding (message "`%s' aborted: %s" (car command) exit-status)))
1122	  (t
1123	   (ding (message "`%s' failed" (car command)))))
1124    (archive-delete-local tmpfile)
1125    success))
1126
1127(defun archive-extract-by-stdout (archive name command &optional stderr-test)
1128  (let ((stderr-file (make-temp-file "arc-stderr")))
1129    (unwind-protect
1130	(prog1
1131	    (apply #'call-process
1132		   (car command)
1133		   nil
1134		   (if stderr-file (list t stderr-file) t)
1135		   nil
1136		   (append (cdr command) (list archive name)))
1137	  (with-temp-buffer
1138	    (insert-file-contents stderr-file)
1139	    (goto-char (point-min))
1140	    (when (if (stringp stderr-test)
1141		      (not (re-search-forward stderr-test nil t))
1142		    (> (buffer-size) 0))
1143	      (message "%s" (buffer-string)))))
1144      (if (file-exists-p stderr-file)
1145	  (delete-file stderr-file)))))
1146
1147(defun archive-extract-by-file (archive name command &optional stdout-test)
1148  (let ((dest (make-temp-file "arc-dir" 'dir))
1149	(stdout-file (make-temp-file "arc-stdout")))
1150    (unwind-protect
1151	(prog1
1152	    (apply #'call-process
1153		   (car command)
1154		   nil
1155		   `(:file ,stdout-file)
1156		   nil
1157                   `(,archive ,name ,@(cdr command) ,dest))
1158	  (with-temp-buffer
1159	    (insert-file-contents stdout-file)
1160	    (goto-char (point-min))
1161	    (when (if (stringp stdout-test)
1162		      (not (re-search-forward stdout-test nil t))
1163		    (> (buffer-size) 0))
1164	      (message "%s" (buffer-string))))
1165	  (if (file-exists-p (expand-file-name name dest))
1166	      (insert-file-contents-literally (expand-file-name name dest))))
1167      (if (file-exists-p stdout-file)
1168	  (delete-file stdout-file))
1169      (if (file-exists-p (expand-file-name name dest))
1170	  (delete-file (expand-file-name name dest)))
1171      (while (file-name-directory name)
1172	(setq name (directory-file-name (file-name-directory name)))
1173	(when (file-directory-p (expand-file-name name dest))
1174	  (delete-directory (expand-file-name name dest))))
1175      (when (file-directory-p dest)
1176	(delete-directory dest)))))
1177
1178(defun archive-extract-other-window ()
1179  "In archive mode, find this member in another window."
1180  (interactive)
1181  (archive-extract t))
1182
1183(defun archive-display-other-window ()
1184  "In archive mode, display this member in another window."
1185  (interactive)
1186  (archive-extract 'display))
1187
1188(defun archive-view ()
1189  "In archive mode, view the member on this line."
1190  (interactive)
1191  (archive-extract 'view))
1192
1193(defun archive-add-new-member (arcbuf name)
1194  "Add current buffer to the archive in ARCBUF naming it NAME."
1195  (interactive
1196   (list (get-buffer
1197	  (read-buffer "Buffer containing archive: "
1198		       ;; Find first archive buffer and suggest that
1199		       (let ((bufs (buffer-list)))
1200			 (while (and bufs
1201                                     (not (with-current-buffer (car bufs)
1202                                            (derived-mode-p 'archive-mode))))
1203                           (setq bufs (cdr bufs)))
1204			 (if bufs
1205			     (car bufs)
1206			   (error "There are no archive buffers")))
1207		       t))
1208	 (read-string "File name in archive: "
1209		      (if buffer-file-name
1210			  (file-name-nondirectory buffer-file-name)
1211			""))))
1212  (with-current-buffer arcbuf
1213    (or (derived-mode-p 'archive-mode)
1214	(error "Buffer is not an archive buffer"))
1215    (if archive-read-only
1216	(error "Archive is read-only")))
1217  (if (eq arcbuf (current-buffer))
1218      (error "An archive buffer cannot be added to itself"))
1219  (if (string= name "")
1220      (error "Archive members may not be given empty names"))
1221  (let ((func (with-current-buffer arcbuf
1222                (archive-name "add-new-member")))
1223	(membuf (current-buffer)))
1224    (if (fboundp func)
1225	(with-current-buffer arcbuf
1226	  (funcall func buffer-file-name membuf name))
1227      (error "Adding a new member is not supported for this archive type"))))
1228;; -------------------------------------------------------------------------
1229;;; Section: IO stuff
1230
1231(defun archive-write-file-member ()
1232  (save-excursion
1233    (save-restriction
1234      (message "Updating archive...")
1235      (widen)
1236      (let ((writer  (with-current-buffer archive-superior-buffer
1237                       (archive-name "write-file-member")))
1238	    (archive (with-current-buffer archive-superior-buffer
1239                       (archive-maybe-copy (buffer-file-name)))))
1240	(if (fboundp writer)
1241	    (funcall writer archive archive-subfile-mode)
1242	  (archive-*-write-file-member archive
1243				       archive-subfile-mode
1244				       (symbol-value writer)))
1245	(set-buffer-modified-p nil)
1246	(message "Updating archive...done"))
1247      (set-buffer archive-superior-buffer)
1248      (if (not archive-remote) (revert-buffer) (archive-maybe-update nil))))
1249  ;; Restore the value of last-coding-system-used, so that basic-save-buffer
1250  ;; won't reset the coding-system of this archive member.
1251  (if (local-variable-p 'archive-member-coding-system)
1252      (setq last-coding-system-used archive-member-coding-system))
1253  t)
1254
1255(defun archive-*-write-file-member (archive descr command)
1256  (let* ((ename (aref descr 0))
1257         (tmpfile (expand-file-name ename archive-tmpdir))
1258         (top (directory-file-name (file-name-as-directory archive-tmpdir)))
1259	 (default-directory (file-name-as-directory top)))
1260    (unwind-protect
1261        (progn
1262          (make-directory (file-name-directory tmpfile) t)
1263	  ;; If the member is itself an archive, write it without
1264	  ;; the dired-like listing we created.
1265	  (if (eq major-mode 'archive-mode)
1266	      (archive-write-file tmpfile)
1267	    (write-region nil nil tmpfile nil 'nomessage))
1268	  ;; basic-save-buffer needs last-coding-system-used to have
1269	  ;; the value used to write the file, so save it before any
1270	  ;; further processing clobbers it (we restore it in
1271	  ;; archive-write-file-member, above).
1272	  (setq archive-member-coding-system last-coding-system-used)
1273	  (if (aref descr 3)
1274	      ;; Set the file modes, but make sure we can read it.
1275	      (set-file-modes tmpfile (logior ?\400 (aref descr 3))))
1276	  (setq ename
1277		(encode-coding-string ename archive-file-name-coding-system))
1278          (let* ((coding-system-for-write 'no-conversion)
1279		 (exitcode (apply #'call-process
1280				  (car command)
1281				  nil
1282				  nil
1283				  nil
1284				  (append (cdr command)
1285					  (list archive ename)))))
1286            (or (zerop exitcode)
1287		(error "Updating was unsuccessful (%S)" exitcode))))
1288      (archive-delete-local tmpfile))))
1289
1290(defun archive-write-file (&optional file)
1291  (save-excursion
1292    (let ((coding-system-for-write 'no-conversion))
1293      (write-region archive-proper-file-start (point-max)
1294		    (or file buffer-file-name) nil t)
1295      (set-buffer-modified-p nil))
1296    t))
1297;; -------------------------------------------------------------------------
1298;;; Section: Marking and unmarking.
1299
1300(defun archive-flag-deleted (p &optional type)
1301  "In archive mode, mark this member to be deleted from the archive.
1302With a prefix argument, mark that many files."
1303  (interactive "p")
1304  (or type (setq type ?D))
1305  (beginning-of-line)
1306  (let ((sign (if (>= p 0) +1 -1))
1307	(modified (buffer-modified-p))
1308        (inhibit-read-only t))
1309    (while (not (zerop p))
1310      (if (archive-get-descr t)
1311          (progn
1312            (delete-char 1)
1313            (insert type)))
1314      (forward-line sign)
1315      (setq p (- p sign)))
1316    (restore-buffer-modified-p modified))
1317  (archive-next-line 0))
1318
1319(defun archive-unflag (p)
1320  "In archive mode, un-mark this member if it is marked to be deleted.
1321With a prefix argument, un-mark that many files forward."
1322  (interactive "p")
1323  (archive-flag-deleted p ?\s))
1324
1325(defun archive-unflag-backwards (p)
1326  "In archive mode, un-mark this member if it is marked to be deleted.
1327With a prefix argument, un-mark that many members backward."
1328  (interactive "p")
1329  (archive-flag-deleted (- p) ?\s))
1330
1331(defun archive-unmark-all-files ()
1332  "Remove all marks."
1333  (interactive)
1334  (let ((modified (buffer-modified-p))
1335	(inhibit-read-only t))
1336    (save-excursion
1337      (goto-char archive-file-list-start)
1338      (while (< (point) archive-file-list-end)
1339        (or (= (following-char) ?\s)
1340            (progn (delete-char 1) (insert ?\s)))
1341        (forward-line 1)))
1342    (restore-buffer-modified-p modified)))
1343
1344(defun archive-mark (p)
1345  "In archive mode, mark this member for group operations.
1346With a prefix argument, mark that many members.
1347Use \\[archive-unmark-all-files] to remove all marks."
1348  (interactive "p")
1349  (archive-flag-deleted p ?*))
1350
1351(defun archive-get-marked (mark &optional default)
1352  (let (files)
1353    (save-excursion
1354      (goto-char archive-file-list-start)
1355      (while (< (point) archive-file-list-end)
1356        (if (= (following-char) mark)
1357	    (setq files (cons (archive-get-descr) files)))
1358        (forward-line 1)))
1359    (or (nreverse files)
1360	(and default
1361	     (list (archive-get-descr))))))
1362;; -------------------------------------------------------------------------
1363;;; Section: Operate
1364
1365(defun archive-next-line (p)
1366  (interactive "p")
1367  (forward-line p)
1368  (or (eobp)
1369      (forward-char archive-file-name-indent)))
1370
1371(defun archive-previous-line (p)
1372  (interactive "p")
1373  (archive-next-line (- p)))
1374
1375(defun archive-chmod-entry (new-mode)
1376  "Change the protection bits associated with all marked or this member.
1377The new protection bits can either be specified as an octal number or
1378as a relative change like \"g+rw\" as for chmod(2)."
1379  (interactive "sNew mode (octal or relative): ")
1380  (if archive-read-only (error "Archive is read-only"))
1381  (let ((func (archive-name "chmod-entry")))
1382    (if (fboundp func)
1383	(progn
1384	  (funcall func new-mode (archive-get-marked ?* t))
1385	  (archive-resummarize))
1386      (error "Setting mode bits is not supported for this archive type"))))
1387
1388(defun archive-chown-entry (new-uid)
1389  "Change the owner of all marked or this member."
1390  (interactive "nNew uid: ")
1391  (if archive-read-only (error "Archive is read-only"))
1392  (let ((func (archive-name "chown-entry")))
1393    (if (fboundp func)
1394	(progn
1395	  (funcall func new-uid (archive-get-marked ?* t))
1396	  (archive-resummarize))
1397      (error "Setting owner is not supported for this archive type"))))
1398
1399(defun archive-chgrp-entry (new-gid)
1400  "Change the group of all marked or this member."
1401  (interactive "nNew gid: ")
1402  (if archive-read-only (error "Archive is read-only"))
1403  (let ((func (archive-name "chgrp-entry")))
1404    (if (fboundp func)
1405	(progn
1406	  (funcall func new-gid (archive-get-marked ?* t))
1407	  (archive-resummarize))
1408      (error "Setting group is not supported for this archive type"))))
1409
1410(defun archive-expunge ()
1411  "Do the flagged deletions."
1412  (interactive)
1413  (let (files)
1414    (save-excursion
1415      (goto-char archive-file-list-start)
1416      (while (< (point) archive-file-list-end)
1417        (if (= (following-char) ?D)
1418	    (setq files (cons (aref (archive-get-descr) 0) files)))
1419        (forward-line 1)))
1420    (setq files (nreverse files))
1421    (and files
1422	 (or (not archive-read-only)
1423	     (error "Archive is read-only"))
1424	 (or (yes-or-no-p (format "Really delete %d member%s? "
1425				  (length files)
1426				  (if (null (cdr files)) "" "s")))
1427	     (error "Operation aborted"))
1428	 (let ((archive (archive-maybe-copy (buffer-file-name)))
1429	       (expunger (archive-name "expunge")))
1430	   (if (fboundp expunger)
1431	       (funcall expunger archive files)
1432	     (archive-*-expunge archive files (symbol-value expunger)))
1433	   (archive-maybe-update nil)
1434	   (if archive-remote
1435	       (archive-resummarize)
1436	     (revert-buffer))))))
1437
1438(defun archive-*-expunge (archive files command)
1439  (apply #'call-process
1440	 (car command)
1441	 nil
1442	 nil
1443	 nil
1444	 (append (cdr command) (cons archive files))))
1445
1446(defun archive-rename-entry (newname)
1447  "Change the name associated with this entry in the archive file."
1448  (interactive "sNew name: ")
1449  (if archive-read-only (error "Archive is read-only"))
1450  (if (string= newname "")
1451      (error "Archive members may not be given empty names"))
1452  (let ((func (archive-name "rename-entry"))
1453	(descr (archive-get-descr)))
1454    (if (fboundp func)
1455        (progn
1456	  (funcall func
1457		   (encode-coding-string newname
1458					 archive-file-name-coding-system)
1459		   descr)
1460	  (archive-resummarize))
1461      (error "Renaming is not supported for this archive type"))))
1462
1463;; Revert the buffer and recompute the dired-like listing.
1464(defun archive-mode-revert (&optional _no-auto-save _no-confirm)
1465  (let ((no (archive-get-lineno)))
1466    (setq archive-files nil)
1467    (let ((revert-buffer-function nil)
1468	  (coding-system-for-read 'no-conversion))
1469      (revert-buffer t t))
1470    (archive-mode)
1471    (goto-char archive-file-list-start)
1472    (archive-next-line no)))
1473
1474(defun archive-undo ()
1475  "Undo in an archive buffer.
1476This doesn't recover lost files, it just undoes changes in the buffer itself."
1477  (interactive)
1478  (let ((inhibit-read-only t))
1479    (undo)))
1480;; -------------------------------------------------------------------------
1481;;; Section: Arc Archives
1482
1483(defun archive-arc-summarize ()
1484  (let ((p 1)
1485	(totalsize 0)
1486	(maxlen 8)
1487        files
1488	visual)
1489    (while (and (< (+ p 29) (point-max))
1490		(= (get-byte p) ?\C-z)
1491		(> (get-byte (1+ p)) 0))
1492      (let* ((namefld (buffer-substring (+ p 2) (+ p 2 13)))
1493	     (fnlen   (or (string-match "\0" namefld) 13))
1494	     (efnname (decode-coding-string (substring namefld 0 fnlen)
1495					    archive-file-name-coding-system))
1496             (csize   (archive-l-e (+ p 15) 4))
1497             (moddate (archive-l-e (+ p 19) 2))
1498             (modtime (archive-l-e (+ p 21) 2))
1499             (ucsize  (archive-l-e (+ p 25) 4))
1500	     (fiddle  (string= efnname (upcase efnname)))
1501             (ifnname (if fiddle (downcase efnname) efnname))
1502             (text    (format "  %8d  %-11s  %-8s  %s"
1503                              ucsize
1504                              (archive-dosdate moddate)
1505                              (archive-dostime modtime)
1506                              ifnname)))
1507        (setq maxlen (max maxlen fnlen)
1508	      totalsize (+ totalsize ucsize)
1509	      visual (cons (vector text
1510				   (- (length text) (length ifnname))
1511				   (length text))
1512			   visual)
1513	      files (cons (vector efnname ifnname fiddle nil (1- p))
1514                          files)
1515              p (+ p 29 csize))))
1516    (goto-char (point-min))
1517    (let ((dash (concat "- --------  -----------  --------  "
1518			(make-string maxlen ?-)
1519			"\n")))
1520      (insert "M   Length  Date         Time      File\n"
1521	      dash)
1522      (archive-summarize-files (nreverse visual))
1523      (insert dash
1524	      (format "  %8d                         %d file%s"
1525		      totalsize
1526		      (length files)
1527		      (if (= 1 (length files)) "" "s"))
1528	      "\n"))
1529    (apply #'vector (nreverse files))))
1530
1531(defun archive-arc-rename-entry (newname descr)
1532  (if (string-match "[:\\/]" newname)
1533      (error "File names in arc files must not contain a directory component"))
1534  (if (> (length newname) 12)
1535      (error "File names in arc files are limited to 12 characters"))
1536  (let ((name (concat newname (substring "\0\0\0\0\0\0\0\0\0\0\0\0\0"
1537					 (length newname))))
1538	(inhibit-read-only t))
1539    (save-restriction
1540      (save-excursion
1541	(widen)
1542	(goto-char (+ archive-proper-file-start (aref descr 4) 2))
1543	(delete-char 13)
1544	(arc-insert-unibyte name)))))
1545;; -------------------------------------------------------------------------
1546;;; Section: Lzh Archives
1547
1548(defun archive-lzh-summarize (&optional start)
1549  (let ((p (or start 1)) ;; 1 for .lzh, something further on for .exe
1550	(totalsize 0)
1551	(maxlen 8)
1552        files
1553	visual)
1554    (while (progn (goto-char p)		;beginning of a base header.
1555		  (looking-at "\\(.\\|\n\\)\\(.\\|\n\\)-l[hz][0-9ds]-"))
1556      (let* ((hsize   (get-byte p))	;size of the base header (level 0 and 1)
1557	     (csize   (archive-l-e (+ p 7) 4)) ;size of a compressed file to follow (level 0 and 2),
1558					;size of extended headers + the compressed file to follow (level 1).
1559             (ucsize  (archive-l-e (+ p 11) 4))	;size of an uncompressed file.
1560	     (time1   (archive-l-e (+ p 15) 2))	;date/time (MSDOS format in level 0, 1 headers
1561	     (time2   (archive-l-e (+ p 17) 2))	;and UNIX format in level 2 header.)
1562	     (hdrlvl  (get-byte (+ p 20))) ;header level
1563	     thsize		;total header size (base + extensions)
1564	     fnlen efnname osid fiddle ifnname width p2
1565	     neh	;beginning of next extension header (level 1 and 2)
1566	     mode modestr uid gid text dir prname
1567	     gname uname modtime moddate)
1568	(if (= hdrlvl 3) (error "can't handle lzh level 3 header type"))
1569	(when (or (= hdrlvl 0) (= hdrlvl 1))
1570	  (setq fnlen   (get-byte (+ p 21))) ;filename length
1571	  (setq efnname (let ((str (buffer-substring (+ p 22) (+ p 22 fnlen))))	;filename from offset 22
1572			(decode-coding-string
1573			 str archive-file-name-coding-system)))
1574	  (setq p2      (+ p 22 fnlen))) ;
1575	(if (= hdrlvl 1)
1576            (setq neh (+ p2 3))         ;specific to level 1 header
1577	  (if (= hdrlvl 2)
1578              (setq neh (+ p 24))))     ;specific to level 2 header
1579	(if neh		;if level 1 or 2 we expect extension headers to follow
1580	    (let* ((ehsize (archive-l-e neh 2))	;size of the extension header
1581		   (etype (get-byte (+ neh 2)))) ;extension type
1582	      (while (not (= ehsize 0))
1583		  (cond
1584		 ((= etype 1)	;file name
1585		  (let ((i (+ neh 3)))
1586		    (while (< i (+ neh ehsize))
1587		      (setq efnname (concat efnname (char-to-string (get-byte i))))
1588		      (setq i (1+ i)))))
1589		 ((= etype 2)	;directory name
1590		  (let ((i (+ neh 3)))
1591		    (while (< i (+ neh ehsize))
1592				    (setq dir (concat dir
1593						       (if (= (get-byte i)
1594							      255)
1595							   "/"
1596							 (char-to-string
1597							  (char-after i)))))
1598				    (setq i (1+ i)))))
1599		 ((= etype 80)		;Unix file permission
1600		  (setq mode (archive-l-e (+ neh 3) 2)))
1601		 ((= etype 81)		;UNIX file group/user ID
1602		  (progn (setq uid (archive-l-e (+ neh 3) 2))
1603			 (setq gid (archive-l-e (+ neh 5) 2))))
1604		 ((= etype 82)		;UNIX file group name
1605		  (let ((i (+ neh 3)))
1606		    (while (< i (+ neh ehsize))
1607		      (setq gname (concat gname (char-to-string (char-after i))))
1608		      (setq i (1+ i)))))
1609		 ((= etype 83)		;UNIX file user name
1610		  (let ((i (+ neh 3)))
1611		    (while (< i (+ neh ehsize))
1612		      (setq uname (concat uname (char-to-string (char-after i))))
1613		      (setq i (1+ i)))))
1614		   )
1615		(setq neh (+ neh ehsize))
1616		(setq ehsize (archive-l-e neh 2))
1617		(setq etype (get-byte (+ neh 2))))
1618	      ;;get total header size for level 1 and 2 headers
1619	      (setq thsize (- neh p))))
1620	(if (= hdrlvl 0)  ;total header size
1621	    (setq thsize hsize))
1622        ;; OS ID field not present in level 0 header, use code 0 "generic"
1623        ;; in that case as per lha program header.c get_header()
1624	(setq osid (cond ((= hdrlvl 0)  0)
1625                         ((= hdrlvl 1)  (char-after (+ p 22 fnlen 2)))
1626                         ((= hdrlvl 2)  (char-after (+ p 23)))))
1627        ;; Filename fiddling must follow the lha program, otherwise the name
1628        ;; passed to "lha pq" etc won't match (which for an extract silently
1629        ;; results in no output).  As of version 1.14i it goes from the OS ID,
1630        ;; - For 'M' MSDOS: msdos_to_unix_filename() downcases always, and
1631        ;;   converts "\" to "/".
1632        ;; - For 0 generic: generic_to_unix_filename() downcases if there's
1633        ;;   no lower case already present, and converts "\" to "/".
1634        ;; - For 'm' macOS: macos_to_unix_filename() changes "/" to ":" and
1635        ;;   ":" to "/"
1636	(setq fiddle (cond ((= ?M osid) t)
1637                           ((= 0 osid)  (string= efnname (upcase efnname)))))
1638	(setq ifnname (if fiddle (downcase efnname) efnname))
1639	(setq prname (if dir (concat dir ifnname) ifnname))
1640	(setq width (if prname (string-width prname) 0))
1641	(setq modestr (if mode (archive-int-to-mode mode) "??????????"))
1642	(setq moddate (if (= hdrlvl 2)
1643			  (archive-unixdate time1 time2) ;level 2 header in UNIX format
1644			(archive-dosdate time2))) ;level 0 and 1 header in DOS format
1645	(setq modtime (if (= hdrlvl 2)
1646			  (archive-unixtime time1 time2)
1647			(archive-dostime time1)))
1648	(setq text    (if archive-alternate-display
1649			  (format "  %8d  %5S  %5S  %s"
1650				  ucsize
1651				  (or uid "?")
1652				  (or gid "?")
1653				  ifnname)
1654			(format "  %10s  %8d  %-11s  %-8s  %s"
1655				modestr
1656				ucsize
1657				moddate
1658				modtime
1659				prname)))
1660        (setq maxlen (max maxlen width)
1661	      totalsize (+ totalsize ucsize)
1662	      visual (cons (vector text
1663				   (- (length text) (length prname))
1664				   (length text))
1665			   visual)
1666	      files (cons (vector prname ifnname fiddle mode (1- p))
1667                          files))
1668	(cond ((= hdrlvl 1)
1669	       (setq p (+ p hsize 2 csize)))
1670	      ((or (= hdrlvl 2) (= hdrlvl 0))
1671	       (setq p (+ p thsize 2 csize))))
1672	))
1673    (goto-char (point-min))
1674    (let ((dash (concat (if archive-alternate-display
1675			    "- --------  -----  -----  "
1676			  "- ----------  --------  -----------  --------  ")
1677			(make-string maxlen ?-)
1678			"\n"))
1679	  (header (if archive-alternate-display
1680		       "M   Length    Uid    Gid  File\n"
1681		    "M   Filemode    Length  Date         Time      File\n"))
1682	  (sumline (if archive-alternate-display
1683		       "  %8.0f                %d file%s"
1684		     "              %8.0f                         %d file%s")))
1685      (insert header dash)
1686      (archive-summarize-files (nreverse visual))
1687      (insert dash
1688	      (format sumline
1689		      totalsize
1690		      (length files)
1691		      (if (= 1 (length files)) "" "s"))
1692	      "\n"))
1693    (apply #'vector (nreverse files))))
1694
1695(defconst archive-lzh-alternate-display t)
1696
1697(defun archive-lzh-extract (archive name)
1698  (archive-extract-by-stdout archive name archive-lzh-extract))
1699
1700(defun archive-lzh-resum (p count)
1701  (let ((sum 0))
1702    (while (> count 0)
1703      (setq count (1- count)
1704	    sum (+ sum (get-byte p))
1705	    p (1+ p)))
1706    (logand sum 255)))
1707
1708(defun archive-lzh-rename-entry (newname descr)
1709  (save-restriction
1710    (save-excursion
1711      (widen)
1712      (let* ((p        (+ archive-proper-file-start (aref descr 4)))
1713	     (oldhsize (get-byte p))
1714	     (oldfnlen (get-byte (+ p 21)))
1715	     (newfnlen (length newname))
1716	     (newhsize (+ oldhsize newfnlen (- oldfnlen)))
1717	     (inhibit-read-only t))
1718	(if (> newhsize 255)
1719	    (error "The file name is too long"))
1720	(goto-char (+ p 21))
1721	(delete-char (1+ oldfnlen))
1722	(arc-insert-unibyte newfnlen newname)
1723	(goto-char p)
1724	(delete-char 2)
1725	(arc-insert-unibyte newhsize (archive-lzh-resum p newhsize))))))
1726
1727(defun archive-lzh-ogm (newval files errtxt ofs)
1728  (save-excursion
1729    (save-restriction
1730      (widen)
1731      (dolist (fil files)
1732	(let* ((p (+ archive-proper-file-start (aref fil 4)))
1733	       (hsize   (get-byte p))
1734	       (fnlen   (get-byte (+ p 21)))
1735	       (p2      (+ p 22 fnlen))
1736	       (creator (if (>= (- hsize fnlen) 24) (get-byte (+ p2 2)) 0))
1737	       (inhibit-read-only t))
1738	  (if (= creator ?U)
1739	      (progn
1740		(or (numberp newval)
1741		    (setq newval (funcall newval (archive-l-e (+ p2 ofs) 2))))
1742		(goto-char (+ p2 ofs))
1743		(delete-char 2)
1744		(arc-insert-unibyte (logand newval 255) (ash newval -8))
1745		(goto-char (1+ p))
1746		(delete-char 1)
1747		(arc-insert-unibyte (archive-lzh-resum (1+ p) hsize)))
1748	    (message "Member %s does not have %s field"
1749		     (aref fil 1) errtxt)))))))
1750
1751(defun archive-lzh-chown-entry (newuid files)
1752  (archive-lzh-ogm newuid files "an uid" 10))
1753
1754(defun archive-lzh-chgrp-entry (newgid files)
1755  (archive-lzh-ogm newgid files "a gid" 12))
1756
1757(defun archive-lzh-chmod-entry (newmode files)
1758  (archive-lzh-ogm
1759   ;; This should work even though newmode will be dynamically accessed.
1760   (lambda (old) (archive-calc-mode old newmode t))
1761   files "a unix-style mode" 8))
1762
1763;; -------------------------------------------------------------------------
1764;;; Section: Lzh Self-Extracting .exe Archives
1765;;
1766;; No support for modifying these files.  It looks like the lha for unix
1767;; program (as of version 1.14i) can't create or retain the DOS exe part.
1768;; If you do an "lha a" on a .exe for instance it renames and writes to a
1769;; plain .lzh.
1770
1771(defun archive-lzh-exe-summarize ()
1772  "Summarize the contents of an LZH self-extracting exe, for `archive-mode'."
1773
1774  ;; Skip the initial executable code part and apply archive-lzh-summarize
1775  ;; to the archive part proper.  The "-lh5-" etc regexp here for the start
1776  ;; is the same as in archive-find-type.
1777  ;;
1778  ;; The lha program (version 1.14i) does this in skip_msdos_sfx1_code() by
1779  ;; a similar scan.  It looks for "..-l..-" plus for level 0 or 1 a test of
1780  ;; the header checksum, or level 2 a test of the "attribute" and size.
1781  ;;
1782  (re-search-forward "..-l[hz][0-9ds]-" nil)
1783  (archive-lzh-summarize (match-beginning 0)))
1784
1785;; `archive-lzh-extract' runs "lha pq", and that works for .exe as well as
1786;; .lzh files
1787(defalias 'archive-lzh-exe-extract 'archive-lzh-extract
1788  "Extract a member from an LZH self-extracting exe, for `archive-mode'.")
1789
1790;; -------------------------------------------------------------------------
1791;;; Section: Zip Archives
1792
1793(defun archive-zip-summarize ()
1794  (goto-char (- (point-max) (- 22 18)))
1795  (search-backward-regexp "[P]K\005\006")
1796  (let ((p (archive-l-e (+ (point) 16) 4))
1797        (maxlen 8)
1798	(totalsize 0)
1799        files
1800	visual
1801        emacs-int-has-32bits)
1802    (when (or (= p #xffffffff) (= p -1))
1803      ;; If the offset of end-of-central-directory is 0xFFFFFFFF, this
1804      ;; is a Zip64 extended ZIP file format, and we need to glean the
1805      ;; info from Zip64 records instead.
1806      ;;
1807      ;; First, find the Zip64 end-of-central-directory locator.
1808      (search-backward "PK\006\007")
1809      (setq p (+ (point-min)
1810                 (archive-l-e (+ (point) 8) 8)))
1811      (goto-char p)
1812      ;; We should be at Zip64 end-of-central-directory record now.
1813      (or (string= "PK\006\006" (buffer-substring p (+ p 4)))
1814          (error "Unrecognized ZIP file format"))
1815      ;; Offset to central directory:
1816      (setq p (archive-l-e (+ p 48) 8)))
1817    (setq p (+ p (point-min)))
1818    (while (string= "PK\001\002" (buffer-substring p (+ p 4)))
1819      (let* ((creator (get-byte (+ p 5)))
1820	     ;; (method  (archive-l-e (+ p 10) 2))
1821             (modtime (archive-l-e (+ p 12) 2))
1822             (moddate (archive-l-e (+ p 14) 2))
1823             (ucsize  (archive-l-e (+ p 24) 4))
1824             (fnlen   (archive-l-e (+ p 28) 2))
1825             (exlen   (archive-l-e (+ p 30) 2))
1826             (fclen   (archive-l-e (+ p 32) 2))
1827             (lheader (archive-l-e (+ p 42) 4))
1828             (efnname (let ((str (buffer-substring (+ p 46) (+ p 46 fnlen))))
1829			(decode-coding-string
1830			 str archive-file-name-coding-system)))
1831             (ucsize  (if (and (or (= ucsize #xffffffff) (= ucsize -1))
1832                               (> exlen 0))
1833                          ;; APPNOTE.TXT, para 4.5.3: the Extra Field
1834                          ;; begins with 2 bytes of signature
1835                          ;; (\000\001), followed by 2 bytes that give
1836                          ;; the size of the extra block, followed by
1837                          ;; an 8-byte uncompressed size.
1838                          (archive-l-e (+ p 46 fnlen 4) 8)
1839                        ucsize))
1840	     (isdir   (and (= ucsize 0)
1841			   (string= (file-name-nondirectory efnname) "")))
1842	     (mode    (cond ((memq creator '(2 3)) ; Unix
1843			     (archive-l-e (+ p 40) 2))
1844			    ((memq creator '(0 5 6 7 10 11 15)) ; Dos etc.
1845			     (logior ?\444
1846				     (if isdir (logior 16384 ?\111) 0)
1847				     (if (zerop
1848					  (logand 1 (get-byte (+ p 38))))
1849					 ?\222 0)))
1850			    (t nil)))
1851	     (modestr (if mode (archive-int-to-mode mode) "??????????"))
1852	     (fiddle  (and archive-zip-case-fiddle
1853			   (not (not (memq creator '(0 2 4 5 9))))
1854			   (string= (upcase efnname) efnname)))
1855             (ifnname (if fiddle (downcase efnname) efnname))
1856	     (width (string-width ifnname))
1857             (text    (format "  %10s  %8d  %-11s  %-8s  %s"
1858			      modestr
1859                              ucsize
1860                              (archive-dosdate moddate)
1861                              (archive-dostime modtime)
1862                              ifnname)))
1863        (setq maxlen (max maxlen width)
1864	      totalsize (+ totalsize ucsize)
1865	      visual (cons (vector text
1866				   (- (length text) (length ifnname))
1867				   (length text))
1868			   visual)
1869	      files (cons (if isdir
1870			      nil
1871			    (vector efnname ifnname fiddle mode
1872				    (list (1- p) lheader)))
1873                          files)
1874              p (+ p 46 fnlen exlen fclen))))
1875    (goto-char (point-min))
1876    (let ((dash (concat "- ----------  --------  -----------  --------  "
1877			(make-string maxlen ?-)
1878			"\n")))
1879      (insert "M Filemode      Length  Date         Time      File\n"
1880	      dash)
1881      (archive-summarize-files (nreverse visual))
1882      (insert dash
1883	      (format "              %8d                         %d file%s"
1884		      totalsize
1885		      (length files)
1886		      (if (= 1 (length files)) "" "s"))
1887	      "\n"))
1888    (apply #'vector (nreverse files))))
1889
1890(defun archive-zip-extract (archive name)
1891  (cond
1892   ((member-ignore-case (car archive-zip-extract) '("pkunzip" "pkzip"))
1893    (archive-*-extract archive name archive-zip-extract))
1894   ((equal (car archive-zip-extract) archive-7z-program)
1895    (let ((archive-7z-extract archive-zip-extract))
1896      (archive-7z-extract archive name)))
1897   (t
1898    (archive-extract-by-stdout
1899     archive
1900     ;; unzip expands wildcards in NAME, so we need to quote it.  But
1901     ;; not on DOS/Windows, since that fails extraction on those
1902     ;; systems (unless w32-quote-process-args is nil), and file names
1903     ;; with wildcards in zip archives don't work there anyway.
1904     ;; FIXME: Does pkunzip need similar treatment?
1905     (if (and (or (not (memq system-type '(windows-nt ms-dos)))
1906		  (and (boundp 'w32-quote-process-args)
1907		       (null w32-quote-process-args)))
1908	      (equal (car archive-zip-extract) "unzip"))
1909	 (shell-quote-argument name)
1910       name)
1911     archive-zip-extract))))
1912
1913(defun archive-zip-write-file-member (archive descr)
1914  (archive-*-write-file-member
1915   archive
1916   descr
1917   (if (aref descr 2) archive-zip-update-case archive-zip-update)))
1918
1919(defun archive-zip-chmod-entry (newmode files)
1920  (save-restriction
1921    (save-excursion
1922      (widen)
1923      (dolist (fil files)
1924	(let* ((p (+ archive-proper-file-start (car (aref fil 4))))
1925	       (creator (get-byte (+ p 5)))
1926	       (oldmode (aref fil 3))
1927	       (newval  (archive-calc-mode oldmode newmode t))
1928	       (inhibit-read-only t))
1929	  (cond ((memq creator '(2 3)) ; Unix
1930		 (goto-char (+ p 40))
1931		 (delete-char 2)
1932		 (arc-insert-unibyte (logand newval 255) (ash newval -8)))
1933		((memq creator '(0 5 6 7 10 11 15)) ; Dos etc.
1934		 (goto-char (+ p 38))
1935		 (arc-insert-unibyte
1936                  (logior (logand (get-byte (point)) 254)
1937			  (logand (logxor 1 (ash newval -7)) 1)))
1938		 (delete-char 1))
1939		(t (message "Don't know how to change mode for this member"))))
1940        ))))
1941;; -------------------------------------------------------------------------
1942;;; Section: Zoo Archives
1943
1944(defun archive-zoo-summarize ()
1945  (let ((p (1+ (archive-l-e 25 4)))
1946        (maxlen 8)
1947	(totalsize 0)
1948        files
1949	visual)
1950    (while (and (string= "\334\247\304\375" (buffer-substring p (+ p 4)))
1951		(> (archive-l-e (+ p 6) 4) 0))
1952      (let* ((next    (1+ (archive-l-e (+ p 6) 4)))
1953             (moddate (archive-l-e (+ p 14) 2))
1954             (modtime (archive-l-e (+ p 16) 2))
1955             (ucsize  (archive-l-e (+ p 20) 4))
1956	     (namefld (buffer-substring (+ p 38) (+ p 38 13)))
1957	     (dirtype (get-byte (+ p 4)))
1958	     (lfnlen  (if (= dirtype 2) (get-byte (+ p 56)) 0))
1959	     (ldirlen (if (= dirtype 2) (get-byte (+ p 57)) 0))
1960	     (fnlen   (or (string-match "\0" namefld) 13))
1961	     (efnname (let ((str
1962			     (concat
1963			      (if (> ldirlen 0)
1964				  (concat (buffer-substring
1965					   (+ p 58 lfnlen)
1966					   (+ p 58 lfnlen ldirlen -1))
1967					  "/")
1968				"")
1969			      (if (> lfnlen 0)
1970				  (buffer-substring (+ p 58)
1971						    (+ p 58 lfnlen -1))
1972				(substring namefld 0 fnlen)))))
1973			(decode-coding-string
1974			 str archive-file-name-coding-system)))
1975	     (fiddle  (and (= lfnlen 0) (string= efnname (upcase efnname))))
1976             (ifnname (if fiddle (downcase efnname) efnname))
1977	     (width (string-width ifnname))
1978             (text    (format "  %8d  %-11s  %-8s  %s"
1979                              ucsize
1980                              (archive-dosdate moddate)
1981                              (archive-dostime modtime)
1982                              ifnname)))
1983        (setq maxlen (max maxlen width)
1984	      totalsize (+ totalsize ucsize)
1985	      visual (cons (vector text
1986				   (- (length text) (length ifnname))
1987				   (length text))
1988			   visual)
1989	      files (cons (vector efnname ifnname fiddle nil (1- p))
1990                          files)
1991              p next)))
1992    (goto-char (point-min))
1993    (let ((dash (concat "- --------  -----------  --------  "
1994			(make-string maxlen ?-)
1995			"\n")))
1996      (insert "M   Length  Date         Time      File\n"
1997	      dash)
1998      (archive-summarize-files (nreverse visual))
1999      (insert dash
2000	      (format "  %8d                         %d file%s"
2001		      totalsize
2002		      (length files)
2003		      (if (= 1 (length files)) "" "s"))
2004	      "\n"))
2005    (apply #'vector (nreverse files))))
2006
2007(defun archive-zoo-extract (archive name)
2008  (archive-extract-by-stdout archive name archive-zoo-extract))
2009
2010;; -------------------------------------------------------------------------
2011;;; Section: Rar Archives
2012
2013(defun archive-rar-summarize (&optional file)
2014  ;; File is used internally for `archive-rar-exe-summarize'.
2015  (unless file (setq file buffer-file-name))
2016  (let* ((copy (file-local-copy file))
2017         (maxname 10)
2018         (maxsize 5)
2019         (files ()))
2020    (with-temp-buffer
2021      (call-process "lsar" nil t nil "-l" (or file copy))
2022      (if copy (delete-file copy))
2023      (goto-char (point-min))
2024      (re-search-forward "^\\(\s+=+\s*\\)+\n")
2025      (while (looking-at (concat "^\s+[0-9.]+\s+D?-+\s+"   ; Flags
2026                                 "\\([0-9-]+\\)\s+"        ; Size
2027                                 "\\([-0-9.%]+\\)\s+"      ; Ratio
2028                                 "\\([0-9a-zA-Z]+\\)\s+"   ; Mode
2029                                 "\\([0-9-]+\\)\s+"        ; Date
2030                                 "\\([0-9:]+\\)\s+"        ; Time
2031                                 "\\(.*\\)\n"              ; Name
2032                                 ))
2033        (goto-char (match-end 0))
2034        (let ((name (match-string 6))
2035              (size (match-string 1)))
2036          (if (> (length name) maxname) (setq maxname (length name)))
2037          (if (> (length size) maxsize) (setq maxsize (length size)))
2038          (push (vector name name nil nil
2039                        ;; Size, Ratio.
2040                        size (match-string 2)
2041                        ;; Date, Time.
2042                        (match-string 4) (match-string 5))
2043                files))))
2044    (setq files (nreverse files))
2045    (goto-char (point-min))
2046    (let* ((format (format " %%s %%s  %%%ds %%5s  %%s" maxsize))
2047           (sep (format format "----------" "-----" (make-string maxsize ?-)
2048                        "-----" ""))
2049           (column (length sep)))
2050      (insert (format format "   Date   " "Time " "Size" "Ratio" "Filename") "\n")
2051      (insert sep (make-string maxname ?-) "\n")
2052      (archive-summarize-files (mapcar (lambda (desc)
2053                                         (let ((text
2054                                                (format format
2055                                                         (aref desc 6)
2056                                                         (aref desc 7)
2057                                                         (aref desc 4)
2058                                                         (aref desc 5)
2059                                                         (aref desc 1))))
2060                                           (vector text
2061                                                   column
2062                                                   (length text))))
2063                                       files))
2064      (insert sep (make-string maxname ?-) "\n")
2065      (apply #'vector files))))
2066
2067(defun archive-rar-extract (archive name)
2068  ;; unrar-free seems to have no way to extract to stdout or even to a file.
2069  (if (file-name-absolute-p name)
2070      ;; The code below assumes the name is relative and may do undesirable
2071      ;; things otherwise.
2072      (error "Can't extract files with non-relative names")
2073    (archive-extract-by-file archive name '("unar" "-no-directory" "-o") "Successfully extracted")))
2074
2075;;; Section: Rar self-extracting .exe archives.
2076
2077(defun archive-rar-exe-summarize ()
2078  (let ((tmpfile (make-temp-file "rarexe")))
2079    (unwind-protect
2080        (progn
2081          (goto-char (point-min))
2082          (re-search-forward "Rar!")
2083          (write-region (match-beginning 0) (point-max) tmpfile)
2084          (archive-rar-summarize tmpfile))
2085      (delete-file tmpfile))))
2086
2087(defun archive-rar-exe-extract (archive name)
2088  (let* ((tmpfile (make-temp-file "rarexe"))
2089         (buf (find-buffer-visiting archive))
2090         (tmpbuf (unless buf (generate-new-buffer " *rar-exe*"))))
2091    (unwind-protect
2092        (progn
2093          (with-current-buffer (or buf tmpbuf)
2094            (save-excursion
2095              (save-restriction
2096                (if buf
2097                    ;; point-max unwidened is assumed to be the end of the
2098                    ;; summary text and the beginning of the actual file data.
2099                    (progn (goto-char (point-max)) (widen))
2100                  (insert-file-contents-literally archive)
2101                  (goto-char (point-min)))
2102                (re-search-forward "Rar!")
2103                (write-region (match-beginning 0) (point-max) tmpfile))))
2104          (archive-rar-extract tmpfile name))
2105      (if tmpbuf (kill-buffer tmpbuf))
2106      (delete-file tmpfile))))
2107
2108;; -------------------------------------------------------------------------
2109;;; Section: 7z Archives
2110
2111(defun archive-7z-summarize ()
2112  (let ((maxname 10)
2113	(maxsize 5)
2114	(file buffer-file-name)
2115	(files ()))
2116    (with-temp-buffer
2117      (call-process archive-7z-program nil t nil "l" "-slt" file)
2118      (goto-char (point-min))
2119      ;; Four dashes start the meta info section that should be skipped.
2120      ;; Archive members start with more than four dashes.
2121      (re-search-forward "^-----+\n")
2122      (while (re-search-forward "^Path = \\(.*\\)\n" nil t)
2123        (goto-char (match-end 0))
2124        (let ((name (match-string 1))
2125              (size (save-excursion
2126		      (and (re-search-forward "^Size = \\(.*\\)\n")
2127			   (match-string 1))))
2128	      (time (save-excursion
2129		      (and (re-search-forward "^Modified = \\(.*\\)\n")
2130			   (match-string 1)))))
2131          (if (> (length name) maxname) (setq maxname (length name)))
2132          (if (> (length size) maxsize) (setq maxsize (length size)))
2133          (push (vector name name nil nil time nil nil size)
2134                files))))
2135    (setq files (nreverse files))
2136    (goto-char (point-min))
2137    (let* ((format (format " %%%ds %%s %%s" maxsize))
2138           (sep (format format (make-string maxsize ?-) "-------------------" ""))
2139           (column (length sep)))
2140      (insert (format format "Size " "Date       Time    " " Filename") "\n")
2141      (insert sep (make-string maxname ?-) "\n")
2142      (archive-summarize-files (mapcar (lambda (desc)
2143                                         (let ((text
2144                                                (format format
2145							(aref desc 7)
2146							(aref desc 4)
2147							(aref desc 1))))
2148                                           (vector text
2149                                                   column
2150                                                   (length text))))
2151                                       files))
2152      (insert sep (make-string maxname ?-) "\n")
2153      (apply #'vector files))))
2154
2155(defun archive-7z-extract (archive name)
2156  ;; 7z doesn't provide a `quiet' option to suppress non-essential
2157  ;; stderr messages.  So redirect stderr to a temp file and display it
2158  ;; in the echo area when it contains no message indicating success.
2159  (archive-extract-by-stdout
2160   archive name archive-7z-extract "Everything is Ok"))
2161
2162(defun archive-7z-write-file-member (archive descr)
2163  (archive-*-write-file-member
2164   archive
2165   descr
2166   archive-7z-update))
2167
2168;; -------------------------------------------------------------------------
2169;;; Section `ar' archives.
2170
2171;; TODO: we currently only handle the basic format of ar archives,
2172;; not the GNU nor the BSD extensions.  As it turns out, this is sufficient
2173;; for .deb packages.
2174
2175(autoload 'tar-grind-file-mode "tar-mode")
2176
2177(defconst archive-ar-file-header-re
2178  "\\(.\\{16\\}\\)\\([ 0-9]\\{12\\}\\)\\([ 0-9]\\{6\\}\\)\\([ 0-9]\\{6\\}\\)\\([ 0-7]\\{8\\}\\)\\([ 0-9]\\{10\\}\\)`\n")
2179
2180(defun archive-ar-summarize ()
2181  ;; File is used internally for `archive-rar-exe-summarize'.
2182  (let* ((maxname 10)
2183         (maxtime 16)
2184         (maxuser 5)
2185         (maxgroup 5)
2186         (maxmode 8)
2187         (maxsize 5)
2188         (files ()))
2189    (goto-char (point-min))
2190    (search-forward "!<arch>\n")
2191    (while (looking-at archive-ar-file-header-re)
2192      (let ((name (match-string 1))
2193            extname
2194            (time (string-to-number (match-string 2)))
2195            (user (match-string 3))
2196            (group (match-string 4))
2197            (mode (string-to-number (match-string 5) 8))
2198            (size (string-to-number (match-string 6))))
2199        ;; Move to the beginning of the data.
2200        (goto-char (match-end 0))
2201        (setq time (format-time-string "%Y-%m-%d %H:%M" time))
2202        (setq extname
2203              (cond ((equal name "//              ")
2204                     (propertize ".<ExtNamesTable>." 'face 'italic))
2205                    ((equal name "/               ")
2206                     (propertize ".<LookupTable>." 'face 'italic))
2207                    ((string-match "/? *\\'" name)
2208                     (substring name 0 (match-beginning 0)))))
2209        (setq user (substring user 0 (string-match " +\\'" user)))
2210        (setq group (substring group 0 (string-match " +\\'" group)))
2211        (setq mode (tar-grind-file-mode mode))
2212        ;; Move to the end of the data.
2213        (forward-char size) (if (eq ?\n (char-after)) (forward-char 1))
2214        (setq size (number-to-string size))
2215        (if (> (length name) maxname) (setq maxname (length name)))
2216        (if (> (length time) maxtime) (setq maxtime (length time)))
2217        (if (> (length user) maxuser) (setq maxuser (length user)))
2218        (if (> (length group) maxgroup) (setq maxgroup (length group)))
2219        (if (> (length mode) maxmode) (setq maxmode (length mode)))
2220        (if (> (length size) maxsize) (setq maxsize (length size)))
2221        (push (vector name extname nil mode
2222                      time user group size)
2223              files)))
2224    (setq files (nreverse files))
2225    (goto-char (point-min))
2226    (let* ((format (format "%%%ds %%%ds/%%-%ds  %%%ds %%%ds %%s"
2227                           maxmode maxuser maxgroup maxsize maxtime))
2228           (sep (format format (make-string maxmode ?-)
2229                         (make-string maxuser ?-)
2230                          (make-string maxgroup ?-)
2231                           (make-string maxsize ?-)
2232                           (make-string maxtime ?-) ""))
2233           (column (length sep)))
2234      (insert (format format "  Mode  " "User" "Group" " Size "
2235                      "      Date      " "Filename")
2236              "\n")
2237      (insert sep (make-string maxname ?-) "\n")
2238      (archive-summarize-files (mapcar (lambda (desc)
2239                                         (let ((text
2240                                                (format format
2241                                                         (aref desc 3)
2242                                                         (aref desc 5)
2243                                                         (aref desc 6)
2244                                                         (aref desc 7)
2245                                                         (aref desc 4)
2246                                                         (aref desc 1))))
2247                                           (vector text
2248                                                   column
2249                                                   (length text))))
2250                                       files))
2251      (insert sep (make-string maxname ?-) "\n")
2252      (apply #'vector files))))
2253
2254(defun archive-ar-extract (archive name)
2255  (let ((destbuf (current-buffer))
2256        (archivebuf (find-file-noselect archive))
2257        (from nil) size)
2258    (with-current-buffer archivebuf
2259      (save-restriction
2260        ;; We may be in archive-mode or not, so either with or without
2261        ;; narrowing and with or without a prepended summary.
2262        (save-excursion
2263          (widen)
2264          (search-forward "!<arch>\n")
2265          (while (and (not from) (looking-at archive-ar-file-header-re))
2266            (let ((this (match-string 1)))
2267              (setq size (string-to-number (match-string 6)))
2268              (goto-char (match-end 0))
2269              (if (equal name this)
2270                  (setq from (point))
2271                ;; Move to the end of the data.
2272                (forward-char size) (if (eq ?\n (char-after)) (forward-char 1)))))
2273          (when from
2274            (set-buffer-multibyte nil)
2275            (with-current-buffer destbuf
2276              ;; Do it within the `widen'.
2277              (insert-buffer-substring archivebuf from (+ from size)))
2278            (set-buffer-multibyte 'to)
2279            ;; Inform the caller that the call succeeded.
2280            t))))))
2281
2282;; -------------------------------------------------------------------------
2283;; This line was a mistake; it is kept now for compatibility.
2284;; rms  15 Oct 98
2285(provide 'archive-mode)
2286
2287(provide 'arc-mode)
2288
2289;;; arc-mode.el ends here
2290