ibuffer-unmark-backward: Unmark the region when is active
[emacs.git] / lisp / files.el
blob84f8dc7db947d01c45d97a138c034244678879c1
1 ;;; files.el --- file input and output commands for Emacs -*- lexical-binding:t -*-
3 ;; Copyright (C) 1985-1987, 1992-2016 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Package: emacs
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; Defines most of Emacs's file- and directory-handling functions,
26 ;; including basic file visiting, backup generation, link handling,
27 ;; ITS-id version control, load- and write-hook handling, and the like.
29 ;;; Code:
31 (defvar font-lock-keywords)
33 (defgroup backup nil
34 "Backups of edited data files."
35 :group 'files)
37 (defgroup find-file nil
38 "Finding files."
39 :group 'files)
42 (defcustom delete-auto-save-files t
43 "Non-nil means delete auto-save file when a buffer is saved or killed.
45 Note that the auto-save file will not be deleted if the buffer is killed
46 when it has unsaved changes."
47 :type 'boolean
48 :group 'auto-save)
50 (defcustom directory-abbrev-alist
51 nil
52 "Alist of abbreviations for file directories.
53 A list of elements of the form (FROM . TO), each meaning to replace
54 FROM with TO when it appears in a directory name. This replacement is
55 done when setting up the default directory of a newly visited file.
57 FROM is matched against directory names anchored at the first
58 character, so it should start with a \"\\\\\\=`\", or, if directory
59 names cannot have embedded newlines, with a \"^\".
61 FROM and TO should be equivalent names, which refer to the
62 same directory. Do not use `~' in the TO strings;
63 they should be ordinary absolute directory names.
65 Use this feature when you have directories which you normally refer to
66 via absolute symbolic links. Make TO the name of the link, and FROM
67 the name it is linked to."
68 :type '(repeat (cons :format "%v"
69 :value ("\\`" . "")
70 (regexp :tag "From")
71 (string :tag "To")))
72 :group 'abbrev
73 :group 'find-file)
75 (defcustom make-backup-files t
76 "Non-nil means make a backup of a file the first time it is saved.
77 This can be done by renaming the file or by copying.
79 Renaming means that Emacs renames the existing file so that it is a
80 backup file, then writes the buffer into a new file. Any other names
81 that the old file had will now refer to the backup file. The new file
82 is owned by you and its group is defaulted.
84 Copying means that Emacs copies the existing file into the backup
85 file, then writes the buffer on top of the existing file. Any other
86 names that the old file had will now refer to the new (edited) file.
87 The file's owner and group are unchanged.
89 The choice of renaming or copying is controlled by the variables
90 `backup-by-copying', `backup-by-copying-when-linked',
91 `backup-by-copying-when-mismatch' and
92 `backup-by-copying-when-privileged-mismatch'. See also `backup-inhibited'."
93 :type 'boolean
94 :group 'backup)
96 ;; Do this so that local variables based on the file name
97 ;; are not overridden by the major mode.
98 (defvar backup-inhibited nil
99 "If non-nil, backups will be inhibited.
100 This variable is intended for use by making it local to a buffer,
101 but it is not an automatically buffer-local variable.")
102 (put 'backup-inhibited 'permanent-local t)
104 (defcustom backup-by-copying nil
105 "Non-nil means always use copying to create backup files.
106 See documentation of variable `make-backup-files'."
107 :type 'boolean
108 :group 'backup)
110 (defcustom backup-by-copying-when-linked nil
111 "Non-nil means use copying to create backups for files with multiple names.
112 This causes the alternate names to refer to the latest version as edited.
113 This variable is relevant only if `backup-by-copying' is nil."
114 :type 'boolean
115 :group 'backup)
117 (defcustom backup-by-copying-when-mismatch t
118 "Non-nil means create backups by copying if this preserves owner or group.
119 Renaming may still be used (subject to control of other variables)
120 when it would not result in changing the owner or group of the file;
121 that is, for files which are owned by you and whose group matches
122 the default for a new file created there by you.
123 This variable is relevant only if `backup-by-copying' is nil."
124 :version "24.1"
125 :type 'boolean
126 :group 'backup)
127 (put 'backup-by-copying-when-mismatch 'permanent-local t)
129 (defcustom backup-by-copying-when-privileged-mismatch 200
130 "Non-nil means create backups by copying to preserve a privileged owner.
131 Renaming may still be used (subject to control of other variables)
132 when it would not result in changing the owner of the file or if the owner
133 has a user id greater than the value of this variable. This is useful
134 when low-numbered uid's are used for special system users (such as root)
135 that must maintain ownership of certain files.
136 This variable is relevant only if `backup-by-copying' and
137 `backup-by-copying-when-mismatch' are nil."
138 :type '(choice (const nil) integer)
139 :group 'backup)
141 (defvar backup-enable-predicate 'normal-backup-enable-predicate
142 "Predicate that looks at a file name and decides whether to make backups.
143 Called with an absolute file name as argument, it returns t to enable backup.")
145 (defcustom buffer-offer-save nil
146 "Non-nil in a buffer means always offer to save buffer on exit.
147 Do so even if the buffer is not visiting a file.
148 Automatically local in all buffers."
149 :type 'boolean
150 :group 'backup)
151 (make-variable-buffer-local 'buffer-offer-save)
152 (put 'buffer-offer-save 'permanent-local t)
154 (defcustom find-file-existing-other-name t
155 "Non-nil means find a file under alternative names, in existing buffers.
156 This means if any existing buffer is visiting the file you want
157 under another name, you get the existing buffer instead of a new buffer."
158 :type 'boolean
159 :group 'find-file)
161 (defcustom find-file-visit-truename nil
162 "Non-nil means visiting a file uses its truename as the visited-file name.
163 That is, the buffer visiting the file has the truename as the
164 value of `buffer-file-name'. The truename of a file is found by
165 chasing all links both at the file level and at the levels of the
166 containing directories."
167 :type 'boolean
168 :group 'find-file)
169 (put 'find-file-visit-truename 'safe-local-variable 'booleanp)
171 (defcustom revert-without-query nil
172 "Specify which files should be reverted without query.
173 The value is a list of regular expressions.
174 If the file name matches one of these regular expressions,
175 then `revert-buffer' reverts the file without querying
176 if the file has changed on disk and you have not edited the buffer."
177 :type '(repeat regexp)
178 :group 'find-file)
180 (defvar buffer-file-number nil
181 "The device number and file number of the file visited in the current buffer.
182 The value is a list of the form (FILENUM DEVNUM).
183 This pair of numbers uniquely identifies the file.
184 If the buffer is visiting a new file, the value is nil.")
185 (make-variable-buffer-local 'buffer-file-number)
186 (put 'buffer-file-number 'permanent-local t)
188 (defvar buffer-file-numbers-unique (not (memq system-type '(windows-nt)))
189 "Non-nil means that `buffer-file-number' uniquely identifies files.")
191 (defvar buffer-file-read-only nil
192 "Non-nil if visited file was read-only when visited.")
193 (make-variable-buffer-local 'buffer-file-read-only)
195 (defcustom small-temporary-file-directory
196 (if (eq system-type 'ms-dos) (getenv "TMPDIR"))
197 "The directory for writing small temporary files.
198 If non-nil, this directory is used instead of `temporary-file-directory'
199 by programs that create small temporary files. This is for systems that
200 have fast storage with limited space, such as a RAM disk."
201 :group 'files
202 :initialize 'custom-initialize-delay
203 :type '(choice (const nil) directory))
205 ;; The system null device. (Should reference NULL_DEVICE from C.)
206 (defvar null-device (purecopy "/dev/null") "The system null device.")
208 (declare-function msdos-long-file-names "msdos.c")
209 (declare-function w32-long-file-name "w32proc.c")
210 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
211 (declare-function dired-unmark "dired" (arg &optional interactive))
212 (declare-function dired-do-flagged-delete "dired" (&optional nomessage))
213 (declare-function dos-8+3-filename "dos-fns" (filename))
214 (declare-function dosified-file-name "dos-fns" (file-name))
216 (defvar file-name-invalid-regexp
217 (cond ((and (eq system-type 'ms-dos) (not (msdos-long-file-names)))
218 (purecopy
219 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
220 "[+, ;=|<>\"?*]\\|\\[\\|\\]\\|" ; invalid characters
221 "[\000-\037]\\|" ; control characters
222 "\\(/\\.\\.?[^/]\\)\\|" ; leading dots
223 "\\(/[^/.]+\\.[^/.]*\\.\\)"))) ; more than a single dot
224 ((memq system-type '(ms-dos windows-nt cygwin))
225 (purecopy
226 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
227 "[|<>\"?*\000-\037]"))) ; invalid characters
228 (t (purecopy "[\000]")))
229 "Regexp recognizing file names which aren't allowed by the filesystem.")
231 (defcustom file-precious-flag nil
232 "Non-nil means protect against I/O errors while saving files.
233 Some modes set this non-nil in particular buffers.
235 This feature works by writing the new contents into a temporary file
236 and then renaming the temporary file to replace the original.
237 In this way, any I/O error in writing leaves the original untouched,
238 and there is never any instant where the file is nonexistent.
240 Note that this feature forces backups to be made by copying.
241 Yet, at the same time, saving a precious file
242 breaks any hard links between it and other files.
244 This feature is advisory: for example, if the directory in which the
245 file is being saved is not writable, Emacs may ignore a non-nil value
246 of `file-precious-flag' and write directly into the file.
248 See also: `break-hardlink-on-save'."
249 :type 'boolean
250 :group 'backup)
252 (defcustom break-hardlink-on-save nil
253 "Whether to allow breaking hardlinks when saving files.
254 If non-nil, then when saving a file that exists under several
255 names \(i.e., has multiple hardlinks), break the hardlink
256 associated with `buffer-file-name' and write to a new file, so
257 that the other instances of the file are not affected by the
258 save.
260 If `buffer-file-name' refers to a symlink, do not break the symlink.
262 Unlike `file-precious-flag', `break-hardlink-on-save' is not advisory.
263 For example, if the directory in which a file is being saved is not
264 itself writable, then error instead of saving in some
265 hardlink-nonbreaking way.
267 See also `backup-by-copying' and `backup-by-copying-when-linked'."
268 :type 'boolean
269 :group 'files
270 :version "23.1")
272 (defcustom version-control nil
273 "Control use of version numbers for backup files.
274 When t, make numeric backup versions unconditionally.
275 When nil, make them for files that have some already.
276 The value `never' means do not make them."
277 :type '(choice (const :tag "Never" never)
278 (const :tag "If existing" nil)
279 (other :tag "Always" t))
280 :group 'backup)
281 (put 'version-control 'safe-local-variable
282 (lambda (x) (or (booleanp x) (equal x 'never))))
284 (defcustom dired-kept-versions 2
285 "When cleaning directory, number of versions to keep."
286 :type 'integer
287 :group 'backup
288 :group 'dired)
290 (defcustom delete-old-versions nil
291 "If t, delete excess backup versions silently.
292 If nil, ask confirmation. Any other value prevents any trimming."
293 :type '(choice (const :tag "Delete" t)
294 (const :tag "Ask" nil)
295 (other :tag "Leave" other))
296 :group 'backup)
298 (defcustom kept-old-versions 2
299 "Number of oldest versions to keep when a new numbered backup is made."
300 :type 'integer
301 :group 'backup)
302 (put 'kept-old-versions 'safe-local-variable 'integerp)
304 (defcustom kept-new-versions 2
305 "Number of newest versions to keep when a new numbered backup is made.
306 Includes the new backup. Must be > 0"
307 :type 'integer
308 :group 'backup)
309 (put 'kept-new-versions 'safe-local-variable 'integerp)
311 (defcustom require-final-newline nil
312 "Whether to add a newline automatically at the end of the file.
314 A value of t means do this only when the file is about to be saved.
315 A value of `visit' means do this right after the file is visited.
316 A value of `visit-save' means do it at both of those times.
317 Any other non-nil value means ask user whether to add a newline, when saving.
318 A value of nil means don't add newlines.
320 Certain major modes set this locally to the value obtained
321 from `mode-require-final-newline'."
322 :safe #'symbolp
323 :type '(choice (const :tag "When visiting" visit)
324 (const :tag "When saving" t)
325 (const :tag "When visiting or saving" visit-save)
326 (const :tag "Don't add newlines" nil)
327 (other :tag "Ask each time" ask))
328 :group 'editing-basics)
330 (defcustom mode-require-final-newline t
331 "Whether to add a newline at end of file, in certain major modes.
332 Those modes set `require-final-newline' to this value when you enable them.
333 They do so because they are often used for files that are supposed
334 to end in newlines, and the question is how to arrange that.
336 A value of t means do this only when the file is about to be saved.
337 A value of `visit' means do this right after the file is visited.
338 A value of `visit-save' means do it at both of those times.
339 Any other non-nil value means ask user whether to add a newline, when saving.
341 A value of nil means do not add newlines. That is a risky choice in this
342 variable since this value is used for modes for files that ought to have
343 final newlines. So if you set this to nil, you must explicitly check and
344 add a final newline, whenever you save a file that really needs one."
345 :type '(choice (const :tag "When visiting" visit)
346 (const :tag "When saving" t)
347 (const :tag "When visiting or saving" visit-save)
348 (const :tag "Don't add newlines" nil)
349 (other :tag "Ask each time" ask))
350 :group 'editing-basics
351 :version "22.1")
353 (defcustom auto-save-default t
354 "Non-nil says by default do auto-saving of every file-visiting buffer."
355 :type 'boolean
356 :group 'auto-save)
358 (defcustom auto-save-file-name-transforms
359 `(("\\`/[^/]*:\\([^/]*/\\)*\\([^/]*\\)\\'"
360 ;; Don't put "\\2" inside expand-file-name, since it will be
361 ;; transformed to "/2" on DOS/Windows.
362 ,(concat temporary-file-directory "\\2") t))
363 "Transforms to apply to buffer file name before making auto-save file name.
364 Each transform is a list (REGEXP REPLACEMENT UNIQUIFY):
365 REGEXP is a regular expression to match against the file name.
366 If it matches, `replace-match' is used to replace the
367 matching part with REPLACEMENT.
368 If the optional element UNIQUIFY is non-nil, the auto-save file name is
369 constructed by taking the directory part of the replaced file-name,
370 concatenated with the buffer file name with all directory separators
371 changed to `!' to prevent clashes. This will not work
372 correctly if your filesystem truncates the resulting name.
374 All the transforms in the list are tried, in the order they are listed.
375 When one transform applies, its result is final;
376 no further transforms are tried.
378 The default value is set up to put the auto-save file into the
379 temporary directory (see the variable `temporary-file-directory') for
380 editing a remote file.
382 On MS-DOS filesystems without long names this variable is always
383 ignored."
384 :group 'auto-save
385 :type '(repeat (list (string :tag "Regexp") (string :tag "Replacement")
386 (boolean :tag "Uniquify")))
387 :initialize 'custom-initialize-delay
388 :version "21.1")
390 (defcustom save-abbrevs t
391 "Non-nil means save word abbrevs too when files are saved.
392 If `silently', don't ask the user before saving."
393 :type '(choice (const t) (const nil) (const silently))
394 :group 'abbrev)
396 (defcustom find-file-run-dired t
397 "Non-nil means allow `find-file' to visit directories.
398 To visit the directory, `find-file' runs `find-directory-functions'."
399 :type 'boolean
400 :group 'find-file)
402 (defcustom find-directory-functions '(cvs-dired-noselect dired-noselect)
403 "List of functions to try in sequence to visit a directory.
404 Each function is called with the directory name as the sole argument
405 and should return either a buffer or nil."
406 :type '(hook :options (cvs-dired-noselect dired-noselect))
407 :group 'find-file)
409 ;; FIXME: also add a hook for `(thing-at-point 'filename)'
410 (defcustom file-name-at-point-functions '(ffap-guess-file-name-at-point)
411 "List of functions to try in sequence to get a file name at point.
412 Each function should return either nil or a file name found at the
413 location of point in the current buffer."
414 :type '(hook :options (ffap-guess-file-name-at-point))
415 :group 'find-file)
417 ;;;It is not useful to make this a local variable.
418 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
419 (define-obsolete-variable-alias 'find-file-not-found-hooks
420 'find-file-not-found-functions "22.1")
421 (defvar find-file-not-found-functions nil
422 "List of functions to be called for `find-file' on nonexistent file.
423 These functions are called as soon as the error is detected.
424 Variable `buffer-file-name' is already set up.
425 The functions are called in the order given until one of them returns non-nil.")
427 ;;;It is not useful to make this a local variable.
428 ;;;(put 'find-file-hooks 'permanent-local t)
429 (define-obsolete-variable-alias 'find-file-hooks 'find-file-hook "22.1")
430 (defcustom find-file-hook nil
431 "List of functions to be called after a buffer is loaded from a file.
432 The buffer's local variables (if any) will have been processed before the
433 functions are called."
434 :group 'find-file
435 :type 'hook
436 :options '(auto-insert)
437 :version "22.1")
439 (define-obsolete-variable-alias 'write-file-hooks 'write-file-functions "22.1")
440 (defvar write-file-functions nil
441 "List of functions to be called before writing out a buffer to a file.
442 If one of them returns non-nil, the file is considered already written
443 and the rest are not called.
444 These hooks are considered to pertain to the visited file.
445 So any buffer-local binding of this variable is discarded if you change
446 the visited file name with \\[set-visited-file-name], but not when you
447 change the major mode.
449 This hook is not run if any of the functions in
450 `write-contents-functions' returns non-nil. Both hooks pertain
451 to how to save a buffer to file, for instance, choosing a suitable
452 coding system and setting mode bits. (See Info
453 node `(elisp)Saving Buffers'.) To perform various checks or
454 updates before the buffer is saved, use `before-save-hook'.")
455 (put 'write-file-functions 'permanent-local t)
457 (defvar local-write-file-hooks nil)
458 (make-variable-buffer-local 'local-write-file-hooks)
459 (put 'local-write-file-hooks 'permanent-local t)
460 (make-obsolete-variable 'local-write-file-hooks 'write-file-functions "22.1")
462 (define-obsolete-variable-alias 'write-contents-hooks
463 'write-contents-functions "22.1")
464 (defvar write-contents-functions nil
465 "List of functions to be called before writing out a buffer to a file.
466 If one of them returns non-nil, the file is considered already written
467 and the rest are not called and neither are the functions in
468 `write-file-functions'.
470 This variable is meant to be used for hooks that pertain to the
471 buffer's contents, not to the particular visited file; thus,
472 `set-visited-file-name' does not clear this variable; but changing the
473 major mode does clear it.
475 For hooks that _do_ pertain to the particular visited file, use
476 `write-file-functions'. Both this variable and
477 `write-file-functions' relate to how a buffer is saved to file.
478 To perform various checks or updates before the buffer is saved,
479 use `before-save-hook'.")
480 (make-variable-buffer-local 'write-contents-functions)
482 (defcustom enable-local-variables t
483 "Control use of local variables in files you visit.
484 The value can be t, nil, :safe, :all, or something else.
486 A value of t means file local variables specifications are obeyed
487 if all the specified variable values are safe; if any values are
488 not safe, Emacs queries you, once, whether to set them all.
489 \(When you say yes to certain values, they are remembered as safe.)
491 :safe means set the safe variables, and ignore the rest.
492 :all means set all variables, whether safe or not.
493 (Don't set it permanently to :all.)
494 A value of nil means always ignore the file local variables.
496 Any other value means always query you once whether to set them all.
497 \(When you say yes to certain values, they are remembered as safe, but
498 this has no effect when `enable-local-variables' is \"something else\".)
500 This variable also controls use of major modes specified in
501 a -*- line.
503 The command \\[normal-mode], when used interactively,
504 always obeys file local variable specifications and the -*- line,
505 and ignores this variable."
506 :risky t
507 :type '(choice (const :tag "Query Unsafe" t)
508 (const :tag "Safe Only" :safe)
509 (const :tag "Do all" :all)
510 (const :tag "Ignore" nil)
511 (other :tag "Query" other))
512 :group 'find-file)
514 (defvar enable-dir-local-variables t
515 "Non-nil means enable use of directory-local variables.
516 Some modes may wish to set this to nil to prevent directory-local
517 settings being applied, but still respect file-local ones.")
519 ;; This is an odd variable IMO.
520 ;; You might wonder why it is needed, when we could just do:
521 ;; (set (make-local-variable 'enable-local-variables) nil)
522 ;; These two are not precisely the same.
523 ;; Setting this variable does not cause -*- mode settings to be
524 ;; ignored, whereas setting enable-local-variables does.
525 ;; Only three places in Emacs use this variable: tar and arc modes,
526 ;; and rmail. The first two don't need it. They already use
527 ;; inhibit-local-variables-regexps, which is probably enough, and
528 ;; could also just set enable-local-variables locally to nil.
529 ;; Them setting it has the side-effect that dir-locals cannot apply to
530 ;; eg tar files (?). FIXME Is this appropriate?
531 ;; AFAICS, rmail is the only thing that needs this, and the only
532 ;; reason it uses it is for BABYL files (which are obsolete).
533 ;; These contain "-*- rmail -*-" in the first line, which rmail wants
534 ;; to respect, so that find-file on a BABYL file will switch to
535 ;; rmail-mode automatically (this is nice, but hardly essential,
536 ;; since most people are used to explicitly running a command to
537 ;; access their mail; M-x gnus etc). Rmail files may happen to
538 ;; contain Local Variables sections in messages, which Rmail wants to
539 ;; ignore. So AFAICS the only reason this variable exists is for a
540 ;; minor convenience feature for handling of an obsolete Rmail file format.
541 (defvar local-enable-local-variables t
542 "Like `enable-local-variables' but meant for buffer-local bindings.
543 The meaningful values are nil and non-nil. The default is non-nil.
544 If a major mode sets this to nil, buffer-locally, then any local
545 variables list in a file visited in that mode will be ignored.
547 This variable does not affect the use of major modes specified
548 in a -*- line.")
550 (defcustom enable-local-eval 'maybe
551 "Control processing of the \"variable\" `eval' in a file's local variables.
552 The value can be t, nil or something else.
553 A value of t means obey `eval' variables.
554 A value of nil means ignore them; anything else means query."
555 :risky t
556 :type '(choice (const :tag "Obey" t)
557 (const :tag "Ignore" nil)
558 (other :tag "Query" other))
559 :group 'find-file)
561 (defcustom view-read-only nil
562 "Non-nil means buffers visiting files read-only do so in view mode.
563 In fact, this means that all read-only buffers normally have
564 View mode enabled, including buffers that are read-only because
565 you visit a file you cannot alter, and buffers you make read-only
566 using \\[read-only-mode]."
567 :type 'boolean
568 :group 'view)
570 (defvar file-name-history nil
571 "History list of file names entered in the minibuffer.
573 Maximum length of the history list is determined by the value
574 of `history-length', which see.")
576 (defvar save-silently nil
577 "If non-nil, avoid messages when saving files.
578 Error-related messages will still be printed, but all other
579 messages will not.")
582 (put 'ange-ftp-completion-hook-function 'safe-magic t)
583 (defun ange-ftp-completion-hook-function (op &rest args)
584 "Provides support for ange-ftp host name completion.
585 Runs the usual ange-ftp hook, but only for completion operations."
586 ;; Having this here avoids the need to load ange-ftp when it's not
587 ;; really in use.
588 (if (memq op '(file-name-completion file-name-all-completions))
589 (apply 'ange-ftp-hook-function op args)
590 (let ((inhibit-file-name-handlers
591 (cons 'ange-ftp-completion-hook-function
592 (and (eq inhibit-file-name-operation op)
593 inhibit-file-name-handlers)))
594 (inhibit-file-name-operation op))
595 (apply op args))))
597 (declare-function dos-convert-standard-filename "dos-fns.el" (filename))
598 (declare-function w32-convert-standard-filename "w32-fns.el" (filename))
600 (defun convert-standard-filename (filename)
601 "Convert a standard file's name to something suitable for the OS.
602 This means to guarantee valid names and perhaps to canonicalize
603 certain patterns.
605 FILENAME should be an absolute file name since the conversion rules
606 sometimes vary depending on the position in the file name. E.g. c:/foo
607 is a valid DOS file name, but c:/bar/c:/foo is not.
609 This function's standard definition is trivial; it just returns
610 the argument. However, on Windows and DOS, replace invalid
611 characters. On DOS, make sure to obey the 8.3 limitations.
612 In the native Windows build, turn Cygwin names into native names.
614 See Info node `(elisp)Standard File Names' for more details."
615 (cond
616 ((eq system-type 'cygwin)
617 (let ((name (copy-sequence filename))
618 (start 0))
619 ;; Replace invalid filename characters with !
620 (while (string-match "[?*:<>|\"\000-\037]" name start)
621 (aset name (match-beginning 0) ?!)
622 (setq start (match-end 0)))
623 name))
624 ((eq system-type 'windows-nt)
625 (w32-convert-standard-filename filename))
626 ((eq system-type 'ms-dos)
627 (dos-convert-standard-filename filename))
628 (t filename)))
630 (defun read-directory-name (prompt &optional dir default-dirname mustmatch initial)
631 "Read directory name, prompting with PROMPT and completing in directory DIR.
632 Value is not expanded---you must call `expand-file-name' yourself.
633 Default name to DEFAULT-DIRNAME if user exits with the same
634 non-empty string that was inserted by this function.
635 (If DEFAULT-DIRNAME is omitted, DIR combined with INITIAL is used,
636 or just DIR if INITIAL is nil.)
637 If the user exits with an empty minibuffer, this function returns
638 an empty string. (This can only happen if the user erased the
639 pre-inserted contents or if `insert-default-directory' is nil.)
640 Fourth arg MUSTMATCH non-nil means require existing directory's name.
641 Non-nil and non-t means also require confirmation after completion.
642 Fifth arg INITIAL specifies text to start with.
643 DIR should be an absolute directory name. It defaults to
644 the value of `default-directory'."
645 (unless dir
646 (setq dir default-directory))
647 (read-file-name prompt dir (or default-dirname
648 (if initial (expand-file-name initial dir)
649 dir))
650 mustmatch initial
651 'file-directory-p))
654 (defun pwd (&optional insert)
655 "Show the current default directory.
656 With prefix argument INSERT, insert the current default directory
657 at point instead."
658 (interactive "P")
659 (if insert
660 (insert default-directory)
661 (message "Directory %s" default-directory)))
663 (defvar cd-path nil
664 "Value of the CDPATH environment variable, as a list.
665 Not actually set up until the first time you use it.")
667 (defun parse-colon-path (search-path)
668 "Explode a search path into a list of directory names.
669 Directories are separated by `path-separator' (which is colon in
670 GNU and Unix systems). Substitute environment variables into the
671 resulting list of directory names. For an empty path element (i.e.,
672 a leading or trailing separator, or two adjacent separators), return
673 nil (meaning `default-directory') as the associated list element."
674 (when (stringp search-path)
675 (mapcar (lambda (f)
676 (if (equal "" f) nil
677 (substitute-in-file-name (file-name-as-directory f))))
678 (split-string search-path path-separator))))
680 (defun cd-absolute (dir)
681 "Change current directory to given absolute file name DIR."
682 ;; Put the name into directory syntax now,
683 ;; because otherwise expand-file-name may give some bad results.
684 (setq dir (file-name-as-directory dir))
685 ;; We used to additionally call abbreviate-file-name here, for an
686 ;; unknown reason. Problem is that most buffers are setup
687 ;; without going through cd-absolute and don't call
688 ;; abbreviate-file-name on their default-directory, so the few that
689 ;; do end up using a superficially different directory.
690 (setq dir (expand-file-name dir))
691 (if (not (file-directory-p dir))
692 (if (file-exists-p dir)
693 (error "%s is not a directory" dir)
694 (error "%s: no such directory" dir))
695 (unless (file-accessible-directory-p dir)
696 (error "Cannot cd to %s: Permission denied" dir))
697 (setq default-directory dir)
698 (setq list-buffers-directory dir)))
700 (defun cd (dir)
701 "Make DIR become the current buffer's default directory.
702 If your environment includes a `CDPATH' variable, try each one of
703 that list of directories (separated by occurrences of
704 `path-separator') when resolving a relative directory name.
705 The path separator is colon in GNU and GNU-like systems."
706 (interactive
707 (list
708 ;; FIXME: There's a subtle bug in the completion below. Seems linked
709 ;; to a fundamental difficulty of implementing `predicate' correctly.
710 ;; The manifestation is that TAB may list non-directories in the case where
711 ;; those files also correspond to valid directories (if your cd-path is (A/
712 ;; B/) and you have A/a a file and B/a a directory, then both `a' and `a/'
713 ;; will be listed as valid completions).
714 ;; This is because `a' (listed because of A/a) is indeed a valid choice
715 ;; (which will lead to the use of B/a).
716 (minibuffer-with-setup-hook
717 (lambda ()
718 (setq minibuffer-completion-table
719 (apply-partially #'locate-file-completion-table
720 cd-path nil))
721 (setq minibuffer-completion-predicate
722 (lambda (dir)
723 (locate-file dir cd-path nil
724 (lambda (f) (and (file-directory-p f) 'dir-ok))))))
725 (unless cd-path
726 (setq cd-path (or (parse-colon-path (getenv "CDPATH"))
727 (list "./"))))
728 (read-directory-name "Change default directory: "
729 default-directory default-directory
730 t))))
731 (unless cd-path
732 (setq cd-path (or (parse-colon-path (getenv "CDPATH"))
733 (list "./"))))
734 (cd-absolute
735 (or (locate-file dir cd-path nil
736 (lambda (f) (and (file-directory-p f) 'dir-ok)))
737 (error "No such directory found via CDPATH environment variable"))))
739 (defsubst directory-name-p (name)
740 "Return non-nil if NAME ends with a directory separator character."
741 (let ((len (length name))
742 (lastc ?.))
743 (if (> len 0)
744 (setq lastc (aref name (1- len))))
745 (or (= lastc ?/)
746 (and (memq system-type '(windows-nt ms-dos))
747 (= lastc ?\\)))))
749 (defun directory-files-recursively (dir regexp &optional include-directories)
750 "Return list of all files under DIR that have file names matching REGEXP.
751 This function works recursively. Files are returned in \"depth first\"
752 order, and files from each directory are sorted in alphabetical order.
753 Each file name appears in the returned list in its absolute form.
754 Optional argument INCLUDE-DIRECTORIES non-nil means also include in the
755 output directories whose names match REGEXP."
756 (let ((result nil)
757 (files nil)
758 ;; When DIR is "/", remote file names like "/method:" could
759 ;; also be offered. We shall suppress them.
760 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
761 (dolist (file (sort (file-name-all-completions "" dir)
762 'string<))
763 (unless (member file '("./" "../"))
764 (if (directory-name-p file)
765 (let* ((leaf (substring file 0 (1- (length file))))
766 (full-file (expand-file-name leaf dir)))
767 ;; Don't follow symlinks to other directories.
768 (unless (file-symlink-p full-file)
769 (setq result
770 (nconc result (directory-files-recursively
771 full-file regexp include-directories))))
772 (when (and include-directories
773 (string-match regexp leaf))
774 (setq result (nconc result (list full-file)))))
775 (when (string-match regexp file)
776 (push (expand-file-name file dir) files)))))
777 (nconc result (nreverse files))))
779 (defvar module-file-suffix)
781 (defun load-file (file)
782 "Load the Lisp file named FILE."
783 ;; This is a case where .elc and .so/.dll make a lot of sense.
784 (interactive (list (let ((completion-ignored-extensions
785 (remove module-file-suffix
786 (remove ".elc"
787 completion-ignored-extensions))))
788 (read-file-name "Load file: " nil nil 'lambda))))
789 (load (expand-file-name file) nil nil t))
791 (defun locate-file (filename path &optional suffixes predicate)
792 "Search for FILENAME through PATH.
793 If found, return the absolute file name of FILENAME; otherwise
794 return nil.
795 PATH should be a list of directories to look in, like the lists in
796 `exec-path' or `load-path'.
797 If SUFFIXES is non-nil, it should be a list of suffixes to append to
798 file name when searching. If SUFFIXES is nil, it is equivalent to (\"\").
799 Use (\"/\") to disable PATH search, but still try the suffixes in SUFFIXES.
800 If non-nil, PREDICATE is used instead of `file-readable-p'.
802 This function will normally skip directories, so if you want it to find
803 directories, make sure the PREDICATE function returns `dir-ok' for them.
805 PREDICATE can also be an integer to pass to the `access' system call,
806 in which case file-name handlers are ignored. This usage is deprecated.
807 For compatibility, PREDICATE can also be one of the symbols
808 `executable', `readable', `writable', or `exists', or a list of
809 one or more of those symbols."
810 (if (and predicate (symbolp predicate) (not (functionp predicate)))
811 (setq predicate (list predicate)))
812 (when (and (consp predicate) (not (functionp predicate)))
813 (setq predicate
814 (logior (if (memq 'executable predicate) 1 0)
815 (if (memq 'writable predicate) 2 0)
816 (if (memq 'readable predicate) 4 0))))
817 (locate-file-internal filename path suffixes predicate))
819 (defun locate-file-completion-table (dirs suffixes string pred action)
820 "Do completion for file names passed to `locate-file'."
821 (cond
822 ((file-name-absolute-p string)
823 ;; FIXME: maybe we should use completion-file-name-table instead,
824 ;; tho at least for `load', the arg is passed through
825 ;; substitute-in-file-name for historical reasons.
826 (read-file-name-internal string pred action))
827 ((eq (car-safe action) 'boundaries)
828 (let ((suffix (cdr action)))
829 `(boundaries
830 ,(length (file-name-directory string))
831 ,@(let ((x (file-name-directory suffix)))
832 (if x (1- (length x)) (length suffix))))))
834 (let ((names '())
835 ;; If we have files like "foo.el" and "foo.elc", we could load one of
836 ;; them with "foo.el", "foo.elc", or "foo", where just "foo" is the
837 ;; preferred way. So if we list all 3, that gives a lot of redundant
838 ;; entries for the poor soul looking just for "foo". OTOH, sometimes
839 ;; the user does want to pay attention to the extension. We try to
840 ;; diffuse this tension by stripping the suffix, except when the
841 ;; result is a single element (i.e. usually we only list "foo" unless
842 ;; it's the only remaining element in the list, in which case we do
843 ;; list "foo", "foo.elc" and "foo.el").
844 (fullnames '())
845 (suffix (concat (regexp-opt suffixes t) "\\'"))
846 (string-dir (file-name-directory string))
847 (string-file (file-name-nondirectory string)))
848 (dolist (dir dirs)
849 (unless dir
850 (setq dir default-directory))
851 (if string-dir (setq dir (expand-file-name string-dir dir)))
852 (when (file-directory-p dir)
853 (dolist (file (file-name-all-completions
854 string-file dir))
855 (if (not (string-match suffix file))
856 (push file names)
857 (push file fullnames)
858 (push (substring file 0 (match-beginning 0)) names)))))
859 ;; Switching from names to names+fullnames creates a non-monotonicity
860 ;; which can cause problems with things like partial-completion.
861 ;; To minimize the problem, filter out completion-regexp-list, so that
862 ;; M-x load-library RET t/x.e TAB finds some files. Also remove elements
863 ;; from `names' which only matched `string' when they still had
864 ;; their suffix.
865 (setq names (all-completions string names))
866 ;; Remove duplicates of the first element, so that we can easily check
867 ;; if `names' really only contains a single element.
868 (when (cdr names) (setcdr names (delete (car names) (cdr names))))
869 (unless (cdr names)
870 ;; There's no more than one matching non-suffixed element, so expand
871 ;; the list by adding the suffixed elements as well.
872 (setq names (nconc names fullnames)))
873 (completion-table-with-context
874 string-dir names string-file pred action)))))
876 (defun locate-file-completion (string path-and-suffixes action)
877 "Do completion for file names passed to `locate-file'.
878 PATH-AND-SUFFIXES is a pair of lists, (DIRECTORIES . SUFFIXES)."
879 (declare (obsolete locate-file-completion-table "23.1"))
880 (locate-file-completion-table (car path-and-suffixes)
881 (cdr path-and-suffixes)
882 string nil action))
884 (defvar locate-dominating-stop-dir-regexp
885 (purecopy "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'")
886 "Regexp of directory names which stop the search in `locate-dominating-file'.
887 Any directory whose name matches this regexp will be treated like
888 a kind of root directory by `locate-dominating-file' which will stop its search
889 when it bumps into it.
890 The default regexp prevents fruitless and time-consuming attempts to find
891 special files in directories in which filenames are interpreted as hostnames,
892 or mount points potentially requiring authentication as a different user.")
894 ;; (defun locate-dominating-files (file regexp)
895 ;; "Look up the directory hierarchy from FILE for a file matching REGEXP.
896 ;; Stop at the first parent where a matching file is found and return the list
897 ;; of files that that match in this directory."
898 ;; (catch 'found
899 ;; ;; `user' is not initialized yet because `file' may not exist, so we may
900 ;; ;; have to walk up part of the hierarchy before we find the "initial UID".
901 ;; (let ((user nil)
902 ;; ;; Abbreviate, so as to stop when we cross ~/.
903 ;; (dir (abbreviate-file-name (file-name-as-directory file)))
904 ;; files)
905 ;; (while (and dir
906 ;; ;; As a heuristic, we stop looking up the hierarchy of
907 ;; ;; directories as soon as we find a directory belonging to
908 ;; ;; another user. This should save us from looking in
909 ;; ;; things like /net and /afs. This assumes that all the
910 ;; ;; files inside a project belong to the same user.
911 ;; (let ((prev-user user))
912 ;; (setq user (nth 2 (file-attributes dir)))
913 ;; (or (null prev-user) (equal user prev-user))))
914 ;; (if (setq files (condition-case nil
915 ;; (directory-files dir 'full regexp 'nosort)
916 ;; (error nil)))
917 ;; (throw 'found files)
918 ;; (if (equal dir
919 ;; (setq dir (file-name-directory
920 ;; (directory-file-name dir))))
921 ;; (setq dir nil))))
922 ;; nil)))
924 (defun locate-dominating-file (file name)
925 "Look up the directory hierarchy from FILE for a directory containing NAME.
926 Stop at the first parent directory containing a file NAME,
927 and return the directory. Return nil if not found.
928 Instead of a string, NAME can also be a predicate taking one argument
929 \(a directory) and returning a non-nil value if that directory is the one for
930 which we're looking."
931 ;; We used to use the above locate-dominating-files code, but the
932 ;; directory-files call is very costly, so we're much better off doing
933 ;; multiple calls using the code in here.
935 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
936 ;; `name' in /home or in /.
937 (setq file (abbreviate-file-name (expand-file-name file)))
938 (let ((root nil)
939 ;; `user' is not initialized outside the loop because
940 ;; `file' may not exist, so we may have to walk up part of the
941 ;; hierarchy before we find the "initial UID". Note: currently unused
942 ;; (user nil)
943 try)
944 (while (not (or root
945 (null file)
946 ;; FIXME: Disabled this heuristic because it is sometimes
947 ;; inappropriate.
948 ;; As a heuristic, we stop looking up the hierarchy of
949 ;; directories as soon as we find a directory belonging
950 ;; to another user. This should save us from looking in
951 ;; things like /net and /afs. This assumes that all the
952 ;; files inside a project belong to the same user.
953 ;; (let ((prev-user user))
954 ;; (setq user (nth 2 (file-attributes file)))
955 ;; (and prev-user (not (equal user prev-user))))
956 (string-match locate-dominating-stop-dir-regexp file)))
957 (setq try (if (stringp name)
958 (file-exists-p (expand-file-name name file))
959 (funcall name file)))
960 (cond (try (setq root file))
961 ((equal file (setq file (file-name-directory
962 (directory-file-name file))))
963 (setq file nil))))
964 (if root (file-name-as-directory root))))
966 (defcustom user-emacs-directory-warning t
967 "Non-nil means warn if cannot access `user-emacs-directory'.
968 Set this to nil at your own risk..."
969 :type 'boolean
970 :group 'initialization
971 :version "24.4")
973 (defun locate-user-emacs-file (new-name &optional old-name)
974 "Return an absolute per-user Emacs-specific file name.
975 If NEW-NAME exists in `user-emacs-directory', return it.
976 Else if OLD-NAME is non-nil and ~/OLD-NAME exists, return ~/OLD-NAME.
977 Else return NEW-NAME in `user-emacs-directory', creating the
978 directory if it does not exist."
979 (convert-standard-filename
980 (let* ((home (concat "~" (or init-file-user "")))
981 (at-home (and old-name (expand-file-name old-name home)))
982 (bestname (abbreviate-file-name
983 (expand-file-name new-name user-emacs-directory))))
984 (if (and at-home (not (file-readable-p bestname))
985 (file-readable-p at-home))
986 at-home
987 ;; Make sure `user-emacs-directory' exists,
988 ;; unless we're in batch mode or dumping Emacs.
989 (or noninteractive
990 purify-flag
991 (let (errtype)
992 (if (file-directory-p user-emacs-directory)
993 (or (file-accessible-directory-p user-emacs-directory)
994 (setq errtype "access"))
995 (with-file-modes ?\700
996 (condition-case nil
997 (make-directory user-emacs-directory)
998 (error (setq errtype "create")))))
999 (when (and errtype
1000 user-emacs-directory-warning
1001 (not (get 'user-emacs-directory-warning 'this-session)))
1002 ;; Only warn once per Emacs session.
1003 (put 'user-emacs-directory-warning 'this-session t)
1004 (display-warning 'initialization
1005 (format "\
1006 Unable to %s `user-emacs-directory' (%s).
1007 Any data that would normally be written there may be lost!
1008 If you never want to see this message again,
1009 customize the variable `user-emacs-directory-warning'."
1010 errtype user-emacs-directory)))))
1011 bestname))))
1014 (defun executable-find (command)
1015 "Search for COMMAND in `exec-path' and return the absolute file name.
1016 Return nil if COMMAND is not found anywhere in `exec-path'."
1017 ;; Use 1 rather than file-executable-p to better match the behavior of
1018 ;; call-process.
1019 (locate-file command exec-path exec-suffixes 1))
1021 (defun load-library (library)
1022 "Load the Emacs Lisp library named LIBRARY.
1023 LIBRARY should be a string.
1024 This is an interface to the function `load'. LIBRARY is searched
1025 for in `load-path', both with and without `load-suffixes' (as
1026 well as `load-file-rep-suffixes').
1028 See Info node `(emacs)Lisp Libraries' for more details.
1029 See `load-file' for a different interface to `load'."
1030 (interactive
1031 (let (completion-ignored-extensions)
1032 (list (completing-read "Load library: "
1033 (apply-partially 'locate-file-completion-table
1034 load-path
1035 (get-load-suffixes))))))
1036 (load library))
1038 (defun file-remote-p (file &optional identification connected)
1039 "Test whether FILE specifies a location on a remote system.
1040 A file is considered remote if accessing it is likely to
1041 be slower or less reliable than accessing local files.
1043 `file-remote-p' never opens a new remote connection. It can
1044 only reuse a connection that is already open.
1046 Return nil or a string identifying the remote connection
1047 \(ideally a prefix of FILE). Return nil if FILE is a relative
1048 file name.
1050 When IDENTIFICATION is nil, the returned string is a complete
1051 remote identifier: with components method, user, and host. The
1052 components are those present in FILE, with defaults filled in for
1053 any that are missing.
1055 IDENTIFICATION can specify which part of the identification to
1056 return. IDENTIFICATION can be the symbol `method', `user',
1057 `host', or `localname'. Any other value is handled like nil and
1058 means to return the complete identification. The string returned
1059 for IDENTIFICATION `localname' can differ depending on whether
1060 there is an existing connection.
1062 If CONNECTED is non-nil, return an identification only if FILE is
1063 located on a remote system and a connection is established to
1064 that remote system.
1066 Tip: You can use this expansion of remote identifier components
1067 to derive a new remote file name from an existing one. For
1068 example, if FILE is \"/sudo::/path/to/file\" then
1070 (concat (file-remote-p FILE) \"/bin/sh\")
1072 returns a remote file name for file \"/bin/sh\" that has the
1073 same remote identifier as FILE but expanded; a name such as
1074 \"/sudo:root@myhost:/bin/sh\"."
1075 (let ((handler (find-file-name-handler file 'file-remote-p)))
1076 (if handler
1077 (funcall handler 'file-remote-p file identification connected)
1078 nil)))
1080 ;; Probably this entire variable should be obsolete now, in favor of
1081 ;; something Tramp-related (?). It is not used in many places.
1082 ;; It's not clear what the best file for this to be in is, but given
1083 ;; it uses custom-initialize-delay, it is easier if it is preloaded
1084 ;; rather than autoloaded.
1085 (defcustom remote-shell-program
1086 ;; This used to try various hard-coded places for remsh, rsh, and
1087 ;; rcmd, trying to guess based on location whether "rsh" was
1088 ;; "restricted shell" or "remote shell", but I don't see the point
1089 ;; in this day and age. Almost everyone will use ssh, and have
1090 ;; whatever command they want to use in PATH.
1091 (purecopy
1092 (let ((list '("ssh" "remsh" "rcmd" "rsh")))
1093 (while (and list
1094 (not (executable-find (car list)))
1095 (setq list (cdr list))))
1096 (or (car list) "ssh")))
1097 "Program to use to execute commands on a remote host (e.g. ssh or rsh)."
1098 :version "24.3" ; ssh rather than rsh, etc
1099 :initialize 'custom-initialize-delay
1100 :group 'environment
1101 :type 'file)
1103 (defcustom remote-file-name-inhibit-cache 10
1104 "Whether to use the remote file-name cache for read access.
1105 When nil, never expire cached values (caution)
1106 When t, never use the cache (safe, but may be slow)
1107 A number means use cached values for that amount of seconds since caching.
1109 The attributes of remote files are cached for better performance.
1110 If they are changed outside of Emacs's control, the cached values
1111 become invalid, and must be reread. If you are sure that nothing
1112 other than Emacs changes the files, you can set this variable to nil.
1114 If a remote file is checked regularly, it might be a good idea to
1115 let-bind this variable to a value less than the interval between
1116 consecutive checks. For example:
1118 (defun display-time-file-nonempty-p (file)
1119 (let ((remote-file-name-inhibit-cache (- display-time-interval 5)))
1120 (and (file-exists-p file)
1121 (< 0 (nth 7 (file-attributes (file-chase-links file)))))))"
1122 :group 'files
1123 :version "24.1"
1124 :type `(choice
1125 (const :tag "Do not inhibit file name cache" nil)
1126 (const :tag "Do not use file name cache" t)
1127 (integer :tag "Do not use file name cache"
1128 :format "Do not use file name cache older then %v seconds"
1129 :value 10)))
1131 (defun file-local-name (file)
1132 "Return the local name component of FILE.
1133 It returns a file name which can be used directly as argument of
1134 `process-file', `start-file-process', or `shell-command'."
1135 (or (file-remote-p file 'localname) file))
1137 (defun file-local-copy (file)
1138 "Copy the file FILE into a temporary file on this machine.
1139 Returns the name of the local copy, or nil, if FILE is directly
1140 accessible."
1141 ;; This formerly had an optional BUFFER argument that wasn't used by
1142 ;; anything.
1143 (let ((handler (find-file-name-handler file 'file-local-copy)))
1144 (if handler
1145 (funcall handler 'file-local-copy file)
1146 nil)))
1148 (defun file-truename (filename &optional counter prev-dirs)
1149 "Return the truename of FILENAME.
1150 If FILENAME is not absolute, first expands it against `default-directory'.
1151 The truename of a file name is found by chasing symbolic links
1152 both at the level of the file and at the level of the directories
1153 containing it, until no links are left at any level.
1155 \(fn FILENAME)" ;; Don't document the optional arguments.
1156 ;; COUNTER and PREV-DIRS are only used in recursive calls.
1157 ;; COUNTER can be a cons cell whose car is the count of how many
1158 ;; more links to chase before getting an error.
1159 ;; PREV-DIRS can be a cons cell whose car is an alist
1160 ;; of truenames we've just recently computed.
1161 (cond ((or (string= filename "") (string= filename "~"))
1162 (setq filename (expand-file-name filename))
1163 (if (string= filename "")
1164 (setq filename "/")))
1165 ((and (string= (substring filename 0 1) "~")
1166 (string-match "~[^/]*/?" filename))
1167 (let ((first-part
1168 (substring filename 0 (match-end 0)))
1169 (rest (substring filename (match-end 0))))
1170 (setq filename (concat (expand-file-name first-part) rest)))))
1172 (or counter (setq counter (list 100)))
1173 (let (done
1174 ;; For speed, remove the ange-ftp completion handler from the list.
1175 ;; We know it's not needed here.
1176 ;; For even more speed, do this only on the outermost call.
1177 (file-name-handler-alist
1178 (if prev-dirs file-name-handler-alist
1179 (let ((tem (copy-sequence file-name-handler-alist)))
1180 (delq (rassq 'ange-ftp-completion-hook-function tem) tem)))))
1181 (or prev-dirs (setq prev-dirs (list nil)))
1183 ;; andrewi@harlequin.co.uk - on Windows, there is an issue with
1184 ;; case differences being ignored by the OS, and short "8.3 DOS"
1185 ;; name aliases existing for all files. (The short names are not
1186 ;; reported by directory-files, but can be used to refer to files.)
1187 ;; It seems appropriate for file-truename to resolve these issues in
1188 ;; the most natural way, which on Windows is to call the function
1189 ;; `w32-long-file-name' - this returns the exact name of a file as
1190 ;; it is stored on disk (expanding short name aliases with the full
1191 ;; name in the process).
1192 (if (eq system-type 'windows-nt)
1193 (unless (string-match "[[*?]" filename)
1194 ;; If filename exists, use its long name. If it doesn't
1195 ;; exist, the recursion below on the directory of filename
1196 ;; will drill down until we find a directory that exists,
1197 ;; and use the long name of that, with the extra
1198 ;; non-existent path components concatenated.
1199 (let ((longname (w32-long-file-name filename)))
1200 (if longname
1201 (setq filename longname)))))
1203 ;; If this file directly leads to a link, process that iteratively
1204 ;; so that we don't use lots of stack.
1205 (while (not done)
1206 (setcar counter (1- (car counter)))
1207 (if (< (car counter) 0)
1208 (error "Apparent cycle of symbolic links for %s" filename))
1209 (let ((handler (find-file-name-handler filename 'file-truename)))
1210 ;; For file name that has a special handler, call handler.
1211 ;; This is so that ange-ftp can save time by doing a no-op.
1212 (if handler
1213 (setq filename (funcall handler 'file-truename filename)
1214 done t)
1215 (let ((dir (or (file-name-directory filename) default-directory))
1216 target dirfile)
1217 ;; Get the truename of the directory.
1218 (setq dirfile (directory-file-name dir))
1219 ;; If these are equal, we have the (or a) root directory.
1220 (or (string= dir dirfile)
1221 (and (file-name-case-insensitive-p dir)
1222 (eq (compare-strings dir 0 nil dirfile 0 nil t) t))
1223 ;; If this is the same dir we last got the truename for,
1224 ;; save time--don't recalculate.
1225 (if (assoc dir (car prev-dirs))
1226 (setq dir (cdr (assoc dir (car prev-dirs))))
1227 (let ((old dir)
1228 (new (file-name-as-directory (file-truename dirfile counter prev-dirs))))
1229 (setcar prev-dirs (cons (cons old new) (car prev-dirs)))
1230 (setq dir new))))
1231 (if (equal ".." (file-name-nondirectory filename))
1232 (setq filename
1233 (directory-file-name (file-name-directory (directory-file-name dir)))
1234 done t)
1235 (if (equal "." (file-name-nondirectory filename))
1236 (setq filename (directory-file-name dir)
1237 done t)
1238 ;; Put it back on the file name.
1239 (setq filename (concat dir (file-name-nondirectory filename)))
1240 ;; Is the file name the name of a link?
1241 (setq target (file-symlink-p filename))
1242 (if target
1243 ;; Yes => chase that link, then start all over
1244 ;; since the link may point to a directory name that uses links.
1245 ;; We can't safely use expand-file-name here
1246 ;; since target might look like foo/../bar where foo
1247 ;; is itself a link. Instead, we handle . and .. above.
1248 (setq filename
1249 (if (file-name-absolute-p target)
1250 target
1251 (concat dir target))
1252 done nil)
1253 ;; No, we are done!
1254 (setq done t))))))))
1255 filename))
1257 (defun file-chase-links (filename &optional limit)
1258 "Chase links in FILENAME until a name that is not a link.
1259 Unlike `file-truename', this does not check whether a parent
1260 directory name is a symbolic link.
1261 If the optional argument LIMIT is a number,
1262 it means chase no more than that many links and then stop."
1263 (let (tem (newname filename)
1264 (count 0))
1265 (while (and (or (null limit) (< count limit))
1266 (setq tem (file-symlink-p newname)))
1267 (save-match-data
1268 (if (and (null limit) (= count 100))
1269 (error "Apparent cycle of symbolic links for %s" filename))
1270 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
1271 (while (string-match "//+" tem)
1272 (setq tem (replace-match "/" nil nil tem)))
1273 ;; Handle `..' by hand, since it needs to work in the
1274 ;; target of any directory symlink.
1275 ;; This code is not quite complete; it does not handle
1276 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
1277 (while (string-match "\\`\\.\\./" tem)
1278 (setq tem (substring tem 3))
1279 (setq newname (expand-file-name newname))
1280 ;; Chase links in the default dir of the symlink.
1281 (setq newname
1282 (file-chase-links
1283 (directory-file-name (file-name-directory newname))))
1284 ;; Now find the parent of that dir.
1285 (setq newname (file-name-directory newname)))
1286 (setq newname (expand-file-name tem (file-name-directory newname)))
1287 (setq count (1+ count))))
1288 newname))
1290 ;; A handy function to display file sizes in human-readable form.
1291 ;; See http://en.wikipedia.org/wiki/Kibibyte for the reference.
1292 (defun file-size-human-readable (file-size &optional flavor)
1293 "Produce a string showing FILE-SIZE in human-readable form.
1295 Optional second argument FLAVOR controls the units and the display format:
1297 If FLAVOR is nil or omitted, each kilobyte is 1024 bytes and the produced
1298 suffixes are \"k\", \"M\", \"G\", \"T\", etc.
1299 If FLAVOR is `si', each kilobyte is 1000 bytes and the produced suffixes
1300 are \"k\", \"M\", \"G\", \"T\", etc.
1301 If FLAVOR is `iec', each kilobyte is 1024 bytes and the produced suffixes
1302 are \"KiB\", \"MiB\", \"GiB\", \"TiB\", etc."
1303 (let ((power (if (or (null flavor) (eq flavor 'iec))
1304 1024.0
1305 1000.0))
1306 (post-fixes
1307 ;; none, kilo, mega, giga, tera, peta, exa, zetta, yotta
1308 (list "" "k" "M" "G" "T" "P" "E" "Z" "Y")))
1309 (while (and (>= file-size power) (cdr post-fixes))
1310 (setq file-size (/ file-size power)
1311 post-fixes (cdr post-fixes)))
1312 (format (if (> (mod file-size 1.0) 0.05)
1313 "%.1f%s%s"
1314 "%.0f%s%s")
1315 file-size
1316 (if (and (eq flavor 'iec) (string= (car post-fixes) "k"))
1318 (car post-fixes))
1319 (if (eq flavor 'iec) "iB" ""))))
1321 (defcustom mounted-file-systems
1322 (if (memq system-type '(windows-nt cygwin))
1323 "^//[^/]+/"
1324 ;; regexp-opt.el is not dumped into emacs binary.
1325 ;;(concat
1326 ;; "^" (regexp-opt '("/afs/" "/media/" "/mnt" "/net/" "/tmp_mnt/"))))
1327 "^\\(?:/\\(?:afs/\\|m\\(?:edia/\\|nt\\)\\|\\(?:ne\\|tmp_mn\\)t/\\)\\)")
1328 "File systems which ought to be mounted."
1329 :group 'files
1330 :version "26.1"
1331 :require 'regexp-opt
1332 :type 'regexp)
1334 (defun temporary-file-directory ()
1335 "The directory for writing temporary files.
1336 In case of a remote `default-directory', this is a directory for
1337 temporary files on that remote host. If such a directory does
1338 not exist, or `default-directory' ought to be located on a
1339 mounted file system (see `mounted-file-systems'), the function
1340 returns `default-directory'.
1341 For a non-remote and non-mounted `default-directory', the value of
1342 the variable `temporary-file-directory' is returned."
1343 (let ((handler (find-file-name-handler
1344 default-directory 'temporary-file-directory)))
1345 (if handler
1346 (funcall handler 'temporary-file-directory)
1347 (if (string-match mounted-file-systems default-directory)
1348 default-directory
1349 temporary-file-directory))))
1351 (defun make-temp-file (prefix &optional dir-flag suffix)
1352 "Create a temporary file.
1353 The returned file name (created by appending some random characters at the end
1354 of PREFIX, and expanding against `temporary-file-directory' if necessary),
1355 is guaranteed to point to a newly created empty file.
1356 You can then use `write-region' to write new data into the file.
1358 If DIR-FLAG is non-nil, create a new empty directory instead of a file.
1360 If SUFFIX is non-nil, add that at the end of the file name."
1361 ;; Create temp files with strict access rights. It's easy to
1362 ;; loosen them later, whereas it's impossible to close the
1363 ;; time-window of loose permissions otherwise.
1364 (with-file-modes ?\700
1365 (let (file)
1366 (while (condition-case ()
1367 (progn
1368 (setq file
1369 (make-temp-name
1370 (if (zerop (length prefix))
1371 (file-name-as-directory
1372 temporary-file-directory)
1373 (expand-file-name prefix
1374 temporary-file-directory))))
1375 (if suffix
1376 (setq file (concat file suffix)))
1377 (if dir-flag
1378 (make-directory file)
1379 (write-region "" nil file nil 'silent nil 'excl))
1380 nil)
1381 (file-already-exists t))
1382 ;; the file was somehow created by someone else between
1383 ;; `make-temp-name' and `write-region', let's try again.
1384 nil)
1385 file)))
1387 (defun make-nearby-temp-file (prefix &optional dir-flag suffix)
1388 "Create a temporary file as close as possible to `default-directory'.
1389 If PREFIX is a relative file name, and `default-directory' is a
1390 remote file name or located on a mounted file systems, the
1391 temporary file is created in the directory returned by the
1392 function `temporary-file-directory'. Otherwise, the function
1393 `make-temp-file' is used. PREFIX, DIR-FLAG and SUFFIX have the
1394 same meaning as in `make-temp-file'."
1395 (let ((handler (find-file-name-handler
1396 default-directory 'make-nearby-temp-file)))
1397 (if (and handler (not (file-name-absolute-p default-directory)))
1398 (funcall handler 'make-nearby-temp-file prefix dir-flag suffix)
1399 (let ((temporary-file-directory (temporary-file-directory)))
1400 (make-temp-file prefix dir-flag suffix)))))
1402 (defun recode-file-name (file coding new-coding &optional ok-if-already-exists)
1403 "Change the encoding of FILE's name from CODING to NEW-CODING.
1404 The value is a new name of FILE.
1405 Signals a `file-already-exists' error if a file of the new name
1406 already exists unless optional fourth argument OK-IF-ALREADY-EXISTS
1407 is non-nil. A number as fourth arg means request confirmation if
1408 the new name already exists. This is what happens in interactive
1409 use with M-x."
1410 (interactive
1411 (let ((default-coding (or file-name-coding-system
1412 default-file-name-coding-system))
1413 (filename (read-file-name "Recode filename: " nil nil t))
1414 from-coding to-coding)
1415 (if (and default-coding
1416 ;; We provide the default coding only when it seems that
1417 ;; the filename is correctly decoded by the default
1418 ;; coding.
1419 (let ((charsets (find-charset-string filename)))
1420 (and (not (memq 'eight-bit-control charsets))
1421 (not (memq 'eight-bit-graphic charsets)))))
1422 (setq from-coding (read-coding-system
1423 (format "Recode filename %s from (default %s): "
1424 filename default-coding)
1425 default-coding))
1426 (setq from-coding (read-coding-system
1427 (format "Recode filename %s from: " filename))))
1429 ;; We provide the default coding only when a user is going to
1430 ;; change the encoding not from the default coding.
1431 (if (eq from-coding default-coding)
1432 (setq to-coding (read-coding-system
1433 (format "Recode filename %s from %s to: "
1434 filename from-coding)))
1435 (setq to-coding (read-coding-system
1436 (format "Recode filename %s from %s to (default %s): "
1437 filename from-coding default-coding)
1438 default-coding)))
1439 (list filename from-coding to-coding)))
1441 (let* ((default-coding (or file-name-coding-system
1442 default-file-name-coding-system))
1443 ;; FILE should have been decoded by DEFAULT-CODING.
1444 (encoded (encode-coding-string file default-coding))
1445 (newname (decode-coding-string encoded coding))
1446 (new-encoded (encode-coding-string newname new-coding))
1447 ;; Suppress further encoding.
1448 (file-name-coding-system nil)
1449 (default-file-name-coding-system nil)
1450 (locale-coding-system nil))
1451 (rename-file encoded new-encoded ok-if-already-exists)
1452 newname))
1454 (defcustom confirm-nonexistent-file-or-buffer 'after-completion
1455 "Whether confirmation is requested before visiting a new file or buffer.
1456 If nil, confirmation is not requested.
1457 If the value is `after-completion', confirmation is only
1458 requested if the user called `minibuffer-complete' right before
1459 `minibuffer-complete-and-exit'.
1460 Any other non-nil value means to request confirmation.
1462 This affects commands like `switch-to-buffer' and `find-file'."
1463 :group 'find-file
1464 :version "23.1"
1465 :type '(choice (const :tag "After completion" after-completion)
1466 (const :tag "Never" nil)
1467 (other :tag "Always" t)))
1469 (defun confirm-nonexistent-file-or-buffer ()
1470 "Whether to request confirmation before visiting a new file or buffer.
1471 The variable `confirm-nonexistent-file-or-buffer' determines the
1472 return value, which may be passed as the REQUIRE-MATCH arg to
1473 `read-buffer' or `find-file-read-args'."
1474 (cond ((eq confirm-nonexistent-file-or-buffer 'after-completion)
1475 'confirm-after-completion)
1476 (confirm-nonexistent-file-or-buffer
1477 'confirm)
1478 (t nil)))
1480 (defmacro minibuffer-with-setup-hook (fun &rest body)
1481 "Temporarily add FUN to `minibuffer-setup-hook' while executing BODY.
1483 By default, FUN is prepended to `minibuffer-setup-hook'. But if FUN is of
1484 the form `(:append FUN1)', FUN1 will be appended to `minibuffer-setup-hook'
1485 instead of prepending it.
1487 BODY should use the minibuffer at most once.
1488 Recursive uses of the minibuffer are unaffected (FUN is not
1489 called additional times).
1491 This macro actually adds an auxiliary function that calls FUN,
1492 rather than FUN itself, to `minibuffer-setup-hook'."
1493 (declare (indent 1) (debug t))
1494 (let ((hook (make-symbol "setup-hook"))
1495 (funsym (make-symbol "fun"))
1496 (append nil))
1497 (when (eq (car-safe fun) :append)
1498 (setq append '(t) fun (cadr fun)))
1499 `(let ((,funsym ,fun)
1500 ,hook)
1501 (setq ,hook
1502 (lambda ()
1503 ;; Clear out this hook so it does not interfere
1504 ;; with any recursive minibuffer usage.
1505 (remove-hook 'minibuffer-setup-hook ,hook)
1506 (funcall ,funsym)))
1507 (unwind-protect
1508 (progn
1509 (add-hook 'minibuffer-setup-hook ,hook ,@append)
1510 ,@body)
1511 (remove-hook 'minibuffer-setup-hook ,hook)))))
1513 (defun find-file-read-args (prompt mustmatch)
1514 (list (read-file-name prompt nil default-directory mustmatch)
1517 (defun find-file (filename &optional wildcards)
1518 "Edit file FILENAME.
1519 Switch to a buffer visiting file FILENAME,
1520 creating one if none already exists.
1521 Interactively, the default if you just type RET is the current directory,
1522 but the visited file name is available through the minibuffer history:
1523 type M-n to pull it into the minibuffer.
1525 You can visit files on remote machines by specifying something
1526 like /ssh:SOME_REMOTE_MACHINE:FILE for the file name. You can
1527 also visit local files as a different user by specifying
1528 /sudo::FILE for the file name.
1529 See the Info node `(tramp)File name Syntax' in the Tramp Info
1530 manual, for more about this.
1532 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1533 expand wildcards (if any) and visit multiple files. You can
1534 suppress wildcard expansion by setting `find-file-wildcards' to nil.
1536 To visit a file without any kind of conversion and without
1537 automatically choosing a major mode, use \\[find-file-literally]."
1538 (interactive
1539 (find-file-read-args "Find file: "
1540 (confirm-nonexistent-file-or-buffer)))
1541 (let ((value (find-file-noselect filename nil nil wildcards)))
1542 (if (listp value)
1543 (mapcar 'switch-to-buffer (nreverse value))
1544 (switch-to-buffer value))))
1546 (defun find-file-other-window (filename &optional wildcards)
1547 "Edit file FILENAME, in another window.
1549 Like \\[find-file] (which see), but creates a new window or reuses
1550 an existing one. See the function `display-buffer'.
1552 Interactively, the default if you just type RET is the current directory,
1553 but the visited file name is available through the minibuffer history:
1554 type M-n to pull it into the minibuffer.
1556 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1557 expand wildcards (if any) and visit multiple files."
1558 (interactive
1559 (find-file-read-args "Find file in other window: "
1560 (confirm-nonexistent-file-or-buffer)))
1561 (let ((value (find-file-noselect filename nil nil wildcards)))
1562 (if (listp value)
1563 (progn
1564 (setq value (nreverse value))
1565 (switch-to-buffer-other-window (car value))
1566 (mapc 'switch-to-buffer (cdr value))
1567 value)
1568 (switch-to-buffer-other-window value))))
1570 (defun find-file-other-frame (filename &optional wildcards)
1571 "Edit file FILENAME, in another frame.
1573 Like \\[find-file] (which see), but creates a new frame or reuses
1574 an existing one. See the function `display-buffer'.
1576 Interactively, the default if you just type RET is the current directory,
1577 but the visited file name is available through the minibuffer history:
1578 type M-n to pull it into the minibuffer.
1580 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1581 expand wildcards (if any) and visit multiple files."
1582 (interactive
1583 (find-file-read-args "Find file in other frame: "
1584 (confirm-nonexistent-file-or-buffer)))
1585 (let ((value (find-file-noselect filename nil nil wildcards)))
1586 (if (listp value)
1587 (progn
1588 (setq value (nreverse value))
1589 (switch-to-buffer-other-frame (car value))
1590 (mapc 'switch-to-buffer (cdr value))
1591 value)
1592 (switch-to-buffer-other-frame value))))
1594 (defun find-file-existing (filename)
1595 "Edit the existing file FILENAME.
1596 Like \\[find-file], but only allow a file that exists, and do not allow
1597 file names with wildcards."
1598 (interactive (nbutlast (find-file-read-args "Find existing file: " t)))
1599 (if (and (not (called-interactively-p 'interactive))
1600 (not (file-exists-p filename)))
1601 (error "%s does not exist" filename)
1602 (find-file filename)
1603 (current-buffer)))
1605 (defun find-file--read-only (fun filename wildcards)
1606 (unless (or (and wildcards find-file-wildcards
1607 (not (string-match "\\`/:" filename))
1608 (string-match "[[*?]" filename))
1609 (file-exists-p filename))
1610 (error "%s does not exist" filename))
1611 (let ((value (funcall fun filename wildcards)))
1612 (mapc (lambda (b) (with-current-buffer b (read-only-mode 1)))
1613 (if (listp value) value (list value)))
1614 value))
1616 (defun find-file-read-only (filename &optional wildcards)
1617 "Edit file FILENAME but don't allow changes.
1618 Like \\[find-file], but marks buffer as read-only.
1619 Use \\[read-only-mode] to permit editing."
1620 (interactive
1621 (find-file-read-args "Find file read-only: "
1622 (confirm-nonexistent-file-or-buffer)))
1623 (find-file--read-only #'find-file filename wildcards))
1625 (defun find-file-read-only-other-window (filename &optional wildcards)
1626 "Edit file FILENAME in another window but don't allow changes.
1627 Like \\[find-file-other-window], but marks buffer as read-only.
1628 Use \\[read-only-mode] to permit editing."
1629 (interactive
1630 (find-file-read-args "Find file read-only other window: "
1631 (confirm-nonexistent-file-or-buffer)))
1632 (find-file--read-only #'find-file-other-window filename wildcards))
1634 (defun find-file-read-only-other-frame (filename &optional wildcards)
1635 "Edit file FILENAME in another frame but don't allow changes.
1636 Like \\[find-file-other-frame], but marks buffer as read-only.
1637 Use \\[read-only-mode] to permit editing."
1638 (interactive
1639 (find-file-read-args "Find file read-only other frame: "
1640 (confirm-nonexistent-file-or-buffer)))
1641 (find-file--read-only #'find-file-other-frame filename wildcards))
1643 (defun find-alternate-file-other-window (filename &optional wildcards)
1644 "Find file FILENAME as a replacement for the file in the next window.
1645 This command does not select that window.
1647 See \\[find-file] for the possible forms of the FILENAME argument.
1649 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1650 expand wildcards (if any) and replace the file with multiple files."
1651 (interactive
1652 (save-selected-window
1653 (other-window 1)
1654 (let ((file buffer-file-name)
1655 (file-name nil)
1656 (file-dir nil))
1657 (and file
1658 (setq file-name (file-name-nondirectory file)
1659 file-dir (file-name-directory file)))
1660 (list (read-file-name
1661 "Find alternate file: " file-dir nil
1662 (confirm-nonexistent-file-or-buffer) file-name)
1663 t))))
1664 (if (one-window-p)
1665 (find-file-other-window filename wildcards)
1666 (save-selected-window
1667 (other-window 1)
1668 (find-alternate-file filename wildcards))))
1670 ;; Defined and used in buffer.c, but not as a DEFVAR_LISP.
1671 (defvar kill-buffer-hook nil
1672 "Hook run when a buffer is killed.
1673 The buffer being killed is current while the hook is running.
1674 See `kill-buffer'.
1676 Note: Be careful with let-binding this hook considering it is
1677 frequently used for cleanup.")
1679 (defun find-alternate-file (filename &optional wildcards)
1680 "Find file FILENAME, select its buffer, kill previous buffer.
1681 If the current buffer now contains an empty file that you just visited
1682 \(presumably by mistake), use this command to visit the file you really want.
1684 See \\[find-file] for the possible forms of the FILENAME argument.
1686 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1687 expand wildcards (if any) and replace the file with multiple files.
1689 If the current buffer is an indirect buffer, or the base buffer
1690 for one or more indirect buffers, the other buffer(s) are not
1691 killed."
1692 (interactive
1693 (let ((file buffer-file-name)
1694 (file-name nil)
1695 (file-dir nil))
1696 (and file
1697 (setq file-name (file-name-nondirectory file)
1698 file-dir (file-name-directory file)))
1699 (list (read-file-name
1700 "Find alternate file: " file-dir nil
1701 (confirm-nonexistent-file-or-buffer) file-name)
1702 t)))
1703 (unless (run-hook-with-args-until-failure 'kill-buffer-query-functions)
1704 (user-error "Aborted"))
1705 (and (buffer-modified-p) buffer-file-name
1706 (not (yes-or-no-p
1707 (format-message "Kill and replace buffer `%s' without saving it? "
1708 (buffer-name))))
1709 (user-error "Aborted"))
1710 (let ((obuf (current-buffer))
1711 (ofile buffer-file-name)
1712 (onum buffer-file-number)
1713 (odir dired-directory)
1714 (otrue buffer-file-truename)
1715 (oname (buffer-name)))
1716 ;; Run `kill-buffer-hook' here. It needs to happen before
1717 ;; variables like `buffer-file-name' etc are set to nil below,
1718 ;; because some of the hooks that could be invoked
1719 ;; (e.g., `save-place-to-alist') depend on those variables.
1721 ;; Note that `kill-buffer-hook' is not what queries whether to
1722 ;; save a modified buffer visiting a file. Rather, `kill-buffer'
1723 ;; asks that itself. Thus, there's no need to temporarily do
1724 ;; `(set-buffer-modified-p nil)' before running this hook.
1725 (run-hooks 'kill-buffer-hook)
1726 ;; Okay, now we can end-of-life the old buffer.
1727 (if (get-buffer " **lose**")
1728 (kill-buffer " **lose**"))
1729 (rename-buffer " **lose**")
1730 (unwind-protect
1731 (progn
1732 (unlock-buffer)
1733 ;; This prevents us from finding the same buffer
1734 ;; if we specified the same file again.
1735 (setq buffer-file-name nil)
1736 (setq buffer-file-number nil)
1737 (setq buffer-file-truename nil)
1738 ;; Likewise for dired buffers.
1739 (setq dired-directory nil)
1740 (find-file filename wildcards))
1741 (when (eq obuf (current-buffer))
1742 ;; This executes if find-file gets an error
1743 ;; and does not really find anything.
1744 ;; We put things back as they were.
1745 ;; If find-file actually finds something, we kill obuf below.
1746 (setq buffer-file-name ofile)
1747 (setq buffer-file-number onum)
1748 (setq buffer-file-truename otrue)
1749 (setq dired-directory odir)
1750 (lock-buffer)
1751 (rename-buffer oname)))
1752 (unless (eq (current-buffer) obuf)
1753 (with-current-buffer obuf
1754 ;; We already ran these; don't run them again.
1755 (let (kill-buffer-query-functions kill-buffer-hook)
1756 (kill-buffer obuf))))))
1758 ;; FIXME we really need to fold the uniquify stuff in here by default,
1759 ;; not using advice, and add it to the doc string.
1760 (defun create-file-buffer (filename)
1761 "Create a suitably named buffer for visiting FILENAME, and return it.
1762 FILENAME (sans directory) is used unchanged if that name is free;
1763 otherwise a string <2> or <3> or ... is appended to get an unused name.
1765 Emacs treats buffers whose names begin with a space as internal buffers.
1766 To avoid confusion when visiting a file whose name begins with a space,
1767 this function prepends a \"|\" to the final result if necessary."
1768 (let ((lastname (file-name-nondirectory filename)))
1769 (if (string= lastname "")
1770 (setq lastname filename))
1771 (generate-new-buffer (if (string-match-p "\\` " lastname)
1772 (concat "|" lastname)
1773 lastname))))
1775 (defun generate-new-buffer (name)
1776 "Create and return a buffer with a name based on NAME.
1777 Choose the buffer's name using `generate-new-buffer-name'."
1778 (get-buffer-create (generate-new-buffer-name name)))
1780 (defcustom automount-dir-prefix (purecopy "^/tmp_mnt/")
1781 "Regexp to match the automounter prefix in a directory name."
1782 :group 'files
1783 :type 'regexp)
1784 (make-obsolete-variable 'automount-dir-prefix 'directory-abbrev-alist "24.3")
1786 (defvar abbreviated-home-dir nil
1787 "The user's homedir abbreviated according to `directory-abbrev-alist'.")
1789 (defun abbreviate-file-name (filename)
1790 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
1791 This also substitutes \"~\" for the user's home directory (unless the
1792 home directory is a root directory) and removes automounter prefixes
1793 \(see the variable `automount-dir-prefix')."
1794 ;; Get rid of the prefixes added by the automounter.
1795 (save-match-data
1796 (if (and automount-dir-prefix
1797 (string-match automount-dir-prefix filename)
1798 (file-exists-p (file-name-directory
1799 (substring filename (1- (match-end 0))))))
1800 (setq filename (substring filename (1- (match-end 0)))))
1801 ;; Avoid treating /home/foo as /home/Foo during `~' substitution.
1802 (let ((case-fold-search (file-name-case-insensitive-p filename)))
1803 ;; If any elt of directory-abbrev-alist matches this name,
1804 ;; abbreviate accordingly.
1805 (dolist (dir-abbrev directory-abbrev-alist)
1806 (if (string-match (car dir-abbrev) filename)
1807 (setq filename
1808 (concat (cdr dir-abbrev)
1809 (substring filename (match-end 0))))))
1810 ;; Compute and save the abbreviated homedir name.
1811 ;; We defer computing this until the first time it's needed, to
1812 ;; give time for directory-abbrev-alist to be set properly.
1813 ;; We include a slash at the end, to avoid spurious matches
1814 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
1815 (or abbreviated-home-dir
1816 (setq abbreviated-home-dir
1817 (let ((abbreviated-home-dir "$foo"))
1818 (concat "\\`" (abbreviate-file-name (expand-file-name "~"))
1819 "\\(/\\|\\'\\)"))))
1821 ;; If FILENAME starts with the abbreviated homedir,
1822 ;; make it start with `~' instead.
1823 (if (and (string-match abbreviated-home-dir filename)
1824 ;; If the home dir is just /, don't change it.
1825 (not (and (= (match-end 0) 1)
1826 (= (aref filename 0) ?/)))
1827 ;; MS-DOS root directories can come with a drive letter;
1828 ;; Novell Netware allows drive letters beyond `Z:'.
1829 (not (and (memq system-type '(ms-dos windows-nt cygwin))
1830 (save-match-data
1831 (string-match "^[a-zA-`]:/$" filename)))))
1832 (setq filename
1833 (concat "~"
1834 (match-string 1 filename)
1835 (substring filename (match-end 0)))))
1836 filename)))
1838 (defun find-buffer-visiting (filename &optional predicate)
1839 "Return the buffer visiting file FILENAME (a string).
1840 This is like `get-file-buffer', except that it checks for any buffer
1841 visiting the same file, possibly under a different name.
1842 If PREDICATE is non-nil, only buffers satisfying it are eligible,
1843 and others are ignored.
1844 If there is no such live buffer, return nil."
1845 (let ((predicate (or predicate #'identity))
1846 (truename (abbreviate-file-name (file-truename filename))))
1847 (or (let ((buf (get-file-buffer filename)))
1848 (when (and buf (funcall predicate buf)) buf))
1849 (let ((list (buffer-list)) found)
1850 (while (and (not found) list)
1851 (with-current-buffer (car list)
1852 (if (and buffer-file-name
1853 (string= buffer-file-truename truename)
1854 (funcall predicate (current-buffer)))
1855 (setq found (car list))))
1856 (setq list (cdr list)))
1857 found)
1858 (let* ((attributes (file-attributes truename))
1859 (number (nthcdr 10 attributes))
1860 (list (buffer-list)) found)
1861 (and buffer-file-numbers-unique
1862 (car-safe number) ;Make sure the inode is not just nil.
1863 (while (and (not found) list)
1864 (with-current-buffer (car list)
1865 (if (and buffer-file-name
1866 (equal buffer-file-number number)
1867 ;; Verify this buffer's file number
1868 ;; still belongs to its file.
1869 (file-exists-p buffer-file-name)
1870 (equal (file-attributes buffer-file-truename)
1871 attributes)
1872 (funcall predicate (current-buffer)))
1873 (setq found (car list))))
1874 (setq list (cdr list))))
1875 found))))
1877 (defcustom find-file-wildcards t
1878 "Non-nil means file-visiting commands should handle wildcards.
1879 For example, if you specify `*.c', that would visit all the files
1880 whose names match the pattern."
1881 :group 'files
1882 :version "20.4"
1883 :type 'boolean)
1885 (defcustom find-file-suppress-same-file-warnings nil
1886 "Non-nil means suppress warning messages for symlinked files.
1887 When nil, Emacs prints a warning when visiting a file that is already
1888 visited, but with a different name. Setting this option to t
1889 suppresses this warning."
1890 :group 'files
1891 :version "21.1"
1892 :type 'boolean)
1894 (defcustom large-file-warning-threshold 10000000
1895 "Maximum size of file above which a confirmation is requested.
1896 When nil, never request confirmation."
1897 :group 'files
1898 :group 'find-file
1899 :version "22.1"
1900 :type '(choice integer (const :tag "Never request confirmation" nil)))
1902 (defcustom out-of-memory-warning-percentage nil
1903 "Warn if file size exceeds this percentage of available free memory.
1904 When nil, never issue warning. Beware: This probably doesn't do what you
1905 think it does, because \"free\" is pretty hard to define in practice."
1906 :group 'files
1907 :group 'find-file
1908 :version "25.1"
1909 :type '(choice integer (const :tag "Never issue warning" nil)))
1911 (defun abort-if-file-too-large (size op-type filename)
1912 "If file SIZE larger than `large-file-warning-threshold', allow user to abort.
1913 OP-TYPE specifies the file operation being performed (for message to user)."
1914 (when (and large-file-warning-threshold size
1915 (> size large-file-warning-threshold)
1916 (not (y-or-n-p (format "File %s is large (%s), really %s? "
1917 (file-name-nondirectory filename)
1918 (file-size-human-readable size) op-type))))
1919 (user-error "Aborted")))
1921 (defun warn-maybe-out-of-memory (size)
1922 "Warn if an attempt to open file of SIZE bytes may run out of memory."
1923 (when (and (numberp size) (not (zerop size))
1924 (integerp out-of-memory-warning-percentage))
1925 (let ((meminfo (memory-info)))
1926 (when (consp meminfo)
1927 (let ((total-free-memory (float (+ (nth 1 meminfo) (nth 3 meminfo)))))
1928 (when (> (/ size 1024)
1929 (/ (* total-free-memory out-of-memory-warning-percentage)
1930 100.0))
1931 (warn
1932 "You are trying to open a file whose size (%s)
1933 exceeds the %S%% of currently available free memory (%s).
1934 If that fails, try to open it with `find-file-literally'
1935 \(but note that some characters might be displayed incorrectly)."
1936 (file-size-human-readable size)
1937 out-of-memory-warning-percentage
1938 (file-size-human-readable (* total-free-memory 1024)))))))))
1940 (defun files--message (format &rest args)
1941 "Like `message', except sometimes don't print to minibuffer.
1942 If the variable `save-silently' is non-nil, the message is not
1943 displayed on the minibuffer."
1944 (apply #'message format args)
1945 (when save-silently (message nil)))
1947 (defun find-file-noselect (filename &optional nowarn rawfile wildcards)
1948 "Read file FILENAME into a buffer and return the buffer.
1949 If a buffer exists visiting FILENAME, return that one, but
1950 verify that the file has not changed since visited or saved.
1951 The buffer is not selected, just returned to the caller.
1952 Optional second arg NOWARN non-nil means suppress any warning messages.
1953 Optional third arg RAWFILE non-nil means the file is read literally.
1954 Optional fourth arg WILDCARDS non-nil means do wildcard processing
1955 and visit all the matching files. When wildcards are actually
1956 used and expanded, return a list of buffers that are visiting
1957 the various files."
1958 (setq filename
1959 (abbreviate-file-name
1960 (expand-file-name filename)))
1961 (if (file-directory-p filename)
1962 (or (and find-file-run-dired
1963 (run-hook-with-args-until-success
1964 'find-directory-functions
1965 (if find-file-visit-truename
1966 (abbreviate-file-name (file-truename filename))
1967 filename)))
1968 (error "%s is a directory" filename))
1969 (if (and wildcards
1970 find-file-wildcards
1971 (not (string-match "\\`/:" filename))
1972 (string-match "[[*?]" filename))
1973 (let ((files (condition-case nil
1974 (file-expand-wildcards filename t)
1975 (error (list filename))))
1976 (find-file-wildcards nil))
1977 (if (null files)
1978 (find-file-noselect filename)
1979 (mapcar #'find-file-noselect files)))
1980 (let* ((buf (get-file-buffer filename))
1981 (truename (abbreviate-file-name (file-truename filename)))
1982 (attributes (file-attributes truename))
1983 (number (nthcdr 10 attributes))
1984 ;; Find any buffer for a file which has same truename.
1985 (other (and (not buf) (find-buffer-visiting filename))))
1986 ;; Let user know if there is a buffer with the same truename.
1987 (if other
1988 (progn
1989 (or nowarn
1990 find-file-suppress-same-file-warnings
1991 (string-equal filename (buffer-file-name other))
1992 (files--message "%s and %s are the same file"
1993 filename (buffer-file-name other)))
1994 ;; Optionally also find that buffer.
1995 (if (or find-file-existing-other-name find-file-visit-truename)
1996 (setq buf other))))
1997 ;; Check to see if the file looks uncommonly large.
1998 (when (not (or buf nowarn))
1999 (abort-if-file-too-large (nth 7 attributes) "open" filename)
2000 (warn-maybe-out-of-memory (nth 7 attributes)))
2001 (if buf
2002 ;; We are using an existing buffer.
2003 (let (nonexistent)
2004 (or nowarn
2005 (verify-visited-file-modtime buf)
2006 (cond ((not (file-exists-p filename))
2007 (setq nonexistent t)
2008 (message "File %s no longer exists!" filename))
2009 ;; Certain files should be reverted automatically
2010 ;; if they have changed on disk and not in the buffer.
2011 ((and (not (buffer-modified-p buf))
2012 (let ((tail revert-without-query)
2013 (found nil))
2014 (while tail
2015 (if (string-match (car tail) filename)
2016 (setq found t))
2017 (setq tail (cdr tail)))
2018 found))
2019 (with-current-buffer buf
2020 (message "Reverting file %s..." filename)
2021 (revert-buffer t t)
2022 (message "Reverting file %s...done" filename)))
2023 ((yes-or-no-p
2024 (if (string= (file-name-nondirectory filename)
2025 (buffer-name buf))
2026 (format
2027 (if (buffer-modified-p buf)
2028 "File %s changed on disk. Discard your edits? "
2029 "File %s changed on disk. Reread from disk? ")
2030 (file-name-nondirectory filename))
2031 (format
2032 (if (buffer-modified-p buf)
2033 "File %s changed on disk. Discard your edits in %s? "
2034 "File %s changed on disk. Reread from disk into %s? ")
2035 (file-name-nondirectory filename)
2036 (buffer-name buf))))
2037 (with-current-buffer buf
2038 (revert-buffer t t)))))
2039 (with-current-buffer buf
2041 ;; Check if a formerly read-only file has become
2042 ;; writable and vice versa, but if the buffer agrees
2043 ;; with the new state of the file, that is ok too.
2044 (let ((read-only (not (file-writable-p buffer-file-name))))
2045 (unless (or nonexistent
2046 (eq read-only buffer-file-read-only)
2047 (eq read-only buffer-read-only))
2048 (when (or nowarn
2049 (let* ((new-status
2050 (if read-only "read-only" "writable"))
2051 (question
2052 (format "File %s is %s on disk. Make buffer %s, too? "
2053 buffer-file-name
2054 new-status new-status)))
2055 (y-or-n-p question)))
2056 (setq buffer-read-only read-only)))
2057 (setq buffer-file-read-only read-only))
2059 (unless (or (eq (null rawfile) (null find-file-literally))
2060 nonexistent
2061 ;; It is confusing to ask whether to visit
2062 ;; non-literally if they have the file in
2063 ;; hexl-mode or image-mode.
2064 (memq major-mode '(hexl-mode image-mode)))
2065 (if (buffer-modified-p)
2066 (if (y-or-n-p
2067 (format
2068 (if rawfile
2069 "The file %s is already visited normally,
2070 and you have edited the buffer. Now you have asked to visit it literally,
2071 meaning no coding system handling, format conversion, or local variables.
2072 Emacs can only visit a file in one way at a time.
2074 Do you want to save the file, and visit it literally instead? "
2075 "The file %s is already visited literally,
2076 meaning no coding system handling, format conversion, or local variables.
2077 You have edited the buffer. Now you have asked to visit the file normally,
2078 but Emacs can only visit a file in one way at a time.
2080 Do you want to save the file, and visit it normally instead? ")
2081 (file-name-nondirectory filename)))
2082 (progn
2083 (save-buffer)
2084 (find-file-noselect-1 buf filename nowarn
2085 rawfile truename number))
2086 (if (y-or-n-p
2087 (format
2088 (if rawfile
2090 Do you want to discard your changes, and visit the file literally now? "
2092 Do you want to discard your changes, and visit the file normally now? ")))
2093 (find-file-noselect-1 buf filename nowarn
2094 rawfile truename number)
2095 (error (if rawfile "File already visited non-literally"
2096 "File already visited literally"))))
2097 (if (y-or-n-p
2098 (format
2099 (if rawfile
2100 "The file %s is already visited normally.
2101 You have asked to visit it literally,
2102 meaning no coding system decoding, format conversion, or local variables.
2103 But Emacs can only visit a file in one way at a time.
2105 Do you want to revisit the file literally now? "
2106 "The file %s is already visited literally,
2107 meaning no coding system decoding, format conversion, or local variables.
2108 You have asked to visit it normally,
2109 but Emacs can only visit a file in one way at a time.
2111 Do you want to revisit the file normally now? ")
2112 (file-name-nondirectory filename)))
2113 (find-file-noselect-1 buf filename nowarn
2114 rawfile truename number)
2115 (error (if rawfile "File already visited non-literally"
2116 "File already visited literally"))))))
2117 ;; Return the buffer we are using.
2118 buf)
2119 ;; Create a new buffer.
2120 (setq buf (create-file-buffer filename))
2121 ;; find-file-noselect-1 may use a different buffer.
2122 (find-file-noselect-1 buf filename nowarn
2123 rawfile truename number))))))
2125 (defun find-file-noselect-1 (buf filename nowarn rawfile truename number)
2126 (let (error)
2127 (with-current-buffer buf
2128 (kill-local-variable 'find-file-literally)
2129 ;; Needed in case we are re-visiting the file with a different
2130 ;; text representation.
2131 (kill-local-variable 'buffer-file-coding-system)
2132 (kill-local-variable 'cursor-type)
2133 (let ((inhibit-read-only t))
2134 (erase-buffer))
2135 (and (default-value 'enable-multibyte-characters)
2136 (not rawfile)
2137 (set-buffer-multibyte t))
2138 (if rawfile
2139 (condition-case ()
2140 (let ((inhibit-read-only t))
2141 (insert-file-contents-literally filename t))
2142 (file-error
2143 (when (and (file-exists-p filename)
2144 (not (file-readable-p filename)))
2145 (kill-buffer buf)
2146 (signal 'file-error (list "File is not readable"
2147 filename)))
2148 ;; Unconditionally set error
2149 (setq error t)))
2150 (condition-case ()
2151 (let ((inhibit-read-only t))
2152 (insert-file-contents filename t))
2153 (file-error
2154 (when (and (file-exists-p filename)
2155 (not (file-readable-p filename)))
2156 (kill-buffer buf)
2157 (signal 'file-error (list "File is not readable"
2158 filename)))
2159 ;; Run find-file-not-found-functions until one returns non-nil.
2160 (or (run-hook-with-args-until-success 'find-file-not-found-functions)
2161 ;; If they fail too, set error.
2162 (setq error t)))))
2163 ;; Record the file's truename, and maybe use that as visited name.
2164 (if (equal filename buffer-file-name)
2165 (setq buffer-file-truename truename)
2166 (setq buffer-file-truename
2167 (abbreviate-file-name (file-truename buffer-file-name))))
2168 (setq buffer-file-number number)
2169 (if find-file-visit-truename
2170 (setq buffer-file-name (expand-file-name buffer-file-truename)))
2171 ;; Set buffer's default directory to that of the file.
2172 (setq default-directory (file-name-directory buffer-file-name))
2173 ;; Turn off backup files for certain file names. Since
2174 ;; this is a permanent local, the major mode won't eliminate it.
2175 (and backup-enable-predicate
2176 (not (funcall backup-enable-predicate buffer-file-name))
2177 (progn
2178 (make-local-variable 'backup-inhibited)
2179 (setq backup-inhibited t)))
2180 (if rawfile
2181 (progn
2182 (set-buffer-multibyte nil)
2183 (setq buffer-file-coding-system 'no-conversion)
2184 (set-buffer-major-mode buf)
2185 (setq-local find-file-literally t))
2186 (after-find-file error (not nowarn)))
2187 (current-buffer))))
2189 (defun insert-file-contents-literally (filename &optional visit beg end replace)
2190 "Like `insert-file-contents', but only reads in the file literally.
2191 See `insert-file-contents' for an explanation of the parameters.
2192 A buffer may be modified in several ways after reading into the buffer,
2193 due to Emacs features such as format decoding, character code
2194 conversion, `find-file-hook', automatic uncompression, etc.
2196 This function ensures that none of these modifications will take place."
2197 (let ((format-alist nil)
2198 (after-insert-file-functions nil)
2199 (coding-system-for-read 'no-conversion)
2200 (coding-system-for-write 'no-conversion)
2201 (inhibit-file-name-handlers
2202 ;; FIXME: Yuck!! We should turn insert-file-contents-literally
2203 ;; into a file operation instead!
2204 (append '(jka-compr-handler image-file-handler epa-file-handler)
2205 inhibit-file-name-handlers))
2206 (inhibit-file-name-operation 'insert-file-contents))
2207 (insert-file-contents filename visit beg end replace)))
2209 (defun insert-file-1 (filename insert-func)
2210 (if (file-directory-p filename)
2211 (signal 'file-error (list "Opening input file" "Is a directory"
2212 filename)))
2213 ;; Check whether the file is uncommonly large
2214 (abort-if-file-too-large (nth 7 (file-attributes filename)) "insert" filename)
2215 (let* ((buffer (find-buffer-visiting (abbreviate-file-name (file-truename filename))
2216 #'buffer-modified-p))
2217 (tem (funcall insert-func filename)))
2218 (push-mark (+ (point) (car (cdr tem))))
2219 (when buffer
2220 (message "File %s already visited and modified in buffer %s"
2221 filename (buffer-name buffer)))))
2223 (defun insert-file-literally (filename)
2224 "Insert contents of file FILENAME into buffer after point with no conversion.
2226 This function is meant for the user to run interactively.
2227 Don't call it from programs! Use `insert-file-contents-literally' instead.
2228 \(Its calling sequence is different; see its documentation)."
2229 (declare (interactive-only insert-file-contents-literally))
2230 (interactive "*fInsert file literally: ")
2231 (insert-file-1 filename #'insert-file-contents-literally))
2233 (defvar find-file-literally nil
2234 "Non-nil if this buffer was made by `find-file-literally' or equivalent.
2235 This has the `permanent-local' property, which takes effect if you
2236 make the variable buffer-local.")
2237 (put 'find-file-literally 'permanent-local t)
2239 (defun find-file-literally (filename)
2240 "Visit file FILENAME with no conversion of any kind.
2241 Format conversion and character code conversion are both disabled,
2242 and multibyte characters are disabled in the resulting buffer.
2243 The major mode used is Fundamental mode regardless of the file name,
2244 and local variable specifications in the file are ignored.
2245 Automatic uncompression and adding a newline at the end of the
2246 file due to `require-final-newline' is also disabled.
2248 You cannot absolutely rely on this function to result in
2249 visiting the file literally. If Emacs already has a buffer
2250 which is visiting the file, you get the existing buffer,
2251 regardless of whether it was created literally or not.
2253 In a Lisp program, if you want to be sure of accessing a file's
2254 contents literally, you should create a temporary buffer and then read
2255 the file contents into it using `insert-file-contents-literally'."
2256 (interactive
2257 (list (read-file-name
2258 "Find file literally: " nil default-directory
2259 (confirm-nonexistent-file-or-buffer))))
2260 (switch-to-buffer (find-file-noselect filename nil t)))
2262 (defun after-find-file (&optional error warn noauto
2263 _after-find-file-from-revert-buffer
2264 nomodes)
2265 "Called after finding a file and by the default revert function.
2266 Sets buffer mode, parses local variables.
2267 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
2268 error in reading the file. WARN non-nil means warn if there
2269 exists an auto-save file more recent than the visited file.
2270 NOAUTO means don't mess with auto-save mode.
2271 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER is ignored
2272 \(see `revert-buffer-in-progress-p' for similar functionality).
2273 Fifth arg NOMODES non-nil means don't alter the file's modes.
2274 Finishes by calling the functions in `find-file-hook'
2275 unless NOMODES is non-nil."
2276 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
2277 (if noninteractive
2279 (let* (not-serious
2280 (msg
2281 (cond
2282 ((not warn) nil)
2283 ((and error (file-attributes buffer-file-name))
2284 (setq buffer-read-only t)
2285 (if (and (file-symlink-p buffer-file-name)
2286 (not (file-exists-p
2287 (file-chase-links buffer-file-name))))
2288 "Symbolic link that points to nonexistent file"
2289 "File exists, but cannot be read"))
2290 ((not buffer-read-only)
2291 (if (and warn
2292 ;; No need to warn if buffer is auto-saved
2293 ;; under the name of the visited file.
2294 (not (and buffer-file-name
2295 auto-save-visited-file-name))
2296 (file-newer-than-file-p (or buffer-auto-save-file-name
2297 (make-auto-save-file-name))
2298 buffer-file-name))
2299 (format "%s has auto save data; consider M-x recover-this-file"
2300 (file-name-nondirectory buffer-file-name))
2301 (setq not-serious t)
2302 (if error "(New file)" nil)))
2303 ((not error)
2304 (setq not-serious t)
2305 "Note: file is write protected")
2306 ((file-attributes (directory-file-name default-directory))
2307 "File not found and directory write-protected")
2308 ((file-exists-p (file-name-directory buffer-file-name))
2309 (setq buffer-read-only nil))
2311 (setq buffer-read-only nil)
2312 "Use M-x make-directory RET RET to create the directory and its parents"))))
2313 (when msg
2314 (message "%s" msg)
2315 (or not-serious (sit-for 1 t))))
2316 (when (and auto-save-default (not noauto))
2317 (auto-save-mode 1)))
2318 ;; Make people do a little extra work (C-x C-q)
2319 ;; before altering a backup file.
2320 (when (backup-file-name-p buffer-file-name)
2321 (setq buffer-read-only t))
2322 ;; When a file is marked read-only,
2323 ;; make the buffer read-only even if root is looking at it.
2324 (when (and (file-modes (buffer-file-name))
2325 (zerop (logand (file-modes (buffer-file-name)) #o222)))
2326 (setq buffer-read-only t))
2327 (unless nomodes
2328 (when (and view-read-only view-mode)
2329 (view-mode -1))
2330 (normal-mode t)
2331 ;; If requested, add a newline at the end of the file.
2332 (and (memq require-final-newline '(visit visit-save))
2333 (> (point-max) (point-min))
2334 (/= (char-after (1- (point-max))) ?\n)
2335 (not (and (eq selective-display t)
2336 (= (char-after (1- (point-max))) ?\r)))
2337 (not buffer-read-only)
2338 (save-excursion
2339 (goto-char (point-max))
2340 (ignore-errors (insert "\n"))))
2341 (when (and buffer-read-only
2342 view-read-only
2343 (not (eq (get major-mode 'mode-class) 'special)))
2344 (view-mode-enter))
2345 (run-hooks 'find-file-hook)))
2347 (define-obsolete-function-alias 'report-errors 'with-demoted-errors "25.1")
2349 (defun normal-mode (&optional find-file)
2350 "Choose the major mode for this buffer automatically.
2351 Also sets up any specified local variables of the file.
2352 Uses the visited file name, the -*- line, and the local variables spec.
2354 This function is called automatically from `find-file'. In that case,
2355 we may set up the file-specified mode and local variables,
2356 depending on the value of `enable-local-variables'.
2357 In addition, if `local-enable-local-variables' is nil, we do
2358 not set local variables (though we do notice a mode specified with -*-.)
2360 `enable-local-variables' is ignored if you run `normal-mode' interactively,
2361 or from Lisp without specifying the optional argument FIND-FILE;
2362 in that case, this function acts as if `enable-local-variables' were t."
2363 (interactive)
2364 (kill-all-local-variables)
2365 (unless delay-mode-hooks
2366 (run-hooks 'change-major-mode-after-body-hook
2367 'after-change-major-mode-hook))
2368 (let ((enable-local-variables (or (not find-file) enable-local-variables)))
2369 ;; FIXME this is less efficient than it could be, since both
2370 ;; s-a-m and h-l-v may parse the same regions, looking for "mode:".
2371 (with-demoted-errors "File mode specification error: %s"
2372 (set-auto-mode))
2373 ;; `delay-mode-hooks' being non-nil will have prevented the major
2374 ;; mode's call to `run-mode-hooks' from calling
2375 ;; `hack-local-variables'. In that case, call it now.
2376 (when delay-mode-hooks
2377 (with-demoted-errors "File local-variables error: %s"
2378 (hack-local-variables 'no-mode))))
2379 ;; Turn font lock off and on, to make sure it takes account of
2380 ;; whatever file local variables are relevant to it.
2381 (when (and font-lock-mode
2382 ;; Font-lock-mode (now in font-core.el) can be ON when
2383 ;; font-lock.el still hasn't been loaded.
2384 (boundp 'font-lock-keywords)
2385 (eq (car font-lock-keywords) t))
2386 (setq font-lock-keywords (cadr font-lock-keywords))
2387 (font-lock-mode 1)))
2389 (defcustom auto-mode-case-fold t
2390 "Non-nil means to try second pass through `auto-mode-alist'.
2391 This means that if the first case-sensitive search through the alist fails
2392 to find a matching major mode, a second case-insensitive search is made.
2393 On systems with case-insensitive file names, this variable is ignored,
2394 since only a single case-insensitive search through the alist is made."
2395 :group 'files
2396 :version "22.1"
2397 :type 'boolean)
2399 (defvar auto-mode-alist
2400 ;; Note: The entries for the modes defined in cc-mode.el (c-mode,
2401 ;; c++-mode, java-mode and more) are added through autoload
2402 ;; directives in that file. That way is discouraged since it
2403 ;; spreads out the definition of the initial value.
2404 (mapcar
2405 (lambda (elt)
2406 (cons (purecopy (car elt)) (cdr elt)))
2407 `(;; do this first, so that .html.pl is Polish html, not Perl
2408 ("\\.[sx]?html?\\(\\.[a-zA-Z_]+\\)?\\'" . html-mode)
2409 ("\\.svgz?\\'" . image-mode)
2410 ("\\.svgz?\\'" . xml-mode)
2411 ("\\.x[bp]m\\'" . image-mode)
2412 ("\\.x[bp]m\\'" . c-mode)
2413 ("\\.p[bpgn]m\\'" . image-mode)
2414 ("\\.tiff?\\'" . image-mode)
2415 ("\\.gif\\'" . image-mode)
2416 ("\\.png\\'" . image-mode)
2417 ("\\.jpe?g\\'" . image-mode)
2418 ("\\.te?xt\\'" . text-mode)
2419 ("\\.[tT]e[xX]\\'" . tex-mode)
2420 ("\\.ins\\'" . tex-mode) ;Installation files for TeX packages.
2421 ("\\.ltx\\'" . latex-mode)
2422 ("\\.dtx\\'" . doctex-mode)
2423 ("\\.org\\'" . org-mode)
2424 ("\\.el\\'" . emacs-lisp-mode)
2425 ("Project\\.ede\\'" . emacs-lisp-mode)
2426 ("\\.\\(scm\\|stk\\|ss\\|sch\\)\\'" . scheme-mode)
2427 ("\\.l\\'" . lisp-mode)
2428 ("\\.li?sp\\'" . lisp-mode)
2429 ("\\.[fF]\\'" . fortran-mode)
2430 ("\\.for\\'" . fortran-mode)
2431 ("\\.p\\'" . pascal-mode)
2432 ("\\.pas\\'" . pascal-mode)
2433 ("\\.\\(dpr\\|DPR\\)\\'" . delphi-mode)
2434 ("\\.ad[abs]\\'" . ada-mode)
2435 ("\\.ad[bs].dg\\'" . ada-mode)
2436 ("\\.\\([pP]\\([Llm]\\|erl\\|od\\)\\|al\\)\\'" . perl-mode)
2437 ("Imakefile\\'" . makefile-imake-mode)
2438 ("Makeppfile\\(?:\\.mk\\)?\\'" . makefile-makepp-mode) ; Put this before .mk
2439 ("\\.makepp\\'" . makefile-makepp-mode)
2440 ,@(if (memq system-type '(berkeley-unix darwin))
2441 '(("\\.mk\\'" . makefile-bsdmake-mode)
2442 ("\\.make\\'" . makefile-bsdmake-mode)
2443 ("GNUmakefile\\'" . makefile-gmake-mode)
2444 ("[Mm]akefile\\'" . makefile-bsdmake-mode))
2445 '(("\\.mk\\'" . makefile-gmake-mode) ; Might be any make, give Gnu the host advantage
2446 ("\\.make\\'" . makefile-gmake-mode)
2447 ("[Mm]akefile\\'" . makefile-gmake-mode)))
2448 ("\\.am\\'" . makefile-automake-mode)
2449 ;; Less common extensions come here
2450 ;; so more common ones above are found faster.
2451 ("\\.texinfo\\'" . texinfo-mode)
2452 ("\\.te?xi\\'" . texinfo-mode)
2453 ("\\.[sS]\\'" . asm-mode)
2454 ("\\.asm\\'" . asm-mode)
2455 ("\\.css\\'" . css-mode)
2456 ("\\.mixal\\'" . mixal-mode)
2457 ("\\.gcov\\'" . compilation-mode)
2458 ;; Besides .gdbinit, gdb documents other names to be usable for init
2459 ;; files, cross-debuggers can use something like
2460 ;; .PROCESSORNAME-gdbinit so that the host and target gdbinit files
2461 ;; don't interfere with each other.
2462 ("/\\.[a-z0-9-]*gdbinit" . gdb-script-mode)
2463 ;; GDB 7.5 introduced OBJFILE-gdb.gdb script files; e.g. a file
2464 ;; named 'emacs-gdb.gdb', if it exists, will be automatically
2465 ;; loaded when GDB reads an objfile called 'emacs'.
2466 ("-gdb\\.gdb" . gdb-script-mode)
2467 ("[cC]hange\\.?[lL]og?\\'" . change-log-mode)
2468 ("[cC]hange[lL]og[-.][0-9]+\\'" . change-log-mode)
2469 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
2470 ("\\.scm\\.[0-9]*\\'" . scheme-mode)
2471 ("\\.[ckz]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode)
2472 ("\\.bash\\'" . sh-mode)
2473 ("\\(/\\|\\`\\)\\.\\(bash_\\(profile\\|history\\|log\\(in\\|out\\)\\)\\|z?log\\(in\\|out\\)\\)\\'" . sh-mode)
2474 ("\\(/\\|\\`\\)\\.\\(shrc\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode)
2475 ("\\(/\\|\\`\\)\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
2476 ("\\.m?spec\\'" . sh-mode)
2477 ("\\.m[mes]\\'" . nroff-mode)
2478 ("\\.man\\'" . nroff-mode)
2479 ("\\.sty\\'" . latex-mode)
2480 ("\\.cl[so]\\'" . latex-mode) ;LaTeX 2e class option
2481 ("\\.bbl\\'" . latex-mode)
2482 ("\\.bib\\'" . bibtex-mode)
2483 ("\\.bst\\'" . bibtex-style-mode)
2484 ("\\.sql\\'" . sql-mode)
2485 ("\\.m[4c]\\'" . m4-mode)
2486 ("\\.mf\\'" . metafont-mode)
2487 ("\\.mp\\'" . metapost-mode)
2488 ("\\.vhdl?\\'" . vhdl-mode)
2489 ("\\.article\\'" . text-mode)
2490 ("\\.letter\\'" . text-mode)
2491 ("\\.i?tcl\\'" . tcl-mode)
2492 ("\\.exp\\'" . tcl-mode)
2493 ("\\.itk\\'" . tcl-mode)
2494 ("\\.icn\\'" . icon-mode)
2495 ("\\.sim\\'" . simula-mode)
2496 ("\\.mss\\'" . scribe-mode)
2497 ;; The Fortran standard does not say anything about file extensions.
2498 ;; .f90 was widely used for F90, now we seem to be trapped into
2499 ;; using a different extension for each language revision.
2500 ;; Anyway, the following extensions are supported by gfortran.
2501 ("\\.f9[05]\\'" . f90-mode)
2502 ("\\.f0[38]\\'" . f90-mode)
2503 ("\\.indent\\.pro\\'" . fundamental-mode) ; to avoid idlwave-mode
2504 ("\\.\\(pro\\|PRO\\)\\'" . idlwave-mode)
2505 ("\\.srt\\'" . srecode-template-mode)
2506 ("\\.prolog\\'" . prolog-mode)
2507 ("\\.tar\\'" . tar-mode)
2508 ;; The list of archive file extensions should be in sync with
2509 ;; `auto-coding-alist' with `no-conversion' coding system.
2510 ("\\.\\(\
2511 arc\\|zip\\|lzh\\|lha\\|zoo\\|[jew]ar\\|xpi\\|rar\\|cbr\\|7z\\|\
2512 ARC\\|ZIP\\|LZH\\|LHA\\|ZOO\\|[JEW]AR\\|XPI\\|RAR\\|CBR\\|7Z\\)\\'" . archive-mode)
2513 ("\\.oxt\\'" . archive-mode) ;(Open|Libre)Office extensions.
2514 ("\\.\\(deb\\|[oi]pk\\)\\'" . archive-mode) ; Debian/Opkg packages.
2515 ;; Mailer puts message to be edited in
2516 ;; /tmp/Re.... or Message
2517 ("\\`/tmp/Re" . text-mode)
2518 ("/Message[0-9]*\\'" . text-mode)
2519 ;; some news reader is reported to use this
2520 ("\\`/tmp/fol/" . text-mode)
2521 ("\\.oak\\'" . scheme-mode)
2522 ("\\.sgml?\\'" . sgml-mode)
2523 ("\\.x[ms]l\\'" . xml-mode)
2524 ("\\.dbk\\'" . xml-mode)
2525 ("\\.dtd\\'" . sgml-mode)
2526 ("\\.ds\\(ss\\)?l\\'" . dsssl-mode)
2527 ("\\.jsm?\\'" . javascript-mode)
2528 ("\\.json\\'" . javascript-mode)
2529 ("\\.[ds]?vh?\\'" . verilog-mode)
2530 ("\\.by\\'" . bovine-grammar-mode)
2531 ("\\.wy\\'" . wisent-grammar-mode)
2532 ;; .emacs or .gnus or .viper following a directory delimiter in
2533 ;; Unix or MS-DOS syntax.
2534 ("[:/\\]\\..*\\(emacs\\|gnus\\|viper\\)\\'" . emacs-lisp-mode)
2535 ("\\`\\..*emacs\\'" . emacs-lisp-mode)
2536 ;; _emacs following a directory delimiter in MS-DOS syntax
2537 ("[:/]_emacs\\'" . emacs-lisp-mode)
2538 ("/crontab\\.X*[0-9]+\\'" . shell-script-mode)
2539 ("\\.ml\\'" . lisp-mode)
2540 ;; Linux-2.6.9 uses some different suffix for linker scripts:
2541 ;; "ld", "lds", "lds.S", "lds.in", "ld.script", and "ld.script.balo".
2542 ;; eCos uses "ld" and "ldi". Netbsd uses "ldscript.*".
2543 ("\\.ld[si]?\\'" . ld-script-mode)
2544 ("ld\\.?script\\'" . ld-script-mode)
2545 ;; .xs is also used for ld scripts, but seems to be more commonly
2546 ;; associated with Perl .xs files (C with Perl bindings). (Bug#7071)
2547 ("\\.xs\\'" . c-mode)
2548 ;; Explained in binutils ld/genscripts.sh. Eg:
2549 ;; A .x script file is the default script.
2550 ;; A .xr script is for linking without relocation (-r flag). Etc.
2551 ("\\.x[abdsru]?[cnw]?\\'" . ld-script-mode)
2552 ("\\.zone\\'" . dns-mode)
2553 ("\\.soa\\'" . dns-mode)
2554 ;; Common Lisp ASDF package system.
2555 ("\\.asd\\'" . lisp-mode)
2556 ("\\.\\(asn\\|mib\\|smi\\)\\'" . snmp-mode)
2557 ("\\.\\(as\\|mi\\|sm\\)2\\'" . snmpv2-mode)
2558 ("\\.\\(diffs?\\|patch\\|rej\\)\\'" . diff-mode)
2559 ("\\.\\(dif\\|pat\\)\\'" . diff-mode) ; for MS-DOS
2560 ("\\.[eE]?[pP][sS]\\'" . ps-mode)
2561 ("\\.\\(?:PDF\\|DVI\\|OD[FGPST]\\|DOCX?\\|XLSX?\\|PPTX?\\|pdf\\|djvu\\|dvi\\|od[fgpst]\\|docx?\\|xlsx?\\|pptx?\\)\\'" . doc-view-mode-maybe)
2562 ("configure\\.\\(ac\\|in\\)\\'" . autoconf-mode)
2563 ("\\.s\\(v\\|iv\\|ieve\\)\\'" . sieve-mode)
2564 ("BROWSE\\'" . ebrowse-tree-mode)
2565 ("\\.ebrowse\\'" . ebrowse-tree-mode)
2566 ("#\\*mail\\*" . mail-mode)
2567 ("\\.g\\'" . antlr-mode)
2568 ("\\.mod\\'" . m2-mode)
2569 ("\\.ses\\'" . ses-mode)
2570 ("\\.docbook\\'" . sgml-mode)
2571 ("\\.com\\'" . dcl-mode)
2572 ("/config\\.\\(?:bat\\|log\\)\\'" . fundamental-mode)
2573 ;; Windows candidates may be opened case sensitively on Unix
2574 ("\\.\\(?:[iI][nN][iI]\\|[lL][sS][tT]\\|[rR][eE][gG]\\|[sS][yY][sS]\\)\\'" . conf-mode)
2575 ("\\.\\(?:desktop\\|la\\)\\'" . conf-unix-mode)
2576 ("\\.ppd\\'" . conf-ppd-mode)
2577 ("java.+\\.conf\\'" . conf-javaprop-mode)
2578 ("\\.properties\\(?:\\.[a-zA-Z0-9._-]+\\)?\\'" . conf-javaprop-mode)
2579 ("\\`/etc/\\(?:DIR_COLORS\\|ethers\\|.?fstab\\|.*hosts\\|lesskey\\|login\\.?de\\(?:fs\\|vperm\\)\\|magic\\|mtab\\|pam\\.d/.*\\|permissions\\(?:\\.d/.+\\)?\\|protocols\\|rpc\\|services\\)\\'" . conf-space-mode)
2580 ("\\`/etc/\\(?:acpid?/.+\\|aliases\\(?:\\.d/.+\\)?\\|default/.+\\|group-?\\|hosts\\..+\\|inittab\\|ksysguarddrc\\|opera6rc\\|passwd-?\\|shadow-?\\|sysconfig/.+\\)\\'" . conf-mode)
2581 ;; ChangeLog.old etc. Other change-log-mode entries are above;
2582 ;; this has lower priority to avoid matching changelog.sgml etc.
2583 ("[cC]hange[lL]og[-.][-0-9a-z]+\\'" . change-log-mode)
2584 ;; either user's dot-files or under /etc or some such
2585 ("/\\.?\\(?:gitconfig\\|gnokiirc\\|hgrc\\|kde.*rc\\|mime\\.types\\|wgetrc\\)\\'" . conf-mode)
2586 ;; alas not all ~/.*rc files are like this
2587 ("/\\.\\(?:enigma\\|gltron\\|gtk\\|hxplayer\\|net\\|neverball\\|qt/.+\\|realplayer\\|scummvm\\|sversion\\|sylpheed/.+\\|xmp\\)rc\\'" . conf-mode)
2588 ("/\\.\\(?:gdbtkinit\\|grip\\|orbital/.+txt\\|rhosts\\|tuxracer/options\\)\\'" . conf-mode)
2589 ("/\\.?X\\(?:default\\|resource\\|re\\)s\\>" . conf-xdefaults-mode)
2590 ("/X11.+app-defaults/\\|\\.ad\\'" . conf-xdefaults-mode)
2591 ("/X11.+locale/.+/Compose\\'" . conf-colon-mode)
2592 ;; this contains everything twice, with space and with colon :-(
2593 ("/X11.+locale/compose\\.dir\\'" . conf-javaprop-mode)
2594 ;; Get rid of any trailing .n.m and try again.
2595 ;; This is for files saved by cvs-merge that look like .#<file>.<rev>
2596 ;; or .#<file>.<rev>-<rev> or VC's <file>.~<rev>~.
2597 ;; Using mode nil rather than `ignore' would let the search continue
2598 ;; through this list (with the shortened name) rather than start over.
2599 ("\\.~?[0-9]+\\.[0-9][-.0-9]*~?\\'" nil t)
2600 ("\\.\\(?:orig\\|in\\|[bB][aA][kK]\\)\\'" nil t)
2601 ;; This should come after "in" stripping (e.g. config.h.in).
2602 ;; *.cf, *.cfg, *.conf, *.config[.local|.de_DE.UTF8|...], */config
2603 ("[/.]c\\(?:on\\)?f\\(?:i?g\\)?\\(?:\\.[a-zA-Z0-9._-]+\\)?\\'" . conf-mode-maybe)
2604 ;; The following should come after the ChangeLog pattern
2605 ;; for the sake of ChangeLog.1, etc.
2606 ;; and after the .scm.[0-9] and CVS' <file>.<rev> patterns too.
2607 ("\\.[1-9]\\'" . nroff-mode)))
2608 "Alist of filename patterns vs corresponding major mode functions.
2609 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
2610 \(NON-NIL stands for anything that is not nil; the value does not matter.)
2611 Visiting a file whose name matches REGEXP specifies FUNCTION as the
2612 mode function to use. FUNCTION will be called, unless it is nil.
2614 If the element has the form (REGEXP FUNCTION NON-NIL), then after
2615 calling FUNCTION (if it's not nil), we delete the suffix that matched
2616 REGEXP and search the list again for another match.
2618 The extensions whose FUNCTION is `archive-mode' should also
2619 appear in `auto-coding-alist' with `no-conversion' coding system.
2621 See also `interpreter-mode-alist', which detects executable script modes
2622 based on the interpreters they specify to run,
2623 and `magic-mode-alist', which determines modes based on file contents.")
2624 (put 'auto-mode-alist 'risky-local-variable t)
2626 (defun conf-mode-maybe ()
2627 "Select Conf mode or XML mode according to start of file."
2628 (if (save-excursion
2629 (save-restriction
2630 (widen)
2631 (goto-char (point-min))
2632 (looking-at "<\\?xml \\|<!-- \\|<!DOCTYPE ")))
2633 (xml-mode)
2634 (conf-mode)))
2636 (defvar interpreter-mode-alist
2637 ;; Note: The entries for the modes defined in cc-mode.el (awk-mode
2638 ;; and pike-mode) are added through autoload directives in that
2639 ;; file. That way is discouraged since it spreads out the
2640 ;; definition of the initial value.
2641 (mapcar
2642 (lambda (l)
2643 (cons (purecopy (car l)) (cdr l)))
2644 '(("\\(mini\\)?perl5?" . perl-mode)
2645 ("wishx?" . tcl-mode)
2646 ("tcl\\(sh\\)?" . tcl-mode)
2647 ("expect" . tcl-mode)
2648 ("octave" . octave-mode)
2649 ("scm" . scheme-mode)
2650 ("[acjkwz]sh" . sh-mode)
2651 ("r?bash2?" . sh-mode)
2652 ("dash" . sh-mode)
2653 ("mksh" . sh-mode)
2654 ("\\(dt\\|pd\\|w\\)ksh" . sh-mode)
2655 ("es" . sh-mode)
2656 ("i?tcsh" . sh-mode)
2657 ("oash" . sh-mode)
2658 ("rc" . sh-mode)
2659 ("rpm" . sh-mode)
2660 ("sh5?" . sh-mode)
2661 ("tail" . text-mode)
2662 ("more" . text-mode)
2663 ("less" . text-mode)
2664 ("pg" . text-mode)
2665 ("make" . makefile-gmake-mode) ; Debian uses this
2666 ("guile" . scheme-mode)
2667 ("clisp" . lisp-mode)
2668 ("emacs" . emacs-lisp-mode)))
2669 "Alist mapping interpreter names to major modes.
2670 This is used for files whose first lines match `auto-mode-interpreter-regexp'.
2671 Each element looks like (REGEXP . MODE).
2672 If REGEXP matches the entire name (minus any directory part) of
2673 the interpreter specified in the first line of a script, enable
2674 major mode MODE.
2676 See also `auto-mode-alist'.")
2678 (define-obsolete-variable-alias 'inhibit-first-line-modes-regexps
2679 'inhibit-file-local-variables-regexps "24.1")
2681 ;; TODO really this should be a list of modes (eg tar-mode), not regexps,
2682 ;; because we are duplicating info from auto-mode-alist.
2683 ;; TODO many elements of this list are also in auto-coding-alist.
2684 (defvar inhibit-local-variables-regexps
2685 (mapcar 'purecopy '("\\.tar\\'" "\\.t[bg]z\\'"
2686 "\\.arc\\'" "\\.zip\\'" "\\.lzh\\'" "\\.lha\\'"
2687 "\\.zoo\\'" "\\.[jew]ar\\'" "\\.xpi\\'" "\\.rar\\'"
2688 "\\.7z\\'"
2689 "\\.sx[dmicw]\\'" "\\.odt\\'"
2690 "\\.diff\\'" "\\.patch\\'"
2691 "\\.tiff?\\'" "\\.gif\\'" "\\.png\\'" "\\.jpe?g\\'"))
2692 "List of regexps matching file names in which to ignore local variables.
2693 This includes `-*-' lines as well as trailing \"Local Variables\" sections.
2694 Files matching this list are typically binary file formats.
2695 They may happen to contain sequences that look like local variable
2696 specifications, but are not really, or they may be containers for
2697 member files with their own local variable sections, which are
2698 not appropriate for the containing file.
2699 The function `inhibit-local-variables-p' uses this.")
2701 (define-obsolete-variable-alias 'inhibit-first-line-modes-suffixes
2702 'inhibit-local-variables-suffixes "24.1")
2704 (defvar inhibit-local-variables-suffixes nil
2705 "List of regexps matching suffixes to remove from file names.
2706 The function `inhibit-local-variables-p' uses this: when checking
2707 a file name, it first discards from the end of the name anything that
2708 matches one of these regexps.")
2710 ;; Can't think of any situation in which you'd want this to be nil...
2711 (defvar inhibit-local-variables-ignore-case t
2712 "Non-nil means `inhibit-local-variables-p' ignores case.")
2714 (defun inhibit-local-variables-p ()
2715 "Return non-nil if file local variables should be ignored.
2716 This checks the file (or buffer) name against `inhibit-local-variables-regexps'
2717 and `inhibit-local-variables-suffixes'. If
2718 `inhibit-local-variables-ignore-case' is non-nil, this ignores case."
2719 (let ((temp inhibit-local-variables-regexps)
2720 (name (if buffer-file-name
2721 (file-name-sans-versions buffer-file-name)
2722 (buffer-name)))
2723 (case-fold-search inhibit-local-variables-ignore-case))
2724 (while (let ((sufs inhibit-local-variables-suffixes))
2725 (while (and sufs (not (string-match (car sufs) name)))
2726 (setq sufs (cdr sufs)))
2727 sufs)
2728 (setq name (substring name 0 (match-beginning 0))))
2729 (while (and temp
2730 (not (string-match (car temp) name)))
2731 (setq temp (cdr temp)))
2732 temp))
2734 (defvar auto-mode-interpreter-regexp
2735 (purecopy "#![ \t]?\\([^ \t\n]*\
2736 /bin/env[ \t]\\)?\\([^ \t\n]+\\)")
2737 "Regexp matching interpreters, for file mode determination.
2738 This regular expression is matched against the first line of a file
2739 to determine the file's mode in `set-auto-mode'. If it matches, the file
2740 is assumed to be interpreted by the interpreter matched by the second group
2741 of the regular expression. The mode is then determined as the mode
2742 associated with that interpreter in `interpreter-mode-alist'.")
2744 (defvar magic-mode-alist nil
2745 "Alist of buffer beginnings vs. corresponding major mode functions.
2746 Each element looks like (REGEXP . FUNCTION) or (MATCH-FUNCTION . FUNCTION).
2747 After visiting a file, if REGEXP matches the text at the beginning of the
2748 buffer, or calling MATCH-FUNCTION returns non-nil, `normal-mode' will
2749 call FUNCTION rather than allowing `auto-mode-alist' to decide the buffer's
2750 major mode.
2752 If FUNCTION is nil, then it is not called. (That is a way of saying
2753 \"allow `auto-mode-alist' to decide for these files.\")")
2754 (put 'magic-mode-alist 'risky-local-variable t)
2756 (defvar magic-fallback-mode-alist
2757 (purecopy
2758 `((image-type-auto-detected-p . image-mode)
2759 ("\\(PK00\\)?[P]K\003\004" . archive-mode) ; zip
2760 ;; The < comes before the groups (but the first) to reduce backtracking.
2761 ;; TODO: UTF-16 <?xml may be preceded by a BOM 0xff 0xfe or 0xfe 0xff.
2762 ;; We use [ \t\r\n] instead of `\\s ' to make regex overflow less likely.
2763 (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
2764 (comment-re (concat "\\(?:!--" incomment-re "*-->[ \t\r\n]*<\\)")))
2765 (concat "\\(?:<\\?xml[ \t\r\n]+[^>]*>\\)?[ \t\r\n]*<"
2766 comment-re "*"
2767 "\\(?:!DOCTYPE[ \t\r\n]+[^>]*>[ \t\r\n]*<[ \t\r\n]*" comment-re "*\\)?"
2768 "[Hh][Tt][Mm][Ll]"))
2769 . html-mode)
2770 ("<!DOCTYPE[ \t\r\n]+[Hh][Tt][Mm][Ll]" . html-mode)
2771 ;; These two must come after html, because they are more general:
2772 ("<\\?xml " . xml-mode)
2773 (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
2774 (comment-re (concat "\\(?:!--" incomment-re "*-->[ \t\r\n]*<\\)")))
2775 (concat "[ \t\r\n]*<" comment-re "*!DOCTYPE "))
2776 . sgml-mode)
2777 ("%!PS" . ps-mode)
2778 ("# xmcd " . conf-unix-mode)))
2779 "Like `magic-mode-alist' but has lower priority than `auto-mode-alist'.
2780 Each element looks like (REGEXP . FUNCTION) or (MATCH-FUNCTION . FUNCTION).
2781 After visiting a file, if REGEXP matches the text at the beginning of the
2782 buffer, or calling MATCH-FUNCTION returns non-nil, `normal-mode' will
2783 call FUNCTION, provided that `magic-mode-alist' and `auto-mode-alist'
2784 have not specified a mode for this file.
2786 If FUNCTION is nil, then it is not called.")
2787 (put 'magic-fallback-mode-alist 'risky-local-variable t)
2789 (defvar magic-mode-regexp-match-limit 4000
2790 "Upper limit on `magic-mode-alist' regexp matches.
2791 Also applies to `magic-fallback-mode-alist'.")
2793 (defun set-auto-mode (&optional keep-mode-if-same)
2794 "Select major mode appropriate for current buffer.
2796 To find the right major mode, this function checks for a -*- mode tag
2797 checks for a `mode:' entry in the Local Variables section of the file,
2798 checks if it uses an interpreter listed in `interpreter-mode-alist',
2799 matches the buffer beginning against `magic-mode-alist',
2800 compares the filename against the entries in `auto-mode-alist',
2801 then matches the buffer beginning against `magic-fallback-mode-alist'.
2803 If `enable-local-variables' is nil, or if the file name matches
2804 `inhibit-local-variables-regexps', this function does not check
2805 for any mode: tag anywhere in the file. If `local-enable-local-variables'
2806 is nil, then the only mode: tag that can be relevant is a -*- one.
2808 If the optional argument KEEP-MODE-IF-SAME is non-nil, then we
2809 set the major mode only if that would change it. In other words
2810 we don't actually set it to the same mode the buffer already has."
2811 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
2812 (let ((try-locals (not (inhibit-local-variables-p)))
2813 end done mode modes)
2814 ;; Once we drop the deprecated feature where mode: is also allowed to
2815 ;; specify minor-modes (ie, there can be more than one "mode:"), we can
2816 ;; remove this section and just let (hack-local-variables t) handle it.
2817 ;; Find a -*- mode tag.
2818 (save-excursion
2819 (goto-char (point-min))
2820 (skip-chars-forward " \t\n")
2821 ;; Note by design local-enable-local-variables does not matter here.
2822 (and enable-local-variables
2823 try-locals
2824 (setq end (set-auto-mode-1))
2825 (if (save-excursion (search-forward ":" end t))
2826 ;; Find all specifications for the `mode:' variable
2827 ;; and execute them left to right.
2828 (while (let ((case-fold-search t))
2829 (or (and (looking-at "mode:")
2830 (goto-char (match-end 0)))
2831 (re-search-forward "[ \t;]mode:" end t)))
2832 (skip-chars-forward " \t")
2833 (let ((beg (point)))
2834 (if (search-forward ";" end t)
2835 (forward-char -1)
2836 (goto-char end))
2837 (skip-chars-backward " \t")
2838 (push (intern (concat (downcase (buffer-substring beg (point))) "-mode"))
2839 modes)))
2840 ;; Simple -*-MODE-*- case.
2841 (push (intern (concat (downcase (buffer-substring (point) end))
2842 "-mode"))
2843 modes))))
2844 ;; If we found modes to use, invoke them now, outside the save-excursion.
2845 (if modes
2846 (catch 'nop
2847 (dolist (mode (nreverse modes))
2848 (if (not (functionp mode))
2849 (message "Ignoring unknown mode `%s'" mode)
2850 (setq done t)
2851 (or (set-auto-mode-0 mode keep-mode-if-same)
2852 ;; continuing would call minor modes again, toggling them off
2853 (throw 'nop nil))))))
2854 ;; hack-local-variables checks local-enable-local-variables etc, but
2855 ;; we might as well be explicit here for the sake of clarity.
2856 (and (not done)
2857 enable-local-variables
2858 local-enable-local-variables
2859 try-locals
2860 (setq mode (hack-local-variables t))
2861 (not (memq mode modes)) ; already tried and failed
2862 (if (not (functionp mode))
2863 (message "Ignoring unknown mode `%s'" mode)
2864 (setq done t)
2865 (set-auto-mode-0 mode keep-mode-if-same)))
2866 ;; If we didn't, look for an interpreter specified in the first line.
2867 ;; As a special case, allow for things like "#!/bin/env perl", which
2868 ;; finds the interpreter anywhere in $PATH.
2869 (and (not done)
2870 (setq mode (save-excursion
2871 (goto-char (point-min))
2872 (if (looking-at auto-mode-interpreter-regexp)
2873 (match-string 2))))
2874 ;; Map interpreter name to a mode, signaling we're done at the
2875 ;; same time.
2876 (setq done (assoc-default
2877 (file-name-nondirectory mode)
2878 (mapcar (lambda (e)
2879 (cons
2880 (format "\\`%s\\'" (car e))
2881 (cdr e)))
2882 interpreter-mode-alist)
2883 #'string-match-p))
2884 ;; If we found an interpreter mode to use, invoke it now.
2885 (set-auto-mode-0 done keep-mode-if-same))
2886 ;; Next try matching the buffer beginning against magic-mode-alist.
2887 (unless done
2888 (if (setq done (save-excursion
2889 (goto-char (point-min))
2890 (save-restriction
2891 (narrow-to-region (point-min)
2892 (min (point-max)
2893 (+ (point-min) magic-mode-regexp-match-limit)))
2894 (assoc-default nil magic-mode-alist
2895 (lambda (re _dummy)
2896 (if (functionp re)
2897 (funcall re)
2898 (looking-at re)))))))
2899 (set-auto-mode-0 done keep-mode-if-same)))
2900 ;; Next compare the filename against the entries in auto-mode-alist.
2901 (unless done
2902 (if buffer-file-name
2903 (let ((name buffer-file-name)
2904 (remote-id (file-remote-p buffer-file-name))
2905 (case-insensitive-p (file-name-case-insensitive-p
2906 buffer-file-name)))
2907 ;; Remove backup-suffixes from file name.
2908 (setq name (file-name-sans-versions name))
2909 ;; Remove remote file name identification.
2910 (when (and (stringp remote-id)
2911 (string-match (regexp-quote remote-id) name))
2912 (setq name (substring name (match-end 0))))
2913 (while name
2914 ;; Find first matching alist entry.
2915 (setq mode
2916 (if case-insensitive-p
2917 ;; Filesystem is case-insensitive.
2918 (let ((case-fold-search t))
2919 (assoc-default name auto-mode-alist
2920 'string-match))
2921 ;; Filesystem is case-sensitive.
2923 ;; First match case-sensitively.
2924 (let ((case-fold-search nil))
2925 (assoc-default name auto-mode-alist
2926 'string-match))
2927 ;; Fallback to case-insensitive match.
2928 (and auto-mode-case-fold
2929 (let ((case-fold-search t))
2930 (assoc-default name auto-mode-alist
2931 'string-match))))))
2932 (if (and mode
2933 (consp mode)
2934 (cadr mode))
2935 (setq mode (car mode)
2936 name (substring name 0 (match-beginning 0)))
2937 (setq name nil))
2938 (when mode
2939 (set-auto-mode-0 mode keep-mode-if-same)
2940 (setq done t))))))
2941 ;; Next try matching the buffer beginning against magic-fallback-mode-alist.
2942 (unless done
2943 (if (setq done (save-excursion
2944 (goto-char (point-min))
2945 (save-restriction
2946 (narrow-to-region (point-min)
2947 (min (point-max)
2948 (+ (point-min) magic-mode-regexp-match-limit)))
2949 (assoc-default nil magic-fallback-mode-alist
2950 (lambda (re _dummy)
2951 (if (functionp re)
2952 (funcall re)
2953 (looking-at re)))))))
2954 (set-auto-mode-0 done keep-mode-if-same)))
2955 (unless done
2956 (set-buffer-major-mode (current-buffer)))))
2958 ;; When `keep-mode-if-same' is set, we are working on behalf of
2959 ;; set-visited-file-name. In that case, if the major mode specified is the
2960 ;; same one we already have, don't actually reset it. We don't want to lose
2961 ;; minor modes such as Font Lock.
2962 (defun set-auto-mode-0 (mode &optional keep-mode-if-same)
2963 "Apply MODE and return it.
2964 If optional arg KEEP-MODE-IF-SAME is non-nil, MODE is chased of
2965 any aliases and compared to current major mode. If they are the
2966 same, do nothing and return nil."
2967 (unless (and keep-mode-if-same
2968 (eq (indirect-function mode)
2969 (indirect-function major-mode)))
2970 (when mode
2971 (funcall mode)
2972 mode)))
2974 (defvar file-auto-mode-skip "^\\(#!\\|'\\\\\"\\)"
2975 "Regexp of lines to skip when looking for file-local settings.
2976 If the first line matches this regular expression, then the -*-...-*- file-
2977 local settings will be consulted on the second line instead of the first.")
2979 (defun set-auto-mode-1 ()
2980 "Find the -*- spec in the buffer.
2981 Call with point at the place to start searching from.
2982 If one is found, set point to the beginning and return the position
2983 of the end. Otherwise, return nil; may change point.
2984 The variable `inhibit-local-variables-regexps' can cause a -*- spec to
2985 be ignored; but `enable-local-variables' and `local-enable-local-variables'
2986 have no effect."
2987 (let (beg end)
2988 (and
2989 ;; Don't look for -*- if this file name matches any
2990 ;; of the regexps in inhibit-local-variables-regexps.
2991 (not (inhibit-local-variables-p))
2992 (search-forward "-*-" (line-end-position
2993 ;; If the file begins with "#!" (exec
2994 ;; interpreter magic), look for mode frobs
2995 ;; in the first two lines. You cannot
2996 ;; necessarily put them in the first line
2997 ;; of such a file without screwing up the
2998 ;; interpreter invocation. The same holds
2999 ;; for '\" in man pages (preprocessor
3000 ;; magic for the `man' program).
3001 (and (looking-at file-auto-mode-skip) 2)) t)
3002 (progn
3003 (skip-chars-forward " \t")
3004 (setq beg (point))
3005 (search-forward "-*-" (line-end-position) t))
3006 (progn
3007 (forward-char -3)
3008 (skip-chars-backward " \t")
3009 (setq end (point))
3010 (goto-char beg)
3011 end))))
3013 ;;; Handling file local variables
3015 (defvar ignored-local-variables
3016 '(ignored-local-variables safe-local-variable-values
3017 file-local-variables-alist dir-local-variables-alist)
3018 "Variables to be ignored in a file's local variable spec.")
3019 (put 'ignored-local-variables 'risky-local-variable t)
3021 (defvar hack-local-variables-hook nil
3022 "Normal hook run after processing a file's local variables specs.
3023 Major modes can use this to examine user-specified local variables
3024 in order to initialize other data structure based on them.")
3026 (defcustom safe-local-variable-values nil
3027 "List variable-value pairs that are considered safe.
3028 Each element is a cons cell (VAR . VAL), where VAR is a variable
3029 symbol and VAL is a value that is considered safe."
3030 :risky t
3031 :group 'find-file
3032 :type 'alist)
3034 (defcustom safe-local-eval-forms
3035 ;; This should be here at least as long as Emacs supports write-file-hooks.
3036 '((add-hook 'write-file-hooks 'time-stamp)
3037 (add-hook 'write-file-functions 'time-stamp)
3038 (add-hook 'before-save-hook 'time-stamp nil t)
3039 (add-hook 'before-save-hook 'delete-trailing-whitespace nil t))
3040 "Expressions that are considered safe in an `eval:' local variable.
3041 Add expressions to this list if you want Emacs to evaluate them, when
3042 they appear in an `eval' local variable specification, without first
3043 asking you for confirmation."
3044 :risky t
3045 :group 'find-file
3046 :version "24.1" ; added write-file-hooks
3047 :type '(repeat sexp))
3049 ;; Risky local variables:
3050 (mapc (lambda (var) (put var 'risky-local-variable t))
3051 '(after-load-alist
3052 buffer-auto-save-file-name
3053 buffer-file-name
3054 buffer-file-truename
3055 buffer-undo-list
3056 debugger
3057 default-text-properties
3058 eval
3059 exec-directory
3060 exec-path
3061 file-name-handler-alist
3062 frame-title-format
3063 global-mode-string
3064 header-line-format
3065 icon-title-format
3066 inhibit-quit
3067 load-path
3068 max-lisp-eval-depth
3069 max-specpdl-size
3070 minor-mode-map-alist
3071 minor-mode-overriding-map-alist
3072 mode-line-format
3073 mode-name
3074 overriding-local-map
3075 overriding-terminal-local-map
3076 process-environment
3077 standard-input
3078 standard-output
3079 unread-command-events))
3081 ;; Safe local variables:
3083 ;; For variables defined by major modes, the safety declarations can go into
3084 ;; the major mode's file, since that will be loaded before file variables are
3085 ;; processed.
3087 ;; For variables defined by minor modes, put the safety declarations in the
3088 ;; file defining the minor mode after the defcustom/defvar using an autoload
3089 ;; cookie, e.g.:
3091 ;; ;;;###autoload(put 'variable 'safe-local-variable 'stringp)
3093 ;; Otherwise, when Emacs visits a file specifying that local variable, the
3094 ;; minor mode file may not be loaded yet.
3096 ;; For variables defined in the C source code the declaration should go here:
3098 (dolist (pair
3099 '((buffer-read-only . booleanp) ;; C source code
3100 (default-directory . stringp) ;; C source code
3101 (fill-column . integerp) ;; C source code
3102 (indent-tabs-mode . booleanp) ;; C source code
3103 (left-margin . integerp) ;; C source code
3104 (no-update-autoloads . booleanp)
3105 (lexical-binding . booleanp) ;; C source code
3106 (tab-width . integerp) ;; C source code
3107 (truncate-lines . booleanp) ;; C source code
3108 (word-wrap . booleanp) ;; C source code
3109 (bidi-display-reordering . booleanp))) ;; C source code
3110 (put (car pair) 'safe-local-variable (cdr pair)))
3112 (put 'bidi-paragraph-direction 'safe-local-variable
3113 (lambda (v) (memq v '(nil right-to-left left-to-right))))
3115 (put 'c-set-style 'safe-local-eval-function t)
3117 (defvar file-local-variables-alist nil
3118 "Alist of file-local variable settings in the current buffer.
3119 Each element in this list has the form (VAR . VALUE), where VAR
3120 is a file-local variable (a symbol) and VALUE is the value
3121 specified. The actual value in the buffer may differ from VALUE,
3122 if it is changed by the major or minor modes, or by the user.")
3123 (make-variable-buffer-local 'file-local-variables-alist)
3124 (put 'file-local-variables-alist 'permanent-local t)
3126 (defvar dir-local-variables-alist nil
3127 "Alist of directory-local variable settings in the current buffer.
3128 Each element in this list has the form (VAR . VALUE), where VAR
3129 is a directory-local variable (a symbol) and VALUE is the value
3130 specified in .dir-locals.el. The actual value in the buffer
3131 may differ from VALUE, if it is changed by the major or minor modes,
3132 or by the user.")
3133 (make-variable-buffer-local 'dir-local-variables-alist)
3135 (defvar before-hack-local-variables-hook nil
3136 "Normal hook run before setting file-local variables.
3137 It is called after checking for unsafe/risky variables and
3138 setting `file-local-variables-alist', and before applying the
3139 variables stored in `file-local-variables-alist'. A hook
3140 function is allowed to change the contents of this alist.
3142 This hook is called only if there is at least one file-local
3143 variable to set.")
3145 (defun hack-local-variables-confirm (all-vars unsafe-vars risky-vars dir-name)
3146 "Get confirmation before setting up local variable values.
3147 ALL-VARS is the list of all variables to be set up.
3148 UNSAFE-VARS is the list of those that aren't marked as safe or risky.
3149 RISKY-VARS is the list of those that are marked as risky.
3150 If these settings come from directory-local variables, then
3151 DIR-NAME is the name of the associated directory. Otherwise it is nil."
3152 (unless noninteractive
3153 (let ((name (cond (dir-name)
3154 (buffer-file-name
3155 (file-name-nondirectory buffer-file-name))
3156 ((concat "buffer " (buffer-name)))))
3157 (offer-save (and (eq enable-local-variables t)
3158 unsafe-vars))
3159 (buf (get-buffer-create "*Local Variables*")))
3160 ;; Set up the contents of the *Local Variables* buffer.
3161 (with-current-buffer buf
3162 (erase-buffer)
3163 (cond
3164 (unsafe-vars
3165 (insert "The local variables list in " name
3166 "\ncontains values that may not be safe (*)"
3167 (if risky-vars
3168 ", and variables that are risky (**)."
3169 ".")))
3170 (risky-vars
3171 (insert "The local variables list in " name
3172 "\ncontains variables that are risky (**)."))
3174 (insert "A local variables list is specified in " name ".")))
3175 (insert "\n\nDo you want to apply it? You can type
3176 y -- to apply the local variables list.
3177 n -- to ignore the local variables list.")
3178 (if offer-save
3179 (insert "
3180 ! -- to apply the local variables list, and permanently mark these
3181 values (*) as safe (in the future, they will be set automatically.)\n\n")
3182 (insert "\n\n"))
3183 (dolist (elt all-vars)
3184 (cond ((member elt unsafe-vars)
3185 (insert " * "))
3186 ((member elt risky-vars)
3187 (insert " ** "))
3189 (insert " ")))
3190 (princ (car elt) buf)
3191 (insert " : ")
3192 ;; Make strings with embedded whitespace easier to read.
3193 (let ((print-escape-newlines t))
3194 (prin1 (cdr elt) buf))
3195 (insert "\n"))
3196 (set (make-local-variable 'cursor-type) nil)
3197 (set-buffer-modified-p nil)
3198 (goto-char (point-min)))
3200 ;; Display the buffer and read a choice.
3201 (save-window-excursion
3202 (pop-to-buffer buf)
3203 (let* ((exit-chars '(?y ?n ?\s ?\C-g ?\C-v))
3204 (prompt (format "Please type %s%s: "
3205 (if offer-save "y, n, or !" "y or n")
3206 (if (< (line-number-at-pos (point-max))
3207 (window-body-height))
3209 (push ?\C-v exit-chars)
3210 ", or C-v to scroll")))
3211 char)
3212 (if offer-save (push ?! exit-chars))
3213 (while (null char)
3214 (setq char (read-char-choice prompt exit-chars t))
3215 (when (eq char ?\C-v)
3216 (condition-case nil
3217 (scroll-up)
3218 (error (goto-char (point-min))
3219 (recenter 1)))
3220 (setq char nil)))
3221 (when (and offer-save (= char ?!) unsafe-vars)
3222 (customize-push-and-save 'safe-local-variable-values unsafe-vars))
3223 (prog1 (memq char '(?! ?\s ?y))
3224 (quit-window t)))))))
3226 (defconst hack-local-variable-regexp
3227 "[ \t]*\\([^][;\"'?()\\ \t\n]+\\)[ \t]*:[ \t]*")
3229 (defun hack-local-variables-prop-line (&optional handle-mode)
3230 "Return local variables specified in the -*- line.
3231 Usually returns an alist of elements (VAR . VAL), where VAR is a
3232 variable and VAL is the specified value. Ignores any
3233 specification for `coding:', and sometimes for `mode' (which
3234 should have already been handled by `set-auto-coding' and
3235 `set-auto-mode', respectively). Return nil if the -*- line is
3236 malformed.
3238 If HANDLE-MODE is nil, we return the alist of all the local
3239 variables in the line except `coding' as described above. If it
3240 is neither nil nor t, we do the same, except that any settings of
3241 `mode' and `coding' are ignored. If HANDLE-MODE is t, we ignore
3242 all settings in the line except for `mode', which \(if present) we
3243 return as the symbol specifying the mode."
3244 (catch 'malformed-line
3245 (save-excursion
3246 (goto-char (point-min))
3247 (let ((end (set-auto-mode-1))
3248 result)
3249 (cond ((not end)
3250 nil)
3251 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
3252 ;; Simple form: "-*- MODENAME -*-".
3253 (if (eq handle-mode t)
3254 (intern (concat (match-string 1) "-mode"))))
3256 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
3257 ;; (last ";" is optional).
3258 ;; If HANDLE-MODE is t, just check for `mode'.
3259 ;; Otherwise, parse the -*- line into the RESULT alist.
3260 (while (not (or (and (eq handle-mode t) result)
3261 (>= (point) end)))
3262 (unless (looking-at hack-local-variable-regexp)
3263 (message "Malformed mode-line: %S"
3264 (buffer-substring-no-properties (point) end))
3265 (throw 'malformed-line nil))
3266 (goto-char (match-end 0))
3267 ;; There used to be a downcase here,
3268 ;; but the manual didn't say so,
3269 ;; and people want to set var names that aren't all lc.
3270 (let* ((key (intern (match-string 1)))
3271 (val (save-restriction
3272 (narrow-to-region (point) end)
3273 (let ((read-circle nil))
3274 (read (current-buffer)))))
3275 ;; It is traditional to ignore
3276 ;; case when checking for `mode' in set-auto-mode,
3277 ;; so we must do that here as well.
3278 ;; That is inconsistent, but we're stuck with it.
3279 ;; The same can be said for `coding' in set-auto-coding.
3280 (keyname (downcase (symbol-name key))))
3281 (cond
3282 ((eq handle-mode t)
3283 (and (equal keyname "mode")
3284 (setq result
3285 (intern (concat (downcase (symbol-name val))
3286 "-mode")))))
3287 ((equal keyname "coding"))
3289 (when (or (not handle-mode)
3290 (not (equal keyname "mode")))
3291 (condition-case nil
3292 (push (cons (cond ((eq key 'eval) 'eval)
3293 ;; Downcase "Mode:".
3294 ((equal keyname "mode") 'mode)
3295 (t (indirect-variable key)))
3296 val)
3297 result)
3298 (error nil)))))
3299 (skip-chars-forward " \t;")))
3300 result))))))
3302 (defun hack-local-variables-filter (variables dir-name)
3303 "Filter local variable settings, querying the user if necessary.
3304 VARIABLES is the alist of variable-value settings. This alist is
3305 filtered based on the values of `ignored-local-variables',
3306 `enable-local-eval', `enable-local-variables', and (if necessary)
3307 user interaction. The results are added to
3308 `file-local-variables-alist', without applying them.
3309 If these settings come from directory-local variables, then
3310 DIR-NAME is the name of the associated directory. Otherwise it is nil."
3311 ;; Find those variables that we may want to save to
3312 ;; `safe-local-variable-values'.
3313 (let (all-vars risky-vars unsafe-vars)
3314 (dolist (elt variables)
3315 (let ((var (car elt))
3316 (val (cdr elt)))
3317 (cond ((memq var ignored-local-variables)
3318 ;; Ignore any variable in `ignored-local-variables'.
3319 nil)
3320 ;; Obey `enable-local-eval'.
3321 ((eq var 'eval)
3322 (when enable-local-eval
3323 (let ((safe (or (hack-one-local-variable-eval-safep val)
3324 ;; In case previously marked safe (bug#5636).
3325 (safe-local-variable-p var val))))
3326 ;; If not safe and e-l-v = :safe, ignore totally.
3327 (when (or safe (not (eq enable-local-variables :safe)))
3328 (push elt all-vars)
3329 (or (eq enable-local-eval t)
3330 safe
3331 (push elt unsafe-vars))))))
3332 ;; Ignore duplicates (except `mode') in the present list.
3333 ((and (assq var all-vars) (not (eq var 'mode))) nil)
3334 ;; Accept known-safe variables.
3335 ((or (memq var '(mode unibyte coding))
3336 (safe-local-variable-p var val))
3337 (push elt all-vars))
3338 ;; The variable is either risky or unsafe:
3339 ((not (eq enable-local-variables :safe))
3340 (push elt all-vars)
3341 (if (risky-local-variable-p var val)
3342 (push elt risky-vars)
3343 (push elt unsafe-vars))))))
3344 (and all-vars
3345 ;; Query, unless all vars are safe or user wants no querying.
3346 (or (and (eq enable-local-variables t)
3347 (null unsafe-vars)
3348 (null risky-vars))
3349 (memq enable-local-variables '(:all :safe))
3350 (hack-local-variables-confirm all-vars unsafe-vars
3351 risky-vars dir-name))
3352 (dolist (elt all-vars)
3353 (unless (memq (car elt) '(eval mode))
3354 (unless dir-name
3355 (setq dir-local-variables-alist
3356 (assq-delete-all (car elt) dir-local-variables-alist)))
3357 (setq file-local-variables-alist
3358 (assq-delete-all (car elt) file-local-variables-alist)))
3359 (push elt file-local-variables-alist)))))
3361 ;; TODO? Warn once per file rather than once per session?
3362 (defvar hack-local-variables--warned-lexical nil)
3364 (defun hack-local-variables (&optional handle-mode)
3365 "Parse and put into effect this buffer's local variables spec.
3366 Uses `hack-local-variables-apply' to apply the variables.
3368 If HANDLE-MODE is nil, we apply all the specified local
3369 variables. If HANDLE-MODE is neither nil nor t, we do the same,
3370 except that any settings of `mode' are ignored.
3372 If HANDLE-MODE is t, all we do is check whether a \"mode:\"
3373 is specified, and return the corresponding mode symbol, or nil.
3374 In this case, we try to ignore minor-modes, and only return a
3375 major-mode.
3377 If `enable-local-variables' or `local-enable-local-variables' is nil,
3378 this function does nothing. If `inhibit-local-variables-regexps'
3379 applies to the file in question, the file is not scanned for
3380 local variables, but directory-local variables may still be applied."
3381 ;; We don't let inhibit-local-variables-p influence the value of
3382 ;; enable-local-variables, because then it would affect dir-local
3383 ;; variables. We don't want to search eg tar files for file local
3384 ;; variable sections, but there is no reason dir-locals cannot apply
3385 ;; to them. The real meaning of inhibit-local-variables-p is "do
3386 ;; not scan this file for local variables".
3387 (let ((enable-local-variables
3388 (and local-enable-local-variables enable-local-variables))
3389 result)
3390 (unless (eq handle-mode t)
3391 (setq file-local-variables-alist nil)
3392 (with-demoted-errors "Directory-local variables error: %s"
3393 ;; Note this is a no-op if enable-local-variables is nil.
3394 (hack-dir-local-variables)))
3395 ;; This entire function is basically a no-op if enable-local-variables
3396 ;; is nil. All it does is set file-local-variables-alist to nil.
3397 (when enable-local-variables
3398 ;; This part used to ignore enable-local-variables when handle-mode
3399 ;; was t. That was inappropriate, eg consider the
3400 ;; (artificial) example of:
3401 ;; (setq local-enable-local-variables nil)
3402 ;; Open a file foo.txt that contains "mode: sh".
3403 ;; It correctly opens in text-mode.
3404 ;; M-x set-visited-file name foo.c, and it incorrectly stays in text-mode.
3405 (unless (or (inhibit-local-variables-p)
3406 ;; If HANDLE-MODE is t, and the prop line specifies a
3407 ;; mode, then we're done, and have no need to scan further.
3408 (and (setq result (hack-local-variables-prop-line
3409 handle-mode))
3410 (eq handle-mode t)))
3411 ;; Look for "Local variables:" line in last page.
3412 (save-excursion
3413 (goto-char (point-max))
3414 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min))
3415 'move)
3416 (when (let ((case-fold-search t))
3417 (search-forward "Local Variables:" nil t))
3418 (skip-chars-forward " \t")
3419 ;; suffix is what comes after "local variables:" in its line.
3420 ;; prefix is what comes before "local variables:" in its line.
3421 (let ((suffix
3422 (concat
3423 (regexp-quote (buffer-substring (point)
3424 (line-end-position)))
3425 "$"))
3426 (prefix
3427 (concat "^" (regexp-quote
3428 (buffer-substring (line-beginning-position)
3429 (match-beginning 0))))))
3431 (forward-line 1)
3432 (let ((startpos (point))
3433 endpos
3434 (thisbuf (current-buffer)))
3435 (save-excursion
3436 (unless (let ((case-fold-search t))
3437 (re-search-forward
3438 (concat prefix "[ \t]*End:[ \t]*" suffix)
3439 nil t))
3440 ;; This used to be an error, but really all it means is
3441 ;; that this may simply not be a local-variables section,
3442 ;; so just ignore it.
3443 (message "Local variables list is not properly terminated"))
3444 (beginning-of-line)
3445 (setq endpos (point)))
3447 (with-temp-buffer
3448 (insert-buffer-substring thisbuf startpos endpos)
3449 (goto-char (point-min))
3450 (subst-char-in-region (point) (point-max) ?\^m ?\n)
3451 (while (not (eobp))
3452 ;; Discard the prefix.
3453 (if (looking-at prefix)
3454 (delete-region (point) (match-end 0))
3455 (error "Local variables entry is missing the prefix"))
3456 (end-of-line)
3457 ;; Discard the suffix.
3458 (if (looking-back suffix (line-beginning-position))
3459 (delete-region (match-beginning 0) (point))
3460 (error "Local variables entry is missing the suffix"))
3461 (forward-line 1))
3462 (goto-char (point-min))
3464 (while (not (or (eobp)
3465 (and (eq handle-mode t) result)))
3466 ;; Find the variable name;
3467 (unless (looking-at hack-local-variable-regexp)
3468 (error "Malformed local variable line: %S"
3469 (buffer-substring-no-properties
3470 (point) (line-end-position))))
3471 (goto-char (match-end 1))
3472 (let* ((str (match-string 1))
3473 (var (intern str))
3474 val val2)
3475 (and (equal (downcase (symbol-name var)) "mode")
3476 (setq var 'mode))
3477 ;; Read the variable value.
3478 (skip-chars-forward "^:")
3479 (forward-char 1)
3480 (let ((read-circle nil))
3481 (setq val (read (current-buffer))))
3482 (if (eq handle-mode t)
3483 (and (eq var 'mode)
3484 ;; Specifying minor-modes via mode: is
3485 ;; deprecated, but try to reject them anyway.
3486 (not (string-match
3487 "-minor\\'"
3488 (setq val2 (downcase (symbol-name val)))))
3489 (setq result (intern (concat val2 "-mode"))))
3490 (cond ((eq var 'coding))
3491 ((eq var 'lexical-binding)
3492 (unless hack-local-variables--warned-lexical
3493 (setq hack-local-variables--warned-lexical t)
3494 (display-warning
3495 'files
3496 (format-message
3497 "%s: `lexical-binding' at end of file unreliable"
3498 (file-name-nondirectory
3499 ;; We are called from
3500 ;; 'with-temp-buffer', so we need
3501 ;; to use 'thisbuf's name in the
3502 ;; warning message.
3503 (or (buffer-file-name thisbuf) ""))))))
3504 ((and (eq var 'mode) handle-mode))
3506 (ignore-errors
3507 (push (cons (if (eq var 'eval)
3508 'eval
3509 (indirect-variable var))
3510 val) result))))))
3511 (forward-line 1))))))))
3512 ;; Now we've read all the local variables.
3513 ;; If HANDLE-MODE is t, return whether the mode was specified.
3514 (if (eq handle-mode t) result
3515 ;; Otherwise, set the variables.
3516 (hack-local-variables-filter result nil)
3517 (hack-local-variables-apply)))))
3519 (defun hack-local-variables-apply ()
3520 "Apply the elements of `file-local-variables-alist'.
3521 If there are any elements, runs `before-hack-local-variables-hook',
3522 then calls `hack-one-local-variable' to apply the alist elements one by one.
3523 Finishes by running `hack-local-variables-hook', regardless of whether
3524 the alist is empty or not.
3526 Note that this function ignores a `mode' entry if it specifies the same
3527 major mode as the buffer already has."
3528 (when file-local-variables-alist
3529 ;; Any 'evals must run in the Right sequence.
3530 (setq file-local-variables-alist
3531 (nreverse file-local-variables-alist))
3532 (run-hooks 'before-hack-local-variables-hook)
3533 (dolist (elt file-local-variables-alist)
3534 (hack-one-local-variable (car elt) (cdr elt))))
3535 (run-hooks 'hack-local-variables-hook))
3537 (defun safe-local-variable-p (sym val)
3538 "Non-nil if SYM is safe as a file-local variable with value VAL.
3539 It is safe if any of these conditions are met:
3541 * There is a matching entry (SYM . VAL) in the
3542 `safe-local-variable-values' user option.
3544 * The `safe-local-variable' property of SYM is a function that
3545 evaluates to a non-nil value with VAL as an argument."
3546 (or (member (cons sym val) safe-local-variable-values)
3547 (let ((safep (get sym 'safe-local-variable)))
3548 (and (functionp safep)
3549 ;; If the function signals an error, that means it
3550 ;; can't assure us that the value is safe.
3551 (with-demoted-errors (funcall safep val))))))
3553 (defun risky-local-variable-p (sym &optional _ignored)
3554 "Non-nil if SYM could be dangerous as a file-local variable.
3555 It is dangerous if either of these conditions are met:
3557 * Its `risky-local-variable' property is non-nil.
3559 * Its name ends with \"hook(s)\", \"function(s)\", \"form(s)\", \"map\",
3560 \"program\", \"command(s)\", \"predicate(s)\", \"frame-alist\",
3561 \"mode-alist\", \"font-lock-(syntactic-)keyword*\",
3562 \"map-alist\", or \"bindat-spec\"."
3563 ;; If this is an alias, check the base name.
3564 (condition-case nil
3565 (setq sym (indirect-variable sym))
3566 (error nil))
3567 (or (get sym 'risky-local-variable)
3568 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|\
3569 -commands?$\\|-predicates?$\\|font-lock-keywords$\\|font-lock-keywords\
3570 -[0-9]+$\\|font-lock-syntactic-keywords$\\|-frame-alist$\\|-mode-alist$\\|\
3571 -map$\\|-map-alist$\\|-bindat-spec$" (symbol-name sym))))
3573 (defun hack-one-local-variable-quotep (exp)
3574 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
3576 (defun hack-one-local-variable-constantp (exp)
3577 (or (and (not (symbolp exp)) (not (consp exp)))
3578 (memq exp '(t nil))
3579 (keywordp exp)
3580 (hack-one-local-variable-quotep exp)))
3582 (defun hack-one-local-variable-eval-safep (exp)
3583 "Return t if it is safe to eval EXP when it is found in a file."
3584 (or (not (consp exp))
3585 ;; Detect certain `put' expressions.
3586 (and (eq (car exp) 'put)
3587 (hack-one-local-variable-quotep (nth 1 exp))
3588 (hack-one-local-variable-quotep (nth 2 exp))
3589 (let ((prop (nth 1 (nth 2 exp)))
3590 (val (nth 3 exp)))
3591 (cond ((memq prop '(lisp-indent-hook
3592 lisp-indent-function
3593 scheme-indent-function))
3594 ;; Only allow safe values (not functions).
3595 (or (numberp val)
3596 (and (hack-one-local-variable-quotep val)
3597 (eq (nth 1 val) 'defun))))
3598 ((eq prop 'edebug-form-spec)
3599 ;; Only allow indirect form specs.
3600 ;; During bootstrapping, edebug-basic-spec might not be
3601 ;; defined yet.
3602 (and (fboundp 'edebug-basic-spec)
3603 (hack-one-local-variable-quotep val)
3604 (edebug-basic-spec (nth 1 val)))))))
3605 ;; Allow expressions that the user requested.
3606 (member exp safe-local-eval-forms)
3607 ;; Certain functions can be allowed with safe arguments
3608 ;; or can specify verification functions to try.
3609 (and (symbolp (car exp))
3610 ;; Allow (minor)-modes calls with no arguments.
3611 ;; This obsoletes the use of "mode:" for such things. (Bug#8613)
3612 (or (and (member (cdr exp) '(nil (1) (0) (-1)))
3613 (string-match "-mode\\'" (symbol-name (car exp))))
3614 (let ((prop (get (car exp) 'safe-local-eval-function)))
3615 (cond ((eq prop t)
3616 (let ((ok t))
3617 (dolist (arg (cdr exp))
3618 (unless (hack-one-local-variable-constantp arg)
3619 (setq ok nil)))
3620 ok))
3621 ((functionp prop)
3622 (funcall prop exp))
3623 ((listp prop)
3624 (let ((ok nil))
3625 (dolist (function prop)
3626 (if (funcall function exp)
3627 (setq ok t)))
3628 ok))))))))
3630 (defun hack-one-local-variable--obsolete (var)
3631 (let ((o (get var 'byte-obsolete-variable)))
3632 (when o
3633 (let ((instead (nth 0 o))
3634 (since (nth 2 o)))
3635 (message "%s is obsolete%s; %s"
3636 var (if since (format " (since %s)" since))
3637 (if (stringp instead)
3638 (substitute-command-keys instead)
3639 (format-message "use `%s' instead" instead)))))))
3641 (defun hack-one-local-variable (var val)
3642 "Set local variable VAR with value VAL.
3643 If VAR is `mode', call `VAL-mode' as a function unless it's
3644 already the major mode."
3645 (pcase var
3646 (`mode
3647 (let ((mode (intern (concat (downcase (symbol-name val))
3648 "-mode"))))
3649 (unless (eq (indirect-function mode)
3650 (indirect-function major-mode))
3651 (funcall mode))))
3652 (`eval
3653 (pcase val
3654 (`(add-hook ',hook . ,_) (hack-one-local-variable--obsolete hook)))
3655 (save-excursion (eval val)))
3657 (hack-one-local-variable--obsolete var)
3658 ;; Make sure the string has no text properties.
3659 ;; Some text properties can get evaluated in various ways,
3660 ;; so it is risky to put them on with a local variable list.
3661 (if (stringp val)
3662 (set-text-properties 0 (length val) nil val))
3663 (set (make-local-variable var) val))))
3665 ;;; Handling directory-local variables, aka project settings.
3667 (defvar dir-locals-class-alist '()
3668 "Alist mapping directory-local variable classes (symbols) to variable lists.")
3670 (defvar dir-locals-directory-cache '()
3671 "List of cached directory roots for directory-local variable classes.
3672 Each element in this list has the form (DIR CLASS MTIME).
3673 DIR is the name of the directory.
3674 CLASS is the name of a variable class (a symbol).
3675 MTIME is the recorded modification time of the directory-local
3676 variables file associated with this entry. This time is a list
3677 of integers (the same format as `file-attributes'), and is
3678 used to test whether the cache entry is still valid.
3679 Alternatively, MTIME can be nil, which means the entry is always
3680 considered valid.")
3682 (defsubst dir-locals-get-class-variables (class)
3683 "Return the variable list for CLASS."
3684 (cdr (assq class dir-locals-class-alist)))
3686 (defun dir-locals-collect-mode-variables (mode-variables variables)
3687 "Collect directory-local variables from MODE-VARIABLES.
3688 VARIABLES is the initial list of variables.
3689 Returns the new list."
3690 (dolist (pair mode-variables variables)
3691 (let* ((variable (car pair))
3692 (value (cdr pair))
3693 (slot (assq variable variables)))
3694 ;; If variables are specified more than once, only use the last. (Why?)
3695 ;; The pseudo-variables mode and eval are different (bug#3430).
3696 (if (and slot (not (memq variable '(mode eval))))
3697 (setcdr slot value)
3698 ;; Need a new cons in case we setcdr later.
3699 (push (cons variable value) variables)))))
3701 (defun dir-locals-collect-variables (class-variables root variables)
3702 "Collect entries from CLASS-VARIABLES into VARIABLES.
3703 ROOT is the root directory of the project.
3704 Return the new variables list."
3705 (let* ((file-name (or (buffer-file-name)
3706 ;; Handle non-file buffers, too.
3707 (expand-file-name default-directory)))
3708 (sub-file-name (if file-name
3709 ;; FIXME: Why not use file-relative-name?
3710 (substring file-name (length root)))))
3711 (condition-case err
3712 (dolist (entry class-variables variables)
3713 (let ((key (car entry)))
3714 (cond
3715 ((stringp key)
3716 ;; Don't include this in the previous condition, because we
3717 ;; want to filter all strings before the next condition.
3718 (when (and sub-file-name
3719 (>= (length sub-file-name) (length key))
3720 (string-prefix-p key sub-file-name))
3721 (setq variables (dir-locals-collect-variables
3722 (cdr entry) root variables))))
3723 ((or (not key)
3724 (derived-mode-p key))
3725 (let* ((alist (cdr entry))
3726 (subdirs (assq 'subdirs alist)))
3727 (if (or (not subdirs)
3728 (progn
3729 (setq alist (delq subdirs alist))
3730 (cdr-safe subdirs))
3731 ;; TODO someone might want to extend this to allow
3732 ;; integer values for subdir, where N means
3733 ;; variables apply to this directory and N levels
3734 ;; below it (0 == nil).
3735 (equal root default-directory))
3736 (setq variables (dir-locals-collect-mode-variables
3737 alist variables))))))))
3738 (error
3739 ;; The file's content might be invalid (e.g. have a merge conflict), but
3740 ;; that shouldn't prevent the user from opening the file.
3741 (message "%s error: %s" dir-locals-file (error-message-string err))
3742 nil))))
3744 (defun dir-locals-set-directory-class (directory class &optional mtime)
3745 "Declare that the DIRECTORY root is an instance of CLASS.
3746 DIRECTORY is the name of a directory, a string.
3747 CLASS is the name of a project class, a symbol.
3748 MTIME is either the modification time of the directory-local
3749 variables file that defined this class, or nil.
3751 When a file beneath DIRECTORY is visited, the mode-specific
3752 variables from CLASS are applied to the buffer. The variables
3753 for a class are defined using `dir-locals-set-class-variables'."
3754 (setq directory (file-name-as-directory (expand-file-name directory)))
3755 (unless (assq class dir-locals-class-alist)
3756 (error "No such class `%s'" (symbol-name class)))
3757 (push (list directory class mtime) dir-locals-directory-cache))
3759 (defun dir-locals-set-class-variables (class variables)
3760 "Map the type CLASS to a list of variable settings.
3761 CLASS is the project class, a symbol. VARIABLES is a list
3762 that declares directory-local variables for the class.
3763 An element in VARIABLES is either of the form:
3764 (MAJOR-MODE . ALIST)
3766 (DIRECTORY . LIST)
3768 In the first form, MAJOR-MODE is a symbol, and ALIST is an alist
3769 whose elements are of the form (VARIABLE . VALUE).
3771 In the second form, DIRECTORY is a directory name (a string), and
3772 LIST is a list of the form accepted by the function.
3774 When a file is visited, the file's class is found. A directory
3775 may be assigned a class using `dir-locals-set-directory-class'.
3776 Then variables are set in the file's buffer according to the
3777 VARIABLES list of the class. The list is processed in order.
3779 * If the element is of the form (MAJOR-MODE . ALIST), and the
3780 buffer's major mode is derived from MAJOR-MODE (as determined
3781 by `derived-mode-p'), then all the variables in ALIST are
3782 applied. A MAJOR-MODE of nil may be used to match any buffer.
3783 `make-local-variable' is called for each variable before it is
3784 set.
3786 * If the element is of the form (DIRECTORY . LIST), and DIRECTORY
3787 is an initial substring of the file's directory, then LIST is
3788 applied by recursively following these rules."
3789 (setf (alist-get class dir-locals-class-alist) variables))
3791 (defconst dir-locals-file ".dir-locals.el"
3792 "File that contains directory-local variables.
3793 It has to be constant to enforce uniform values across different
3794 environments and users.
3795 See also `dir-locals-file-2', whose values override this one's.
3796 See Info node `(elisp)Directory Local Variables' for details.")
3798 (defconst dir-locals-file-2 ".dir-locals-2.el"
3799 "File that contains directory-local variables.
3800 This essentially a second file that can be used like
3801 `dir-locals-file', so that users can have specify their personal
3802 dir-local variables even if the current directory already has a
3803 `dir-locals-file' that is shared with other users (such as in a
3804 git repository).
3805 See Info node `(elisp)Directory Local Variables' for details.")
3807 (defun dir-locals--all-files (directory)
3808 "Return a list of all readable dir-locals files in DIRECTORY.
3809 The returned list is sorted by increasing priority. That is,
3810 values specified in the last file should take precedence over
3811 those in the first."
3812 (when (file-readable-p directory)
3813 (let* ((file-1 (expand-file-name (if (eq system-type 'ms-dos)
3814 (dosified-file-name dir-locals-file)
3815 dir-locals-file)
3816 directory))
3817 (file-2 (when (string-match "\\.el\\'" file-1)
3818 (replace-match "-2.el" t nil file-1)))
3819 (out nil))
3820 ;; The order here is important.
3821 (dolist (f (list file-2 file-1))
3822 (when (and f
3823 (file-readable-p f)
3824 (file-regular-p f)
3825 (not (file-directory-p f)))
3826 (push f out)))
3827 out)))
3829 (defun dir-locals-find-file (file)
3830 "Find the directory-local variables for FILE.
3831 This searches upward in the directory tree from FILE.
3832 It stops at the first directory that has been registered in
3833 `dir-locals-directory-cache' or contains a `dir-locals-file'.
3834 If it finds an entry in the cache, it checks that it is valid.
3835 A cache entry with no modification time element (normally, one that
3836 has been assigned directly using `dir-locals-set-directory-class', not
3837 set from a file) is always valid.
3838 A cache entry based on a `dir-locals-file' is valid if the modification
3839 time stored in the cache matches the current file modification time.
3840 If not, the cache entry is cleared so that the file will be re-read.
3842 This function returns either:
3843 - nil (no directory local variables found),
3844 - the matching entry from `dir-locals-directory-cache' (a list),
3845 - or the full path to the directory (a string) containing at
3846 least one `dir-locals-file' in the case of no valid cache
3847 entry."
3848 (setq file (expand-file-name file))
3849 (let* ((locals-dir (locate-dominating-file (file-name-directory file)
3850 #'dir-locals--all-files))
3851 dir-elt)
3852 ;; `locate-dominating-file' may have abbreviated the name.
3853 (when locals-dir
3854 (setq locals-dir (expand-file-name locals-dir)))
3855 ;; Find the best cached value in `dir-locals-directory-cache'.
3856 (dolist (elt dir-locals-directory-cache)
3857 (when (and (string-prefix-p (car elt) file
3858 (memq system-type
3859 '(windows-nt cygwin ms-dos)))
3860 (> (length (car elt)) (length (car dir-elt))))
3861 (setq dir-elt elt)))
3862 (if (and dir-elt
3863 (or (null locals-dir)
3864 (<= (length locals-dir)
3865 (length (car dir-elt)))))
3866 ;; Found a potential cache entry. Check validity.
3867 ;; A cache entry with no MTIME is assumed to always be valid
3868 ;; (ie, set directly, not from a dir-locals file).
3869 ;; Note, we don't bother to check that there is a matching class
3870 ;; element in dir-locals-class-alist, since that's done by
3871 ;; dir-locals-set-directory-class.
3872 (if (or (null (nth 2 dir-elt))
3873 (let ((cached-files (dir-locals--all-files (car dir-elt))))
3874 ;; The entry MTIME should match the most recent
3875 ;; MTIME among matching files.
3876 (and cached-files
3877 (= (float-time (nth 2 dir-elt))
3878 (apply #'max (mapcar (lambda (f)
3879 (float-time
3880 (nth 5 (file-attributes f))))
3881 cached-files))))))
3882 ;; This cache entry is OK.
3883 dir-elt
3884 ;; This cache entry is invalid; clear it.
3885 (setq dir-locals-directory-cache
3886 (delq dir-elt dir-locals-directory-cache))
3887 ;; Return the first existing dir-locals file. Might be the same
3888 ;; as dir-elt's, might not (eg latter might have been deleted).
3889 locals-dir)
3890 ;; No cache entry.
3891 locals-dir)))
3893 (defun dir-locals-read-from-dir (dir)
3894 "Load all variables files in DIR and register a new class and instance.
3895 DIR is the absolute name of a directory which must contain at
3896 least one dir-local file (which is a file holding variables to
3897 apply).
3898 Return the new class name, which is a symbol named DIR."
3899 (require 'map)
3900 (let* ((class-name (intern dir))
3901 (files (dir-locals--all-files dir))
3902 (read-circle nil)
3903 (success nil)
3904 (variables))
3905 (with-demoted-errors "Error reading dir-locals: %S"
3906 (dolist (file files)
3907 (with-temp-buffer
3908 (insert-file-contents file)
3909 (condition-case-unless-debug nil
3910 (setq variables
3911 (map-merge-with 'list (lambda (a b) (map-merge 'list a b))
3912 variables
3913 (read (current-buffer))))
3914 (end-of-file nil))))
3915 (setq success t))
3916 (dir-locals-set-class-variables class-name variables)
3917 (dir-locals-set-directory-class
3918 dir class-name
3919 (seconds-to-time
3920 (if success
3921 (apply #'max (mapcar (lambda (file)
3922 (float-time (nth 5 (file-attributes file))))
3923 files))
3924 ;; If there was a problem, use the values we could get but
3925 ;; don't let the cache prevent future reads.
3926 0)))
3927 class-name))
3929 (define-obsolete-function-alias 'dir-locals-read-from-file
3930 'dir-locals-read-from-dir "25.1")
3932 (defcustom enable-remote-dir-locals nil
3933 "Non-nil means dir-local variables will be applied to remote files."
3934 :version "24.3"
3935 :type 'boolean
3936 :group 'find-file)
3938 (defvar hack-dir-local-variables--warned-coding nil)
3940 (defun hack-dir-local-variables ()
3941 "Read per-directory local variables for the current buffer.
3942 Store the directory-local variables in `dir-local-variables-alist'
3943 and `file-local-variables-alist', without applying them.
3945 This does nothing if either `enable-local-variables' or
3946 `enable-dir-local-variables' are nil."
3947 (when (and enable-local-variables
3948 enable-dir-local-variables
3949 (or enable-remote-dir-locals
3950 (not (file-remote-p (or (buffer-file-name)
3951 default-directory)))))
3952 ;; Find the variables file.
3953 (let ((dir-or-cache (dir-locals-find-file
3954 (or (buffer-file-name) default-directory)))
3955 (class nil)
3956 (dir-name nil))
3957 (cond
3958 ((stringp dir-or-cache)
3959 (setq dir-name dir-or-cache
3960 class (dir-locals-read-from-dir dir-or-cache)))
3961 ((consp dir-or-cache)
3962 (setq dir-name (nth 0 dir-or-cache))
3963 (setq class (nth 1 dir-or-cache))))
3964 (when class
3965 (let ((variables
3966 (dir-locals-collect-variables
3967 (dir-locals-get-class-variables class) dir-name nil)))
3968 (when variables
3969 (dolist (elt variables)
3970 (if (eq (car elt) 'coding)
3971 (unless hack-dir-local-variables--warned-coding
3972 (setq hack-dir-local-variables--warned-coding t)
3973 (display-warning 'files
3974 "Coding cannot be specified by dir-locals"))
3975 (unless (memq (car elt) '(eval mode))
3976 (setq dir-local-variables-alist
3977 (assq-delete-all (car elt) dir-local-variables-alist)))
3978 (push elt dir-local-variables-alist)))
3979 (hack-local-variables-filter variables dir-name)))))))
3981 (defun hack-dir-local-variables-non-file-buffer ()
3982 "Apply directory-local variables to a non-file buffer.
3983 For non-file buffers, such as Dired buffers, directory-local
3984 variables are looked for in `default-directory' and its parent
3985 directories."
3986 (hack-dir-local-variables)
3987 (hack-local-variables-apply))
3990 (defcustom change-major-mode-with-file-name t
3991 "Non-nil means \\[write-file] should set the major mode from the file name.
3992 However, the mode will not be changed if
3993 \(1) a local variables list or the `-*-' line specifies a major mode, or
3994 \(2) the current major mode is a \"special\" mode,
3995 not suitable for ordinary files, or
3996 \(3) the new file name does not particularly specify any mode."
3997 :type 'boolean
3998 :group 'editing-basics)
4000 (defun set-visited-file-name (filename &optional no-query along-with-file)
4001 "Change name of file visited in current buffer to FILENAME.
4002 This also renames the buffer to correspond to the new file.
4003 The next time the buffer is saved it will go in the newly specified file.
4004 FILENAME nil or an empty string means mark buffer as not visiting any file.
4005 Remember to delete the initial contents of the minibuffer
4006 if you wish to pass an empty string as the argument.
4008 The optional second argument NO-QUERY, if non-nil, inhibits asking for
4009 confirmation in the case where another buffer is already visiting FILENAME.
4011 The optional third argument ALONG-WITH-FILE, if non-nil, means that
4012 the old visited file has been renamed to the new name FILENAME."
4013 (interactive "FSet visited file name: ")
4014 (if (buffer-base-buffer)
4015 (error "An indirect buffer cannot visit a file"))
4016 (let (truename old-try-locals)
4017 (if filename
4018 (setq filename
4019 (if (string-equal filename "")
4021 (expand-file-name filename))))
4022 (if filename
4023 (progn
4024 (setq truename (file-truename filename))
4025 (if find-file-visit-truename
4026 (setq filename truename))))
4027 (if filename
4028 (let ((new-name (file-name-nondirectory filename)))
4029 (if (string= new-name "")
4030 (error "Empty file name"))))
4031 (let ((buffer (and filename (find-buffer-visiting filename))))
4032 (and buffer (not (eq buffer (current-buffer)))
4033 (not no-query)
4034 (not (y-or-n-p (format "A buffer is visiting %s; proceed? "
4035 filename)))
4036 (user-error "Aborted")))
4037 (or (equal filename buffer-file-name)
4038 (progn
4039 (and filename (lock-buffer filename))
4040 (unlock-buffer)))
4041 (setq old-try-locals (not (inhibit-local-variables-p))
4042 buffer-file-name filename)
4043 (if filename ; make buffer name reflect filename.
4044 (let ((new-name (file-name-nondirectory buffer-file-name)))
4045 (setq default-directory (file-name-directory buffer-file-name))
4046 ;; If new-name == old-name, renaming would add a spurious <2>
4047 ;; and it's considered as a feature in rename-buffer.
4048 (or (string= new-name (buffer-name))
4049 (rename-buffer new-name t))))
4050 (setq buffer-backed-up nil)
4051 (or along-with-file
4052 (clear-visited-file-modtime))
4053 ;; Abbreviate the file names of the buffer.
4054 (if truename
4055 (progn
4056 (setq buffer-file-truename (abbreviate-file-name truename))
4057 (if find-file-visit-truename
4058 (setq buffer-file-name truename))))
4059 (setq buffer-file-number
4060 (if filename
4061 (nthcdr 10 (file-attributes buffer-file-name))
4062 nil))
4063 ;; write-file-functions is normally used for things like ftp-find-file
4064 ;; that visit things that are not local files as if they were files.
4065 ;; Changing to visit an ordinary local file instead should flush the hook.
4066 (kill-local-variable 'write-file-functions)
4067 (kill-local-variable 'local-write-file-hooks)
4068 (kill-local-variable 'revert-buffer-function)
4069 (kill-local-variable 'backup-inhibited)
4070 ;; If buffer was read-only because of version control,
4071 ;; that reason is gone now, so make it writable.
4072 (if vc-mode
4073 (setq buffer-read-only nil))
4074 (kill-local-variable 'vc-mode)
4075 ;; Turn off backup files for certain file names.
4076 ;; Since this is a permanent local, the major mode won't eliminate it.
4077 (and buffer-file-name
4078 backup-enable-predicate
4079 (not (funcall backup-enable-predicate buffer-file-name))
4080 (progn
4081 (make-local-variable 'backup-inhibited)
4082 (setq backup-inhibited t)))
4083 (let ((oauto buffer-auto-save-file-name))
4084 (cond ((null filename)
4085 (setq buffer-auto-save-file-name nil))
4086 ((not buffer-auto-save-file-name)
4087 ;; If auto-save was not already on, turn it on if appropriate.
4088 (and buffer-file-name auto-save-default (auto-save-mode t)))
4090 ;; If auto save is on, start using a new name. We
4091 ;; deliberately don't rename or delete the old auto save
4092 ;; for the old visited file name. This is because
4093 ;; perhaps the user wants to save the new state and then
4094 ;; compare with the previous state from the auto save
4095 ;; file.
4096 (setq buffer-auto-save-file-name (make-auto-save-file-name))))
4097 ;; Rename the old auto save file if any.
4098 (and oauto buffer-auto-save-file-name
4099 (file-exists-p oauto)
4100 (rename-file oauto buffer-auto-save-file-name t)))
4101 (and buffer-file-name
4102 (not along-with-file)
4103 (set-buffer-modified-p t))
4104 ;; Update the major mode, if the file name determines it.
4105 (condition-case nil
4106 ;; Don't change the mode if it is special.
4107 (or (not change-major-mode-with-file-name)
4108 (get major-mode 'mode-class)
4109 ;; Don't change the mode if the local variable list specifies it.
4110 ;; The file name can influence whether the local variables apply.
4111 (and old-try-locals
4112 ;; h-l-v also checks it, but might as well be explicit.
4113 (not (inhibit-local-variables-p))
4114 (hack-local-variables t))
4115 ;; TODO consider making normal-mode handle this case.
4116 (let ((old major-mode))
4117 (set-auto-mode t)
4118 (or (eq old major-mode)
4119 (hack-local-variables))))
4120 (error nil))))
4122 (defun write-file (filename &optional confirm)
4123 "Write current buffer into file FILENAME.
4124 This makes the buffer visit that file, and marks it as not modified.
4126 If you specify just a directory name as FILENAME, that means to use
4127 the default file name but in that directory. You can also yank
4128 the default file name into the minibuffer to edit it, using \\<minibuffer-local-map>\\[next-history-element].
4130 If the buffer is not already visiting a file, the default file name
4131 for the output file is the buffer name.
4133 If optional second arg CONFIRM is non-nil, this function
4134 asks for confirmation before overwriting an existing file.
4135 Interactively, confirmation is required unless you supply a prefix argument."
4136 ;; (interactive "FWrite file: ")
4137 (interactive
4138 (list (if buffer-file-name
4139 (read-file-name "Write file: "
4140 nil nil nil nil)
4141 (read-file-name "Write file: " default-directory
4142 (expand-file-name
4143 (file-name-nondirectory (buffer-name))
4144 default-directory)
4145 nil nil))
4146 (not current-prefix-arg)))
4147 (or (null filename) (string-equal filename "")
4148 (progn
4149 ;; If arg is just a directory,
4150 ;; use the default file name, but in that directory.
4151 (if (file-directory-p filename)
4152 (setq filename (concat (file-name-as-directory filename)
4153 (file-name-nondirectory
4154 (or buffer-file-name (buffer-name))))))
4155 (and confirm
4156 (file-exists-p filename)
4157 ;; NS does its own confirm dialog.
4158 (not (and (eq (framep-on-display) 'ns)
4159 (listp last-nonmenu-event)
4160 use-dialog-box))
4161 (or (y-or-n-p (format-message
4162 "File `%s' exists; overwrite? " filename))
4163 (user-error "Canceled")))
4164 (set-visited-file-name filename (not confirm))))
4165 (set-buffer-modified-p t)
4166 ;; Make buffer writable if file is writable.
4167 (and buffer-file-name
4168 (file-writable-p buffer-file-name)
4169 (setq buffer-read-only nil))
4170 (save-buffer)
4171 ;; It's likely that the VC status at the new location is different from
4172 ;; the one at the old location.
4173 (vc-refresh-state))
4175 (defun file-extended-attributes (filename)
4176 "Return an alist of extended attributes of file FILENAME.
4178 Extended attributes are platform-specific metadata about the file,
4179 such as SELinux context, list of ACL entries, etc."
4180 `((acl . ,(file-acl filename))
4181 (selinux-context . ,(file-selinux-context filename))))
4183 (defun set-file-extended-attributes (filename attributes)
4184 "Set extended attributes of file FILENAME to ATTRIBUTES.
4186 ATTRIBUTES must be an alist of file attributes as returned by
4187 `file-extended-attributes'.
4188 Value is t if the function succeeds in setting the attributes."
4189 (let (result rv)
4190 (dolist (elt attributes)
4191 (let ((attr (car elt))
4192 (val (cdr elt)))
4193 (cond ((eq attr 'acl)
4194 (setq rv (set-file-acl filename val)))
4195 ((eq attr 'selinux-context)
4196 (setq rv (set-file-selinux-context filename val))))
4197 (setq result (or result rv))))
4199 result))
4201 (defun backup-buffer ()
4202 "Make a backup of the disk file visited by the current buffer, if appropriate.
4203 This is normally done before saving the buffer the first time.
4205 A backup may be done by renaming or by copying; see documentation of
4206 variable `make-backup-files'. If it's done by renaming, then the file is
4207 no longer accessible under its old name.
4209 The value is non-nil after a backup was made by renaming.
4210 It has the form (MODES EXTENDED-ATTRIBUTES BACKUPNAME).
4211 MODES is the result of `file-modes' on the original
4212 file; this means that the caller, after saving the buffer, should change
4213 the modes of the new file to agree with the old modes.
4214 EXTENDED-ATTRIBUTES is the result of `file-extended-attributes'
4215 on the original file; this means that the caller, after saving
4216 the buffer, should change the extended attributes of the new file
4217 to agree with the old attributes.
4218 BACKUPNAME is the backup file name, which is the old file renamed."
4219 (when (and make-backup-files (not backup-inhibited) (not buffer-backed-up))
4220 (let ((attributes (file-attributes buffer-file-name)))
4221 (when (and attributes (memq (aref (elt attributes 8) 0) '(?- ?l)))
4222 ;; If specified name is a symbolic link, chase it to the target.
4223 ;; This makes backups in the directory where the real file is.
4224 (let* ((real-file-name (file-chase-links buffer-file-name))
4225 (backup-info (find-backup-file-name real-file-name)))
4226 (when backup-info
4227 (let* ((backupname (car backup-info))
4228 (targets (cdr backup-info))
4229 (old-versions
4230 ;; If have old versions to maybe delete,
4231 ;; ask the user to confirm now, before doing anything.
4232 ;; But don't actually delete til later.
4233 (and targets
4234 (booleanp delete-old-versions)
4235 (or delete-old-versions
4236 (y-or-n-p
4237 (format "Delete excess backup versions of %s? "
4238 real-file-name)))
4239 targets))
4240 (modes (file-modes buffer-file-name))
4241 (extended-attributes
4242 (file-extended-attributes buffer-file-name))
4243 (copy-when-priv-mismatch
4244 backup-by-copying-when-privileged-mismatch)
4245 (make-copy
4246 (or file-precious-flag backup-by-copying
4247 ;; Don't rename a suid or sgid file.
4248 (and modes (< 0 (logand modes #o6000)))
4249 (not (file-writable-p
4250 (file-name-directory real-file-name)))
4251 (and backup-by-copying-when-linked
4252 (< 1 (file-nlinks real-file-name)))
4253 (and (or backup-by-copying-when-mismatch
4254 (and (integerp copy-when-priv-mismatch)
4255 (let ((attr (file-attributes
4256 real-file-name
4257 'integer)))
4258 (<= (nth 2 attr)
4259 copy-when-priv-mismatch))))
4260 (not (file-ownership-preserved-p real-file-name
4261 t)))))
4262 setmodes)
4263 (condition-case ()
4264 (progn
4265 ;; Actually make the backup file.
4266 (if make-copy
4267 (backup-buffer-copy real-file-name backupname
4268 modes extended-attributes)
4269 ;; rename-file should delete old backup.
4270 (rename-file real-file-name backupname t)
4271 (setq setmodes (list modes extended-attributes
4272 backupname)))
4273 (setq buffer-backed-up t)
4274 ;; Now delete the old versions, if desired.
4275 (dolist (old-version old-versions)
4276 (delete-file old-version)))
4277 (file-error nil))
4278 ;; If trouble writing the backup, write it in .emacs.d/%backup%.
4279 (when (not buffer-backed-up)
4280 (setq backupname (locate-user-emacs-file "%backup%~"))
4281 (message "Cannot write backup file; backing up in %s"
4282 backupname)
4283 (sleep-for 1)
4284 (backup-buffer-copy real-file-name backupname
4285 modes extended-attributes)
4286 (setq buffer-backed-up t))
4287 setmodes)))))))
4289 (defun backup-buffer-copy (from-name to-name modes extended-attributes)
4290 ;; Create temp files with strict access rights. It's easy to
4291 ;; loosen them later, whereas it's impossible to close the
4292 ;; time-window of loose permissions otherwise.
4293 (with-file-modes ?\700
4294 (when (condition-case nil
4295 ;; Try to overwrite old backup first.
4296 (copy-file from-name to-name t t t)
4297 (error t))
4298 (while (condition-case nil
4299 (progn
4300 (when (file-exists-p to-name)
4301 (delete-file to-name))
4302 (copy-file from-name to-name nil t t)
4303 nil)
4304 (file-already-exists t))
4305 ;; The file was somehow created by someone else between
4306 ;; `delete-file' and `copy-file', so let's try again.
4307 ;; rms says "I think there is also a possible race
4308 ;; condition for making backup files" (emacs-devel 20070821).
4309 nil)))
4310 ;; If set-file-extended-attributes fails, fall back on set-file-modes.
4311 (unless (and extended-attributes
4312 (with-demoted-errors
4313 (set-file-extended-attributes to-name extended-attributes)))
4314 (and modes
4315 (set-file-modes to-name (logand modes #o1777)))))
4317 (defvar file-name-version-regexp
4318 "\\(?:~\\|\\.~[-[:alnum:]:#@^._]+\\(?:~[[:digit:]]+\\)?~\\)"
4319 ;; The last ~[[:digit]]+ matches relative versions in git,
4320 ;; e.g. `foo.js.~HEAD~1~'.
4321 "Regular expression matching the backup/version part of a file name.
4322 Used by `file-name-sans-versions'.")
4324 (defun file-name-sans-versions (name &optional keep-backup-version)
4325 "Return file NAME sans backup versions or strings.
4326 This is a separate procedure so your site-init or startup file can
4327 redefine it.
4328 If the optional argument KEEP-BACKUP-VERSION is non-nil,
4329 we do not remove backup version numbers, only true file version numbers.
4330 See also `file-name-version-regexp'."
4331 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
4332 (if handler
4333 (funcall handler 'file-name-sans-versions name keep-backup-version)
4334 (substring name 0
4335 (unless keep-backup-version
4336 (string-match (concat file-name-version-regexp "\\'")
4337 name))))))
4339 (defun file-ownership-preserved-p (file &optional group)
4340 "Return t if deleting FILE and rewriting it would preserve the owner.
4341 Return also t if FILE does not exist. If GROUP is non-nil, check whether
4342 the group would be preserved too."
4343 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
4344 (if handler
4345 (funcall handler 'file-ownership-preserved-p file group)
4346 (let ((attributes (file-attributes file 'integer)))
4347 ;; Return t if the file doesn't exist, since it's true that no
4348 ;; information would be lost by an (attempted) delete and create.
4349 (or (null attributes)
4350 (and (or (= (nth 2 attributes) (user-uid))
4351 ;; Files created on Windows by Administrator (RID=500)
4352 ;; have the Administrators group (RID=544) recorded as
4353 ;; their owner. Rewriting them will still preserve the
4354 ;; owner.
4355 (and (eq system-type 'windows-nt)
4356 (= (user-uid) 500) (= (nth 2 attributes) 544)))
4357 (or (not group)
4358 ;; On BSD-derived systems files always inherit the parent
4359 ;; directory's group, so skip the group-gid test.
4360 (memq system-type '(berkeley-unix darwin gnu/kfreebsd))
4361 (= (nth 3 attributes) (group-gid)))
4362 (let* ((parent (or (file-name-directory file) "."))
4363 (parent-attributes (file-attributes parent 'integer)))
4364 (and parent-attributes
4365 ;; On some systems, a file created in a setuid directory
4366 ;; inherits that directory's owner.
4368 (= (nth 2 parent-attributes) (user-uid))
4369 (string-match "^...[^sS]" (nth 8 parent-attributes)))
4370 ;; On many systems, a file created in a setgid directory
4371 ;; inherits that directory's group. On some systems
4372 ;; this happens even if the setgid bit is not set.
4373 (or (not group)
4374 (= (nth 3 parent-attributes)
4375 (nth 3 attributes)))))))))))
4377 (defun file-name-sans-extension (filename)
4378 "Return FILENAME sans final \"extension\".
4379 The extension, in a file name, is the part that begins with the last `.',
4380 except that a leading `.' of the file name, if there is one, doesn't count."
4381 (save-match-data
4382 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
4383 directory)
4384 (if (and (string-match "\\.[^.]*\\'" file)
4385 (not (eq 0 (match-beginning 0))))
4386 (if (setq directory (file-name-directory filename))
4387 ;; Don't use expand-file-name here; if DIRECTORY is relative,
4388 ;; we don't want to expand it.
4389 (concat directory (substring file 0 (match-beginning 0)))
4390 (substring file 0 (match-beginning 0)))
4391 filename))))
4393 (defun file-name-extension (filename &optional period)
4394 "Return FILENAME's final \"extension\".
4395 The extension, in a file name, is the part that begins with the last `.',
4396 excluding version numbers and backup suffixes, except that a leading `.'
4397 of the file name, if there is one, doesn't count.
4398 Return nil for extensionless file names such as `foo'.
4399 Return the empty string for file names such as `foo.'.
4401 By default, the returned value excludes the period that starts the
4402 extension, but if the optional argument PERIOD is non-nil, the period
4403 is included in the value, and in that case, if FILENAME has no
4404 extension, the value is \"\"."
4405 (save-match-data
4406 (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
4407 (if (and (string-match "\\.[^.]*\\'" file)
4408 (not (eq 0 (match-beginning 0))))
4409 (substring file (+ (match-beginning 0) (if period 0 1)))
4410 (if period
4411 "")))))
4413 (defun file-name-base (&optional filename)
4414 "Return the base name of the FILENAME: no directory, no extension.
4415 FILENAME defaults to `buffer-file-name'."
4416 (file-name-sans-extension
4417 (file-name-nondirectory (or filename (buffer-file-name)))))
4419 (defcustom make-backup-file-name-function
4420 #'make-backup-file-name--default-function
4421 "A function that `make-backup-file-name' uses to create backup file names.
4422 The function receives a single argument, the original file name.
4424 If you change this, you may need to change `backup-file-name-p' and
4425 `file-name-sans-versions' too.
4427 You could make this buffer-local to do something special for specific files.
4429 For historical reasons, a value of nil means to use the default function.
4430 This should not be relied upon.
4432 See also `backup-directory-alist'."
4433 :version "24.4" ; nil -> make-backup-file-name--default-function
4434 :group 'backup
4435 :type '(choice (const :tag "Deprecated way to get the default function" nil)
4436 (function :tag "Function")))
4438 (defcustom backup-directory-alist nil
4439 "Alist of filename patterns and backup directory names.
4440 Each element looks like (REGEXP . DIRECTORY). Backups of files with
4441 names matching REGEXP will be made in DIRECTORY. DIRECTORY may be
4442 relative or absolute. If it is absolute, so that all matching files
4443 are backed up into the same directory, the file names in this
4444 directory will be the full name of the file backed up with all
4445 directory separators changed to `!' to prevent clashes. This will not
4446 work correctly if your filesystem truncates the resulting name.
4448 For the common case of all backups going into one directory, the alist
4449 should contain a single element pairing \".\" with the appropriate
4450 directory name.
4452 If this variable is nil, or it fails to match a filename, the backup
4453 is made in the original file's directory.
4455 On MS-DOS filesystems without long names this variable is always
4456 ignored."
4457 :group 'backup
4458 :type '(repeat (cons (regexp :tag "Regexp matching filename")
4459 (directory :tag "Backup directory name"))))
4461 (defun normal-backup-enable-predicate (name)
4462 "Default `backup-enable-predicate' function.
4463 Checks for files in `temporary-file-directory',
4464 `small-temporary-file-directory', and \"/tmp\"."
4465 (let ((temporary-file-directory temporary-file-directory)
4466 caseless)
4467 ;; On MS-Windows, file-truename will convert short 8+3 aliases to
4468 ;; their long file-name equivalents, so compare-strings does TRT.
4469 (if (memq system-type '(ms-dos windows-nt))
4470 (setq temporary-file-directory (file-truename temporary-file-directory)
4471 name (file-truename name)
4472 caseless t))
4473 (not (or (let ((comp (compare-strings temporary-file-directory 0 nil
4474 name 0 nil caseless)))
4475 ;; Directory is under temporary-file-directory.
4476 (and (not (eq comp t))
4477 (< comp (- (length temporary-file-directory)))))
4478 (let ((comp (compare-strings "/tmp" 0 nil
4479 name 0 nil)))
4480 ;; Directory is under /tmp.
4481 (and (not (eq comp t))
4482 (< comp (- (length "/tmp")))))
4483 (if small-temporary-file-directory
4484 (let ((comp (compare-strings small-temporary-file-directory
4485 0 nil
4486 name 0 nil caseless)))
4487 ;; Directory is under small-temporary-file-directory.
4488 (and (not (eq comp t))
4489 (< comp (- (length small-temporary-file-directory))))))))))
4491 (defun make-backup-file-name (file)
4492 "Create the non-numeric backup file name for FILE.
4493 This calls the function that `make-backup-file-name-function' specifies,
4494 with a single argument FILE."
4495 (funcall (or make-backup-file-name-function
4496 #'make-backup-file-name--default-function)
4497 file))
4499 (defun make-backup-file-name--default-function (file)
4500 "Default function for `make-backup-file-name'.
4501 Normally this just returns FILE's name with `~' appended.
4502 It searches for a match for FILE in `backup-directory-alist'.
4503 If the directory for the backup doesn't exist, it is created."
4504 (if (and (eq system-type 'ms-dos)
4505 (not (msdos-long-file-names)))
4506 (let ((fn (file-name-nondirectory file)))
4507 (concat (file-name-directory file)
4508 (or (and (string-match "\\`[^.]+\\'" fn)
4509 (concat (match-string 0 fn) ".~"))
4510 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
4511 (concat (match-string 0 fn) "~")))))
4512 (concat (make-backup-file-name-1 file) "~")))
4514 (defun make-backup-file-name-1 (file)
4515 "Subroutine of `make-backup-file-name--default-function'.
4516 The function `find-backup-file-name' also uses this."
4517 (let ((alist backup-directory-alist)
4518 elt backup-directory abs-backup-directory)
4519 (while alist
4520 (setq elt (pop alist))
4521 (if (string-match (car elt) file)
4522 (setq backup-directory (cdr elt)
4523 alist nil)))
4524 ;; If backup-directory is relative, it should be relative to the
4525 ;; file's directory. By expanding explicitly here, we avoid
4526 ;; depending on default-directory.
4527 (if backup-directory
4528 (setq abs-backup-directory
4529 (expand-file-name backup-directory
4530 (file-name-directory file))))
4531 (if (and abs-backup-directory (not (file-exists-p abs-backup-directory)))
4532 (condition-case nil
4533 (make-directory abs-backup-directory 'parents)
4534 (file-error (setq backup-directory nil
4535 abs-backup-directory nil))))
4536 (if (null backup-directory)
4537 file
4538 (if (file-name-absolute-p backup-directory)
4539 (progn
4540 (when (memq system-type '(windows-nt ms-dos cygwin))
4541 ;; Normalize DOSish file names: downcase the drive
4542 ;; letter, if any, and replace the leading "x:" with
4543 ;; "/drive_x".
4544 (or (file-name-absolute-p file)
4545 (setq file (expand-file-name file))) ; make defaults explicit
4546 ;; Replace any invalid file-name characters (for the
4547 ;; case of backing up remote files).
4548 (setq file (expand-file-name (convert-standard-filename file)))
4549 (if (eq (aref file 1) ?:)
4550 (setq file (concat "/"
4551 "drive_"
4552 (char-to-string (downcase (aref file 0)))
4553 (if (eq (aref file 2) ?/)
4555 "/")
4556 (substring file 2)))))
4557 ;; Make the name unique by substituting directory
4558 ;; separators. It may not really be worth bothering about
4559 ;; doubling `!'s in the original name...
4560 (expand-file-name
4561 (subst-char-in-string
4562 ?/ ?!
4563 (replace-regexp-in-string "!" "!!" file))
4564 backup-directory))
4565 (expand-file-name (file-name-nondirectory file)
4566 (file-name-as-directory abs-backup-directory))))))
4568 (defun backup-file-name-p (file)
4569 "Return non-nil if FILE is a backup file name (numeric or not).
4570 This is a separate function so you can redefine it for customization.
4571 You may need to redefine `file-name-sans-versions' as well."
4572 (string-match "~\\'" file))
4574 (defvar backup-extract-version-start)
4576 ;; This is used in various files.
4577 ;; The usage of backup-extract-version-start is not very clean,
4578 ;; but I can't see a good alternative, so as of now I am leaving it alone.
4579 (defun backup-extract-version (fn)
4580 "Given the name of a numeric backup file, FN, return the backup number.
4581 Uses the free variable `backup-extract-version-start', whose value should be
4582 the index in the name where the version number begins."
4583 (if (and (string-match "[0-9]+~/?$" fn backup-extract-version-start)
4584 (= (match-beginning 0) backup-extract-version-start))
4585 (string-to-number (substring fn backup-extract-version-start -1))
4588 (defun find-backup-file-name (fn)
4589 "Find a file name for a backup file FN, and suggestions for deletions.
4590 Value is a list whose car is the name for the backup file
4591 and whose cdr is a list of old versions to consider deleting now.
4592 If the value is nil, don't make a backup.
4593 Uses `backup-directory-alist' in the same way as
4594 `make-backup-file-name--default-function' does."
4595 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
4596 ;; Run a handler for this function so that ange-ftp can refuse to do it.
4597 (if handler
4598 (funcall handler 'find-backup-file-name fn)
4599 (if (or (eq version-control 'never)
4600 ;; We don't support numbered backups on plain MS-DOS
4601 ;; when long file names are unavailable.
4602 (and (eq system-type 'ms-dos)
4603 (not (msdos-long-file-names))))
4604 (list (make-backup-file-name fn))
4605 (let* ((basic-name (make-backup-file-name-1 fn))
4606 (base-versions (concat (file-name-nondirectory basic-name)
4607 ".~"))
4608 (backup-extract-version-start (length base-versions))
4609 (high-water-mark 0)
4610 (number-to-delete 0)
4611 possibilities deserve-versions-p versions)
4612 (condition-case ()
4613 (setq possibilities (file-name-all-completions
4614 base-versions
4615 (file-name-directory basic-name))
4616 versions (sort (mapcar #'backup-extract-version
4617 possibilities)
4618 #'<)
4619 high-water-mark (apply 'max 0 versions)
4620 deserve-versions-p (or version-control
4621 (> high-water-mark 0))
4622 number-to-delete (- (length versions)
4623 kept-old-versions
4624 kept-new-versions
4625 -1))
4626 (file-error (setq possibilities nil)))
4627 (if (not deserve-versions-p)
4628 (list (make-backup-file-name fn))
4629 (cons (format "%s.~%d~" basic-name (1+ high-water-mark))
4630 (if (and (> number-to-delete 0)
4631 ;; Delete nothing if there is overflow
4632 ;; in the number of versions to keep.
4633 (>= (+ kept-new-versions kept-old-versions -1) 0))
4634 (mapcar (lambda (n)
4635 (format "%s.~%d~" basic-name n))
4636 (let ((v (nthcdr kept-old-versions versions)))
4637 (rplacd (nthcdr (1- number-to-delete) v) ())
4638 v))))))))))
4640 (defun file-nlinks (filename)
4641 "Return number of names file FILENAME has."
4642 (car (cdr (file-attributes filename))))
4644 ;; (defun file-relative-name (filename &optional directory)
4645 ;; "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
4646 ;; This function returns a relative file name which is equivalent to FILENAME
4647 ;; when used with that default directory as the default.
4648 ;; If this is impossible (which can happen on MSDOS and Windows
4649 ;; when the file name and directory use different drive names)
4650 ;; then it returns FILENAME."
4651 ;; (save-match-data
4652 ;; (let ((fname (expand-file-name filename)))
4653 ;; (setq directory (file-name-as-directory
4654 ;; (expand-file-name (or directory default-directory))))
4655 ;; ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
4656 ;; ;; drive names, they can't be relative, so return the absolute name.
4657 ;; (if (and (or (eq system-type 'ms-dos)
4658 ;; (eq system-type 'cygwin)
4659 ;; (eq system-type 'windows-nt))
4660 ;; (not (string-equal (substring fname 0 2)
4661 ;; (substring directory 0 2))))
4662 ;; filename
4663 ;; (let ((ancestor ".")
4664 ;; (fname-dir (file-name-as-directory fname)))
4665 ;; (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
4666 ;; (not (string-match (concat "^" (regexp-quote directory)) fname)))
4667 ;; (setq directory (file-name-directory (substring directory 0 -1))
4668 ;; ancestor (if (equal ancestor ".")
4669 ;; ".."
4670 ;; (concat "../" ancestor))))
4671 ;; ;; Now ancestor is empty, or .., or ../.., etc.
4672 ;; (if (string-match (concat "^" (regexp-quote directory)) fname)
4673 ;; ;; We matched within FNAME's directory part.
4674 ;; ;; Add the rest of FNAME onto ANCESTOR.
4675 ;; (let ((rest (substring fname (match-end 0))))
4676 ;; (if (and (equal ancestor ".")
4677 ;; (not (equal rest "")))
4678 ;; ;; But don't bother with ANCESTOR if it would give us `./'.
4679 ;; rest
4680 ;; (concat (file-name-as-directory ancestor) rest)))
4681 ;; ;; We matched FNAME's directory equivalent.
4682 ;; ancestor))))))
4684 (defun file-relative-name (filename &optional directory)
4685 "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
4686 This function returns a relative file name which is equivalent to FILENAME
4687 when used with that default directory as the default.
4688 If FILENAME is a relative file name, it will be interpreted as existing in
4689 `default-directory'.
4690 If FILENAME and DIRECTORY lie on different machines or on different drives
4691 on a DOS/Windows machine, it returns FILENAME in expanded form."
4692 (save-match-data
4693 (setq directory
4694 (file-name-as-directory (expand-file-name (or directory
4695 default-directory))))
4696 (setq filename (expand-file-name filename))
4697 (let ((fremote (file-remote-p filename))
4698 (dremote (file-remote-p directory))
4699 (fold-case (or (file-name-case-insensitive-p filename)
4700 read-file-name-completion-ignore-case)))
4701 (if ;; Conditions for separate trees
4703 ;; Test for different filesystems on DOS/Windows
4704 (and
4705 ;; Should `cygwin' really be included here? --stef
4706 (memq system-type '(ms-dos cygwin windows-nt))
4708 ;; Test for different drive letters
4709 (not (eq t (compare-strings filename 0 2 directory 0 2 fold-case)))
4710 ;; Test for UNCs on different servers
4711 (not (eq t (compare-strings
4712 (progn
4713 (if (string-match "\\`//\\([^:/]+\\)/" filename)
4714 (match-string 1 filename)
4715 ;; Windows file names cannot have ? in
4716 ;; them, so use that to detect when
4717 ;; neither FILENAME nor DIRECTORY is a
4718 ;; UNC.
4719 "?"))
4720 0 nil
4721 (progn
4722 (if (string-match "\\`//\\([^:/]+\\)/" directory)
4723 (match-string 1 directory)
4724 "?"))
4725 0 nil t)))))
4726 ;; Test for different remote file system identification
4727 (not (equal fremote dremote)))
4728 filename
4729 (let ((ancestor ".")
4730 (filename-dir (file-name-as-directory filename)))
4731 (while (not
4732 (or (string-prefix-p directory filename-dir fold-case)
4733 (string-prefix-p directory filename fold-case)))
4734 (setq directory (file-name-directory (substring directory 0 -1))
4735 ancestor (if (equal ancestor ".")
4736 ".."
4737 (concat "../" ancestor))))
4738 ;; Now ancestor is empty, or .., or ../.., etc.
4739 (if (string-prefix-p directory filename fold-case)
4740 ;; We matched within FILENAME's directory part.
4741 ;; Add the rest of FILENAME onto ANCESTOR.
4742 (let ((rest (substring filename (length directory))))
4743 (if (and (equal ancestor ".") (not (equal rest "")))
4744 ;; But don't bother with ANCESTOR if it would give us `./'.
4745 rest
4746 (concat (file-name-as-directory ancestor) rest)))
4747 ;; We matched FILENAME's directory equivalent.
4748 ancestor))))))
4750 (defun save-buffer (&optional arg)
4751 "Save current buffer in visited file if modified.
4752 Variations are described below.
4754 By default, makes the previous version into a backup file
4755 if previously requested or if this is the first save.
4756 Prefixed with one \\[universal-argument], marks this version
4757 to become a backup when the next save is done.
4758 Prefixed with two \\[universal-argument]'s,
4759 makes the previous version into a backup file.
4760 Prefixed with three \\[universal-argument]'s, marks this version
4761 to become a backup when the next save is done,
4762 and makes the previous version into a backup file.
4764 With a numeric prefix argument of 0, never make the previous version
4765 into a backup file.
4767 Note that the various variables that control backups, such
4768 as `version-control', `backup-enable-predicate', `vc-make-backup-files',
4769 and `backup-inhibited', to name just the more popular ones, still
4770 control whether a backup will actually be produced, even when you
4771 invoke this command prefixed with two or three \\[universal-argument]'s.
4773 If a file's name is FOO, the names of its numbered backup versions are
4774 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
4775 Numeric backups (rather than FOO~) will be made if value of
4776 `version-control' is not the atom `never' and either there are already
4777 numeric versions of the file being backed up, or `version-control' is
4778 non-nil.
4779 We don't want excessive versions piling up, so there are variables
4780 `kept-old-versions', which tells Emacs how many oldest versions to keep,
4781 and `kept-new-versions', which tells how many newest versions to keep.
4782 Defaults are 2 old versions and 2 new.
4783 `dired-kept-versions' controls dired's clean-directory (.) command.
4784 If `delete-old-versions' is nil, system will query user
4785 before trimming versions. Otherwise it does it silently.
4787 If `vc-make-backup-files' is nil, which is the default,
4788 no backup files are made for files managed by version control.
4789 (This is because the version control system itself records previous versions.)
4791 See the subroutine `basic-save-buffer' for more information."
4792 (interactive "p")
4793 (let ((modp (buffer-modified-p))
4794 (make-backup-files (or (and make-backup-files (not (eq arg 0)))
4795 (memq arg '(16 64)))))
4796 (and modp (memq arg '(16 64)) (setq buffer-backed-up nil))
4797 ;; We used to display the message below only for files > 50KB, but
4798 ;; then Rmail-mbox never displays it due to buffer swapping. If
4799 ;; the test is ever re-introduced, be sure to handle saving of
4800 ;; Rmail files.
4801 (if (and modp
4802 (buffer-file-name)
4803 (not noninteractive)
4804 (not save-silently))
4805 (message "Saving file %s..." (buffer-file-name)))
4806 (basic-save-buffer (called-interactively-p 'any))
4807 (and modp (memq arg '(4 64)) (setq buffer-backed-up nil))))
4809 (defun delete-auto-save-file-if-necessary (&optional force)
4810 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
4811 Normally delete only if the file was written by this Emacs since
4812 the last real save, but optional arg FORCE non-nil means delete anyway."
4813 (and buffer-auto-save-file-name delete-auto-save-files
4814 (not (string= buffer-file-name buffer-auto-save-file-name))
4815 (or force (recent-auto-save-p))
4816 (progn
4817 (condition-case ()
4818 (delete-file buffer-auto-save-file-name)
4819 (file-error nil))
4820 (set-buffer-auto-saved))))
4822 (defvar auto-save-hook nil
4823 "Normal hook run just before auto-saving.")
4825 (defcustom before-save-hook nil
4826 "Normal hook that is run before a buffer is saved to its file."
4827 :options '(copyright-update time-stamp)
4828 :type 'hook
4829 :group 'files)
4831 (defcustom after-save-hook nil
4832 "Normal hook that is run after a buffer is saved to its file."
4833 :options '(executable-make-buffer-file-executable-if-script-p)
4834 :type 'hook
4835 :group 'files)
4837 (defvar save-buffer-coding-system nil
4838 "If non-nil, use this coding system for saving the buffer.
4839 More precisely, use this coding system in place of the
4840 value of `buffer-file-coding-system', when saving the buffer.
4841 Calling `write-region' for any purpose other than saving the buffer
4842 will still use `buffer-file-coding-system'; this variable has no effect
4843 in such cases.")
4845 (make-variable-buffer-local 'save-buffer-coding-system)
4846 (put 'save-buffer-coding-system 'permanent-local t)
4848 (defun basic-save-buffer (&optional called-interactively)
4849 "Save the current buffer in its visited file, if it has been modified.
4850 The hooks `write-contents-functions' and `write-file-functions' get a chance
4851 to do the job of saving; if they do not, then the buffer is saved in
4852 the visited file in the usual way.
4853 Before and after saving the buffer, this function runs
4854 `before-save-hook' and `after-save-hook', respectively."
4855 (interactive '(called-interactively))
4856 (save-current-buffer
4857 ;; In an indirect buffer, save its base buffer instead.
4858 (if (buffer-base-buffer)
4859 (set-buffer (buffer-base-buffer)))
4860 (if (or (buffer-modified-p)
4861 ;; handle the case when no modification has been made but
4862 ;; the file disappeared since visited
4863 (and buffer-file-name
4864 (not (file-exists-p buffer-file-name))))
4865 (let ((recent-save (recent-auto-save-p))
4866 setmodes)
4867 ;; If buffer has no file name, ask user for one.
4868 (or buffer-file-name
4869 (let ((filename
4870 (expand-file-name
4871 (read-file-name "File to save in: "
4872 nil (expand-file-name (buffer-name))))))
4873 (if (file-exists-p filename)
4874 (if (file-directory-p filename)
4875 ;; Signal an error if the user specified the name of an
4876 ;; existing directory.
4877 (error "%s is a directory" filename)
4878 (unless (y-or-n-p (format-message
4879 "File `%s' exists; overwrite? "
4880 filename))
4881 (error "Canceled"))))
4882 (set-visited-file-name filename)))
4883 (or (verify-visited-file-modtime (current-buffer))
4884 (not (file-exists-p buffer-file-name))
4885 (yes-or-no-p
4886 (format
4887 "%s has changed since visited or saved. Save anyway? "
4888 (file-name-nondirectory buffer-file-name)))
4889 (user-error "Save not confirmed"))
4890 (save-restriction
4891 (widen)
4892 (save-excursion
4893 (and (> (point-max) (point-min))
4894 (not find-file-literally)
4895 (/= (char-after (1- (point-max))) ?\n)
4896 (not (and (eq selective-display t)
4897 (= (char-after (1- (point-max))) ?\r)))
4898 (or (eq require-final-newline t)
4899 (eq require-final-newline 'visit-save)
4900 (and require-final-newline
4901 (y-or-n-p
4902 (format "Buffer %s does not end in newline. Add one? "
4903 (buffer-name)))))
4904 (save-excursion
4905 (goto-char (point-max))
4906 (insert ?\n))))
4907 ;; Support VC version backups.
4908 (vc-before-save)
4909 ;; Don't let errors prevent saving the buffer.
4910 (with-demoted-errors (run-hooks 'before-save-hook))
4911 (or (run-hook-with-args-until-success 'write-contents-functions)
4912 (run-hook-with-args-until-success 'local-write-file-hooks)
4913 (run-hook-with-args-until-success 'write-file-functions)
4914 ;; If a hook returned t, file is already "written".
4915 ;; Otherwise, write it the usual way now.
4916 (let ((dir (file-name-directory
4917 (expand-file-name buffer-file-name))))
4918 (unless (file-exists-p dir)
4919 (if (y-or-n-p
4920 (format-message
4921 "Directory `%s' does not exist; create? " dir))
4922 (make-directory dir t)
4923 (error "Canceled")))
4924 (setq setmodes (basic-save-buffer-1))))
4925 ;; Now we have saved the current buffer. Let's make sure
4926 ;; that buffer-file-coding-system is fixed to what
4927 ;; actually used for saving by binding it locally.
4928 (if save-buffer-coding-system
4929 (setq save-buffer-coding-system last-coding-system-used)
4930 (setq buffer-file-coding-system last-coding-system-used))
4931 (setq buffer-file-number
4932 (nthcdr 10 (file-attributes buffer-file-name)))
4933 (if setmodes
4934 (condition-case ()
4935 (progn
4936 (unless
4937 (with-demoted-errors
4938 (set-file-modes buffer-file-name (car setmodes)))
4939 (set-file-extended-attributes buffer-file-name
4940 (nth 1 setmodes))))
4941 (error nil))))
4942 ;; If the auto-save file was recent before this command,
4943 ;; delete it now.
4944 (delete-auto-save-file-if-necessary recent-save)
4945 ;; Support VC `implicit' locking.
4946 (vc-after-save)
4947 (run-hooks 'after-save-hook))
4948 (or noninteractive
4949 (not called-interactively)
4950 (files--message "(No changes need to be saved)")))))
4952 ;; This does the "real job" of writing a buffer into its visited file
4953 ;; and making a backup file. This is what is normally done
4954 ;; but inhibited if one of write-file-functions returns non-nil.
4955 ;; It returns a value (MODES EXTENDED-ATTRIBUTES BACKUPNAME), like
4956 ;; backup-buffer.
4957 (defun basic-save-buffer-1 ()
4958 (prog1
4959 (if save-buffer-coding-system
4960 (let ((coding-system-for-write save-buffer-coding-system))
4961 (basic-save-buffer-2))
4962 (basic-save-buffer-2))
4963 (if buffer-file-coding-system-explicit
4964 (setcar buffer-file-coding-system-explicit last-coding-system-used))))
4966 ;; This returns a value (MODES EXTENDED-ATTRIBUTES BACKUPNAME), like
4967 ;; backup-buffer.
4968 (defun basic-save-buffer-2 ()
4969 (let (tempsetmodes setmodes)
4970 (if (not (file-writable-p buffer-file-name))
4971 (let ((dir (file-name-directory buffer-file-name)))
4972 (if (not (file-directory-p dir))
4973 (if (file-exists-p dir)
4974 (error "%s is not a directory" dir)
4975 (error "%s: no such directory" dir))
4976 (if (not (file-exists-p buffer-file-name))
4977 (error "Directory %s write-protected" dir)
4978 (if (yes-or-no-p
4979 (format
4980 "File %s is write-protected; try to save anyway? "
4981 (file-name-nondirectory
4982 buffer-file-name)))
4983 (setq tempsetmodes t)
4984 (error "Attempt to save to a file which you aren't allowed to write"))))))
4985 (or buffer-backed-up
4986 (setq setmodes (backup-buffer)))
4987 (let* ((dir (file-name-directory buffer-file-name))
4988 (dir-writable (file-writable-p dir)))
4989 (if (or (and file-precious-flag dir-writable)
4990 (and break-hardlink-on-save
4991 (file-exists-p buffer-file-name)
4992 (> (file-nlinks buffer-file-name) 1)
4993 (or dir-writable
4994 (error (concat "Directory %s write-protected; "
4995 "cannot break hardlink when saving")
4996 dir))))
4997 ;; Write temp name, then rename it.
4998 ;; This requires write access to the containing dir,
4999 ;; which is why we don't try it if we don't have that access.
5000 (let ((realname buffer-file-name)
5001 tempname succeed
5002 (umask (default-file-modes))
5003 (old-modtime (visited-file-modtime)))
5004 ;; Create temp files with strict access rights. It's easy to
5005 ;; loosen them later, whereas it's impossible to close the
5006 ;; time-window of loose permissions otherwise.
5007 (unwind-protect
5008 (progn
5009 (clear-visited-file-modtime)
5010 (set-default-file-modes ?\700)
5011 ;; Try various temporary names.
5012 ;; This code follows the example of make-temp-file,
5013 ;; but it calls write-region in the appropriate way
5014 ;; for saving the buffer.
5015 (while (condition-case ()
5016 (progn
5017 (setq tempname
5018 (make-temp-name
5019 (expand-file-name "tmp" dir)))
5020 ;; Pass in nil&nil rather than point-min&max
5021 ;; cause we're saving the whole buffer.
5022 ;; write-region-annotate-functions may use it.
5023 (write-region nil nil
5024 tempname nil realname
5025 buffer-file-truename 'excl)
5026 (when save-silently (message nil))
5027 nil)
5028 (file-already-exists t))
5029 ;; The file was somehow created by someone else between
5030 ;; `make-temp-name' and `write-region', let's try again.
5031 nil)
5032 (setq succeed t))
5033 ;; Reset the umask.
5034 (set-default-file-modes umask)
5035 ;; If we failed, restore the buffer's modtime.
5036 (unless succeed
5037 (set-visited-file-modtime old-modtime)))
5038 ;; Since we have created an entirely new file,
5039 ;; make sure it gets the right permission bits set.
5040 (setq setmodes (or setmodes
5041 (list (or (file-modes buffer-file-name)
5042 (logand ?\666 umask))
5043 (file-extended-attributes buffer-file-name)
5044 buffer-file-name)))
5045 ;; We succeeded in writing the temp file,
5046 ;; so rename it.
5047 (rename-file tempname buffer-file-name t))
5048 ;; If file not writable, see if we can make it writable
5049 ;; temporarily while we write it.
5050 ;; But no need to do so if we have just backed it up
5051 ;; (setmodes is set) because that says we're superseding.
5052 (cond ((and tempsetmodes (not setmodes))
5053 ;; Change the mode back, after writing.
5054 (setq setmodes (list (file-modes buffer-file-name)
5055 (file-extended-attributes buffer-file-name)
5056 buffer-file-name))
5057 ;; If set-file-extended-attributes fails, fall back on
5058 ;; set-file-modes.
5059 (unless
5060 (with-demoted-errors
5061 (set-file-extended-attributes buffer-file-name
5062 (nth 1 setmodes)))
5063 (set-file-modes buffer-file-name
5064 (logior (car setmodes) 128))))))
5065 (let (success)
5066 (unwind-protect
5067 (progn
5068 ;; Pass in nil&nil rather than point-min&max to indicate
5069 ;; we're saving the buffer rather than just a region.
5070 ;; write-region-annotate-functions may make us of it.
5071 (write-region nil nil
5072 buffer-file-name nil t buffer-file-truename)
5073 (when save-silently (message nil))
5074 (setq success t))
5075 ;; If we get an error writing the new file, and we made
5076 ;; the backup by renaming, undo the backing-up.
5077 (and setmodes (not success)
5078 (progn
5079 (rename-file (nth 2 setmodes) buffer-file-name t)
5080 (setq buffer-backed-up nil))))))
5081 setmodes))
5083 (declare-function diff-no-select "diff"
5084 (old new &optional switches no-async buf))
5086 (defvar save-some-buffers-action-alist
5087 `((?\C-r
5088 ,(lambda (buf)
5089 (if (not enable-recursive-minibuffers)
5090 (progn (display-buffer buf)
5091 (setq other-window-scroll-buffer buf))
5092 (view-buffer buf (lambda (_) (exit-recursive-edit)))
5093 (recursive-edit))
5094 ;; Return nil to ask about BUF again.
5095 nil)
5096 ,(purecopy "view this buffer"))
5097 (?d ,(lambda (buf)
5098 (if (null (buffer-file-name buf))
5099 (message "Not applicable: no file")
5100 (require 'diff) ;for diff-no-select.
5101 (let ((diffbuf (diff-no-select (buffer-file-name buf) buf
5102 nil 'noasync)))
5103 (if (not enable-recursive-minibuffers)
5104 (progn (display-buffer diffbuf)
5105 (setq other-window-scroll-buffer diffbuf))
5106 (view-buffer diffbuf (lambda (_) (exit-recursive-edit)))
5107 (recursive-edit))))
5108 ;; Return nil to ask about BUF again.
5109 nil)
5110 ,(purecopy "view changes in this buffer")))
5111 "ACTION-ALIST argument used in call to `map-y-or-n-p'.")
5112 (put 'save-some-buffers-action-alist 'risky-local-variable t)
5114 (defvar buffer-save-without-query nil
5115 "Non-nil means `save-some-buffers' should save this buffer without asking.")
5116 (make-variable-buffer-local 'buffer-save-without-query)
5118 (defun save-some-buffers (&optional arg pred)
5119 "Save some modified file-visiting buffers. Asks user about each one.
5120 You can answer `y' to save, `n' not to save, `C-r' to look at the
5121 buffer in question with `view-buffer' before deciding or `d' to
5122 view the differences using `diff-buffer-with-file'.
5124 This command first saves any buffers where `buffer-save-without-query' is
5125 non-nil, without asking.
5127 Optional argument (the prefix) non-nil means save all with no questions.
5128 Optional second argument PRED determines which buffers are considered:
5129 If PRED is nil, all the file-visiting buffers are considered.
5130 If PRED is t, then certain non-file buffers will also be considered.
5131 If PRED is a zero-argument function, it indicates for each buffer whether
5132 to consider it or not when called with that buffer current.
5134 See `save-some-buffers-action-alist' if you want to
5135 change the additional actions you can take on files."
5136 (interactive "P")
5137 (save-window-excursion
5138 (let* (queried autosaved-buffers
5139 files-done abbrevs-done)
5140 (dolist (buffer (buffer-list))
5141 ;; First save any buffers that we're supposed to save unconditionally.
5142 ;; That way the following code won't ask about them.
5143 (with-current-buffer buffer
5144 (when (and buffer-save-without-query (buffer-modified-p))
5145 (push (buffer-name) autosaved-buffers)
5146 (save-buffer))))
5147 ;; Ask about those buffers that merit it,
5148 ;; and record the number thus saved.
5149 (setq files-done
5150 (map-y-or-n-p
5151 (lambda (buffer)
5152 ;; Note that killing some buffers may kill others via
5153 ;; hooks (e.g. Rmail and its viewing buffer).
5154 (and (buffer-live-p buffer)
5155 (buffer-modified-p buffer)
5156 (not (buffer-base-buffer buffer))
5158 (buffer-file-name buffer)
5159 (and pred
5160 (progn
5161 (set-buffer buffer)
5162 (and buffer-offer-save (> (buffer-size) 0)))))
5163 (or (not (functionp pred))
5164 (with-current-buffer buffer (funcall pred)))
5165 (if arg
5167 (setq queried t)
5168 (if (buffer-file-name buffer)
5169 (format "Save file %s? "
5170 (buffer-file-name buffer))
5171 (format "Save buffer %s? "
5172 (buffer-name buffer))))))
5173 (lambda (buffer)
5174 (with-current-buffer buffer
5175 (save-buffer)))
5176 (buffer-list)
5177 '("buffer" "buffers" "save")
5178 save-some-buffers-action-alist))
5179 ;; Maybe to save abbrevs, and record whether
5180 ;; we either saved them or asked to.
5181 (and save-abbrevs abbrevs-changed
5182 (progn
5183 (if (or arg
5184 (eq save-abbrevs 'silently)
5185 (y-or-n-p (format "Save abbrevs in %s? " abbrev-file-name)))
5186 (write-abbrev-file nil))
5187 ;; Don't keep bothering user if he says no.
5188 (setq abbrevs-changed nil)
5189 (setq abbrevs-done t)))
5190 (or queried (> files-done 0) abbrevs-done
5191 (cond
5192 ((null autosaved-buffers)
5193 (when (called-interactively-p 'any)
5194 (files--message "(No files need saving)")))
5195 ((= (length autosaved-buffers) 1)
5196 (files--message "(Saved %s)" (car autosaved-buffers)))
5198 (files--message "(Saved %d files: %s)"
5199 (length autosaved-buffers)
5200 (mapconcat 'identity autosaved-buffers ", "))))))))
5202 (defun clear-visited-file-modtime ()
5203 "Clear out records of last mod time of visited file.
5204 Next attempt to save will not complain of a discrepancy."
5205 (set-visited-file-modtime 0))
5207 (defun not-modified (&optional arg)
5208 "Mark current buffer as unmodified, not needing to be saved.
5209 With prefix ARG, mark buffer as modified, so \\[save-buffer] will save.
5211 It is not a good idea to use this function in Lisp programs, because it
5212 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
5213 (declare (interactive-only set-buffer-modified-p))
5214 (interactive "P")
5215 (files--message (if arg "Modification-flag set"
5216 "Modification-flag cleared"))
5217 (set-buffer-modified-p arg))
5219 (defun toggle-read-only (&optional arg interactive)
5220 "Change whether this buffer is read-only."
5221 (declare (obsolete read-only-mode "24.3"))
5222 (interactive (list current-prefix-arg t))
5223 (if interactive
5224 (call-interactively 'read-only-mode)
5225 (read-only-mode (or arg 'toggle))))
5227 (defun insert-file (filename)
5228 "Insert contents of file FILENAME into buffer after point.
5229 Set mark after the inserted text.
5231 This function is meant for the user to run interactively.
5232 Don't call it from programs! Use `insert-file-contents' instead.
5233 \(Its calling sequence is different; see its documentation)."
5234 (declare (interactive-only insert-file-contents))
5235 (interactive "*fInsert file: ")
5236 (insert-file-1 filename #'insert-file-contents))
5238 (defun append-to-file (start end filename)
5239 "Append the contents of the region to the end of file FILENAME.
5240 When called from a function, expects three arguments,
5241 START, END and FILENAME. START and END are normally buffer positions
5242 specifying the part of the buffer to write.
5243 If START is nil, that means to use the entire buffer contents.
5244 If START is a string, then output that string to the file
5245 instead of any buffer contents; END is ignored.
5247 This does character code conversion and applies annotations
5248 like `write-region' does."
5249 (interactive "r\nFAppend to file: ")
5250 (prog1 (write-region start end filename t)
5251 (when save-silently (message nil))))
5253 (defun file-newest-backup (filename)
5254 "Return most recent backup file for FILENAME or nil if no backups exist."
5255 ;; `make-backup-file-name' will get us the right directory for
5256 ;; ordinary or numeric backups. It might create a directory for
5257 ;; backups as a side-effect, according to `backup-directory-alist'.
5258 (let* ((filename (file-name-sans-versions
5259 (make-backup-file-name (expand-file-name filename))))
5260 (file (file-name-nondirectory filename))
5261 (dir (file-name-directory filename))
5262 (comp (file-name-all-completions file dir))
5263 (newest nil)
5264 tem)
5265 (while comp
5266 (setq tem (pop comp))
5267 (cond ((and (backup-file-name-p tem)
5268 (string= (file-name-sans-versions tem) file))
5269 (setq tem (concat dir tem))
5270 (if (or (null newest)
5271 (file-newer-than-file-p tem newest))
5272 (setq newest tem)))))
5273 newest))
5275 (defun rename-uniquely ()
5276 "Rename current buffer to a similar name not already taken.
5277 This function is useful for creating multiple shell process buffers
5278 or multiple mail buffers, etc.
5280 Note that some commands, in particular those based on `compilation-mode'
5281 \(`compile', `grep', etc.) will reuse the current buffer if it has the
5282 appropriate mode even if it has been renamed. So as well as renaming
5283 the buffer, you also need to switch buffers before running another
5284 instance of such commands."
5285 (interactive)
5286 (save-match-data
5287 (let ((base-name (buffer-name)))
5288 (and (string-match "<[0-9]+>\\'" base-name)
5289 (not (and buffer-file-name
5290 (string= base-name
5291 (file-name-nondirectory buffer-file-name))))
5292 ;; If the existing buffer name has a <NNN>,
5293 ;; which isn't part of the file name (if any),
5294 ;; then get rid of that.
5295 (setq base-name (substring base-name 0 (match-beginning 0))))
5296 (rename-buffer (generate-new-buffer-name base-name))
5297 (force-mode-line-update))))
5299 (defun make-directory (dir &optional parents)
5300 "Create the directory DIR and optionally any nonexistent parent dirs.
5301 If DIR already exists as a directory, signal an error, unless
5302 PARENTS is non-nil.
5304 Interactively, the default choice of directory to create is the
5305 current buffer's default directory. That is useful when you have
5306 visited a file in a nonexistent directory.
5308 Noninteractively, the second (optional) argument PARENTS, if
5309 non-nil, says whether to create parent directories that don't
5310 exist. Interactively, this happens by default.
5312 If creating the directory or directories fail, an error will be
5313 raised."
5314 (interactive
5315 (list (read-file-name "Make directory: " default-directory default-directory
5316 nil nil)
5318 ;; If default-directory is a remote directory,
5319 ;; make sure we find its make-directory handler.
5320 (setq dir (expand-file-name dir))
5321 (let ((handler (find-file-name-handler dir 'make-directory)))
5322 (if handler
5323 (funcall handler 'make-directory dir parents)
5324 (if (not parents)
5325 (make-directory-internal dir)
5326 (let ((dir (directory-file-name (expand-file-name dir)))
5327 create-list)
5328 (while (and (not (file-exists-p dir))
5329 ;; If directory is its own parent, then we can't
5330 ;; keep looping forever
5331 (not (equal dir
5332 (directory-file-name
5333 (file-name-directory dir)))))
5334 (setq create-list (cons dir create-list)
5335 dir (directory-file-name (file-name-directory dir))))
5336 (while create-list
5337 (make-directory-internal (car create-list))
5338 (setq create-list (cdr create-list))))))))
5340 (defconst directory-files-no-dot-files-regexp
5341 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"
5342 "Regexp matching any file name except \".\" and \"..\".")
5344 (defun files--force (no-such fn &rest args)
5345 "Use NO-SUCH to affect behavior of function FN applied to list ARGS.
5346 This acts like (apply FN ARGS) except it returns NO-SUCH if it is
5347 non-nil and if FN fails due to a missing file or directory."
5348 (condition-case err
5349 (apply fn args)
5350 (file-missing (or no-such (signal (car err) (cdr err))))))
5352 (defun delete-directory (directory &optional recursive trash)
5353 "Delete the directory named DIRECTORY. Does not follow symlinks.
5354 If RECURSIVE is non-nil, delete files in DIRECTORY as well, with
5355 no error if something else is simultaneously deleting them.
5356 TRASH non-nil means to trash the directory instead, provided
5357 `delete-by-moving-to-trash' is non-nil.
5359 When called interactively, TRASH is nil if and only if a prefix
5360 argument is given, and a further prompt asks the user for
5361 RECURSIVE if DIRECTORY is nonempty."
5362 (interactive
5363 (let* ((trashing (and delete-by-moving-to-trash
5364 (null current-prefix-arg)))
5365 (dir (expand-file-name
5366 (read-directory-name
5367 (if trashing
5368 "Move directory to trash: "
5369 "Delete directory: ")
5370 default-directory default-directory nil nil))))
5371 (list dir
5372 (if (directory-files dir nil directory-files-no-dot-files-regexp)
5373 (y-or-n-p
5374 (format-message "Directory `%s' is not empty, really %s? "
5375 dir (if trashing "trash" "delete")))
5376 nil)
5377 (null current-prefix-arg))))
5378 ;; If default-directory is a remote directory, make sure we find its
5379 ;; delete-directory handler.
5380 (setq directory (directory-file-name (expand-file-name directory)))
5381 (let ((handler (find-file-name-handler directory 'delete-directory)))
5382 (cond
5383 (handler
5384 (funcall handler 'delete-directory directory recursive))
5385 ((and delete-by-moving-to-trash trash)
5386 ;; Only move non-empty dir to trash if recursive deletion was
5387 ;; requested. This mimics the non-`delete-by-moving-to-trash'
5388 ;; case, where the operation fails in delete-directory-internal.
5389 ;; As `move-file-to-trash' trashes directories (empty or
5390 ;; otherwise) as a unit, we do not need to recurse here.
5391 (if (and (not recursive)
5392 ;; Check if directory is empty apart from "." and "..".
5393 (directory-files
5394 directory 'full directory-files-no-dot-files-regexp))
5395 (error "Directory is not empty, not moving to trash")
5396 (move-file-to-trash directory)))
5397 ;; Otherwise, call ourselves recursively if needed.
5399 (when (or (not recursive) (file-symlink-p directory)
5400 (let* ((files
5401 (files--force t #'directory-files directory 'full
5402 directory-files-no-dot-files-regexp))
5403 (directory-exists (listp files)))
5404 (when directory-exists
5405 (mapc (lambda (file)
5406 ;; This test is equivalent to but more efficient
5407 ;; than (and (file-directory-p fn)
5408 ;; (not (file-symlink-p fn))).
5409 (if (eq t (car (file-attributes file)))
5410 (delete-directory file recursive)
5411 (files--force t #'delete-file file)))
5412 files))
5413 directory-exists))
5414 (files--force recursive #'delete-directory-internal directory))))))
5416 (defun file-equal-p (file1 file2)
5417 "Return non-nil if files FILE1 and FILE2 name the same file.
5418 If FILE1 or FILE2 does not exist, the return value is unspecified."
5419 (let ((handler (or (find-file-name-handler file1 'file-equal-p)
5420 (find-file-name-handler file2 'file-equal-p))))
5421 (if handler
5422 (funcall handler 'file-equal-p file1 file2)
5423 (let (f1-attr f2-attr)
5424 (and (setq f1-attr (file-attributes (file-truename file1)))
5425 (setq f2-attr (file-attributes (file-truename file2)))
5426 (equal f1-attr f2-attr))))))
5428 (defun file-in-directory-p (file dir)
5429 "Return non-nil if FILE is in DIR or a subdirectory of DIR.
5430 A directory is considered to be \"in\" itself.
5431 Return nil if DIR is not an existing directory."
5432 (let ((handler (or (find-file-name-handler file 'file-in-directory-p)
5433 (find-file-name-handler dir 'file-in-directory-p))))
5434 (if handler
5435 (funcall handler 'file-in-directory-p file dir)
5436 (when (file-directory-p dir) ; DIR must exist.
5437 (setq file (file-truename file)
5438 dir (file-truename dir))
5439 (let ((ls1 (split-string file "/" t))
5440 (ls2 (split-string dir "/" t))
5441 (root
5442 (cond
5443 ;; A UNC on Windows systems, or a "super-root" on Apollo.
5444 ((string-match "\\`//" file) "//")
5445 ((string-match "\\`/" file) "/")
5446 (t "")))
5447 (mismatch nil))
5448 (while (and ls1 ls2 (not mismatch))
5449 (if (string-equal (car ls1) (car ls2))
5450 (setq root (concat root (car ls1) "/"))
5451 (setq mismatch t))
5452 (setq ls1 (cdr ls1)
5453 ls2 (cdr ls2)))
5454 (unless mismatch
5455 (file-equal-p root dir)))))))
5457 (defun copy-directory (directory newname &optional keep-time parents copy-contents)
5458 "Copy DIRECTORY to NEWNAME. Both args must be strings.
5459 This function always sets the file modes of the output files to match
5460 the corresponding input file.
5462 The third arg KEEP-TIME non-nil means give the output files the same
5463 last-modified time as the old ones. (This works on only some systems.)
5465 A prefix arg makes KEEP-TIME non-nil.
5467 Noninteractively, the last argument PARENTS says whether to
5468 create parent directories if they don't exist. Interactively,
5469 this happens by default.
5471 If NEWNAME names an existing directory, copy DIRECTORY as a
5472 subdirectory there. However, if called from Lisp with a non-nil
5473 optional argument COPY-CONTENTS, copy the contents of DIRECTORY
5474 directly into NEWNAME instead."
5475 (interactive
5476 (let ((dir (read-directory-name
5477 "Copy directory: " default-directory default-directory t nil)))
5478 (list dir
5479 (read-directory-name
5480 (format "Copy directory %s to: " dir)
5481 default-directory default-directory nil nil)
5482 current-prefix-arg t nil)))
5483 (when (file-in-directory-p newname directory)
5484 (error "Cannot copy `%s' into its subdirectory `%s'"
5485 directory newname))
5486 ;; If default-directory is a remote directory, make sure we find its
5487 ;; copy-directory handler.
5488 (let ((handler (or (find-file-name-handler directory 'copy-directory)
5489 (find-file-name-handler newname 'copy-directory))))
5490 (if handler
5491 (funcall handler 'copy-directory directory
5492 newname keep-time parents copy-contents)
5494 ;; Compute target name.
5495 (setq directory (directory-file-name (expand-file-name directory))
5496 newname (directory-file-name (expand-file-name newname)))
5498 (cond ((not (file-directory-p newname))
5499 ;; If NEWNAME is not an existing directory, create it;
5500 ;; that is where we will copy the files of DIRECTORY.
5501 (make-directory newname parents))
5502 ;; If NEWNAME is an existing directory and COPY-CONTENTS
5503 ;; is nil, copy into NEWNAME/[DIRECTORY-BASENAME].
5504 ((not copy-contents)
5505 (setq newname (expand-file-name
5506 (file-name-nondirectory
5507 (directory-file-name directory))
5508 newname))
5509 (and (file-exists-p newname)
5510 (not (file-directory-p newname))
5511 (error "Cannot overwrite non-directory %s with a directory"
5512 newname))
5513 (make-directory newname t)))
5515 ;; Copy recursively.
5516 (dolist (file
5517 ;; We do not want to copy "." and "..".
5518 (directory-files directory 'full
5519 directory-files-no-dot-files-regexp))
5520 (let ((target (expand-file-name (file-name-nondirectory file) newname))
5521 (filetype (car (file-attributes file))))
5522 (cond
5523 ((eq filetype t) ; Directory but not a symlink.
5524 (copy-directory file newname keep-time parents))
5525 ((stringp filetype) ; Symbolic link
5526 (make-symbolic-link filetype target t))
5527 ((copy-file file target t keep-time)))))
5529 ;; Set directory attributes.
5530 (let ((modes (file-modes directory))
5531 (times (and keep-time (nth 5 (file-attributes directory)))))
5532 (if modes (set-file-modes newname modes))
5533 (if times (set-file-times newname times))))))
5536 ;; At time of writing, only info uses this.
5537 (defun prune-directory-list (dirs &optional keep reject)
5538 "Return a copy of DIRS with all non-existent directories removed.
5539 The optional argument KEEP is a list of directories to retain even if
5540 they don't exist, and REJECT is a list of directories to remove from
5541 DIRS, even if they exist; REJECT takes precedence over KEEP.
5543 Note that membership in REJECT and KEEP is checked using simple string
5544 comparison."
5545 (apply #'nconc
5546 (mapcar (lambda (dir)
5547 (and (not (member dir reject))
5548 (or (member dir keep) (file-directory-p dir))
5549 (list dir)))
5550 dirs)))
5553 (put 'revert-buffer-function 'permanent-local t)
5554 (defvar revert-buffer-function #'revert-buffer--default
5555 "Function to use to revert this buffer.
5556 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
5557 which are the arguments that `revert-buffer' received.
5558 It also has access to the `preserve-modes' argument of `revert-buffer'
5559 via the `revert-buffer-preserve-modes' dynamic variable.
5561 For historical reasons, a value of nil means to use the default function.
5562 This should not be relied upon.")
5564 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
5565 (defvar revert-buffer-insert-file-contents-function
5566 #'revert-buffer-insert-file-contents--default-function
5567 "Function to use to insert contents when reverting this buffer.
5568 The function receives two arguments: the first the nominal file name to use;
5569 the second is t if reading the auto-save file.
5571 The function is responsible for updating (or preserving) point.
5573 For historical reasons, a value of nil means to use the default function.
5574 This should not be relied upon.")
5576 (defun buffer-stale--default-function (&optional _noconfirm)
5577 "Default function to use for `buffer-stale-function'.
5578 This function ignores its argument.
5579 This returns non-nil if the current buffer is visiting a readable file
5580 whose modification time does not match that of the buffer.
5582 This function only handles buffers that are visiting files.
5583 Non-file buffers need a custom function"
5584 (and buffer-file-name
5585 (file-readable-p buffer-file-name)
5586 (not (buffer-modified-p (current-buffer)))
5587 (not (verify-visited-file-modtime (current-buffer)))))
5589 (defvar buffer-stale-function #'buffer-stale--default-function
5590 "Function to check whether a buffer needs reverting.
5591 This should be a function with one optional argument NOCONFIRM.
5592 Auto Revert Mode passes t for NOCONFIRM. The function should return
5593 non-nil if the buffer should be reverted. A return value of
5594 `fast' means that the need for reverting was not checked, but
5595 that reverting the buffer is fast. The buffer is current when
5596 this function is called.
5598 The idea behind the NOCONFIRM argument is that it should be
5599 non-nil if the buffer is going to be reverted without asking the
5600 user. In such situations, one has to be careful with potentially
5601 time consuming operations.
5603 For historical reasons, a value of nil means to use the default function.
5604 This should not be relied upon.
5606 For more information on how this variable is used by Auto Revert mode,
5607 see Info node `(emacs)Supporting additional buffers'.")
5609 (defvar before-revert-hook nil
5610 "Normal hook for `revert-buffer' to run before reverting.
5611 The function `revert-buffer--default' runs this.
5612 A customized `revert-buffer-function' need not run this hook.")
5614 (defvar after-revert-hook nil
5615 "Normal hook for `revert-buffer' to run after reverting.
5616 Note that the hook value that it runs is the value that was in effect
5617 before reverting; that makes a difference if you have buffer-local
5618 hook functions.
5620 The function `revert-buffer--default' runs this.
5621 A customized `revert-buffer-function' need not run this hook.")
5623 (defvar revert-buffer-in-progress-p nil
5624 "Non-nil if a `revert-buffer' operation is in progress, nil otherwise.")
5626 (defvar revert-buffer-internal-hook)
5628 ;; `revert-buffer-function' was defined long ago to be a function of only
5629 ;; 2 arguments, so we have to use a dynbind variable to pass the
5630 ;; `preserve-modes' argument of `revert-buffer'.
5631 (defvar revert-buffer-preserve-modes)
5633 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
5634 "Replace current buffer text with the text of the visited file on disk.
5635 This undoes all changes since the file was visited or saved.
5636 With a prefix argument, offer to revert from latest auto-save file, if
5637 that is more recent than the visited file.
5639 This command also implements an interface for special buffers
5640 that contain text which doesn't come from a file, but reflects
5641 some other data instead (e.g. Dired buffers, `buffer-list'
5642 buffers). This is done via the variable `revert-buffer-function'.
5643 In these cases, it should reconstruct the buffer contents from the
5644 appropriate data.
5646 When called from Lisp, the first argument is IGNORE-AUTO; only offer
5647 to revert from the auto-save file when this is nil. Note that the
5648 sense of this argument is the reverse of the prefix argument, for the
5649 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
5650 to nil.
5652 Optional second argument NOCONFIRM means don't ask for confirmation
5653 at all. (The variable `revert-without-query' offers another way to
5654 revert buffers without querying for confirmation.)
5656 Optional third argument PRESERVE-MODES non-nil means don't alter
5657 the files modes. Normally we reinitialize them using `normal-mode'.
5659 This function binds `revert-buffer-in-progress-p' non-nil while it operates.
5661 This function calls the function that `revert-buffer-function' specifies
5662 to do the work, with arguments IGNORE-AUTO and NOCONFIRM.
5663 The default function runs the hooks `before-revert-hook' and
5664 `after-revert-hook'."
5665 ;; I admit it's odd to reverse the sense of the prefix argument, but
5666 ;; there is a lot of code out there which assumes that the first
5667 ;; argument should be t to avoid consulting the auto-save file, and
5668 ;; there's no straightforward way to encourage authors to notice a
5669 ;; reversal of the argument sense. So I'm just changing the user
5670 ;; interface, but leaving the programmatic interface the same.
5671 (interactive (list (not current-prefix-arg)))
5672 (let ((revert-buffer-in-progress-p t)
5673 (revert-buffer-preserve-modes preserve-modes))
5674 (funcall (or revert-buffer-function #'revert-buffer--default)
5675 ignore-auto noconfirm)))
5677 (defun revert-buffer--default (ignore-auto noconfirm)
5678 "Default function for `revert-buffer'.
5679 The arguments IGNORE-AUTO and NOCONFIRM are as described for `revert-buffer'.
5680 Runs the hooks `before-revert-hook' and `after-revert-hook' at the
5681 start and end.
5683 Calls `revert-buffer-insert-file-contents-function' to reread the
5684 contents of the visited file, with two arguments: the first is the file
5685 name, the second is non-nil if reading an auto-save file.
5687 This function only handles buffers that are visiting files.
5688 Non-file buffers need a custom function."
5689 (with-current-buffer (or (buffer-base-buffer (current-buffer))
5690 (current-buffer))
5691 (let* ((auto-save-p (and (not ignore-auto)
5692 (recent-auto-save-p)
5693 buffer-auto-save-file-name
5694 (file-readable-p buffer-auto-save-file-name)
5695 (y-or-n-p
5696 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
5697 (file-name (if auto-save-p
5698 buffer-auto-save-file-name
5699 buffer-file-name)))
5700 (cond ((null file-name)
5701 (error "Buffer does not seem to be associated with any file"))
5702 ((or noconfirm
5703 (and (not (buffer-modified-p))
5704 (catch 'found
5705 (dolist (regexp revert-without-query)
5706 (when (string-match regexp file-name)
5707 (throw 'found t)))))
5708 (yes-or-no-p (format "Revert buffer from file %s? "
5709 file-name)))
5710 (run-hooks 'before-revert-hook)
5711 ;; If file was backed up but has changed since,
5712 ;; we should make another backup.
5713 (and (not auto-save-p)
5714 (not (verify-visited-file-modtime (current-buffer)))
5715 (setq buffer-backed-up nil))
5716 ;; Effectively copy the after-revert-hook status,
5717 ;; since after-find-file will clobber it.
5718 (let ((global-hook (default-value 'after-revert-hook))
5719 (local-hook (when (local-variable-p 'after-revert-hook)
5720 after-revert-hook))
5721 (inhibit-read-only t))
5722 ;; FIXME: Throw away undo-log when preserve-modes is nil?
5723 (funcall
5724 (or revert-buffer-insert-file-contents-function
5725 #'revert-buffer-insert-file-contents--default-function)
5726 file-name auto-save-p)
5727 ;; Recompute the truename in case changes in symlinks
5728 ;; have changed the truename.
5729 (setq buffer-file-truename
5730 (abbreviate-file-name (file-truename buffer-file-name)))
5731 (after-find-file nil nil t nil revert-buffer-preserve-modes)
5732 ;; Run after-revert-hook as it was before we reverted.
5733 (setq-default revert-buffer-internal-hook global-hook)
5734 (if local-hook
5735 (set (make-local-variable 'revert-buffer-internal-hook)
5736 local-hook)
5737 (kill-local-variable 'revert-buffer-internal-hook))
5738 (run-hooks 'revert-buffer-internal-hook))
5739 t)))))
5741 (defun revert-buffer-insert-file-contents--default-function (file-name auto-save-p)
5742 "Default function for `revert-buffer-insert-file-contents-function'.
5743 The function `revert-buffer--default' calls this.
5744 FILE-NAME is the name of the file. AUTO-SAVE-P is non-nil if this is
5745 an auto-save file."
5746 (cond
5747 ((not (file-exists-p file-name))
5748 (error (if buffer-file-number
5749 "File %s no longer exists!"
5750 "Cannot revert nonexistent file %s")
5751 file-name))
5752 ((not (file-readable-p file-name))
5753 (error (if buffer-file-number
5754 "File %s no longer readable!"
5755 "Cannot revert unreadable file %s")
5756 file-name))
5758 ;; Bind buffer-file-name to nil
5759 ;; so that we don't try to lock the file.
5760 (let ((buffer-file-name nil))
5761 (or auto-save-p
5762 (unlock-buffer)))
5763 (widen)
5764 (let ((coding-system-for-read
5765 ;; Auto-saved file should be read by Emacs's
5766 ;; internal coding.
5767 (if auto-save-p 'auto-save-coding
5768 (or coding-system-for-read
5769 (and
5770 buffer-file-coding-system-explicit
5771 (car buffer-file-coding-system-explicit))))))
5772 (if (and (not enable-multibyte-characters)
5773 coding-system-for-read
5774 (not (memq (coding-system-base
5775 coding-system-for-read)
5776 '(no-conversion raw-text))))
5777 ;; As a coding system suitable for multibyte
5778 ;; buffer is specified, make the current
5779 ;; buffer multibyte.
5780 (set-buffer-multibyte t))
5782 ;; This force after-insert-file-set-coding
5783 ;; (called from insert-file-contents) to set
5784 ;; buffer-file-coding-system to a proper value.
5785 (kill-local-variable 'buffer-file-coding-system)
5787 ;; Note that this preserves point in an intelligent way.
5788 (if revert-buffer-preserve-modes
5789 (let ((buffer-file-format buffer-file-format))
5790 (insert-file-contents file-name (not auto-save-p)
5791 nil nil t))
5792 (insert-file-contents file-name (not auto-save-p)
5793 nil nil t))))))
5795 (defun recover-this-file ()
5796 "Recover the visited file--get contents from its last auto-save file."
5797 (interactive)
5798 (recover-file buffer-file-name))
5800 (defun recover-file (file)
5801 "Visit file FILE, but get contents from its last auto-save file."
5802 ;; Actually putting the file name in the minibuffer should be used
5803 ;; only rarely.
5804 ;; Not just because users often use the default.
5805 (interactive "FRecover file: ")
5806 (setq file (expand-file-name file))
5807 (if (auto-save-file-name-p (file-name-nondirectory file))
5808 (error "%s is an auto-save file" (abbreviate-file-name file)))
5809 (let ((file-name (let ((buffer-file-name file))
5810 (make-auto-save-file-name))))
5811 (cond ((if (file-exists-p file)
5812 (not (file-newer-than-file-p file-name file))
5813 (not (file-exists-p file-name)))
5814 (error "Auto-save file %s not current"
5815 (abbreviate-file-name file-name)))
5816 ((with-temp-buffer-window
5817 "*Directory*" nil
5818 #'(lambda (window _value)
5819 (with-selected-window window
5820 (unwind-protect
5821 (yes-or-no-p (format "Recover auto save file %s? " file-name))
5822 (when (window-live-p window)
5823 (quit-restore-window window 'kill)))))
5824 (with-current-buffer standard-output
5825 (let ((switches dired-listing-switches))
5826 (if (file-symlink-p file)
5827 (setq switches (concat switches " -L")))
5828 ;; Use insert-directory-safely, not insert-directory,
5829 ;; because these files might not exist. In particular,
5830 ;; FILE might not exist if the auto-save file was for
5831 ;; a buffer that didn't visit a file, such as "*mail*".
5832 ;; The code in v20.x called `ls' directly, so we need
5833 ;; to emulate what `ls' did in that case.
5834 (insert-directory-safely file switches)
5835 (insert-directory-safely file-name switches))))
5836 (switch-to-buffer (find-file-noselect file t))
5837 (let ((inhibit-read-only t)
5838 ;; Keep the current buffer-file-coding-system.
5839 (coding-system buffer-file-coding-system)
5840 ;; Auto-saved file should be read with special coding.
5841 (coding-system-for-read 'auto-save-coding))
5842 (erase-buffer)
5843 (insert-file-contents file-name nil)
5844 (set-buffer-file-coding-system coding-system))
5845 (after-find-file nil nil t))
5846 (t (user-error "Recover-file canceled")))))
5848 (defun recover-session ()
5849 "Recover auto save files from a previous Emacs session.
5850 This command first displays a Dired buffer showing you the
5851 previous sessions that you could recover from.
5852 To choose one, move point to the proper line and then type C-c C-c.
5853 Then you'll be asked about a number of files to recover."
5854 (interactive)
5855 (if (null auto-save-list-file-prefix)
5856 (error "You set `auto-save-list-file-prefix' to disable making session files"))
5857 (let ((dir (file-name-directory auto-save-list-file-prefix))
5858 (nd (file-name-nondirectory auto-save-list-file-prefix)))
5859 (unless (file-directory-p dir)
5860 (make-directory dir t))
5861 (unless (directory-files dir nil
5862 (if (string= "" nd)
5863 directory-files-no-dot-files-regexp
5864 (concat "\\`" (regexp-quote nd)))
5866 (error "No previous sessions to recover")))
5867 (let ((ls-lisp-support-shell-wildcards t))
5868 (dired (concat auto-save-list-file-prefix "*")
5869 (concat dired-listing-switches " -t")))
5870 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
5871 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish)
5872 (save-excursion
5873 (goto-char (point-min))
5874 (or (looking-at " Move to the session you want to recover,")
5875 (let ((inhibit-read-only t))
5876 ;; Each line starts with a space
5877 ;; so that Font Lock mode won't highlight the first character.
5878 (insert " To recover a session, move to it and type C-c C-c.\n"
5879 (substitute-command-keys
5880 " To delete a session file, type \
5881 \\[dired-flag-file-deletion] on its line to flag
5882 the file for deletion, then \\[dired-do-flagged-delete] to \
5883 delete flagged files.\n\n"))))))
5885 (defun recover-session-finish ()
5886 "Choose one saved session to recover auto-save files from.
5887 This command is used in the special Dired buffer created by
5888 \\[recover-session]."
5889 (interactive)
5890 ;; Get the name of the session file to recover from.
5891 (let ((file (dired-get-filename))
5892 files
5893 (buffer (get-buffer-create " *recover*")))
5894 (dired-unmark 1)
5895 (dired-do-flagged-delete t)
5896 (unwind-protect
5897 (with-current-buffer buffer
5898 ;; Read in the auto-save-list file.
5899 (erase-buffer)
5900 (insert-file-contents file)
5901 ;; Loop thru the text of that file
5902 ;; and get out the names of the files to recover.
5903 (while (not (eobp))
5904 (let (thisfile autofile)
5905 (if (eolp)
5906 ;; This is a pair of lines for a non-file-visiting buffer.
5907 ;; Get the auto-save file name and manufacture
5908 ;; a "visited file name" from that.
5909 (progn
5910 (forward-line 1)
5911 ;; If there is no auto-save file name, the
5912 ;; auto-save-list file is probably corrupted.
5913 (unless (eolp)
5914 (setq autofile
5915 (buffer-substring-no-properties
5916 (point)
5917 (line-end-position)))
5918 (setq thisfile
5919 (expand-file-name
5920 (substring
5921 (file-name-nondirectory autofile)
5922 1 -1)
5923 (file-name-directory autofile))))
5924 (forward-line 1))
5925 ;; This pair of lines is a file-visiting
5926 ;; buffer. Use the visited file name.
5927 (progn
5928 (setq thisfile
5929 (buffer-substring-no-properties
5930 (point) (progn (end-of-line) (point))))
5931 (forward-line 1)
5932 (setq autofile
5933 (buffer-substring-no-properties
5934 (point) (progn (end-of-line) (point))))
5935 (forward-line 1)))
5936 ;; Ignore a file if its auto-save file does not exist now.
5937 (if (and autofile (file-exists-p autofile))
5938 (setq files (cons thisfile files)))))
5939 (setq files (nreverse files))
5940 ;; The file contains a pair of line for each auto-saved buffer.
5941 ;; The first line of the pair contains the visited file name
5942 ;; or is empty if the buffer was not visiting a file.
5943 ;; The second line is the auto-save file name.
5944 (if files
5945 (map-y-or-n-p "Recover %s? "
5946 (lambda (file)
5947 (condition-case nil
5948 (save-excursion (recover-file file))
5949 (error
5950 "Failed to recover `%s'" file)))
5951 files
5952 '("file" "files" "recover"))
5953 (message "No files can be recovered from this session now")))
5954 (kill-buffer buffer))))
5956 (defun kill-buffer-ask (buffer)
5957 "Kill BUFFER if confirmed."
5958 (when (yes-or-no-p (format "Buffer %s %s. Kill? "
5959 (buffer-name buffer)
5960 (if (buffer-modified-p buffer)
5961 "HAS BEEN EDITED" "is unmodified")))
5962 (kill-buffer buffer)))
5964 (defun kill-some-buffers (&optional list)
5965 "Kill some buffers. Asks the user whether to kill each one of them.
5966 Non-interactively, if optional argument LIST is non-nil, it
5967 specifies the list of buffers to kill, asking for approval for each one."
5968 (interactive)
5969 (if (null list)
5970 (setq list (buffer-list)))
5971 (while list
5972 (let* ((buffer (car list))
5973 (name (buffer-name buffer)))
5974 (and name ; Can be nil for an indirect buffer
5975 ; if we killed the base buffer.
5976 (not (string-equal name ""))
5977 (/= (aref name 0) ?\s)
5978 (kill-buffer-ask buffer)))
5979 (setq list (cdr list))))
5981 (defun kill-matching-buffers (regexp &optional internal-too)
5982 "Kill buffers whose name matches the specified REGEXP.
5983 The optional second argument indicates whether to kill internal buffers too."
5984 (interactive "sKill buffers matching this regular expression: \nP")
5985 (dolist (buffer (buffer-list))
5986 (let ((name (buffer-name buffer)))
5987 (when (and name (not (string-equal name ""))
5988 (or internal-too (/= (aref name 0) ?\s))
5989 (string-match regexp name))
5990 (kill-buffer-ask buffer)))))
5993 (defun rename-auto-save-file ()
5994 "Adjust current buffer's auto save file name for current conditions.
5995 Also rename any existing auto save file, if it was made in this session."
5996 (let ((osave buffer-auto-save-file-name))
5997 (setq buffer-auto-save-file-name
5998 (make-auto-save-file-name))
5999 (if (and osave buffer-auto-save-file-name
6000 (not (string= buffer-auto-save-file-name buffer-file-name))
6001 (not (string= buffer-auto-save-file-name osave))
6002 (file-exists-p osave)
6003 (recent-auto-save-p))
6004 (rename-file osave buffer-auto-save-file-name t))))
6006 (defun make-auto-save-file-name ()
6007 "Return file name to use for auto-saves of current buffer.
6008 Does not consider `auto-save-visited-file-name' as that variable is checked
6009 before calling this function. You can redefine this for customization.
6010 See also `auto-save-file-name-p'."
6011 (if buffer-file-name
6012 (let ((handler (find-file-name-handler buffer-file-name
6013 'make-auto-save-file-name)))
6014 (if handler
6015 (funcall handler 'make-auto-save-file-name)
6016 (let ((list auto-save-file-name-transforms)
6017 (filename buffer-file-name)
6018 result uniq)
6019 ;; Apply user-specified translations
6020 ;; to the file name.
6021 (while (and list (not result))
6022 (if (string-match (car (car list)) filename)
6023 (setq result (replace-match (cadr (car list)) t nil
6024 filename)
6025 uniq (car (cddr (car list)))))
6026 (setq list (cdr list)))
6027 (if result
6028 (if uniq
6029 (setq filename (concat
6030 (file-name-directory result)
6031 (subst-char-in-string
6032 ?/ ?!
6033 (replace-regexp-in-string "!" "!!"
6034 filename))))
6035 (setq filename result)))
6036 (setq result
6037 (if (and (eq system-type 'ms-dos)
6038 (not (msdos-long-file-names)))
6039 ;; We truncate the file name to DOS 8+3 limits
6040 ;; before doing anything else, because the regexp
6041 ;; passed to string-match below cannot handle
6042 ;; extensions longer than 3 characters, multiple
6043 ;; dots, and other atrocities.
6044 (let ((fn (dos-8+3-filename
6045 (file-name-nondirectory buffer-file-name))))
6046 (string-match
6047 "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'"
6049 (concat (file-name-directory buffer-file-name)
6050 "#" (match-string 1 fn)
6051 "." (match-string 3 fn) "#"))
6052 (concat (file-name-directory filename)
6054 (file-name-nondirectory filename)
6055 "#")))
6056 ;; Make sure auto-save file names don't contain characters
6057 ;; invalid for the underlying filesystem.
6058 (if (and (memq system-type '(ms-dos windows-nt cygwin))
6059 ;; Don't modify remote (ange-ftp) filenames
6060 (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" result)))
6061 (convert-standard-filename result)
6062 result))))
6064 ;; Deal with buffers that don't have any associated files. (Mail
6065 ;; mode tends to create a good number of these.)
6067 (let ((buffer-name (buffer-name))
6068 (limit 0)
6069 file-name)
6070 ;; Restrict the characters used in the file name to those which
6071 ;; are known to be safe on all filesystems, url-encoding the
6072 ;; rest.
6073 ;; We do this on all platforms, because even if we are not
6074 ;; running on DOS/Windows, the current directory may be on a
6075 ;; mounted VFAT filesystem, such as a USB memory stick.
6076 (while (string-match "[^A-Za-z0-9-_.~#+]" buffer-name limit)
6077 (let* ((character (aref buffer-name (match-beginning 0)))
6078 (replacement
6079 ;; For multibyte characters, this will produce more than
6080 ;; 2 hex digits, so is not true URL encoding.
6081 (format "%%%02X" character)))
6082 (setq buffer-name (replace-match replacement t t buffer-name))
6083 (setq limit (1+ (match-end 0)))))
6084 ;; Generate the file name.
6085 (setq file-name
6086 (make-temp-file
6087 (let ((fname
6088 (expand-file-name
6089 (format "#%s#" buffer-name)
6090 ;; Try a few alternative directories, to get one we can
6091 ;; write it.
6092 (cond
6093 ((file-writable-p default-directory) default-directory)
6094 ((file-writable-p "/var/tmp/") "/var/tmp/")
6095 ("~/")))))
6096 (if (and (memq system-type '(ms-dos windows-nt cygwin))
6097 ;; Don't modify remote (ange-ftp) filenames
6098 (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" fname)))
6099 ;; The call to convert-standard-filename is in case
6100 ;; buffer-name includes characters not allowed by the
6101 ;; DOS/Windows filesystems. make-temp-file writes to the
6102 ;; file it creates, so we must fix the file name _before_
6103 ;; make-temp-file is called.
6104 (convert-standard-filename fname)
6105 fname))
6106 nil "#"))
6107 ;; make-temp-file creates the file,
6108 ;; but we don't want it to exist until we do an auto-save.
6109 (condition-case ()
6110 (delete-file file-name)
6111 (file-error nil))
6112 file-name)))
6114 (defun auto-save-file-name-p (filename)
6115 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
6116 FILENAME should lack slashes. You can redefine this for customization."
6117 (string-match "\\`#.*#\\'" filename))
6119 (defun wildcard-to-regexp (wildcard)
6120 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
6121 The generated regexp will match a filename only if the filename
6122 matches that wildcard according to shell rules. Only wildcards known
6123 by `sh' are supported."
6124 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
6125 ;; Copy the initial run of non-special characters.
6126 (result (substring wildcard 0 i))
6127 (len (length wildcard)))
6128 ;; If no special characters, we're almost done.
6129 (if i
6130 (while (< i len)
6131 (let ((ch (aref wildcard i))
6133 (setq
6134 result
6135 (concat result
6136 (cond
6137 ((and (eq ch ?\[)
6138 (< (1+ i) len)
6139 (eq (aref wildcard (1+ i)) ?\]))
6140 "\\[")
6141 ((eq ch ?\[) ; [...] maps to regexp char class
6142 (progn
6143 (setq i (1+ i))
6144 (concat
6145 (cond
6146 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
6147 (progn
6148 (setq i (1+ i))
6149 (if (eq (aref wildcard i) ?\])
6150 (progn
6151 (setq i (1+ i))
6152 "[^]")
6153 "[^")))
6154 ((eq (aref wildcard i) ?^)
6155 ;; Found "[^". Insert a `\0' character
6156 ;; (which cannot happen in a filename)
6157 ;; into the character class, so that `^'
6158 ;; is not the first character after `[',
6159 ;; and thus non-special in a regexp.
6160 (progn
6161 (setq i (1+ i))
6162 "[\000^"))
6163 ((eq (aref wildcard i) ?\])
6164 ;; I don't think `]' can appear in a
6165 ;; character class in a wildcard, but
6166 ;; let's be general here.
6167 (progn
6168 (setq i (1+ i))
6169 "[]"))
6170 (t "["))
6171 (prog1 ; copy everything upto next `]'.
6172 (substring wildcard
6174 (setq j (string-match
6175 "]" wildcard i)))
6176 (setq i (if j (1- j) (1- len)))))))
6177 ((eq ch ?.) "\\.")
6178 ((eq ch ?*) "[^\000]*")
6179 ((eq ch ?+) "\\+")
6180 ((eq ch ?^) "\\^")
6181 ((eq ch ?$) "\\$")
6182 ((eq ch ?\\) "\\\\") ; probably cannot happen...
6183 ((eq ch ??) "[^\000]")
6184 (t (char-to-string ch)))))
6185 (setq i (1+ i)))))
6186 ;; Shell wildcards should match the entire filename,
6187 ;; not its part. Make the regexp say so.
6188 (concat "\\`" result "\\'")))
6190 (defcustom list-directory-brief-switches
6191 (purecopy "-CF")
6192 "Switches for `list-directory' to pass to `ls' for brief listing."
6193 :type 'string
6194 :group 'dired)
6196 (defcustom list-directory-verbose-switches
6197 (purecopy "-l")
6198 "Switches for `list-directory' to pass to `ls' for verbose listing."
6199 :type 'string
6200 :group 'dired)
6202 (defun file-expand-wildcards (pattern &optional full)
6203 "Expand wildcard pattern PATTERN.
6204 This returns a list of file names which match the pattern.
6205 Files are sorted in `string<' order.
6207 If PATTERN is written as an absolute file name,
6208 the values are absolute also.
6210 If PATTERN is written as a relative file name, it is interpreted
6211 relative to the current default directory, `default-directory'.
6212 The file names returned are normally also relative to the current
6213 default directory. However, if FULL is non-nil, they are absolute."
6214 (save-match-data
6215 (let* ((nondir (file-name-nondirectory pattern))
6216 (dirpart (file-name-directory pattern))
6217 ;; A list of all dirs that DIRPART specifies.
6218 ;; This can be more than one dir
6219 ;; if DIRPART contains wildcards.
6220 (dirs (if (and dirpart
6221 (string-match "[[*?]" (file-local-name dirpart)))
6222 (mapcar 'file-name-as-directory
6223 (file-expand-wildcards (directory-file-name dirpart)))
6224 (list dirpart)))
6225 contents)
6226 (dolist (dir dirs)
6227 (when (or (null dir) ; Possible if DIRPART is not wild.
6228 (file-accessible-directory-p dir))
6229 (let ((this-dir-contents
6230 ;; Filter out "." and ".."
6231 (delq nil
6232 (mapcar #'(lambda (name)
6233 (unless (string-match "\\`\\.\\.?\\'"
6234 (file-name-nondirectory name))
6235 name))
6236 (directory-files (or dir ".") full
6237 (wildcard-to-regexp nondir))))))
6238 (setq contents
6239 (nconc
6240 (if (and dir (not full))
6241 (mapcar #'(lambda (name) (concat dir name))
6242 this-dir-contents)
6243 this-dir-contents)
6244 contents)))))
6245 contents)))
6247 ;; Let Tramp know that `file-expand-wildcards' does not need an advice.
6248 (provide 'files '(remote-wildcards))
6250 (defun list-directory (dirname &optional verbose)
6251 "Display a list of files in or matching DIRNAME, a la `ls'.
6252 DIRNAME is globbed by the shell if necessary.
6253 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
6254 Actions controlled by variables `list-directory-brief-switches'
6255 and `list-directory-verbose-switches'."
6256 (interactive (let ((pfx current-prefix-arg))
6257 (list (read-directory-name (if pfx "List directory (verbose): "
6258 "List directory (brief): ")
6259 nil default-directory nil)
6260 pfx)))
6261 (let ((switches (if verbose list-directory-verbose-switches
6262 list-directory-brief-switches))
6263 buffer)
6264 (or dirname (setq dirname default-directory))
6265 (setq dirname (expand-file-name dirname))
6266 (with-output-to-temp-buffer "*Directory*"
6267 (setq buffer standard-output)
6268 (buffer-disable-undo standard-output)
6269 (princ "Directory ")
6270 (princ dirname)
6271 (terpri)
6272 (with-current-buffer "*Directory*"
6273 (let ((wildcard (not (file-directory-p dirname))))
6274 (insert-directory dirname switches wildcard (not wildcard)))))
6275 ;; Finishing with-output-to-temp-buffer seems to clobber default-directory.
6276 (with-current-buffer buffer
6277 (setq default-directory
6278 (if (file-directory-p dirname)
6279 (file-name-as-directory dirname)
6280 (file-name-directory dirname))))))
6282 (defun shell-quote-wildcard-pattern (pattern)
6283 "Quote characters special to the shell in PATTERN, leave wildcards alone.
6285 PATTERN is assumed to represent a file-name wildcard suitable for the
6286 underlying filesystem. For Unix and GNU/Linux, each character from the
6287 set [ \\t\\n;<>&|()\\=`\\='\"#$] is quoted with a backslash; for DOS/Windows, all
6288 the parts of the pattern which don't include wildcard characters are
6289 quoted with double quotes.
6291 This function leaves alone existing quote characters (\\ on Unix and \"
6292 on Windows), so PATTERN can use them to quote wildcard characters that
6293 need to be passed verbatim to shell commands."
6294 (save-match-data
6295 (cond
6296 ((memq system-type '(ms-dos windows-nt cygwin))
6297 ;; DOS/Windows don't allow `"' in file names. So if the
6298 ;; argument has quotes, we can safely assume it is already
6299 ;; quoted by the caller.
6300 (if (or (string-match "[\"]" pattern)
6301 ;; We quote [&()#$`'] in case their shell is a port of a
6302 ;; Unixy shell. We quote [,=+] because stock DOS and
6303 ;; Windows shells require that in some cases, such as
6304 ;; passing arguments to batch files that use positional
6305 ;; arguments like %1.
6306 (not (string-match "[ \t;&()#$`',=+]" pattern)))
6307 pattern
6308 (let ((result "\"")
6309 (beg 0)
6310 end)
6311 (while (string-match "[*?]+" pattern beg)
6312 (setq end (match-beginning 0)
6313 result (concat result (substring pattern beg end)
6314 "\""
6315 (substring pattern end (match-end 0))
6316 "\"")
6317 beg (match-end 0)))
6318 (concat result (substring pattern beg) "\""))))
6320 (let ((beg 0))
6321 (while (string-match "[ \t\n;<>&|()`'\"#$]" pattern beg)
6322 (setq pattern
6323 (concat (substring pattern 0 (match-beginning 0))
6324 "\\"
6325 (substring pattern (match-beginning 0)))
6326 beg (1+ (match-end 0)))))
6327 pattern))))
6330 (defvar insert-directory-program (purecopy "ls")
6331 "Absolute or relative name of the `ls' program used by `insert-directory'.")
6333 (defcustom directory-free-space-program (purecopy "df")
6334 "Program to get the amount of free space on a file system.
6335 We assume the output has the format of `df'.
6336 The value of this variable must be just a command name or file name;
6337 if you want to specify options, use `directory-free-space-args'.
6339 A value of nil disables this feature.
6341 If the function `file-system-info' is defined, it is always used in
6342 preference to the program given by this variable."
6343 :type '(choice (string :tag "Program") (const :tag "None" nil))
6344 :group 'dired)
6346 (defcustom directory-free-space-args
6347 (purecopy (if (eq system-type 'darwin) "-k" "-Pk"))
6348 "Options to use when running `directory-free-space-program'."
6349 :type 'string
6350 :group 'dired)
6352 (defun get-free-disk-space (dir)
6353 "Return the amount of free space on directory DIR's file system.
6354 The return value is a string describing the amount of free
6355 space (normally, the number of free 1KB blocks).
6357 This function calls `file-system-info' if it is available, or
6358 invokes the program specified by `directory-free-space-program'
6359 and `directory-free-space-args'. If the system call or program
6360 is unsuccessful, or if DIR is a remote directory, this function
6361 returns nil."
6362 (unless (file-remote-p (expand-file-name dir))
6363 ;; Try to find the number of free blocks. Non-Posix systems don't
6364 ;; always have df, but might have an equivalent system call.
6365 (if (fboundp 'file-system-info)
6366 (let ((fsinfo (file-system-info dir)))
6367 (if fsinfo
6368 (format "%.0f" (/ (nth 2 fsinfo) 1024))))
6369 (setq dir (expand-file-name dir))
6370 (save-match-data
6371 (with-temp-buffer
6372 (when (and directory-free-space-program
6373 ;; Avoid failure if the default directory does
6374 ;; not exist (Bug#2631, Bug#3911).
6375 (let ((default-directory
6376 (locate-dominating-file dir 'file-directory-p)))
6377 (eq (process-file directory-free-space-program
6378 nil t nil
6379 directory-free-space-args
6380 (file-relative-name dir))
6381 0)))
6382 ;; Assume that the "available" column is before the
6383 ;; "capacity" column. Find the "%" and scan backward.
6384 (goto-char (point-min))
6385 (forward-line 1)
6386 (when (re-search-forward
6387 "[[:space:]]+[^[:space:]]+%[^%]*$"
6388 (line-end-position) t)
6389 (goto-char (match-beginning 0))
6390 (let ((endpt (point)))
6391 (skip-chars-backward "^[:space:]")
6392 (buffer-substring-no-properties (point) endpt)))))))))
6394 ;; The following expression replaces `dired-move-to-filename-regexp'.
6395 (defvar directory-listing-before-filename-regexp
6396 (let* ((l "\\([A-Za-z]\\|[^\0-\177]\\)")
6397 (l-or-quote "\\([A-Za-z']\\|[^\0-\177]\\)")
6398 ;; In some locales, month abbreviations are as short as 2 letters,
6399 ;; and they can be followed by ".".
6400 ;; In Breton, a month name can include a quote character.
6401 (month (concat l-or-quote l-or-quote "+\\.?"))
6402 (s " ")
6403 (yyyy "[0-9][0-9][0-9][0-9]")
6404 (dd "[ 0-3][0-9]")
6405 (HH:MM "[ 0-2][0-9][:.][0-5][0-9]")
6406 (seconds "[0-6][0-9]\\([.,][0-9]+\\)?")
6407 (zone "[-+][0-2][0-9][0-5][0-9]")
6408 (iso-mm-dd "[01][0-9]-[0-3][0-9]")
6409 (iso-time (concat HH:MM "\\(:" seconds "\\( ?" zone "\\)?\\)?"))
6410 (iso (concat "\\(\\(" yyyy "-\\)?" iso-mm-dd "[ T]" iso-time
6411 "\\|" yyyy "-" iso-mm-dd "\\)"))
6412 (western (concat "\\(" month s "+" dd "\\|" dd "\\.?" s month "\\)"
6413 s "+"
6414 "\\(" HH:MM "\\|" yyyy "\\)"))
6415 (western-comma (concat month s "+" dd "," s "+" yyyy))
6416 ;; Japanese MS-Windows ls-lisp has one-digit months, and
6417 ;; omits the Kanji characters after month and day-of-month.
6418 ;; On Mac OS X 10.3, the date format in East Asian locales is
6419 ;; day-of-month digits followed by month digits.
6420 (mm "[ 0-1]?[0-9]")
6421 (east-asian
6422 (concat "\\(" mm l "?" s dd l "?" s "+"
6423 "\\|" dd s mm s "+" "\\)"
6424 "\\(" HH:MM "\\|" yyyy l "?" "\\)")))
6425 ;; The "[0-9]" below requires the previous column to end in a digit.
6426 ;; This avoids recognizing `1 may 1997' as a date in the line:
6427 ;; -r--r--r-- 1 may 1997 1168 Oct 19 16:49 README
6429 ;; The "[BkKMGTPEZY]?" below supports "ls -alh" output.
6431 ;; For non-iso date formats, we add the ".*" in order to find
6432 ;; the last possible match. This avoids recognizing
6433 ;; `jservice 10 1024' as a date in the line:
6434 ;; drwxr-xr-x 3 jservice 10 1024 Jul 2 1997 esg-host
6436 ;; vc dired listings provide the state or blanks between file
6437 ;; permissions and date. The state is always surrounded by
6438 ;; parentheses:
6439 ;; -rw-r--r-- (modified) 2005-10-22 21:25 files.el
6440 ;; This is not supported yet.
6441 (purecopy (concat "\\([0-9][BkKMGTPEZY]? " iso
6442 "\\|.*[0-9][BkKMGTPEZY]? "
6443 "\\(" western "\\|" western-comma "\\|" east-asian "\\)"
6444 "\\) +")))
6445 "Regular expression to match up to the file name in a directory listing.
6446 The default value is designed to recognize dates and times
6447 regardless of the language.")
6449 (defvar insert-directory-ls-version 'unknown)
6451 ;; insert-directory
6452 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
6453 ;; FULL-DIRECTORY-P is nil.
6454 ;; The single line of output must display FILE's name as it was
6455 ;; given, namely, an absolute path name.
6456 ;; - must insert exactly one line for each file if WILDCARD or
6457 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
6458 ;; before the file lines, plus optional text after the file lines.
6459 ;; Lines are delimited by "\n", so filenames containing "\n" are not
6460 ;; allowed.
6461 ;; File lines should display the basename.
6462 ;; - must be consistent with
6463 ;; - functions dired-move-to-filename, (these two define what a file line is)
6464 ;; dired-move-to-end-of-filename,
6465 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
6466 ;; dired-insert-headerline
6467 ;; dired-after-subdir-garbage (defines what a "total" line is)
6468 ;; - variable dired-subdir-regexp
6469 ;; - may be passed "--dired" as the first argument in SWITCHES.
6470 ;; Filename handlers might have to remove this switch if their
6471 ;; "ls" command does not support it.
6472 (defun insert-directory (file switches &optional wildcard full-directory-p)
6473 "Insert directory listing for FILE, formatted according to SWITCHES.
6474 Leaves point after the inserted text.
6475 SWITCHES may be a string of options, or a list of strings
6476 representing individual options.
6477 Optional third arg WILDCARD means treat FILE as shell wildcard.
6478 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
6479 switches do not contain `d', so that a full listing is expected.
6481 This works by running a directory listing program
6482 whose name is in the variable `insert-directory-program'.
6483 If WILDCARD, it also runs the shell specified by `shell-file-name'.
6485 When SWITCHES contains the long `--dired' option, this function
6486 treats it specially, for the sake of dired. However, the
6487 normally equivalent short `-D' option is just passed on to
6488 `insert-directory-program', as any other option."
6489 ;; We need the directory in order to find the right handler.
6490 (let ((handler (find-file-name-handler (expand-file-name file)
6491 'insert-directory)))
6492 (if handler
6493 (funcall handler 'insert-directory file switches
6494 wildcard full-directory-p)
6495 (let (result (beg (point)))
6497 ;; Read the actual directory using `insert-directory-program'.
6498 ;; RESULT gets the status code.
6499 (let* (;; We at first read by no-conversion, then after
6500 ;; putting text property `dired-filename, decode one
6501 ;; bunch by one to preserve that property.
6502 (coding-system-for-read 'no-conversion)
6503 ;; This is to control encoding the arguments in call-process.
6504 (coding-system-for-write
6505 (and enable-multibyte-characters
6506 (or file-name-coding-system
6507 default-file-name-coding-system))))
6508 (setq result
6509 (if wildcard
6510 ;; Run ls in the directory part of the file pattern
6511 ;; using the last component as argument.
6512 (let ((default-directory
6513 (if (file-name-absolute-p file)
6514 (file-name-directory file)
6515 (file-name-directory (expand-file-name file))))
6516 (pattern (file-name-nondirectory file)))
6517 ;; NB since switches is passed to the shell, be
6518 ;; careful of malicious values, eg "-l;reboot".
6519 ;; See eg dired-safe-switches-p.
6520 (call-process
6521 shell-file-name nil t nil
6522 "-c"
6523 (concat (if (memq system-type '(ms-dos windows-nt))
6525 "\\") ; Disregard Unix shell aliases!
6526 insert-directory-program
6527 " -d "
6528 (if (stringp switches)
6529 switches
6530 (mapconcat 'identity switches " "))
6531 " -- "
6532 ;; Quote some characters that have
6533 ;; special meanings in shells; but
6534 ;; don't quote the wildcards--we want
6535 ;; them to be special. We also
6536 ;; currently don't quote the quoting
6537 ;; characters in case people want to
6538 ;; use them explicitly to quote
6539 ;; wildcard characters.
6540 (shell-quote-wildcard-pattern pattern))))
6541 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
6542 ;; directory if FILE is a symbolic link.
6543 (unless full-directory-p
6544 (setq switches
6545 (cond
6546 ((stringp switches) (concat switches " -d"))
6547 ((member "-d" switches) switches)
6548 (t (append switches '("-d"))))))
6549 (apply 'call-process
6550 insert-directory-program nil t nil
6551 (append
6552 (if (listp switches) switches
6553 (unless (equal switches "")
6554 ;; Split the switches at any spaces so we can
6555 ;; pass separate options as separate args.
6556 (split-string switches)))
6557 ;; Avoid lossage if FILE starts with `-'.
6558 '("--")
6559 (progn
6560 (if (string-match "\\`~" file)
6561 (setq file (expand-file-name file)))
6562 (list
6563 (if full-directory-p
6564 (concat (file-name-as-directory file) ".")
6565 file))))))))
6567 ;; If we got "//DIRED//" in the output, it means we got a real
6568 ;; directory listing, even if `ls' returned nonzero.
6569 ;; So ignore any errors.
6570 (when (if (stringp switches)
6571 (string-match "--dired\\>" switches)
6572 (member "--dired" switches))
6573 (save-excursion
6574 (forward-line -2)
6575 (when (looking-at "//SUBDIRED//")
6576 (forward-line -1))
6577 (if (looking-at "//DIRED//")
6578 (setq result 0))))
6580 (when (and (not (eq 0 result))
6581 (eq insert-directory-ls-version 'unknown))
6582 ;; The first time ls returns an error,
6583 ;; find the version numbers of ls,
6584 ;; and set insert-directory-ls-version
6585 ;; to > if it is more than 5.2.1, < if it is less, nil if it
6586 ;; is equal or if the info cannot be obtained.
6587 ;; (That can mean it isn't GNU ls.)
6588 (let ((version-out
6589 (with-temp-buffer
6590 (call-process "ls" nil t nil "--version")
6591 (buffer-string))))
6592 (if (string-match "ls (.*utils) \\([0-9.]*\\)$" version-out)
6593 (let* ((version (match-string 1 version-out))
6594 (split (split-string version "[.]"))
6595 (numbers (mapcar 'string-to-number split))
6596 (min '(5 2 1))
6597 comparison)
6598 (while (and (not comparison) (or numbers min))
6599 (cond ((null min)
6600 (setq comparison '>))
6601 ((null numbers)
6602 (setq comparison '<))
6603 ((> (car numbers) (car min))
6604 (setq comparison '>))
6605 ((< (car numbers) (car min))
6606 (setq comparison '<))
6608 (setq numbers (cdr numbers)
6609 min (cdr min)))))
6610 (setq insert-directory-ls-version (or comparison '=)))
6611 (setq insert-directory-ls-version nil))))
6613 ;; For GNU ls versions 5.2.2 and up, ignore minor errors.
6614 (when (and (eq 1 result) (eq insert-directory-ls-version '>))
6615 (setq result 0))
6617 ;; If `insert-directory-program' failed, signal an error.
6618 (unless (eq 0 result)
6619 ;; Delete the error message it may have output.
6620 (delete-region beg (point))
6621 ;; On non-Posix systems, we cannot open a directory, so
6622 ;; don't even try, because that will always result in
6623 ;; the ubiquitous "Access denied". Instead, show the
6624 ;; command line so the user can try to guess what went wrong.
6625 (if (and (file-directory-p file)
6626 (memq system-type '(ms-dos windows-nt)))
6627 (error
6628 "Reading directory: \"%s %s -- %s\" exited with status %s"
6629 insert-directory-program
6630 (if (listp switches) (concat switches) switches)
6631 file result)
6632 ;; Unix. Access the file to get a suitable error.
6633 (access-file file "Reading directory")
6634 (error "Listing directory failed but `access-file' worked")))
6636 (when (if (stringp switches)
6637 (string-match "--dired\\>" switches)
6638 (member "--dired" switches))
6639 ;; The following overshoots by one line for an empty
6640 ;; directory listed with "--dired", but without "-a"
6641 ;; switch, where the ls output contains a
6642 ;; "//DIRED-OPTIONS//" line, but no "//DIRED//" line.
6643 ;; We take care of that case later.
6644 (forward-line -2)
6645 (when (looking-at "//SUBDIRED//")
6646 (delete-region (point) (progn (forward-line 1) (point)))
6647 (forward-line -1))
6648 (if (looking-at "//DIRED//")
6649 (let ((end (line-end-position))
6650 (linebeg (point))
6651 error-lines)
6652 ;; Find all the lines that are error messages,
6653 ;; and record the bounds of each one.
6654 (goto-char beg)
6655 (while (< (point) linebeg)
6656 (or (eql (following-char) ?\s)
6657 (push (list (point) (line-end-position)) error-lines))
6658 (forward-line 1))
6659 (setq error-lines (nreverse error-lines))
6660 ;; Now read the numeric positions of file names.
6661 (goto-char linebeg)
6662 (forward-word-strictly 1)
6663 (forward-char 3)
6664 (while (< (point) end)
6665 (let ((start (insert-directory-adj-pos
6666 (+ beg (read (current-buffer)))
6667 error-lines))
6668 (end (insert-directory-adj-pos
6669 (+ beg (read (current-buffer)))
6670 error-lines)))
6671 (if (memq (char-after end) '(?\n ?\s))
6672 ;; End is followed by \n or by " -> ".
6673 (put-text-property start end 'dired-filename t)
6674 ;; It seems that we can't trust ls's output as to
6675 ;; byte positions of filenames.
6676 (put-text-property beg (point) 'dired-filename nil)
6677 (end-of-line))))
6678 (goto-char end)
6679 (beginning-of-line)
6680 (delete-region (point) (progn (forward-line 1) (point))))
6681 ;; Take care of the case where the ls output contains a
6682 ;; "//DIRED-OPTIONS//"-line, but no "//DIRED//"-line
6683 ;; and we went one line too far back (see above).
6684 (forward-line 1))
6685 (if (looking-at "//DIRED-OPTIONS//")
6686 (delete-region (point) (progn (forward-line 1) (point)))))
6688 ;; Now decode what read if necessary.
6689 (let ((coding (or coding-system-for-read
6690 file-name-coding-system
6691 default-file-name-coding-system
6692 'undecided))
6693 coding-no-eol
6694 val pos)
6695 (when (and enable-multibyte-characters
6696 (not (memq (coding-system-base coding)
6697 '(raw-text no-conversion))))
6698 ;; If no coding system is specified or detection is
6699 ;; requested, detect the coding.
6700 (if (eq (coding-system-base coding) 'undecided)
6701 (setq coding (detect-coding-region beg (point) t)))
6702 (if (not (eq (coding-system-base coding) 'undecided))
6703 (save-restriction
6704 (setq coding-no-eol
6705 (coding-system-change-eol-conversion coding 'unix))
6706 (narrow-to-region beg (point))
6707 (goto-char (point-min))
6708 (while (not (eobp))
6709 (setq pos (point)
6710 val (get-text-property (point) 'dired-filename))
6711 (goto-char (next-single-property-change
6712 (point) 'dired-filename nil (point-max)))
6713 ;; Force no eol conversion on a file name, so
6714 ;; that CR is preserved.
6715 (decode-coding-region pos (point)
6716 (if val coding-no-eol coding))
6717 (if val
6718 (put-text-property pos (point)
6719 'dired-filename t)))))))
6721 (if full-directory-p
6722 ;; Try to insert the amount of free space.
6723 (save-excursion
6724 (goto-char beg)
6725 ;; First find the line to put it on.
6726 (when (re-search-forward "^ *\\(total\\)" nil t)
6727 (let ((available (get-free-disk-space ".")))
6728 (when available
6729 ;; Replace "total" with "used", to avoid confusion.
6730 (replace-match "total used in directory" nil nil nil 1)
6731 (end-of-line)
6732 (insert " available " available))))))))))
6734 (defun insert-directory-adj-pos (pos error-lines)
6735 "Convert `ls --dired' file name position value POS to a buffer position.
6736 File name position values returned in ls --dired output
6737 count only stdout; they don't count the error messages sent to stderr.
6738 So this function converts to them to real buffer positions.
6739 ERROR-LINES is a list of buffer positions of error message lines,
6740 of the form (START END)."
6741 (while (and error-lines (< (caar error-lines) pos))
6742 (setq pos (+ pos (- (nth 1 (car error-lines)) (nth 0 (car error-lines)))))
6743 (pop error-lines))
6744 pos)
6746 (defun insert-directory-safely (file switches
6747 &optional wildcard full-directory-p)
6748 "Insert directory listing for FILE, formatted according to SWITCHES.
6750 Like `insert-directory', but if FILE does not exist, it inserts a
6751 message to that effect instead of signaling an error."
6752 (if (file-exists-p file)
6753 (insert-directory file switches wildcard full-directory-p)
6754 ;; Simulate the message printed by `ls'.
6755 (insert (format "%s: No such file or directory\n" file))))
6757 (defcustom kill-emacs-query-functions nil
6758 "Functions to call with no arguments to query about killing Emacs.
6759 If any of these functions returns nil, killing Emacs is canceled.
6760 `save-buffers-kill-emacs' calls these functions, but `kill-emacs',
6761 the low level primitive, does not. See also `kill-emacs-hook'."
6762 :type 'hook
6763 :version "26.1"
6764 :group 'convenience)
6766 (defcustom confirm-kill-emacs nil
6767 "How to ask for confirmation when leaving Emacs.
6768 If nil, the default, don't ask at all. If the value is non-nil, it should
6769 be a predicate function; for example `yes-or-no-p'."
6770 :type '(choice (const :tag "Ask with yes-or-no-p" yes-or-no-p)
6771 (const :tag "Ask with y-or-n-p" y-or-n-p)
6772 (const :tag "Don't confirm" nil)
6773 (function :tag "Predicate function"))
6774 :group 'convenience
6775 :version "21.1")
6777 (defcustom confirm-kill-processes t
6778 "Non-nil if Emacs should confirm killing processes on exit.
6779 If this variable is nil, the value of
6780 `process-query-on-exit-flag' is ignored. Otherwise, if there are
6781 processes with a non-nil `process-query-on-exit-flag', Emacs will
6782 prompt the user before killing them."
6783 :type 'boolean
6784 :group 'convenience
6785 :version "26.1")
6787 (defun save-buffers-kill-emacs (&optional arg)
6788 "Offer to save each buffer, then kill this Emacs process.
6789 With prefix ARG, silently save all file-visiting buffers without asking.
6790 If there are active processes where `process-query-on-exit-flag'
6791 returns non-nil and `confirm-kill-processes' is non-nil,
6792 asks whether processes should be killed.
6793 Runs the members of `kill-emacs-query-functions' in turn and stops
6794 if any returns nil. If `confirm-kill-emacs' is non-nil, calls it."
6795 (interactive "P")
6796 (save-some-buffers arg t)
6797 (let ((confirm confirm-kill-emacs))
6798 (and
6799 (or (not (memq t (mapcar (function
6800 (lambda (buf) (and (buffer-file-name buf)
6801 (buffer-modified-p buf))))
6802 (buffer-list))))
6803 (progn (setq confirm nil)
6804 (yes-or-no-p "Modified buffers exist; exit anyway? ")))
6805 (or (not (fboundp 'process-list))
6806 ;; process-list is not defined on MSDOS.
6807 (not confirm-kill-processes)
6808 (let ((processes (process-list))
6809 active)
6810 (while processes
6811 (and (memq (process-status (car processes)) '(run stop open listen))
6812 (process-query-on-exit-flag (car processes))
6813 (setq active t))
6814 (setq processes (cdr processes)))
6815 (or (not active)
6816 (with-current-buffer-window
6817 (get-buffer-create "*Process List*") nil
6818 #'(lambda (window _value)
6819 (with-selected-window window
6820 (unwind-protect
6821 (progn
6822 (setq confirm nil)
6823 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))
6824 (when (window-live-p window)
6825 (quit-restore-window window 'kill)))))
6826 (list-processes t)))))
6827 ;; Query the user for other things, perhaps.
6828 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
6829 (or (null confirm)
6830 (funcall confirm "Really exit Emacs? "))
6831 (kill-emacs))))
6833 (defun save-buffers-kill-terminal (&optional arg)
6834 "Offer to save each buffer, then kill the current connection.
6835 If the current frame has no client, kill Emacs itself using
6836 `save-buffers-kill-emacs'.
6838 With prefix ARG, silently save all file-visiting buffers, then kill.
6840 If emacsclient was started with a list of filenames to edit, then
6841 only these files will be asked to be saved."
6842 (interactive "P")
6843 (if (frame-parameter nil 'client)
6844 (server-save-buffers-kill-terminal arg)
6845 (save-buffers-kill-emacs arg)))
6847 ;; We use /: as a prefix to "quote" a file name
6848 ;; so that magic file name handlers will not apply to it.
6850 (setq file-name-handler-alist
6851 (cons (cons (purecopy "\\`/:") 'file-name-non-special)
6852 file-name-handler-alist))
6854 ;; We depend on being the last handler on the list,
6855 ;; so that anything else which does need handling
6856 ;; has been handled already.
6857 ;; So it is safe for us to inhibit *all* magic file name handlers.
6859 (defun file-name-non-special (operation &rest arguments)
6860 (let ((file-name-handler-alist nil)
6861 (default-directory
6862 (if (eq operation 'insert-directory)
6863 (directory-file-name
6864 (expand-file-name
6865 (unhandled-file-name-directory default-directory)))
6866 default-directory))
6867 ;; Get a list of the indices of the args which are file names.
6868 (file-arg-indices
6869 (cdr (or (assq operation
6870 ;; The first six are special because they
6871 ;; return a file name. We want to include the /:
6872 ;; in the return value.
6873 ;; So just avoid stripping it in the first place.
6874 '((expand-file-name . nil)
6875 (file-name-directory . nil)
6876 (file-name-as-directory . nil)
6877 (directory-file-name . nil)
6878 (file-name-sans-versions . nil)
6879 (find-backup-file-name . nil)
6880 ;; `identity' means just return the first arg
6881 ;; not stripped of its quoting.
6882 (substitute-in-file-name identity)
6883 ;; `add' means add "/:" to the result.
6884 (file-truename add 0)
6885 (insert-file-contents insert-file-contents 0)
6886 ;; `unquote-then-quote' means set buffer-file-name
6887 ;; temporarily to unquoted filename.
6888 (verify-visited-file-modtime unquote-then-quote)
6889 ;; List the arguments which are filenames.
6890 (file-name-completion 1)
6891 (file-name-all-completions 1)
6892 (write-region 2 5)
6893 (rename-file 0 1)
6894 (copy-file 0 1)
6895 (make-symbolic-link 0 1)
6896 (add-name-to-file 0 1)))
6897 ;; For all other operations, treat the first argument only
6898 ;; as the file name.
6899 '(nil 0))))
6900 method
6901 ;; Copy ARGUMENTS so we can replace elements in it.
6902 (arguments (copy-sequence arguments)))
6903 (if (symbolp (car file-arg-indices))
6904 (setq method (pop file-arg-indices)))
6905 ;; Strip off the /: from the file names that have it.
6906 (save-match-data
6907 (while (consp file-arg-indices)
6908 (let ((pair (nthcdr (car file-arg-indices) arguments)))
6909 (and (car pair)
6910 (string-match "\\`/:" (car pair))
6911 (setcar pair
6912 (if (= (length (car pair)) 2)
6914 (substring (car pair) 2)))))
6915 (setq file-arg-indices (cdr file-arg-indices))))
6916 (pcase method
6917 (`identity (car arguments))
6918 (`add (concat "/:" (apply operation arguments)))
6919 (`insert-file-contents
6920 (let ((visit (nth 1 arguments)))
6921 (unwind-protect
6922 (apply operation arguments)
6923 (when (and visit buffer-file-name)
6924 (setq buffer-file-name (concat "/:" buffer-file-name))))))
6925 (`unquote-then-quote
6926 (let ((buffer-file-name (substring buffer-file-name 2)))
6927 (apply operation arguments)))
6929 (apply operation arguments)))))
6931 ;; Symbolic modes and read-file-modes.
6933 (defun file-modes-char-to-who (char)
6934 "Convert CHAR to a numeric bit-mask for extracting mode bits.
6935 CHAR is in [ugoa] and represents the category of users (Owner, Group,
6936 Others, or All) for whom to produce the mask.
6937 The bit-mask that is returned extracts from mode bits the access rights
6938 for the specified category of users."
6939 (cond ((= char ?u) #o4700)
6940 ((= char ?g) #o2070)
6941 ((= char ?o) #o1007)
6942 ((= char ?a) #o7777)
6943 (t (error "%c: bad `who' character" char))))
6945 (defun file-modes-char-to-right (char &optional from)
6946 "Convert CHAR to a numeric value of mode bits.
6947 CHAR is in [rwxXstugo] and represents symbolic access permissions.
6948 If CHAR is in [Xugo], the value is taken from FROM (or 0 if omitted)."
6949 (or from (setq from 0))
6950 (cond ((= char ?r) #o0444)
6951 ((= char ?w) #o0222)
6952 ((= char ?x) #o0111)
6953 ((= char ?s) #o6000)
6954 ((= char ?t) #o1000)
6955 ;; Rights relative to the previous file modes.
6956 ((= char ?X) (if (= (logand from #o111) 0) 0 #o0111))
6957 ((= char ?u) (let ((uright (logand #o4700 from)))
6958 (+ uright (/ uright #o10) (/ uright #o100))))
6959 ((= char ?g) (let ((gright (logand #o2070 from)))
6960 (+ gright (/ gright #o10) (* gright #o10))))
6961 ((= char ?o) (let ((oright (logand #o1007 from)))
6962 (+ oright (* oright #o10) (* oright #o100))))
6963 (t (error "%c: bad right character" char))))
6965 (defun file-modes-rights-to-number (rights who-mask &optional from)
6966 "Convert a symbolic mode string specification to an equivalent number.
6967 RIGHTS is the symbolic mode spec, it should match \"([+=-][rwxXstugo]*)+\".
6968 WHO-MASK is the bit-mask specifying the category of users to which to
6969 apply the access permissions. See `file-modes-char-to-who'.
6970 FROM (or 0 if nil) gives the mode bits on which to base permissions if
6971 RIGHTS request to add, remove, or set permissions based on existing ones,
6972 as in \"og+rX-w\"."
6973 (let* ((num-rights (or from 0))
6974 (list-rights (string-to-list rights))
6975 (op (pop list-rights)))
6976 (while (memq op '(?+ ?- ?=))
6977 (let ((num-right 0)
6978 char-right)
6979 (while (memq (setq char-right (pop list-rights))
6980 '(?r ?w ?x ?X ?s ?t ?u ?g ?o))
6981 (setq num-right
6982 (logior num-right
6983 (file-modes-char-to-right char-right num-rights))))
6984 (setq num-right (logand who-mask num-right)
6985 num-rights
6986 (cond ((= op ?+) (logior num-rights num-right))
6987 ((= op ?-) (logand num-rights (lognot num-right)))
6988 (t (logior (logand num-rights (lognot who-mask)) num-right)))
6989 op char-right)))
6990 num-rights))
6992 (defun file-modes-symbolic-to-number (modes &optional from)
6993 "Convert symbolic file modes to numeric file modes.
6994 MODES is the string to convert, it should match
6995 \"[ugoa]*([+-=][rwxXstugo]*)+,...\".
6996 See Info node `(coreutils)File permissions' for more information on this
6997 notation.
6998 FROM (or 0 if nil) gives the mode bits on which to base permissions if
6999 MODES request to add, remove, or set permissions based on existing ones,
7000 as in \"og+rX-w\"."
7001 (save-match-data
7002 (let ((case-fold-search nil)
7003 (num-modes (or from 0)))
7004 (while (/= (string-to-char modes) 0)
7005 (if (string-match "^\\([ugoa]*\\)\\([+=-][rwxXstugo]*\\)+\\(,\\|\\)" modes)
7006 (let ((num-who (apply 'logior 0
7007 (mapcar 'file-modes-char-to-who
7008 (match-string 1 modes)))))
7009 (when (= num-who 0)
7010 (setq num-who (logior #o7000 (default-file-modes))))
7011 (setq num-modes
7012 (file-modes-rights-to-number (substring modes (match-end 1))
7013 num-who num-modes)
7014 modes (substring modes (match-end 3))))
7015 (error "Parse error in modes near `%s'" (substring modes 0))))
7016 num-modes)))
7018 (defun read-file-modes (&optional prompt orig-file)
7019 "Read file modes in octal or symbolic notation and return its numeric value.
7020 PROMPT is used as the prompt, default to \"File modes (octal or symbolic): \".
7021 ORIG-FILE is the name of a file on whose mode bits to base returned
7022 permissions if what user types requests to add, remove, or set permissions
7023 based on existing mode bits, as in \"og+rX-w\"."
7024 (let* ((modes (or (if orig-file (file-modes orig-file) 0)
7025 (error "File not found")))
7026 (modestr (and (stringp orig-file)
7027 (nth 8 (file-attributes orig-file))))
7028 (default
7029 (and (stringp modestr)
7030 (string-match "^.\\(...\\)\\(...\\)\\(...\\)$" modestr)
7031 (replace-regexp-in-string
7032 "-" ""
7033 (format "u=%s,g=%s,o=%s"
7034 (match-string 1 modestr)
7035 (match-string 2 modestr)
7036 (match-string 3 modestr)))))
7037 (value (read-string (or prompt "File modes (octal or symbolic): ")
7038 nil nil default)))
7039 (save-match-data
7040 (if (string-match "^[0-7]+" value)
7041 (string-to-number value 8)
7042 (file-modes-symbolic-to-number value modes)))))
7044 (define-obsolete-variable-alias 'cache-long-line-scans
7045 'cache-long-scans "24.4")
7047 ;; Trashcan handling.
7048 (defcustom trash-directory nil
7049 "Directory for `move-file-to-trash' to move files and directories to.
7050 This directory is only used when the function `system-move-file-to-trash'
7051 is not defined.
7052 Relative paths are interpreted relative to `default-directory'.
7053 If the value is nil, Emacs uses a freedesktop.org-style trashcan."
7054 :type '(choice (const nil) directory)
7055 :group 'auto-save
7056 :version "23.2")
7058 (defvar trash--hexify-table)
7060 (declare-function system-move-file-to-trash "w32fns.c" (filename))
7062 (defun move-file-to-trash (filename)
7063 "Move the file (or directory) named FILENAME to the trash.
7064 When `delete-by-moving-to-trash' is non-nil, this function is
7065 called by `delete-file' and `delete-directory' instead of
7066 deleting files outright.
7068 If the function `system-move-file-to-trash' is defined, call it
7069 with FILENAME as an argument.
7070 Otherwise, if `trash-directory' is non-nil, move FILENAME to that
7071 directory.
7072 Otherwise, trash FILENAME using the freedesktop.org conventions,
7073 like the GNOME, KDE and XFCE desktop environments. Emacs only
7074 moves files to \"home trash\", ignoring per-volume trashcans."
7075 (interactive "fMove file to trash: ")
7076 (cond (trash-directory
7077 ;; If `trash-directory' is non-nil, move the file there.
7078 (let* ((trash-dir (expand-file-name trash-directory))
7079 (fn (directory-file-name (expand-file-name filename)))
7080 (new-fn (expand-file-name (file-name-nondirectory fn)
7081 trash-dir)))
7082 ;; We can't trash a parent directory of trash-directory.
7083 (if (string-prefix-p fn trash-dir)
7084 (error "Trash directory `%s' is a subdirectory of `%s'"
7085 trash-dir filename))
7086 (unless (file-directory-p trash-dir)
7087 (make-directory trash-dir t))
7088 ;; Ensure that the trashed file-name is unique.
7089 (if (file-exists-p new-fn)
7090 (let ((version-control t)
7091 (backup-directory-alist nil))
7092 (setq new-fn (car (find-backup-file-name new-fn)))))
7093 (let (delete-by-moving-to-trash)
7094 (rename-file fn new-fn))))
7095 ;; If `system-move-file-to-trash' is defined, use it.
7096 ((fboundp 'system-move-file-to-trash)
7097 (system-move-file-to-trash filename))
7098 ;; Otherwise, use the freedesktop.org method, as specified at
7099 ;; http://freedesktop.org/wiki/Specifications/trash-spec
7101 (let* ((xdg-data-dir
7102 (directory-file-name
7103 (expand-file-name "Trash"
7104 (or (getenv "XDG_DATA_HOME")
7105 "~/.local/share"))))
7106 (trash-files-dir (expand-file-name "files" xdg-data-dir))
7107 (trash-info-dir (expand-file-name "info" xdg-data-dir))
7108 (fn (directory-file-name (expand-file-name filename))))
7110 ;; Check if we have permissions to delete.
7111 (unless (file-writable-p (directory-file-name
7112 (file-name-directory fn)))
7113 (error "Cannot move %s to trash: Permission denied" filename))
7114 ;; The trashed file cannot be the trash dir or its parent.
7115 (if (string-prefix-p fn trash-files-dir)
7116 (error "The trash directory %s is a subdirectory of %s"
7117 trash-files-dir filename))
7118 (if (string-prefix-p fn trash-info-dir)
7119 (error "The trash directory %s is a subdirectory of %s"
7120 trash-info-dir filename))
7122 ;; Ensure that the trash directory exists; otherwise, create it.
7123 (with-file-modes #o700
7124 (unless (file-exists-p trash-files-dir)
7125 (make-directory trash-files-dir t))
7126 (unless (file-exists-p trash-info-dir)
7127 (make-directory trash-info-dir t)))
7129 ;; Try to move to trash with .trashinfo undo information
7130 (save-excursion
7131 (with-temp-buffer
7132 (set-buffer-file-coding-system 'utf-8-unix)
7133 (insert "[Trash Info]\nPath=")
7134 ;; Perform url-encoding on FN. For compatibility with
7135 ;; other programs (e.g. XFCE Thunar), allow literal "/"
7136 ;; for path separators.
7137 (unless (boundp 'trash--hexify-table)
7138 (setq trash--hexify-table (make-vector 256 nil))
7139 (let ((unreserved-chars
7140 (list ?/ ?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m
7141 ?n ?o ?p ?q ?r ?s ?t ?u ?v ?w ?x ?y ?z ?A
7142 ?B ?C ?D ?E ?F ?G ?H ?I ?J ?K ?L ?M ?N ?O
7143 ?P ?Q ?R ?S ?T ?U ?V ?W ?X ?Y ?Z ?0 ?1 ?2
7144 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?- ?_ ?. ?! ?~ ?* ?'
7145 ?\( ?\))))
7146 (dotimes (byte 256)
7147 (aset trash--hexify-table byte
7148 (if (memq byte unreserved-chars)
7149 (char-to-string byte)
7150 (format "%%%02x" byte))))))
7151 (mapc (lambda (byte)
7152 (insert (aref trash--hexify-table byte)))
7153 (if (multibyte-string-p fn)
7154 (encode-coding-string fn 'utf-8)
7155 fn))
7156 (insert "\nDeletionDate="
7157 (format-time-string "%Y-%m-%dT%T")
7158 "\n")
7160 ;; Attempt to make .trashinfo file, trying up to 5
7161 ;; times. The .trashinfo file is opened with O_EXCL,
7162 ;; as per trash-spec 0.7, even if that can be a problem
7163 ;; on old NFS versions...
7164 (let* ((tries 5)
7165 (base-fn (expand-file-name
7166 (file-name-nondirectory fn)
7167 trash-files-dir))
7168 (new-fn base-fn)
7169 success info-fn)
7170 (while (> tries 0)
7171 (setq info-fn (expand-file-name
7172 (concat (file-name-nondirectory new-fn)
7173 ".trashinfo")
7174 trash-info-dir))
7175 (unless (condition-case nil
7176 (progn
7177 (write-region nil nil info-fn nil
7178 'quiet info-fn 'excl)
7179 (setq tries 0 success t))
7180 (file-already-exists nil))
7181 (setq tries (1- tries))
7182 ;; Uniquify new-fn. (Some file managers do not
7183 ;; like Emacs-style backup file names---e.g. bug
7184 ;; 170956 in Konqueror bug tracker.)
7185 (setq new-fn (make-temp-name (concat base-fn "_")))))
7186 (unless success
7187 (error "Cannot move %s to trash: Lock failed" filename))
7189 ;; Finally, try to move the file to the trashcan.
7190 (let ((delete-by-moving-to-trash nil))
7191 (rename-file fn new-fn)))))))))
7193 (defsubst file-attribute-type (attributes)
7194 "The type field in ATTRIBUTES returned by `file-attributes'.
7195 The value is either t for directory, string (name linked to) for
7196 symbolic link, or nil."
7197 (nth 0 attributes))
7199 (defsubst file-attribute-link-number (attributes)
7200 "Return the number of links in ATTRIBUTES returned by `file-attributes'."
7201 (nth 1 attributes))
7203 (defsubst file-attribute-user-id (attributes)
7204 "The UID field in ATTRIBUTES returned by `file-attributes'.
7205 This is either a string or a number. If a string value cannot be
7206 looked up, a numeric value, either an integer or a float, is
7207 returned."
7208 (nth 2 attributes))
7210 (defsubst file-attribute-group-id (attributes)
7211 "The GID field in ATTRIBUTES returned by `file-attributes'.
7212 This is either a string or a number. If a string value cannot be
7213 looked up, a numeric value, either an integer or a float, is
7214 returned."
7215 (nth 3 attributes))
7217 (defsubst file-attribute-access-time (attributes)
7218 "The last access time in ATTRIBUTES returned by `file-attributes'.
7219 This a list of integers (HIGH LOW USEC PSEC) in the same style
7220 as (current-time)."
7221 (nth 4 attributes))
7223 (defsubst file-attribute-modification-time (attributes)
7224 "The modification time in ATTRIBUTES returned by `file-attributes'.
7225 This is the time of the last change to the file's contents, and
7226 is a list of integers (HIGH LOW USEC PSEC) in the same style
7227 as (current-time)."
7228 (nth 5 attributes))
7230 (defsubst file-attribute-status-change-time (attributes)
7231 "The status modification time in ATTRIBUTES returned by `file-attributes'.
7232 This is the time of last change to the file's attributes: owner
7233 and group, access mode bits, etc, and is a list of integers (HIGH
7234 LOW USEC PSEC) in the same style as (current-time)."
7235 (nth 6 attributes))
7237 (defsubst file-attribute-size (attributes)
7238 "The size (in bytes) in ATTRIBUTES returned by `file-attributes'.
7239 This is a floating point number if the size is too large for an integer."
7240 (nth 7 attributes))
7242 (defsubst file-attribute-modes (attributes)
7243 "The file modes in ATTRIBUTES returned by `file-attributes'.
7244 This is a string of ten letters or dashes as in ls -l."
7245 (nth 8 attributes))
7247 (defsubst file-attribute-inode-number (attributes)
7248 "The inode number in ATTRIBUTES returned by `file-attributes'.
7249 If it is larger than what an Emacs integer can hold, this is of
7250 the form (HIGH . LOW): first the high bits, then the low 16 bits.
7251 If even HIGH is too large for an Emacs integer, this is instead
7252 of the form (HIGH MIDDLE . LOW): first the high bits, then the
7253 middle 24 bits, and finally the low 16 bits."
7254 (nth 10 attributes))
7256 (defsubst file-attribute-device-number (attributes)
7257 "The file system device number in ATTRIBUTES returned by `file-attributes'.
7258 If it is larger than what an Emacs integer can hold, this is of
7259 the form (HIGH . LOW): first the high bits, then the low 16 bits.
7260 If even HIGH is too large for an Emacs integer, this is instead
7261 of the form (HIGH MIDDLE . LOW): first the high bits, then the
7262 middle 24 bits, and finally the low 16 bits."
7263 (nth 11 attributes))
7265 (defun file-attribute-collect (attributes &rest attr-names)
7266 "Return a sublist of ATTRIBUTES returned by `file-attributes'.
7267 ATTR-NAMES are symbols with the selected attribute names.
7269 Valid attribute names are: type, link-number, user-id, group-id,
7270 access-time, modification-time, status-change-time, size, modes,
7271 inode-number and device-number."
7272 (let ((all '(type link-number user-id group-id access-time
7273 modification-time status-change-time
7274 size modes inode-number device-number))
7275 result)
7276 (while attr-names
7277 (let ((attr (pop attr-names)))
7278 (if (memq attr all)
7279 (push (funcall
7280 (intern (format "file-attribute-%s" (symbol-name attr)))
7281 attributes)
7282 result)
7283 (error "Wrong attribute name '%S'" attr))))
7284 (nreverse result)))
7286 (define-key ctl-x-map "\C-f" 'find-file)
7287 (define-key ctl-x-map "\C-r" 'find-file-read-only)
7288 (define-key ctl-x-map "\C-v" 'find-alternate-file)
7289 (define-key ctl-x-map "\C-s" 'save-buffer)
7290 (define-key ctl-x-map "s" 'save-some-buffers)
7291 (define-key ctl-x-map "\C-w" 'write-file)
7292 (define-key ctl-x-map "i" 'insert-file)
7293 (define-key esc-map "~" 'not-modified)
7294 (define-key ctl-x-map "\C-d" 'list-directory)
7295 (define-key ctl-x-map "\C-c" 'save-buffers-kill-terminal)
7296 (define-key ctl-x-map "\C-q" 'read-only-mode)
7298 (define-key ctl-x-4-map "f" 'find-file-other-window)
7299 (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
7300 (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
7301 (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
7302 (define-key ctl-x-4-map "\C-o" 'display-buffer)
7304 (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
7305 (define-key ctl-x-5-map "f" 'find-file-other-frame)
7306 (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
7307 (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
7308 (define-key ctl-x-5-map "\C-o" 'display-buffer-other-frame)
7310 ;;; files.el ends here