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