; Spelling fixes
[emacs.git] / lisp / files.el
blobc7de4453d75747cdf05fc16c876bfde8030514a4
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
2913 nil magic-mode-alist
2914 (lambda (re _dummy)
2915 (cond
2916 ((functionp re)
2917 (funcall re))
2918 ((stringp re)
2919 (looking-at re))
2921 (error
2922 "Problem in magic-mode-alist with element %s"
2923 re))))))))
2924 (set-auto-mode-0 done keep-mode-if-same)))
2925 ;; Next compare the filename against the entries in auto-mode-alist.
2926 (unless done
2927 (if buffer-file-name
2928 (let ((name buffer-file-name)
2929 (remote-id (file-remote-p buffer-file-name))
2930 (case-insensitive-p (file-name-case-insensitive-p
2931 buffer-file-name)))
2932 ;; Remove backup-suffixes from file name.
2933 (setq name (file-name-sans-versions name))
2934 ;; Remove remote file name identification.
2935 (when (and (stringp remote-id)
2936 (string-match (regexp-quote remote-id) name))
2937 (setq name (substring name (match-end 0))))
2938 (while name
2939 ;; Find first matching alist entry.
2940 (setq mode
2941 (if case-insensitive-p
2942 ;; Filesystem is case-insensitive.
2943 (let ((case-fold-search t))
2944 (assoc-default name auto-mode-alist
2945 'string-match))
2946 ;; Filesystem is case-sensitive.
2948 ;; First match case-sensitively.
2949 (let ((case-fold-search nil))
2950 (assoc-default name auto-mode-alist
2951 'string-match))
2952 ;; Fallback to case-insensitive match.
2953 (and auto-mode-case-fold
2954 (let ((case-fold-search t))
2955 (assoc-default name auto-mode-alist
2956 'string-match))))))
2957 (if (and mode
2958 (consp mode)
2959 (cadr mode))
2960 (setq mode (car mode)
2961 name (substring name 0 (match-beginning 0)))
2962 (setq name nil))
2963 (when mode
2964 (set-auto-mode-0 mode keep-mode-if-same)
2965 (setq done t))))))
2966 ;; Next try matching the buffer beginning against magic-fallback-mode-alist.
2967 (unless done
2968 (if (setq done (save-excursion
2969 (goto-char (point-min))
2970 (save-restriction
2971 (narrow-to-region (point-min)
2972 (min (point-max)
2973 (+ (point-min) magic-mode-regexp-match-limit)))
2974 (assoc-default nil magic-fallback-mode-alist
2975 (lambda (re _dummy)
2976 (cond
2977 ((functionp re)
2978 (funcall re))
2979 ((stringp re)
2980 (looking-at re))
2982 (error
2983 "Problem with magic-fallback-mode-alist element: %s"
2984 re))))))))
2985 (set-auto-mode-0 done keep-mode-if-same)))
2986 (unless done
2987 (set-buffer-major-mode (current-buffer)))))
2989 ;; When `keep-mode-if-same' is set, we are working on behalf of
2990 ;; set-visited-file-name. In that case, if the major mode specified is the
2991 ;; same one we already have, don't actually reset it. We don't want to lose
2992 ;; minor modes such as Font Lock.
2993 (defun set-auto-mode-0 (mode &optional keep-mode-if-same)
2994 "Apply MODE and return it.
2995 If optional arg KEEP-MODE-IF-SAME is non-nil, MODE is chased of
2996 any aliases and compared to current major mode. If they are the
2997 same, do nothing and return nil."
2998 (unless (and keep-mode-if-same
2999 (eq (indirect-function mode)
3000 (indirect-function major-mode)))
3001 (when mode
3002 (funcall mode)
3003 mode)))
3005 (defvar file-auto-mode-skip "^\\(#!\\|'\\\\\"\\)"
3006 "Regexp of lines to skip when looking for file-local settings.
3007 If the first line matches this regular expression, then the -*-...-*- file-
3008 local settings will be consulted on the second line instead of the first.")
3010 (defun set-auto-mode-1 ()
3011 "Find the -*- spec in the buffer.
3012 Call with point at the place to start searching from.
3013 If one is found, set point to the beginning and return the position
3014 of the end. Otherwise, return nil; may change point.
3015 The variable `inhibit-local-variables-regexps' can cause a -*- spec to
3016 be ignored; but `enable-local-variables' and `local-enable-local-variables'
3017 have no effect."
3018 (let (beg end)
3019 (and
3020 ;; Don't look for -*- if this file name matches any
3021 ;; of the regexps in inhibit-local-variables-regexps.
3022 (not (inhibit-local-variables-p))
3023 (search-forward "-*-" (line-end-position
3024 ;; If the file begins with "#!" (exec
3025 ;; interpreter magic), look for mode frobs
3026 ;; in the first two lines. You cannot
3027 ;; necessarily put them in the first line
3028 ;; of such a file without screwing up the
3029 ;; interpreter invocation. The same holds
3030 ;; for '\" in man pages (preprocessor
3031 ;; magic for the `man' program).
3032 (and (looking-at file-auto-mode-skip) 2)) t)
3033 (progn
3034 (skip-chars-forward " \t")
3035 (setq beg (point))
3036 (search-forward "-*-" (line-end-position) t))
3037 (progn
3038 (forward-char -3)
3039 (skip-chars-backward " \t")
3040 (setq end (point))
3041 (goto-char beg)
3042 end))))
3044 ;;; Handling file local variables
3046 (defvar ignored-local-variables
3047 '(ignored-local-variables safe-local-variable-values
3048 file-local-variables-alist dir-local-variables-alist)
3049 "Variables to be ignored in a file's local variable spec.")
3050 (put 'ignored-local-variables 'risky-local-variable t)
3052 (defvar hack-local-variables-hook nil
3053 "Normal hook run after processing a file's local variables specs.
3054 Major modes can use this to examine user-specified local variables
3055 in order to initialize other data structure based on them.")
3057 (defcustom safe-local-variable-values nil
3058 "List variable-value pairs that are considered safe.
3059 Each element is a cons cell (VAR . VAL), where VAR is a variable
3060 symbol and VAL is a value that is considered safe."
3061 :risky t
3062 :group 'find-file
3063 :type 'alist)
3065 (defcustom safe-local-eval-forms
3066 ;; This should be here at least as long as Emacs supports write-file-hooks.
3067 '((add-hook 'write-file-hooks 'time-stamp)
3068 (add-hook 'write-file-functions 'time-stamp)
3069 (add-hook 'before-save-hook 'time-stamp nil t)
3070 (add-hook 'before-save-hook 'delete-trailing-whitespace nil t))
3071 "Expressions that are considered safe in an `eval:' local variable.
3072 Add expressions to this list if you want Emacs to evaluate them, when
3073 they appear in an `eval' local variable specification, without first
3074 asking you for confirmation."
3075 :risky t
3076 :group 'find-file
3077 :version "24.1" ; added write-file-hooks
3078 :type '(repeat sexp))
3080 ;; Risky local variables:
3081 (mapc (lambda (var) (put var 'risky-local-variable t))
3082 '(after-load-alist
3083 buffer-auto-save-file-name
3084 buffer-file-name
3085 buffer-file-truename
3086 buffer-undo-list
3087 debugger
3088 default-text-properties
3089 eval
3090 exec-directory
3091 exec-path
3092 file-name-handler-alist
3093 frame-title-format
3094 global-mode-string
3095 header-line-format
3096 icon-title-format
3097 inhibit-quit
3098 load-path
3099 max-lisp-eval-depth
3100 max-specpdl-size
3101 minor-mode-map-alist
3102 minor-mode-overriding-map-alist
3103 mode-line-format
3104 mode-name
3105 overriding-local-map
3106 overriding-terminal-local-map
3107 process-environment
3108 standard-input
3109 standard-output
3110 unread-command-events))
3112 ;; Safe local variables:
3114 ;; For variables defined by major modes, the safety declarations can go into
3115 ;; the major mode's file, since that will be loaded before file variables are
3116 ;; processed.
3118 ;; For variables defined by minor modes, put the safety declarations in the
3119 ;; file defining the minor mode after the defcustom/defvar using an autoload
3120 ;; cookie, e.g.:
3122 ;; ;;;###autoload(put 'variable 'safe-local-variable 'stringp)
3124 ;; Otherwise, when Emacs visits a file specifying that local variable, the
3125 ;; minor mode file may not be loaded yet.
3127 ;; For variables defined in the C source code the declaration should go here:
3129 (dolist (pair
3130 '((buffer-read-only . booleanp) ;; C source code
3131 (default-directory . stringp) ;; C source code
3132 (fill-column . integerp) ;; C source code
3133 (indent-tabs-mode . booleanp) ;; C source code
3134 (left-margin . integerp) ;; C source code
3135 (no-update-autoloads . booleanp)
3136 (lexical-binding . booleanp) ;; C source code
3137 (tab-width . integerp) ;; C source code
3138 (truncate-lines . booleanp) ;; C source code
3139 (word-wrap . booleanp) ;; C source code
3140 (bidi-display-reordering . booleanp))) ;; C source code
3141 (put (car pair) 'safe-local-variable (cdr pair)))
3143 (put 'bidi-paragraph-direction 'safe-local-variable
3144 (lambda (v) (memq v '(nil right-to-left left-to-right))))
3146 (put 'c-set-style 'safe-local-eval-function t)
3148 (defvar file-local-variables-alist nil
3149 "Alist of file-local variable settings in the current buffer.
3150 Each element in this list has the form (VAR . VALUE), where VAR
3151 is a file-local variable (a symbol) and VALUE is the value
3152 specified. The actual value in the buffer may differ from VALUE,
3153 if it is changed by the major or minor modes, or by the user.")
3154 (make-variable-buffer-local 'file-local-variables-alist)
3155 (put 'file-local-variables-alist 'permanent-local t)
3157 (defvar dir-local-variables-alist nil
3158 "Alist of directory-local variable settings in the current buffer.
3159 Each element in this list has the form (VAR . VALUE), where VAR
3160 is a directory-local variable (a symbol) and VALUE is the value
3161 specified in .dir-locals.el. The actual value in the buffer
3162 may differ from VALUE, if it is changed by the major or minor modes,
3163 or by the user.")
3164 (make-variable-buffer-local 'dir-local-variables-alist)
3166 (defvar before-hack-local-variables-hook nil
3167 "Normal hook run before setting file-local variables.
3168 It is called after checking for unsafe/risky variables and
3169 setting `file-local-variables-alist', and before applying the
3170 variables stored in `file-local-variables-alist'. A hook
3171 function is allowed to change the contents of this alist.
3173 This hook is called only if there is at least one file-local
3174 variable to set.")
3176 (defun hack-local-variables-confirm (all-vars unsafe-vars risky-vars dir-name)
3177 "Get confirmation before setting up local variable values.
3178 ALL-VARS is the list of all variables to be set up.
3179 UNSAFE-VARS is the list of those that aren't marked as safe or risky.
3180 RISKY-VARS is the list of those that are marked as risky.
3181 If these settings come from directory-local variables, then
3182 DIR-NAME is the name of the associated directory. Otherwise it is nil."
3183 (unless noninteractive
3184 (let ((name (cond (dir-name)
3185 (buffer-file-name
3186 (file-name-nondirectory buffer-file-name))
3187 ((concat "buffer " (buffer-name)))))
3188 (offer-save (and (eq enable-local-variables t)
3189 unsafe-vars))
3190 (buf (get-buffer-create "*Local Variables*")))
3191 ;; Set up the contents of the *Local Variables* buffer.
3192 (with-current-buffer buf
3193 (erase-buffer)
3194 (cond
3195 (unsafe-vars
3196 (insert "The local variables list in " name
3197 "\ncontains values that may not be safe (*)"
3198 (if risky-vars
3199 ", and variables that are risky (**)."
3200 ".")))
3201 (risky-vars
3202 (insert "The local variables list in " name
3203 "\ncontains variables that are risky (**)."))
3205 (insert "A local variables list is specified in " name ".")))
3206 (insert "\n\nDo you want to apply it? You can type
3207 y -- to apply the local variables list.
3208 n -- to ignore the local variables list.")
3209 (if offer-save
3210 (insert "
3211 ! -- to apply the local variables list, and permanently mark these
3212 values (*) as safe (in the future, they will be set automatically.)\n\n")
3213 (insert "\n\n"))
3214 (dolist (elt all-vars)
3215 (cond ((member elt unsafe-vars)
3216 (insert " * "))
3217 ((member elt risky-vars)
3218 (insert " ** "))
3220 (insert " ")))
3221 (princ (car elt) buf)
3222 (insert " : ")
3223 ;; Make strings with embedded whitespace easier to read.
3224 (let ((print-escape-newlines t))
3225 (prin1 (cdr elt) buf))
3226 (insert "\n"))
3227 (set (make-local-variable 'cursor-type) nil)
3228 (set-buffer-modified-p nil)
3229 (goto-char (point-min)))
3231 ;; Display the buffer and read a choice.
3232 (save-window-excursion
3233 (pop-to-buffer buf)
3234 (let* ((exit-chars '(?y ?n ?\s ?\C-g ?\C-v))
3235 (prompt (format "Please type %s%s: "
3236 (if offer-save "y, n, or !" "y or n")
3237 (if (< (line-number-at-pos (point-max))
3238 (window-body-height))
3240 (push ?\C-v exit-chars)
3241 ", or C-v to scroll")))
3242 char)
3243 (if offer-save (push ?! exit-chars))
3244 (while (null char)
3245 (setq char (read-char-choice prompt exit-chars t))
3246 (when (eq char ?\C-v)
3247 (condition-case nil
3248 (scroll-up)
3249 (error (goto-char (point-min))
3250 (recenter 1)))
3251 (setq char nil)))
3252 (when (and offer-save (= char ?!) unsafe-vars)
3253 (customize-push-and-save 'safe-local-variable-values unsafe-vars))
3254 (prog1 (memq char '(?! ?\s ?y))
3255 (quit-window t)))))))
3257 (defconst hack-local-variable-regexp
3258 "[ \t]*\\([^][;\"'?()\\ \t\n]+\\)[ \t]*:[ \t]*")
3260 (defun hack-local-variables-prop-line (&optional handle-mode)
3261 "Return local variables specified in the -*- line.
3262 Usually returns an alist of elements (VAR . VAL), where VAR is a
3263 variable and VAL is the specified value. Ignores any
3264 specification for `coding:', and sometimes for `mode' (which
3265 should have already been handled by `set-auto-coding' and
3266 `set-auto-mode', respectively). Return nil if the -*- line is
3267 malformed.
3269 If HANDLE-MODE is nil, we return the alist of all the local
3270 variables in the line except `coding' as described above. If it
3271 is neither nil nor t, we do the same, except that any settings of
3272 `mode' and `coding' are ignored. If HANDLE-MODE is t, we ignore
3273 all settings in the line except for `mode', which \(if present) we
3274 return as the symbol specifying the mode."
3275 (catch 'malformed-line
3276 (save-excursion
3277 (goto-char (point-min))
3278 (let ((end (set-auto-mode-1))
3279 result)
3280 (cond ((not end)
3281 nil)
3282 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
3283 ;; Simple form: "-*- MODENAME -*-".
3284 (if (eq handle-mode t)
3285 (intern (concat (match-string 1) "-mode"))))
3287 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
3288 ;; (last ";" is optional).
3289 ;; If HANDLE-MODE is t, just check for `mode'.
3290 ;; Otherwise, parse the -*- line into the RESULT alist.
3291 (while (not (or (and (eq handle-mode t) result)
3292 (>= (point) end)))
3293 (unless (looking-at hack-local-variable-regexp)
3294 (message "Malformed mode-line: %S"
3295 (buffer-substring-no-properties (point) end))
3296 (throw 'malformed-line nil))
3297 (goto-char (match-end 0))
3298 ;; There used to be a downcase here,
3299 ;; but the manual didn't say so,
3300 ;; and people want to set var names that aren't all lc.
3301 (let* ((key (intern (match-string 1)))
3302 (val (save-restriction
3303 (narrow-to-region (point) end)
3304 (let ((read-circle nil))
3305 (read (current-buffer)))))
3306 ;; It is traditional to ignore
3307 ;; case when checking for `mode' in set-auto-mode,
3308 ;; so we must do that here as well.
3309 ;; That is inconsistent, but we're stuck with it.
3310 ;; The same can be said for `coding' in set-auto-coding.
3311 (keyname (downcase (symbol-name key))))
3312 (cond
3313 ((eq handle-mode t)
3314 (and (equal keyname "mode")
3315 (setq result
3316 (intern (concat (downcase (symbol-name val))
3317 "-mode")))))
3318 ((equal keyname "coding"))
3320 (when (or (not handle-mode)
3321 (not (equal keyname "mode")))
3322 (condition-case nil
3323 (push (cons (cond ((eq key 'eval) 'eval)
3324 ;; Downcase "Mode:".
3325 ((equal keyname "mode") 'mode)
3326 (t (indirect-variable key)))
3327 val)
3328 result)
3329 (error nil)))))
3330 (skip-chars-forward " \t;")))
3331 result))))))
3333 (defun hack-local-variables-filter (variables dir-name)
3334 "Filter local variable settings, querying the user if necessary.
3335 VARIABLES is the alist of variable-value settings. This alist is
3336 filtered based on the values of `ignored-local-variables',
3337 `enable-local-eval', `enable-local-variables', and (if necessary)
3338 user interaction. The results are added to
3339 `file-local-variables-alist', without applying them.
3340 If these settings come from directory-local variables, then
3341 DIR-NAME is the name of the associated directory. Otherwise it is nil."
3342 ;; Find those variables that we may want to save to
3343 ;; `safe-local-variable-values'.
3344 (let (all-vars risky-vars unsafe-vars)
3345 (dolist (elt variables)
3346 (let ((var (car elt))
3347 (val (cdr elt)))
3348 (cond ((memq var ignored-local-variables)
3349 ;; Ignore any variable in `ignored-local-variables'.
3350 nil)
3351 ;; Obey `enable-local-eval'.
3352 ((eq var 'eval)
3353 (when enable-local-eval
3354 (let ((safe (or (hack-one-local-variable-eval-safep val)
3355 ;; In case previously marked safe (bug#5636).
3356 (safe-local-variable-p var val))))
3357 ;; If not safe and e-l-v = :safe, ignore totally.
3358 (when (or safe (not (eq enable-local-variables :safe)))
3359 (push elt all-vars)
3360 (or (eq enable-local-eval t)
3361 safe
3362 (push elt unsafe-vars))))))
3363 ;; Ignore duplicates (except `mode') in the present list.
3364 ((and (assq var all-vars) (not (eq var 'mode))) nil)
3365 ;; Accept known-safe variables.
3366 ((or (memq var '(mode unibyte coding))
3367 (safe-local-variable-p var val))
3368 (push elt all-vars))
3369 ;; The variable is either risky or unsafe:
3370 ((not (eq enable-local-variables :safe))
3371 (push elt all-vars)
3372 (if (risky-local-variable-p var val)
3373 (push elt risky-vars)
3374 (push elt unsafe-vars))))))
3375 (and all-vars
3376 ;; Query, unless all vars are safe or user wants no querying.
3377 (or (and (eq enable-local-variables t)
3378 (null unsafe-vars)
3379 (null risky-vars))
3380 (memq enable-local-variables '(:all :safe))
3381 (hack-local-variables-confirm all-vars unsafe-vars
3382 risky-vars dir-name))
3383 (dolist (elt all-vars)
3384 (unless (memq (car elt) '(eval mode))
3385 (unless dir-name
3386 (setq dir-local-variables-alist
3387 (assq-delete-all (car elt) dir-local-variables-alist)))
3388 (setq file-local-variables-alist
3389 (assq-delete-all (car elt) file-local-variables-alist)))
3390 (push elt file-local-variables-alist)))))
3392 ;; TODO? Warn once per file rather than once per session?
3393 (defvar hack-local-variables--warned-lexical nil)
3395 (defun hack-local-variables (&optional handle-mode)
3396 "Parse and put into effect this buffer's local variables spec.
3397 Uses `hack-local-variables-apply' to apply the variables.
3399 If HANDLE-MODE is nil, we apply all the specified local
3400 variables. If HANDLE-MODE is neither nil nor t, we do the same,
3401 except that any settings of `mode' are ignored.
3403 If HANDLE-MODE is t, all we do is check whether a \"mode:\"
3404 is specified, and return the corresponding mode symbol, or nil.
3405 In this case, we try to ignore minor-modes, and only return a
3406 major-mode.
3408 If `enable-local-variables' or `local-enable-local-variables' is nil,
3409 this function does nothing. If `inhibit-local-variables-regexps'
3410 applies to the file in question, the file is not scanned for
3411 local variables, but directory-local variables may still be applied."
3412 ;; We don't let inhibit-local-variables-p influence the value of
3413 ;; enable-local-variables, because then it would affect dir-local
3414 ;; variables. We don't want to search eg tar files for file local
3415 ;; variable sections, but there is no reason dir-locals cannot apply
3416 ;; to them. The real meaning of inhibit-local-variables-p is "do
3417 ;; not scan this file for local variables".
3418 (let ((enable-local-variables
3419 (and local-enable-local-variables enable-local-variables))
3420 result)
3421 (unless (eq handle-mode t)
3422 (setq file-local-variables-alist nil)
3423 (with-demoted-errors "Directory-local variables error: %s"
3424 ;; Note this is a no-op if enable-local-variables is nil.
3425 (hack-dir-local-variables)))
3426 ;; This entire function is basically a no-op if enable-local-variables
3427 ;; is nil. All it does is set file-local-variables-alist to nil.
3428 (when enable-local-variables
3429 ;; This part used to ignore enable-local-variables when handle-mode
3430 ;; was t. That was inappropriate, eg consider the
3431 ;; (artificial) example of:
3432 ;; (setq local-enable-local-variables nil)
3433 ;; Open a file foo.txt that contains "mode: sh".
3434 ;; It correctly opens in text-mode.
3435 ;; M-x set-visited-file name foo.c, and it incorrectly stays in text-mode.
3436 (unless (or (inhibit-local-variables-p)
3437 ;; If HANDLE-MODE is t, and the prop line specifies a
3438 ;; mode, then we're done, and have no need to scan further.
3439 (and (setq result (hack-local-variables-prop-line
3440 handle-mode))
3441 (eq handle-mode t)))
3442 ;; Look for "Local variables:" line in last page.
3443 (save-excursion
3444 (goto-char (point-max))
3445 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min))
3446 'move)
3447 (when (let ((case-fold-search t))
3448 (search-forward "Local Variables:" nil t))
3449 (skip-chars-forward " \t")
3450 ;; suffix is what comes after "local variables:" in its line.
3451 ;; prefix is what comes before "local variables:" in its line.
3452 (let ((suffix
3453 (concat
3454 (regexp-quote (buffer-substring (point)
3455 (line-end-position)))
3456 "$"))
3457 (prefix
3458 (concat "^" (regexp-quote
3459 (buffer-substring (line-beginning-position)
3460 (match-beginning 0))))))
3462 (forward-line 1)
3463 (let ((startpos (point))
3464 endpos
3465 (thisbuf (current-buffer)))
3466 (save-excursion
3467 (unless (let ((case-fold-search t))
3468 (re-search-forward
3469 (concat prefix "[ \t]*End:[ \t]*" suffix)
3470 nil t))
3471 ;; This used to be an error, but really all it means is
3472 ;; that this may simply not be a local-variables section,
3473 ;; so just ignore it.
3474 (message "Local variables list is not properly terminated"))
3475 (beginning-of-line)
3476 (setq endpos (point)))
3478 (with-temp-buffer
3479 (insert-buffer-substring thisbuf startpos endpos)
3480 (goto-char (point-min))
3481 (subst-char-in-region (point) (point-max) ?\^m ?\n)
3482 (while (not (eobp))
3483 ;; Discard the prefix.
3484 (if (looking-at prefix)
3485 (delete-region (point) (match-end 0))
3486 (error "Local variables entry is missing the prefix"))
3487 (end-of-line)
3488 ;; Discard the suffix.
3489 (if (looking-back suffix (line-beginning-position))
3490 (delete-region (match-beginning 0) (point))
3491 (error "Local variables entry is missing the suffix"))
3492 (forward-line 1))
3493 (goto-char (point-min))
3495 (while (not (or (eobp)
3496 (and (eq handle-mode t) result)))
3497 ;; Find the variable name;
3498 (unless (looking-at hack-local-variable-regexp)
3499 (error "Malformed local variable line: %S"
3500 (buffer-substring-no-properties
3501 (point) (line-end-position))))
3502 (goto-char (match-end 1))
3503 (let* ((str (match-string 1))
3504 (var (intern str))
3505 val val2)
3506 (and (equal (downcase (symbol-name var)) "mode")
3507 (setq var 'mode))
3508 ;; Read the variable value.
3509 (skip-chars-forward "^:")
3510 (forward-char 1)
3511 (let ((read-circle nil))
3512 (setq val (read (current-buffer))))
3513 (if (eq handle-mode t)
3514 (and (eq var 'mode)
3515 ;; Specifying minor-modes via mode: is
3516 ;; deprecated, but try to reject them anyway.
3517 (not (string-match
3518 "-minor\\'"
3519 (setq val2 (downcase (symbol-name val)))))
3520 (setq result (intern (concat val2 "-mode"))))
3521 (cond ((eq var 'coding))
3522 ((eq var 'lexical-binding)
3523 (unless hack-local-variables--warned-lexical
3524 (setq hack-local-variables--warned-lexical t)
3525 (display-warning
3526 'files
3527 (format-message
3528 "%s: `lexical-binding' at end of file unreliable"
3529 (file-name-nondirectory
3530 ;; We are called from
3531 ;; 'with-temp-buffer', so we need
3532 ;; to use 'thisbuf's name in the
3533 ;; warning message.
3534 (or (buffer-file-name thisbuf) ""))))))
3535 ((and (eq var 'mode) handle-mode))
3537 (ignore-errors
3538 (push (cons (if (eq var 'eval)
3539 'eval
3540 (indirect-variable var))
3541 val) result))))))
3542 (forward-line 1))))))))
3543 ;; Now we've read all the local variables.
3544 ;; If HANDLE-MODE is t, return whether the mode was specified.
3545 (if (eq handle-mode t) result
3546 ;; Otherwise, set the variables.
3547 (hack-local-variables-filter result nil)
3548 (hack-local-variables-apply)))))
3550 (defun hack-local-variables-apply ()
3551 "Apply the elements of `file-local-variables-alist'.
3552 If there are any elements, runs `before-hack-local-variables-hook',
3553 then calls `hack-one-local-variable' to apply the alist elements one by one.
3554 Finishes by running `hack-local-variables-hook', regardless of whether
3555 the alist is empty or not.
3557 Note that this function ignores a `mode' entry if it specifies the same
3558 major mode as the buffer already has."
3559 (when file-local-variables-alist
3560 ;; Any 'evals must run in the Right sequence.
3561 (setq file-local-variables-alist
3562 (nreverse file-local-variables-alist))
3563 (run-hooks 'before-hack-local-variables-hook)
3564 (dolist (elt file-local-variables-alist)
3565 (hack-one-local-variable (car elt) (cdr elt))))
3566 (run-hooks 'hack-local-variables-hook))
3568 (defun safe-local-variable-p (sym val)
3569 "Non-nil if SYM is safe as a file-local variable with value VAL.
3570 It is safe if any of these conditions are met:
3572 * There is a matching entry (SYM . VAL) in the
3573 `safe-local-variable-values' user option.
3575 * The `safe-local-variable' property of SYM is a function that
3576 evaluates to a non-nil value with VAL as an argument."
3577 (or (member (cons sym val) safe-local-variable-values)
3578 (let ((safep (get sym 'safe-local-variable)))
3579 (and (functionp safep)
3580 ;; If the function signals an error, that means it
3581 ;; can't assure us that the value is safe.
3582 (with-demoted-errors (funcall safep val))))))
3584 (defun risky-local-variable-p (sym &optional _ignored)
3585 "Non-nil if SYM could be dangerous as a file-local variable.
3586 It is dangerous if either of these conditions are met:
3588 * Its `risky-local-variable' property is non-nil.
3590 * Its name ends with \"hook(s)\", \"function(s)\", \"form(s)\", \"map\",
3591 \"program\", \"command(s)\", \"predicate(s)\", \"frame-alist\",
3592 \"mode-alist\", \"font-lock-(syntactic-)keyword*\",
3593 \"map-alist\", or \"bindat-spec\"."
3594 ;; If this is an alias, check the base name.
3595 (condition-case nil
3596 (setq sym (indirect-variable sym))
3597 (error nil))
3598 (or (get sym 'risky-local-variable)
3599 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|\
3600 -commands?$\\|-predicates?$\\|font-lock-keywords$\\|font-lock-keywords\
3601 -[0-9]+$\\|font-lock-syntactic-keywords$\\|-frame-alist$\\|-mode-alist$\\|\
3602 -map$\\|-map-alist$\\|-bindat-spec$" (symbol-name sym))))
3604 (defun hack-one-local-variable-quotep (exp)
3605 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
3607 (defun hack-one-local-variable-constantp (exp)
3608 (or (and (not (symbolp exp)) (not (consp exp)))
3609 (memq exp '(t nil))
3610 (keywordp exp)
3611 (hack-one-local-variable-quotep exp)))
3613 (defun hack-one-local-variable-eval-safep (exp)
3614 "Return t if it is safe to eval EXP when it is found in a file."
3615 (or (not (consp exp))
3616 ;; Detect certain `put' expressions.
3617 (and (eq (car exp) 'put)
3618 (hack-one-local-variable-quotep (nth 1 exp))
3619 (hack-one-local-variable-quotep (nth 2 exp))
3620 (let ((prop (nth 1 (nth 2 exp)))
3621 (val (nth 3 exp)))
3622 (cond ((memq prop '(lisp-indent-hook
3623 lisp-indent-function
3624 scheme-indent-function))
3625 ;; Only allow safe values (not functions).
3626 (or (numberp val)
3627 (and (hack-one-local-variable-quotep val)
3628 (eq (nth 1 val) 'defun))))
3629 ((eq prop 'edebug-form-spec)
3630 ;; Only allow indirect form specs.
3631 ;; During bootstrapping, edebug-basic-spec might not be
3632 ;; defined yet.
3633 (and (fboundp 'edebug-basic-spec)
3634 (hack-one-local-variable-quotep val)
3635 (edebug-basic-spec (nth 1 val)))))))
3636 ;; Allow expressions that the user requested.
3637 (member exp safe-local-eval-forms)
3638 ;; Certain functions can be allowed with safe arguments
3639 ;; or can specify verification functions to try.
3640 (and (symbolp (car exp))
3641 ;; Allow (minor)-modes calls with no arguments.
3642 ;; This obsoletes the use of "mode:" for such things. (Bug#8613)
3643 (or (and (member (cdr exp) '(nil (1) (0) (-1)))
3644 (string-match "-mode\\'" (symbol-name (car exp))))
3645 (let ((prop (get (car exp) 'safe-local-eval-function)))
3646 (cond ((eq prop t)
3647 (let ((ok t))
3648 (dolist (arg (cdr exp))
3649 (unless (hack-one-local-variable-constantp arg)
3650 (setq ok nil)))
3651 ok))
3652 ((functionp prop)
3653 (funcall prop exp))
3654 ((listp prop)
3655 (let ((ok nil))
3656 (dolist (function prop)
3657 (if (funcall function exp)
3658 (setq ok t)))
3659 ok))))))))
3661 (defun hack-one-local-variable--obsolete (var)
3662 (let ((o (get var 'byte-obsolete-variable)))
3663 (when o
3664 (let ((instead (nth 0 o))
3665 (since (nth 2 o)))
3666 (message "%s is obsolete%s; %s"
3667 var (if since (format " (since %s)" since))
3668 (if (stringp instead)
3669 (substitute-command-keys instead)
3670 (format-message "use `%s' instead" instead)))))))
3672 (defun hack-one-local-variable (var val)
3673 "Set local variable VAR with value VAL.
3674 If VAR is `mode', call `VAL-mode' as a function unless it's
3675 already the major mode."
3676 (pcase var
3677 (`mode
3678 (let ((mode (intern (concat (downcase (symbol-name val))
3679 "-mode"))))
3680 (unless (eq (indirect-function mode)
3681 (indirect-function major-mode))
3682 (funcall mode))))
3683 (`eval
3684 (pcase val
3685 (`(add-hook ',hook . ,_) (hack-one-local-variable--obsolete hook)))
3686 (save-excursion (eval val)))
3688 (hack-one-local-variable--obsolete var)
3689 ;; Make sure the string has no text properties.
3690 ;; Some text properties can get evaluated in various ways,
3691 ;; so it is risky to put them on with a local variable list.
3692 (if (stringp val)
3693 (set-text-properties 0 (length val) nil val))
3694 (set (make-local-variable var) val))))
3696 ;;; Handling directory-local variables, aka project settings.
3698 (defvar dir-locals-class-alist '()
3699 "Alist mapping directory-local variable classes (symbols) to variable lists.")
3701 (defvar dir-locals-directory-cache '()
3702 "List of cached directory roots for directory-local variable classes.
3703 Each element in this list has the form (DIR CLASS MTIME).
3704 DIR is the name of the directory.
3705 CLASS is the name of a variable class (a symbol).
3706 MTIME is the recorded modification time of the directory-local
3707 variables file associated with this entry. This time is a list
3708 of integers (the same format as `file-attributes'), and is
3709 used to test whether the cache entry is still valid.
3710 Alternatively, MTIME can be nil, which means the entry is always
3711 considered valid.")
3713 (defsubst dir-locals-get-class-variables (class)
3714 "Return the variable list for CLASS."
3715 (cdr (assq class dir-locals-class-alist)))
3717 (defun dir-locals-collect-mode-variables (mode-variables variables)
3718 "Collect directory-local variables from MODE-VARIABLES.
3719 VARIABLES is the initial list of variables.
3720 Returns the new list."
3721 (dolist (pair mode-variables variables)
3722 (let* ((variable (car pair))
3723 (value (cdr pair))
3724 (slot (assq variable variables)))
3725 ;; If variables are specified more than once, only use the last. (Why?)
3726 ;; The pseudo-variables mode and eval are different (bug#3430).
3727 (if (and slot (not (memq variable '(mode eval))))
3728 (setcdr slot value)
3729 ;; Need a new cons in case we setcdr later.
3730 (push (cons variable value) variables)))))
3732 (defun dir-locals-collect-variables (class-variables root variables)
3733 "Collect entries from CLASS-VARIABLES into VARIABLES.
3734 ROOT is the root directory of the project.
3735 Return the new variables list."
3736 (let* ((file-name (or (buffer-file-name)
3737 ;; Handle non-file buffers, too.
3738 (expand-file-name default-directory)))
3739 (sub-file-name (if (and file-name
3740 (file-name-absolute-p file-name))
3741 ;; FIXME: Why not use file-relative-name?
3742 (substring file-name (length root)))))
3743 (condition-case err
3744 (dolist (entry class-variables variables)
3745 (let ((key (car entry)))
3746 (cond
3747 ((stringp key)
3748 ;; Don't include this in the previous condition, because we
3749 ;; want to filter all strings before the next condition.
3750 (when (and sub-file-name
3751 (>= (length sub-file-name) (length key))
3752 (string-prefix-p key sub-file-name))
3753 (setq variables (dir-locals-collect-variables
3754 (cdr entry) root variables))))
3755 ((or (not key)
3756 (derived-mode-p key))
3757 (let* ((alist (cdr entry))
3758 (subdirs (assq 'subdirs alist)))
3759 (if (or (not subdirs)
3760 (progn
3761 (setq alist (delq subdirs alist))
3762 (cdr-safe subdirs))
3763 ;; TODO someone might want to extend this to allow
3764 ;; integer values for subdir, where N means
3765 ;; variables apply to this directory and N levels
3766 ;; below it (0 == nil).
3767 (equal root default-directory))
3768 (setq variables (dir-locals-collect-mode-variables
3769 alist variables))))))))
3770 (error
3771 ;; The file's content might be invalid (e.g. have a merge conflict), but
3772 ;; that shouldn't prevent the user from opening the file.
3773 (message "%s error: %s" dir-locals-file (error-message-string err))
3774 nil))))
3776 (defun dir-locals-set-directory-class (directory class &optional mtime)
3777 "Declare that the DIRECTORY root is an instance of CLASS.
3778 DIRECTORY is the name of a directory, a string.
3779 CLASS is the name of a project class, a symbol.
3780 MTIME is either the modification time of the directory-local
3781 variables file that defined this class, or nil.
3783 When a file beneath DIRECTORY is visited, the mode-specific
3784 variables from CLASS are applied to the buffer. The variables
3785 for a class are defined using `dir-locals-set-class-variables'."
3786 (setq directory (file-name-as-directory (expand-file-name directory)))
3787 (unless (assq class dir-locals-class-alist)
3788 (error "No such class `%s'" (symbol-name class)))
3789 (push (list directory class mtime) dir-locals-directory-cache))
3791 (defun dir-locals-set-class-variables (class variables)
3792 "Map the type CLASS to a list of variable settings.
3793 CLASS is the project class, a symbol. VARIABLES is a list
3794 that declares directory-local variables for the class.
3795 An element in VARIABLES is either of the form:
3796 (MAJOR-MODE . ALIST)
3798 (DIRECTORY . LIST)
3800 In the first form, MAJOR-MODE is a symbol, and ALIST is an alist
3801 whose elements are of the form (VARIABLE . VALUE).
3803 In the second form, DIRECTORY is a directory name (a string), and
3804 LIST is a list of the form accepted by the function.
3806 When a file is visited, the file's class is found. A directory
3807 may be assigned a class using `dir-locals-set-directory-class'.
3808 Then variables are set in the file's buffer according to the
3809 VARIABLES list of the class. The list is processed in order.
3811 * If the element is of the form (MAJOR-MODE . ALIST), and the
3812 buffer's major mode is derived from MAJOR-MODE (as determined
3813 by `derived-mode-p'), then all the variables in ALIST are
3814 applied. A MAJOR-MODE of nil may be used to match any buffer.
3815 `make-local-variable' is called for each variable before it is
3816 set.
3818 * If the element is of the form (DIRECTORY . LIST), and DIRECTORY
3819 is an initial substring of the file's directory, then LIST is
3820 applied by recursively following these rules."
3821 (setf (alist-get class dir-locals-class-alist) variables))
3823 (defconst dir-locals-file ".dir-locals.el"
3824 "File that contains directory-local variables.
3825 It has to be constant to enforce uniform values across different
3826 environments and users.
3827 See also `dir-locals-file-2', whose values override this one's.
3828 See Info node `(elisp)Directory Local Variables' for details.")
3830 (defconst dir-locals-file-2 ".dir-locals-2.el"
3831 "File that contains directory-local variables.
3832 This essentially a second file that can be used like
3833 `dir-locals-file', so that users can have specify their personal
3834 dir-local variables even if the current directory already has a
3835 `dir-locals-file' that is shared with other users (such as in a
3836 git repository).
3837 See Info node `(elisp)Directory Local Variables' for details.")
3839 (defun dir-locals--all-files (directory)
3840 "Return a list of all readable dir-locals files in DIRECTORY.
3841 The returned list is sorted by increasing priority. That is,
3842 values specified in the last file should take precedence over
3843 those in the first."
3844 (when (file-readable-p directory)
3845 (let* ((file-1 (expand-file-name (if (eq system-type 'ms-dos)
3846 (dosified-file-name dir-locals-file)
3847 dir-locals-file)
3848 directory))
3849 (file-2 (when (string-match "\\.el\\'" file-1)
3850 (replace-match "-2.el" t nil file-1)))
3851 (out nil))
3852 ;; The order here is important.
3853 (dolist (f (list file-2 file-1))
3854 (when (and f
3855 (file-readable-p f)
3856 (file-regular-p f)
3857 (not (file-directory-p f)))
3858 (push f out)))
3859 out)))
3861 (defun dir-locals-find-file (file)
3862 "Find the directory-local variables for FILE.
3863 This searches upward in the directory tree from FILE.
3864 It stops at the first directory that has been registered in
3865 `dir-locals-directory-cache' or contains a `dir-locals-file'.
3866 If it finds an entry in the cache, it checks that it is valid.
3867 A cache entry with no modification time element (normally, one that
3868 has been assigned directly using `dir-locals-set-directory-class', not
3869 set from a file) is always valid.
3870 A cache entry based on a `dir-locals-file' is valid if the modification
3871 time stored in the cache matches the current file modification time.
3872 If not, the cache entry is cleared so that the file will be re-read.
3874 This function returns either:
3875 - nil (no directory local variables found),
3876 - the matching entry from `dir-locals-directory-cache' (a list),
3877 - or the full path to the directory (a string) containing at
3878 least one `dir-locals-file' in the case of no valid cache
3879 entry."
3880 (setq file (expand-file-name file))
3881 (let* ((locals-dir (locate-dominating-file (file-name-directory file)
3882 #'dir-locals--all-files))
3883 dir-elt)
3884 ;; `locate-dominating-file' may have abbreviated the name.
3885 (when locals-dir
3886 (setq locals-dir (expand-file-name locals-dir)))
3887 ;; Find the best cached value in `dir-locals-directory-cache'.
3888 (dolist (elt dir-locals-directory-cache)
3889 (when (and (string-prefix-p (car elt) file
3890 (memq system-type
3891 '(windows-nt cygwin ms-dos)))
3892 (> (length (car elt)) (length (car dir-elt))))
3893 (setq dir-elt elt)))
3894 (if (and dir-elt
3895 (or (null locals-dir)
3896 (<= (length locals-dir)
3897 (length (car dir-elt)))))
3898 ;; Found a potential cache entry. Check validity.
3899 ;; A cache entry with no MTIME is assumed to always be valid
3900 ;; (ie, set directly, not from a dir-locals file).
3901 ;; Note, we don't bother to check that there is a matching class
3902 ;; element in dir-locals-class-alist, since that's done by
3903 ;; dir-locals-set-directory-class.
3904 (if (or (null (nth 2 dir-elt))
3905 (let ((cached-files (dir-locals--all-files (car dir-elt))))
3906 ;; The entry MTIME should match the most recent
3907 ;; MTIME among matching files.
3908 (and cached-files
3909 (= (float-time (nth 2 dir-elt))
3910 (apply #'max (mapcar (lambda (f)
3911 (float-time
3912 (nth 5 (file-attributes f))))
3913 cached-files))))))
3914 ;; This cache entry is OK.
3915 dir-elt
3916 ;; This cache entry is invalid; clear it.
3917 (setq dir-locals-directory-cache
3918 (delq dir-elt dir-locals-directory-cache))
3919 ;; Return the first existing dir-locals file. Might be the same
3920 ;; as dir-elt's, might not (eg latter might have been deleted).
3921 locals-dir)
3922 ;; No cache entry.
3923 locals-dir)))
3925 (defun dir-locals-read-from-dir (dir)
3926 "Load all variables files in DIR and register a new class and instance.
3927 DIR is the absolute name of a directory which must contain at
3928 least one dir-local file (which is a file holding variables to
3929 apply).
3930 Return the new class name, which is a symbol named DIR."
3931 (require 'map)
3932 (let* ((class-name (intern dir))
3933 (files (dir-locals--all-files dir))
3934 (read-circle nil)
3935 (success nil)
3936 (variables))
3937 (with-demoted-errors "Error reading dir-locals: %S"
3938 (dolist (file files)
3939 (with-temp-buffer
3940 (insert-file-contents file)
3941 (condition-case-unless-debug nil
3942 (setq variables
3943 (map-merge-with 'list (lambda (a b) (map-merge 'list a b))
3944 variables
3945 (read (current-buffer))))
3946 (end-of-file nil))))
3947 (setq success t))
3948 (dir-locals-set-class-variables class-name variables)
3949 (dir-locals-set-directory-class
3950 dir class-name
3951 (seconds-to-time
3952 (if success
3953 (apply #'max (mapcar (lambda (file)
3954 (float-time (nth 5 (file-attributes file))))
3955 files))
3956 ;; If there was a problem, use the values we could get but
3957 ;; don't let the cache prevent future reads.
3958 0)))
3959 class-name))
3961 (define-obsolete-function-alias 'dir-locals-read-from-file
3962 'dir-locals-read-from-dir "25.1")
3964 (defcustom enable-remote-dir-locals nil
3965 "Non-nil means dir-local variables will be applied to remote files."
3966 :version "24.3"
3967 :type 'boolean
3968 :group 'find-file)
3970 (defvar hack-dir-local-variables--warned-coding nil)
3972 (defun hack-dir-local-variables ()
3973 "Read per-directory local variables for the current buffer.
3974 Store the directory-local variables in `dir-local-variables-alist'
3975 and `file-local-variables-alist', without applying them.
3977 This does nothing if either `enable-local-variables' or
3978 `enable-dir-local-variables' are nil."
3979 (when (and enable-local-variables
3980 enable-dir-local-variables
3981 (or enable-remote-dir-locals
3982 (not (file-remote-p (or (buffer-file-name)
3983 default-directory)))))
3984 ;; Find the variables file.
3985 (let ((dir-or-cache (dir-locals-find-file
3986 (or (buffer-file-name) default-directory)))
3987 (class nil)
3988 (dir-name nil))
3989 (cond
3990 ((stringp dir-or-cache)
3991 (setq dir-name dir-or-cache
3992 class (dir-locals-read-from-dir dir-or-cache)))
3993 ((consp dir-or-cache)
3994 (setq dir-name (nth 0 dir-or-cache))
3995 (setq class (nth 1 dir-or-cache))))
3996 (when class
3997 (let ((variables
3998 (dir-locals-collect-variables
3999 (dir-locals-get-class-variables class) dir-name nil)))
4000 (when variables
4001 (dolist (elt variables)
4002 (if (eq (car elt) 'coding)
4003 (unless hack-dir-local-variables--warned-coding
4004 (setq hack-dir-local-variables--warned-coding t)
4005 (display-warning 'files
4006 "Coding cannot be specified by dir-locals"))
4007 (unless (memq (car elt) '(eval mode))
4008 (setq dir-local-variables-alist
4009 (assq-delete-all (car elt) dir-local-variables-alist)))
4010 (push elt dir-local-variables-alist)))
4011 (hack-local-variables-filter variables dir-name)))))))
4013 (defun hack-dir-local-variables-non-file-buffer ()
4014 "Apply directory-local variables to a non-file buffer.
4015 For non-file buffers, such as Dired buffers, directory-local
4016 variables are looked for in `default-directory' and its parent
4017 directories."
4018 (hack-dir-local-variables)
4019 (hack-local-variables-apply))
4022 (defcustom change-major-mode-with-file-name t
4023 "Non-nil means \\[write-file] should set the major mode from the file name.
4024 However, the mode will not be changed if
4025 \(1) a local variables list or the `-*-' line specifies a major mode, or
4026 \(2) the current major mode is a \"special\" mode,
4027 not suitable for ordinary files, or
4028 \(3) the new file name does not particularly specify any mode."
4029 :type 'boolean
4030 :group 'editing-basics)
4032 (defun set-visited-file-name (filename &optional no-query along-with-file)
4033 "Change name of file visited in current buffer to FILENAME.
4034 This also renames the buffer to correspond to the new file.
4035 The next time the buffer is saved it will go in the newly specified file.
4036 FILENAME nil or an empty string means mark buffer as not visiting any file.
4037 Remember to delete the initial contents of the minibuffer
4038 if you wish to pass an empty string as the argument.
4040 The optional second argument NO-QUERY, if non-nil, inhibits asking for
4041 confirmation in the case where another buffer is already visiting FILENAME.
4043 The optional third argument ALONG-WITH-FILE, if non-nil, means that
4044 the old visited file has been renamed to the new name FILENAME."
4045 (interactive "FSet visited file name: ")
4046 (if (buffer-base-buffer)
4047 (error "An indirect buffer cannot visit a file"))
4048 (let (truename old-try-locals)
4049 (if filename
4050 (setq filename
4051 (if (string-equal filename "")
4053 (expand-file-name filename))))
4054 (if filename
4055 (progn
4056 (setq truename (file-truename filename))
4057 (if find-file-visit-truename
4058 (setq filename truename))))
4059 (if filename
4060 (let ((new-name (file-name-nondirectory filename)))
4061 (if (string= new-name "")
4062 (error "Empty file name"))))
4063 (let ((buffer (and filename (find-buffer-visiting filename))))
4064 (and buffer (not (eq buffer (current-buffer)))
4065 (not no-query)
4066 (not (y-or-n-p (format "A buffer is visiting %s; proceed? "
4067 filename)))
4068 (user-error "Aborted")))
4069 (or (equal filename buffer-file-name)
4070 (progn
4071 (and filename (lock-buffer filename))
4072 (unlock-buffer)))
4073 (setq old-try-locals (not (inhibit-local-variables-p))
4074 buffer-file-name filename)
4075 (if filename ; make buffer name reflect filename.
4076 (let ((new-name (file-name-nondirectory buffer-file-name)))
4077 (setq default-directory (file-name-directory buffer-file-name))
4078 ;; If new-name == old-name, renaming would add a spurious <2>
4079 ;; and it's considered as a feature in rename-buffer.
4080 (or (string= new-name (buffer-name))
4081 (rename-buffer new-name t))))
4082 (setq buffer-backed-up nil)
4083 (or along-with-file
4084 (clear-visited-file-modtime))
4085 ;; Abbreviate the file names of the buffer.
4086 (if truename
4087 (progn
4088 (setq buffer-file-truename (abbreviate-file-name truename))
4089 (if find-file-visit-truename
4090 (setq buffer-file-name truename))))
4091 (setq buffer-file-number
4092 (if filename
4093 (nthcdr 10 (file-attributes buffer-file-name))
4094 nil))
4095 ;; write-file-functions is normally used for things like ftp-find-file
4096 ;; that visit things that are not local files as if they were files.
4097 ;; Changing to visit an ordinary local file instead should flush the hook.
4098 (kill-local-variable 'write-file-functions)
4099 (kill-local-variable 'local-write-file-hooks)
4100 (kill-local-variable 'revert-buffer-function)
4101 (kill-local-variable 'backup-inhibited)
4102 ;; If buffer was read-only because of version control,
4103 ;; that reason is gone now, so make it writable.
4104 (if vc-mode
4105 (setq buffer-read-only nil))
4106 (kill-local-variable 'vc-mode)
4107 ;; Turn off backup files for certain file names.
4108 ;; Since this is a permanent local, the major mode won't eliminate it.
4109 (and buffer-file-name
4110 backup-enable-predicate
4111 (not (funcall backup-enable-predicate buffer-file-name))
4112 (progn
4113 (make-local-variable 'backup-inhibited)
4114 (setq backup-inhibited t)))
4115 (let ((oauto buffer-auto-save-file-name))
4116 (cond ((null filename)
4117 (setq buffer-auto-save-file-name nil))
4118 ((not buffer-auto-save-file-name)
4119 ;; If auto-save was not already on, turn it on if appropriate.
4120 (and buffer-file-name auto-save-default (auto-save-mode t)))
4122 ;; If auto save is on, start using a new name. We
4123 ;; deliberately don't rename or delete the old auto save
4124 ;; for the old visited file name. This is because
4125 ;; perhaps the user wants to save the new state and then
4126 ;; compare with the previous state from the auto save
4127 ;; file.
4128 (setq buffer-auto-save-file-name (make-auto-save-file-name))))
4129 ;; Rename the old auto save file if any.
4130 (and oauto buffer-auto-save-file-name
4131 (file-exists-p oauto)
4132 (rename-file oauto buffer-auto-save-file-name t)))
4133 (and buffer-file-name
4134 (not along-with-file)
4135 (set-buffer-modified-p t))
4136 ;; Update the major mode, if the file name determines it.
4137 (condition-case nil
4138 ;; Don't change the mode if it is special.
4139 (or (not change-major-mode-with-file-name)
4140 (get major-mode 'mode-class)
4141 ;; Don't change the mode if the local variable list specifies it.
4142 ;; The file name can influence whether the local variables apply.
4143 (and old-try-locals
4144 ;; h-l-v also checks it, but might as well be explicit.
4145 (not (inhibit-local-variables-p))
4146 (hack-local-variables t))
4147 ;; TODO consider making normal-mode handle this case.
4148 (let ((old major-mode))
4149 (set-auto-mode t)
4150 (or (eq old major-mode)
4151 (hack-local-variables))))
4152 (error nil))))
4154 (defun write-file (filename &optional confirm)
4155 "Write current buffer into file FILENAME.
4156 This makes the buffer visit that file, and marks it as not modified.
4158 If you specify just a directory name as FILENAME, that means to use
4159 the default file name but in that directory. You can also yank
4160 the default file name into the minibuffer to edit it, using \\<minibuffer-local-map>\\[next-history-element].
4162 If the buffer is not already visiting a file, the default file name
4163 for the output file is the buffer name.
4165 If optional second arg CONFIRM is non-nil, this function
4166 asks for confirmation before overwriting an existing file.
4167 Interactively, confirmation is required unless you supply a prefix argument."
4168 ;; (interactive "FWrite file: ")
4169 (interactive
4170 (list (if buffer-file-name
4171 (read-file-name "Write file: "
4172 nil nil nil nil)
4173 (read-file-name "Write file: " default-directory
4174 (expand-file-name
4175 (file-name-nondirectory (buffer-name))
4176 default-directory)
4177 nil nil))
4178 (not current-prefix-arg)))
4179 (or (null filename) (string-equal filename "")
4180 (progn
4181 ;; If arg is just a directory,
4182 ;; use the default file name, but in that directory.
4183 (if (file-directory-p filename)
4184 (setq filename (concat (file-name-as-directory filename)
4185 (file-name-nondirectory
4186 (or buffer-file-name (buffer-name))))))
4187 (and confirm
4188 (file-exists-p filename)
4189 ;; NS does its own confirm dialog.
4190 (not (and (eq (framep-on-display) 'ns)
4191 (listp last-nonmenu-event)
4192 use-dialog-box))
4193 (or (y-or-n-p (format-message
4194 "File `%s' exists; overwrite? " filename))
4195 (user-error "Canceled")))
4196 (set-visited-file-name filename (not confirm))))
4197 (set-buffer-modified-p t)
4198 ;; Make buffer writable if file is writable.
4199 (and buffer-file-name
4200 (file-writable-p buffer-file-name)
4201 (setq buffer-read-only nil))
4202 (save-buffer)
4203 ;; It's likely that the VC status at the new location is different from
4204 ;; the one at the old location.
4205 (vc-refresh-state))
4207 (defun file-extended-attributes (filename)
4208 "Return an alist of extended attributes of file FILENAME.
4210 Extended attributes are platform-specific metadata about the file,
4211 such as SELinux context, list of ACL entries, etc."
4212 `((acl . ,(file-acl filename))
4213 (selinux-context . ,(file-selinux-context filename))))
4215 (defun set-file-extended-attributes (filename attributes)
4216 "Set extended attributes of file FILENAME to ATTRIBUTES.
4218 ATTRIBUTES must be an alist of file attributes as returned by
4219 `file-extended-attributes'.
4220 Value is t if the function succeeds in setting the attributes."
4221 (let (result rv)
4222 (dolist (elt attributes)
4223 (let ((attr (car elt))
4224 (val (cdr elt)))
4225 (cond ((eq attr 'acl)
4226 (setq rv (set-file-acl filename val)))
4227 ((eq attr 'selinux-context)
4228 (setq rv (set-file-selinux-context filename val))))
4229 (setq result (or result rv))))
4231 result))
4233 (defun backup-buffer ()
4234 "Make a backup of the disk file visited by the current buffer, if appropriate.
4235 This is normally done before saving the buffer the first time.
4237 A backup may be done by renaming or by copying; see documentation of
4238 variable `make-backup-files'. If it's done by renaming, then the file is
4239 no longer accessible under its old name.
4241 The value is non-nil after a backup was made by renaming.
4242 It has the form (MODES EXTENDED-ATTRIBUTES BACKUPNAME).
4243 MODES is the result of `file-modes' on the original
4244 file; this means that the caller, after saving the buffer, should change
4245 the modes of the new file to agree with the old modes.
4246 EXTENDED-ATTRIBUTES is the result of `file-extended-attributes'
4247 on the original file; this means that the caller, after saving
4248 the buffer, should change the extended attributes of the new file
4249 to agree with the old attributes.
4250 BACKUPNAME is the backup file name, which is the old file renamed."
4251 (when (and make-backup-files (not backup-inhibited) (not buffer-backed-up))
4252 (let ((attributes (file-attributes buffer-file-name)))
4253 (when (and attributes (memq (aref (elt attributes 8) 0) '(?- ?l)))
4254 ;; If specified name is a symbolic link, chase it to the target.
4255 ;; This makes backups in the directory where the real file is.
4256 (let* ((real-file-name (file-chase-links buffer-file-name))
4257 (backup-info (find-backup-file-name real-file-name)))
4258 (when backup-info
4259 (let* ((backupname (car backup-info))
4260 (targets (cdr backup-info))
4261 (old-versions
4262 ;; If have old versions to maybe delete,
4263 ;; ask the user to confirm now, before doing anything.
4264 ;; But don't actually delete til later.
4265 (and targets
4266 (booleanp delete-old-versions)
4267 (or delete-old-versions
4268 (y-or-n-p
4269 (format "Delete excess backup versions of %s? "
4270 real-file-name)))
4271 targets))
4272 (modes (file-modes buffer-file-name))
4273 (extended-attributes
4274 (file-extended-attributes buffer-file-name))
4275 (copy-when-priv-mismatch
4276 backup-by-copying-when-privileged-mismatch)
4277 (make-copy
4278 (or file-precious-flag backup-by-copying
4279 ;; Don't rename a suid or sgid file.
4280 (and modes (< 0 (logand modes #o6000)))
4281 (not (file-writable-p
4282 (file-name-directory real-file-name)))
4283 (and backup-by-copying-when-linked
4284 (< 1 (file-nlinks real-file-name)))
4285 (and (or backup-by-copying-when-mismatch
4286 (and (integerp copy-when-priv-mismatch)
4287 (let ((attr (file-attributes
4288 real-file-name
4289 'integer)))
4290 (<= (nth 2 attr)
4291 copy-when-priv-mismatch))))
4292 (not (file-ownership-preserved-p real-file-name
4293 t)))))
4294 setmodes)
4295 (condition-case ()
4296 (progn
4297 ;; Actually make the backup file.
4298 (if make-copy
4299 (backup-buffer-copy real-file-name backupname
4300 modes extended-attributes)
4301 ;; rename-file should delete old backup.
4302 (rename-file real-file-name backupname t)
4303 (setq setmodes (list modes extended-attributes
4304 backupname)))
4305 (setq buffer-backed-up t)
4306 ;; Now delete the old versions, if desired.
4307 (dolist (old-version old-versions)
4308 (delete-file old-version)))
4309 (file-error nil))
4310 ;; If trouble writing the backup, write it in .emacs.d/%backup%.
4311 (when (not buffer-backed-up)
4312 (setq backupname (locate-user-emacs-file "%backup%~"))
4313 (message "Cannot write backup file; backing up in %s"
4314 backupname)
4315 (sleep-for 1)
4316 (backup-buffer-copy real-file-name backupname
4317 modes extended-attributes)
4318 (setq buffer-backed-up t))
4319 setmodes)))))))
4321 (defun backup-buffer-copy (from-name to-name modes extended-attributes)
4322 ;; Create temp files with strict access rights. It's easy to
4323 ;; loosen them later, whereas it's impossible to close the
4324 ;; time-window of loose permissions otherwise.
4325 (with-file-modes ?\700
4326 (when (condition-case nil
4327 ;; Try to overwrite old backup first.
4328 (copy-file from-name to-name t t t)
4329 (error t))
4330 (while (condition-case nil
4331 (progn
4332 (when (file-exists-p to-name)
4333 (delete-file to-name))
4334 (copy-file from-name to-name nil t t)
4335 nil)
4336 (file-already-exists t))
4337 ;; The file was somehow created by someone else between
4338 ;; `delete-file' and `copy-file', so let's try again.
4339 ;; rms says "I think there is also a possible race
4340 ;; condition for making backup files" (emacs-devel 20070821).
4341 nil)))
4342 ;; If set-file-extended-attributes fails, fall back on set-file-modes.
4343 (unless (and extended-attributes
4344 (with-demoted-errors
4345 (set-file-extended-attributes to-name extended-attributes)))
4346 (and modes
4347 (set-file-modes to-name (logand modes #o1777)))))
4349 (defvar file-name-version-regexp
4350 "\\(?:~\\|\\.~[-[:alnum:]:#@^._]+\\(?:~[[:digit:]]+\\)?~\\)"
4351 ;; The last ~[[:digit]]+ matches relative versions in git,
4352 ;; e.g. `foo.js.~HEAD~1~'.
4353 "Regular expression matching the backup/version part of a file name.
4354 Used by `file-name-sans-versions'.")
4356 (defun file-name-sans-versions (name &optional keep-backup-version)
4357 "Return file NAME sans backup versions or strings.
4358 This is a separate procedure so your site-init or startup file can
4359 redefine it.
4360 If the optional argument KEEP-BACKUP-VERSION is non-nil,
4361 we do not remove backup version numbers, only true file version numbers.
4362 See also `file-name-version-regexp'."
4363 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
4364 (if handler
4365 (funcall handler 'file-name-sans-versions name keep-backup-version)
4366 (substring name 0
4367 (unless keep-backup-version
4368 (string-match (concat file-name-version-regexp "\\'")
4369 name))))))
4371 (defun file-ownership-preserved-p (file &optional group)
4372 "Return t if deleting FILE and rewriting it would preserve the owner.
4373 Return also t if FILE does not exist. If GROUP is non-nil, check whether
4374 the group would be preserved too."
4375 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
4376 (if handler
4377 (funcall handler 'file-ownership-preserved-p file group)
4378 (let ((attributes (file-attributes file 'integer)))
4379 ;; Return t if the file doesn't exist, since it's true that no
4380 ;; information would be lost by an (attempted) delete and create.
4381 (or (null attributes)
4382 (and (or (= (nth 2 attributes) (user-uid))
4383 ;; Files created on Windows by Administrator (RID=500)
4384 ;; have the Administrators group (RID=544) recorded as
4385 ;; their owner. Rewriting them will still preserve the
4386 ;; owner.
4387 (and (eq system-type 'windows-nt)
4388 (= (user-uid) 500) (= (nth 2 attributes) 544)))
4389 (or (not group)
4390 ;; On BSD-derived systems files always inherit the parent
4391 ;; directory's group, so skip the group-gid test.
4392 (memq system-type '(berkeley-unix darwin gnu/kfreebsd))
4393 (= (nth 3 attributes) (group-gid)))
4394 (let* ((parent (or (file-name-directory file) "."))
4395 (parent-attributes (file-attributes parent 'integer)))
4396 (and parent-attributes
4397 ;; On some systems, a file created in a setuid directory
4398 ;; inherits that directory's owner.
4400 (= (nth 2 parent-attributes) (user-uid))
4401 (string-match "^...[^sS]" (nth 8 parent-attributes)))
4402 ;; On many systems, a file created in a setgid directory
4403 ;; inherits that directory's group. On some systems
4404 ;; this happens even if the setgid bit is not set.
4405 (or (not group)
4406 (= (nth 3 parent-attributes)
4407 (nth 3 attributes)))))))))))
4409 (defun file-name-sans-extension (filename)
4410 "Return FILENAME sans final \"extension\".
4411 The extension, in a file name, is the part that begins with the last `.',
4412 except that a leading `.' of the file name, if there is one, doesn't count."
4413 (save-match-data
4414 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
4415 directory)
4416 (if (and (string-match "\\.[^.]*\\'" file)
4417 (not (eq 0 (match-beginning 0))))
4418 (if (setq directory (file-name-directory filename))
4419 ;; Don't use expand-file-name here; if DIRECTORY is relative,
4420 ;; we don't want to expand it.
4421 (concat directory (substring file 0 (match-beginning 0)))
4422 (substring file 0 (match-beginning 0)))
4423 filename))))
4425 (defun file-name-extension (filename &optional period)
4426 "Return FILENAME's final \"extension\".
4427 The extension, in a file name, is the part that begins with the last `.',
4428 excluding version numbers and backup suffixes, except that a leading `.'
4429 of the file name, if there is one, doesn't count.
4430 Return nil for extensionless file names such as `foo'.
4431 Return the empty string for file names such as `foo.'.
4433 By default, the returned value excludes the period that starts the
4434 extension, but if the optional argument PERIOD is non-nil, the period
4435 is included in the value, and in that case, if FILENAME has no
4436 extension, the value is \"\"."
4437 (save-match-data
4438 (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
4439 (if (and (string-match "\\.[^.]*\\'" file)
4440 (not (eq 0 (match-beginning 0))))
4441 (substring file (+ (match-beginning 0) (if period 0 1)))
4442 (if period
4443 "")))))
4445 (defun file-name-base (&optional filename)
4446 "Return the base name of the FILENAME: no directory, no extension.
4447 FILENAME defaults to `buffer-file-name'."
4448 (file-name-sans-extension
4449 (file-name-nondirectory (or filename (buffer-file-name)))))
4451 (defcustom make-backup-file-name-function
4452 #'make-backup-file-name--default-function
4453 "A function that `make-backup-file-name' uses to create backup file names.
4454 The function receives a single argument, the original file name.
4456 If you change this, you may need to change `backup-file-name-p' and
4457 `file-name-sans-versions' too.
4459 You could make this buffer-local to do something special for specific files.
4461 For historical reasons, a value of nil means to use the default function.
4462 This should not be relied upon.
4464 See also `backup-directory-alist'."
4465 :version "24.4" ; nil -> make-backup-file-name--default-function
4466 :group 'backup
4467 :type '(choice (const :tag "Deprecated way to get the default function" nil)
4468 (function :tag "Function")))
4470 (defcustom backup-directory-alist nil
4471 "Alist of filename patterns and backup directory names.
4472 Each element looks like (REGEXP . DIRECTORY). Backups of files with
4473 names matching REGEXP will be made in DIRECTORY. DIRECTORY may be
4474 relative or absolute. If it is absolute, so that all matching files
4475 are backed up into the same directory, the file names in this
4476 directory will be the full name of the file backed up with all
4477 directory separators changed to `!' to prevent clashes. This will not
4478 work correctly if your filesystem truncates the resulting name.
4480 For the common case of all backups going into one directory, the alist
4481 should contain a single element pairing \".\" with the appropriate
4482 directory name.
4484 If this variable is nil, or it fails to match a filename, the backup
4485 is made in the original file's directory.
4487 On MS-DOS filesystems without long names this variable is always
4488 ignored."
4489 :group 'backup
4490 :type '(repeat (cons (regexp :tag "Regexp matching filename")
4491 (directory :tag "Backup directory name"))))
4493 (defun normal-backup-enable-predicate (name)
4494 "Default `backup-enable-predicate' function.
4495 Checks for files in `temporary-file-directory',
4496 `small-temporary-file-directory', and \"/tmp\"."
4497 (let ((temporary-file-directory temporary-file-directory)
4498 caseless)
4499 ;; On MS-Windows, file-truename will convert short 8+3 aliases to
4500 ;; their long file-name equivalents, so compare-strings does TRT.
4501 (if (memq system-type '(ms-dos windows-nt))
4502 (setq temporary-file-directory (file-truename temporary-file-directory)
4503 name (file-truename name)
4504 caseless t))
4505 (not (or (let ((comp (compare-strings temporary-file-directory 0 nil
4506 name 0 nil caseless)))
4507 ;; Directory is under temporary-file-directory.
4508 (and (not (eq comp t))
4509 (< comp (- (length temporary-file-directory)))))
4510 (let ((comp (compare-strings "/tmp" 0 nil
4511 name 0 nil)))
4512 ;; Directory is under /tmp.
4513 (and (not (eq comp t))
4514 (< comp (- (length "/tmp")))))
4515 (if small-temporary-file-directory
4516 (let ((comp (compare-strings small-temporary-file-directory
4517 0 nil
4518 name 0 nil caseless)))
4519 ;; Directory is under small-temporary-file-directory.
4520 (and (not (eq comp t))
4521 (< comp (- (length small-temporary-file-directory))))))))))
4523 (defun make-backup-file-name (file)
4524 "Create the non-numeric backup file name for FILE.
4525 This calls the function that `make-backup-file-name-function' specifies,
4526 with a single argument FILE."
4527 (funcall (or make-backup-file-name-function
4528 #'make-backup-file-name--default-function)
4529 file))
4531 (defun make-backup-file-name--default-function (file)
4532 "Default function for `make-backup-file-name'.
4533 Normally this just returns FILE's name with `~' appended.
4534 It searches for a match for FILE in `backup-directory-alist'.
4535 If the directory for the backup doesn't exist, it is created."
4536 (if (and (eq system-type 'ms-dos)
4537 (not (msdos-long-file-names)))
4538 (let ((fn (file-name-nondirectory file)))
4539 (concat (file-name-directory file)
4540 (or (and (string-match "\\`[^.]+\\'" fn)
4541 (concat (match-string 0 fn) ".~"))
4542 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
4543 (concat (match-string 0 fn) "~")))))
4544 (concat (make-backup-file-name-1 file) "~")))
4546 (defun make-backup-file-name-1 (file)
4547 "Subroutine of `make-backup-file-name--default-function'.
4548 The function `find-backup-file-name' also uses this."
4549 (let ((alist backup-directory-alist)
4550 elt backup-directory abs-backup-directory)
4551 (while alist
4552 (setq elt (pop alist))
4553 (if (string-match (car elt) file)
4554 (setq backup-directory (cdr elt)
4555 alist nil)))
4556 ;; If backup-directory is relative, it should be relative to the
4557 ;; file's directory. By expanding explicitly here, we avoid
4558 ;; depending on default-directory.
4559 (if backup-directory
4560 (setq abs-backup-directory
4561 (expand-file-name backup-directory
4562 (file-name-directory file))))
4563 (if (and abs-backup-directory (not (file-exists-p abs-backup-directory)))
4564 (condition-case nil
4565 (make-directory abs-backup-directory 'parents)
4566 (file-error (setq backup-directory nil
4567 abs-backup-directory nil))))
4568 (if (null backup-directory)
4569 file
4570 (if (file-name-absolute-p backup-directory)
4571 (progn
4572 (when (memq system-type '(windows-nt ms-dos cygwin))
4573 ;; Normalize DOSish file names: downcase the drive
4574 ;; letter, if any, and replace the leading "x:" with
4575 ;; "/drive_x".
4576 (or (file-name-absolute-p file)
4577 (setq file (expand-file-name file))) ; make defaults explicit
4578 ;; Replace any invalid file-name characters (for the
4579 ;; case of backing up remote files).
4580 (setq file (expand-file-name (convert-standard-filename file)))
4581 (if (eq (aref file 1) ?:)
4582 (setq file (concat "/"
4583 "drive_"
4584 (char-to-string (downcase (aref file 0)))
4585 (if (eq (aref file 2) ?/)
4587 "/")
4588 (substring file 2)))))
4589 ;; Make the name unique by substituting directory
4590 ;; separators. It may not really be worth bothering about
4591 ;; doubling `!'s in the original name...
4592 (expand-file-name
4593 (subst-char-in-string
4594 ?/ ?!
4595 (replace-regexp-in-string "!" "!!" file))
4596 backup-directory))
4597 (expand-file-name (file-name-nondirectory file)
4598 (file-name-as-directory abs-backup-directory))))))
4600 (defun backup-file-name-p (file)
4601 "Return non-nil if FILE is a backup file name (numeric or not).
4602 This is a separate function so you can redefine it for customization.
4603 You may need to redefine `file-name-sans-versions' as well."
4604 (string-match "~\\'" file))
4606 (defvar backup-extract-version-start)
4608 ;; This is used in various files.
4609 ;; The usage of backup-extract-version-start is not very clean,
4610 ;; but I can't see a good alternative, so as of now I am leaving it alone.
4611 (defun backup-extract-version (fn)
4612 "Given the name of a numeric backup file, FN, return the backup number.
4613 Uses the free variable `backup-extract-version-start', whose value should be
4614 the index in the name where the version number begins."
4615 (if (and (string-match "[0-9]+~/?$" fn backup-extract-version-start)
4616 (= (match-beginning 0) backup-extract-version-start))
4617 (string-to-number (substring fn backup-extract-version-start -1))
4620 (defun find-backup-file-name (fn)
4621 "Find a file name for a backup file FN, and suggestions for deletions.
4622 Value is a list whose car is the name for the backup file
4623 and whose cdr is a list of old versions to consider deleting now.
4624 If the value is nil, don't make a backup.
4625 Uses `backup-directory-alist' in the same way as
4626 `make-backup-file-name--default-function' does."
4627 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
4628 ;; Run a handler for this function so that ange-ftp can refuse to do it.
4629 (if handler
4630 (funcall handler 'find-backup-file-name fn)
4631 (if (or (eq version-control 'never)
4632 ;; We don't support numbered backups on plain MS-DOS
4633 ;; when long file names are unavailable.
4634 (and (eq system-type 'ms-dos)
4635 (not (msdos-long-file-names))))
4636 (list (make-backup-file-name fn))
4637 (let* ((basic-name (make-backup-file-name-1 fn))
4638 (base-versions (concat (file-name-nondirectory basic-name)
4639 ".~"))
4640 (backup-extract-version-start (length base-versions))
4641 (high-water-mark 0)
4642 (number-to-delete 0)
4643 possibilities deserve-versions-p versions)
4644 (condition-case ()
4645 (setq possibilities (file-name-all-completions
4646 base-versions
4647 (file-name-directory basic-name))
4648 versions (sort (mapcar #'backup-extract-version
4649 possibilities)
4650 #'<)
4651 high-water-mark (apply 'max 0 versions)
4652 deserve-versions-p (or version-control
4653 (> high-water-mark 0))
4654 number-to-delete (- (length versions)
4655 kept-old-versions
4656 kept-new-versions
4657 -1))
4658 (file-error (setq possibilities nil)))
4659 (if (not deserve-versions-p)
4660 (list (make-backup-file-name fn))
4661 (cons (format "%s.~%d~" basic-name (1+ high-water-mark))
4662 (if (and (> number-to-delete 0)
4663 ;; Delete nothing if there is overflow
4664 ;; in the number of versions to keep.
4665 (>= (+ kept-new-versions kept-old-versions -1) 0))
4666 (mapcar (lambda (n)
4667 (format "%s.~%d~" basic-name n))
4668 (let ((v (nthcdr kept-old-versions versions)))
4669 (rplacd (nthcdr (1- number-to-delete) v) ())
4670 v))))))))))
4672 (defun file-nlinks (filename)
4673 "Return number of names file FILENAME has."
4674 (car (cdr (file-attributes filename))))
4676 ;; (defun file-relative-name (filename &optional directory)
4677 ;; "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
4678 ;; This function returns a relative file name which is equivalent to FILENAME
4679 ;; when used with that default directory as the default.
4680 ;; If this is impossible (which can happen on MSDOS and Windows
4681 ;; when the file name and directory use different drive names)
4682 ;; then it returns FILENAME."
4683 ;; (save-match-data
4684 ;; (let ((fname (expand-file-name filename)))
4685 ;; (setq directory (file-name-as-directory
4686 ;; (expand-file-name (or directory default-directory))))
4687 ;; ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
4688 ;; ;; drive names, they can't be relative, so return the absolute name.
4689 ;; (if (and (or (eq system-type 'ms-dos)
4690 ;; (eq system-type 'cygwin)
4691 ;; (eq system-type 'windows-nt))
4692 ;; (not (string-equal (substring fname 0 2)
4693 ;; (substring directory 0 2))))
4694 ;; filename
4695 ;; (let ((ancestor ".")
4696 ;; (fname-dir (file-name-as-directory fname)))
4697 ;; (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
4698 ;; (not (string-match (concat "^" (regexp-quote directory)) fname)))
4699 ;; (setq directory (file-name-directory (substring directory 0 -1))
4700 ;; ancestor (if (equal ancestor ".")
4701 ;; ".."
4702 ;; (concat "../" ancestor))))
4703 ;; ;; Now ancestor is empty, or .., or ../.., etc.
4704 ;; (if (string-match (concat "^" (regexp-quote directory)) fname)
4705 ;; ;; We matched within FNAME's directory part.
4706 ;; ;; Add the rest of FNAME onto ANCESTOR.
4707 ;; (let ((rest (substring fname (match-end 0))))
4708 ;; (if (and (equal ancestor ".")
4709 ;; (not (equal rest "")))
4710 ;; ;; But don't bother with ANCESTOR if it would give us `./'.
4711 ;; rest
4712 ;; (concat (file-name-as-directory ancestor) rest)))
4713 ;; ;; We matched FNAME's directory equivalent.
4714 ;; ancestor))))))
4716 (defun file-relative-name (filename &optional directory)
4717 "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
4718 This function returns a relative file name which is equivalent to FILENAME
4719 when used with that default directory as the default.
4720 If FILENAME is a relative file name, it will be interpreted as existing in
4721 `default-directory'.
4722 If FILENAME and DIRECTORY lie on different machines or on different drives
4723 on a DOS/Windows machine, it returns FILENAME in expanded form."
4724 (save-match-data
4725 (setq directory
4726 (file-name-as-directory (expand-file-name (or directory
4727 default-directory))))
4728 (setq filename (expand-file-name filename))
4729 (let ((fremote (file-remote-p filename))
4730 (dremote (file-remote-p directory))
4731 (fold-case (or (file-name-case-insensitive-p filename)
4732 read-file-name-completion-ignore-case)))
4733 (if ;; Conditions for separate trees
4735 ;; Test for different filesystems on DOS/Windows
4736 (and
4737 ;; Should `cygwin' really be included here? --stef
4738 (memq system-type '(ms-dos cygwin windows-nt))
4740 ;; Test for different drive letters
4741 (not (eq t (compare-strings filename 0 2 directory 0 2 fold-case)))
4742 ;; Test for UNCs on different servers
4743 (not (eq t (compare-strings
4744 (progn
4745 (if (string-match "\\`//\\([^:/]+\\)/" filename)
4746 (match-string 1 filename)
4747 ;; Windows file names cannot have ? in
4748 ;; them, so use that to detect when
4749 ;; neither FILENAME nor DIRECTORY is a
4750 ;; UNC.
4751 "?"))
4752 0 nil
4753 (progn
4754 (if (string-match "\\`//\\([^:/]+\\)/" directory)
4755 (match-string 1 directory)
4756 "?"))
4757 0 nil t)))))
4758 ;; Test for different remote file system identification
4759 (not (equal fremote dremote)))
4760 filename
4761 (let ((ancestor ".")
4762 (filename-dir (file-name-as-directory filename)))
4763 (while (not
4764 (or (string-prefix-p directory filename-dir fold-case)
4765 (string-prefix-p directory filename fold-case)))
4766 (setq directory (file-name-directory (substring directory 0 -1))
4767 ancestor (if (equal ancestor ".")
4768 ".."
4769 (concat "../" ancestor))))
4770 ;; Now ancestor is empty, or .., or ../.., etc.
4771 (if (string-prefix-p directory filename fold-case)
4772 ;; We matched within FILENAME's directory part.
4773 ;; Add the rest of FILENAME onto ANCESTOR.
4774 (let ((rest (substring filename (length directory))))
4775 (if (and (equal ancestor ".") (not (equal rest "")))
4776 ;; But don't bother with ANCESTOR if it would give us `./'.
4777 rest
4778 (concat (file-name-as-directory ancestor) rest)))
4779 ;; We matched FILENAME's directory equivalent.
4780 ancestor))))))
4782 (defun save-buffer (&optional arg)
4783 "Save current buffer in visited file if modified.
4784 Variations are described below.
4786 By default, makes the previous version into a backup file
4787 if previously requested or if this is the first save.
4788 Prefixed with one \\[universal-argument], marks this version
4789 to become a backup when the next save is done.
4790 Prefixed with two \\[universal-argument]'s,
4791 makes the previous version into a backup file.
4792 Prefixed with three \\[universal-argument]'s, marks this version
4793 to become a backup when the next save is done,
4794 and makes the previous version into a backup file.
4796 With a numeric prefix argument of 0, never make the previous version
4797 into a backup file.
4799 Note that the various variables that control backups, such
4800 as `version-control', `backup-enable-predicate', `vc-make-backup-files',
4801 and `backup-inhibited', to name just the more popular ones, still
4802 control whether a backup will actually be produced, even when you
4803 invoke this command prefixed with two or three \\[universal-argument]'s.
4805 If a file's name is FOO, the names of its numbered backup versions are
4806 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
4807 Numeric backups (rather than FOO~) will be made if value of
4808 `version-control' is not the atom `never' and either there are already
4809 numeric versions of the file being backed up, or `version-control' is
4810 non-nil.
4811 We don't want excessive versions piling up, so there are variables
4812 `kept-old-versions', which tells Emacs how many oldest versions to keep,
4813 and `kept-new-versions', which tells how many newest versions to keep.
4814 Defaults are 2 old versions and 2 new.
4815 `dired-kept-versions' controls dired's clean-directory (.) command.
4816 If `delete-old-versions' is nil, system will query user
4817 before trimming versions. Otherwise it does it silently.
4819 If `vc-make-backup-files' is nil, which is the default,
4820 no backup files are made for files managed by version control.
4821 (This is because the version control system itself records previous versions.)
4823 See the subroutine `basic-save-buffer' for more information."
4824 (interactive "p")
4825 (let ((modp (buffer-modified-p))
4826 (make-backup-files (or (and make-backup-files (not (eq arg 0)))
4827 (memq arg '(16 64)))))
4828 (and modp (memq arg '(16 64)) (setq buffer-backed-up nil))
4829 ;; We used to display the message below only for files > 50KB, but
4830 ;; then Rmail-mbox never displays it due to buffer swapping. If
4831 ;; the test is ever re-introduced, be sure to handle saving of
4832 ;; Rmail files.
4833 (if (and modp
4834 (buffer-file-name)
4835 (not noninteractive)
4836 (not save-silently))
4837 (message "Saving file %s..." (buffer-file-name)))
4838 (basic-save-buffer (called-interactively-p 'any))
4839 (and modp (memq arg '(4 64)) (setq buffer-backed-up nil))))
4841 (defun delete-auto-save-file-if-necessary (&optional force)
4842 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
4843 Normally delete only if the file was written by this Emacs since
4844 the last real save, but optional arg FORCE non-nil means delete anyway."
4845 (and buffer-auto-save-file-name delete-auto-save-files
4846 (not (string= buffer-file-name buffer-auto-save-file-name))
4847 (or force (recent-auto-save-p))
4848 (progn
4849 (condition-case ()
4850 (delete-file buffer-auto-save-file-name)
4851 (file-error nil))
4852 (set-buffer-auto-saved))))
4854 (defvar auto-save-hook nil
4855 "Normal hook run just before auto-saving.")
4857 (defcustom before-save-hook nil
4858 "Normal hook that is run before a buffer is saved to its file."
4859 :options '(copyright-update time-stamp)
4860 :type 'hook
4861 :group 'files)
4863 (defcustom after-save-hook nil
4864 "Normal hook that is run after a buffer is saved to its file."
4865 :options '(executable-make-buffer-file-executable-if-script-p)
4866 :type 'hook
4867 :group 'files)
4869 (defvar save-buffer-coding-system nil
4870 "If non-nil, use this coding system for saving the buffer.
4871 More precisely, use this coding system in place of the
4872 value of `buffer-file-coding-system', when saving the buffer.
4873 Calling `write-region' for any purpose other than saving the buffer
4874 will still use `buffer-file-coding-system'; this variable has no effect
4875 in such cases.")
4877 (make-variable-buffer-local 'save-buffer-coding-system)
4878 (put 'save-buffer-coding-system 'permanent-local t)
4880 (defun basic-save-buffer (&optional called-interactively)
4881 "Save the current buffer in its visited file, if it has been modified.
4882 The hooks `write-contents-functions' and `write-file-functions' get a chance
4883 to do the job of saving; if they do not, then the buffer is saved in
4884 the visited file in the usual way.
4885 Before and after saving the buffer, this function runs
4886 `before-save-hook' and `after-save-hook', respectively."
4887 (interactive '(called-interactively))
4888 (save-current-buffer
4889 ;; In an indirect buffer, save its base buffer instead.
4890 (if (buffer-base-buffer)
4891 (set-buffer (buffer-base-buffer)))
4892 (if (or (buffer-modified-p)
4893 ;; handle the case when no modification has been made but
4894 ;; the file disappeared since visited
4895 (and buffer-file-name
4896 (not (file-exists-p buffer-file-name))))
4897 (let ((recent-save (recent-auto-save-p))
4898 setmodes)
4899 ;; If buffer has no file name, ask user for one.
4900 (or buffer-file-name
4901 (let ((filename
4902 (expand-file-name
4903 (read-file-name "File to save in: "
4904 nil (expand-file-name (buffer-name))))))
4905 (if (file-exists-p filename)
4906 (if (file-directory-p filename)
4907 ;; Signal an error if the user specified the name of an
4908 ;; existing directory.
4909 (error "%s is a directory" filename)
4910 (unless (y-or-n-p (format-message
4911 "File `%s' exists; overwrite? "
4912 filename))
4913 (error "Canceled"))))
4914 (set-visited-file-name filename)))
4915 (or (verify-visited-file-modtime (current-buffer))
4916 (not (file-exists-p buffer-file-name))
4917 (yes-or-no-p
4918 (format
4919 "%s has changed since visited or saved. Save anyway? "
4920 (file-name-nondirectory buffer-file-name)))
4921 (user-error "Save not confirmed"))
4922 (save-restriction
4923 (widen)
4924 (save-excursion
4925 (and (> (point-max) (point-min))
4926 (not find-file-literally)
4927 (/= (char-after (1- (point-max))) ?\n)
4928 (not (and (eq selective-display t)
4929 (= (char-after (1- (point-max))) ?\r)))
4930 (or (eq require-final-newline t)
4931 (eq require-final-newline 'visit-save)
4932 (and require-final-newline
4933 (y-or-n-p
4934 (format "Buffer %s does not end in newline. Add one? "
4935 (buffer-name)))))
4936 (save-excursion
4937 (goto-char (point-max))
4938 (insert ?\n))))
4939 ;; Support VC version backups.
4940 (vc-before-save)
4941 ;; Don't let errors prevent saving the buffer.
4942 (with-demoted-errors (run-hooks 'before-save-hook))
4943 (or (run-hook-with-args-until-success 'write-contents-functions)
4944 (run-hook-with-args-until-success 'local-write-file-hooks)
4945 (run-hook-with-args-until-success 'write-file-functions)
4946 ;; If a hook returned t, file is already "written".
4947 ;; Otherwise, write it the usual way now.
4948 (let ((dir (file-name-directory
4949 (expand-file-name buffer-file-name))))
4950 (unless (file-exists-p dir)
4951 (if (y-or-n-p
4952 (format-message
4953 "Directory `%s' does not exist; create? " dir))
4954 (make-directory dir t)
4955 (error "Canceled")))
4956 (setq setmodes (basic-save-buffer-1))))
4957 ;; Now we have saved the current buffer. Let's make sure
4958 ;; that buffer-file-coding-system is fixed to what
4959 ;; actually used for saving by binding it locally.
4960 (if save-buffer-coding-system
4961 (setq save-buffer-coding-system last-coding-system-used)
4962 (setq buffer-file-coding-system last-coding-system-used))
4963 (setq buffer-file-number
4964 (nthcdr 10 (file-attributes buffer-file-name)))
4965 (if setmodes
4966 (condition-case ()
4967 (progn
4968 (unless
4969 (with-demoted-errors
4970 (set-file-modes buffer-file-name (car setmodes)))
4971 (set-file-extended-attributes buffer-file-name
4972 (nth 1 setmodes))))
4973 (error nil))))
4974 ;; If the auto-save file was recent before this command,
4975 ;; delete it now.
4976 (delete-auto-save-file-if-necessary recent-save)
4977 ;; Support VC `implicit' locking.
4978 (vc-after-save)
4979 (run-hooks 'after-save-hook))
4980 (or noninteractive
4981 (not called-interactively)
4982 (files--message "(No changes need to be saved)")))))
4984 ;; This does the "real job" of writing a buffer into its visited file
4985 ;; and making a backup file. This is what is normally done
4986 ;; but inhibited if one of write-file-functions returns non-nil.
4987 ;; It returns a value (MODES EXTENDED-ATTRIBUTES BACKUPNAME), like
4988 ;; backup-buffer.
4989 (defun basic-save-buffer-1 ()
4990 (prog1
4991 (if save-buffer-coding-system
4992 (let ((coding-system-for-write save-buffer-coding-system))
4993 (basic-save-buffer-2))
4994 (basic-save-buffer-2))
4995 (if buffer-file-coding-system-explicit
4996 (setcar buffer-file-coding-system-explicit last-coding-system-used))))
4998 ;; This returns a value (MODES EXTENDED-ATTRIBUTES BACKUPNAME), like
4999 ;; backup-buffer.
5000 (defun basic-save-buffer-2 ()
5001 (let (tempsetmodes setmodes)
5002 (if (not (file-writable-p buffer-file-name))
5003 (let ((dir (file-name-directory buffer-file-name)))
5004 (if (not (file-directory-p dir))
5005 (if (file-exists-p dir)
5006 (error "%s is not a directory" dir)
5007 (error "%s: no such directory" dir))
5008 (if (not (file-exists-p buffer-file-name))
5009 (error "Directory %s write-protected" dir)
5010 (if (yes-or-no-p
5011 (format
5012 "File %s is write-protected; try to save anyway? "
5013 (file-name-nondirectory
5014 buffer-file-name)))
5015 (setq tempsetmodes t)
5016 (error "Attempt to save to a file which you aren't allowed to write"))))))
5017 (or buffer-backed-up
5018 (setq setmodes (backup-buffer)))
5019 (let* ((dir (file-name-directory buffer-file-name))
5020 (dir-writable (file-writable-p dir)))
5021 (if (or (and file-precious-flag dir-writable)
5022 (and break-hardlink-on-save
5023 (file-exists-p buffer-file-name)
5024 (> (file-nlinks buffer-file-name) 1)
5025 (or dir-writable
5026 (error (concat "Directory %s write-protected; "
5027 "cannot break hardlink when saving")
5028 dir))))
5029 ;; Write temp name, then rename it.
5030 ;; This requires write access to the containing dir,
5031 ;; which is why we don't try it if we don't have that access.
5032 (let ((realname buffer-file-name)
5033 tempname succeed
5034 (umask (default-file-modes))
5035 (old-modtime (visited-file-modtime)))
5036 ;; Create temp files with strict access rights. It's easy to
5037 ;; loosen them later, whereas it's impossible to close the
5038 ;; time-window of loose permissions otherwise.
5039 (unwind-protect
5040 (progn
5041 (clear-visited-file-modtime)
5042 (set-default-file-modes ?\700)
5043 ;; Try various temporary names.
5044 ;; This code follows the example of make-temp-file,
5045 ;; but it calls write-region in the appropriate way
5046 ;; for saving the buffer.
5047 (while (condition-case ()
5048 (progn
5049 (setq tempname
5050 (make-temp-name
5051 (expand-file-name "tmp" dir)))
5052 ;; Pass in nil&nil rather than point-min&max
5053 ;; cause we're saving the whole buffer.
5054 ;; write-region-annotate-functions may use it.
5055 (write-region nil nil
5056 tempname nil realname
5057 buffer-file-truename 'excl)
5058 (when save-silently (message nil))
5059 nil)
5060 (file-already-exists t))
5061 ;; The file was somehow created by someone else between
5062 ;; `make-temp-name' and `write-region', let's try again.
5063 nil)
5064 (setq succeed t))
5065 ;; Reset the umask.
5066 (set-default-file-modes umask)
5067 ;; If we failed, restore the buffer's modtime.
5068 (unless succeed
5069 (set-visited-file-modtime old-modtime)))
5070 ;; Since we have created an entirely new file,
5071 ;; make sure it gets the right permission bits set.
5072 (setq setmodes (or setmodes
5073 (list (or (file-modes buffer-file-name)
5074 (logand ?\666 umask))
5075 (file-extended-attributes buffer-file-name)
5076 buffer-file-name)))
5077 ;; We succeeded in writing the temp file,
5078 ;; so rename it.
5079 (rename-file tempname buffer-file-name t))
5080 ;; If file not writable, see if we can make it writable
5081 ;; temporarily while we write it.
5082 ;; But no need to do so if we have just backed it up
5083 ;; (setmodes is set) because that says we're superseding.
5084 (cond ((and tempsetmodes (not setmodes))
5085 ;; Change the mode back, after writing.
5086 (setq setmodes (list (file-modes buffer-file-name)
5087 (file-extended-attributes buffer-file-name)
5088 buffer-file-name))
5089 ;; If set-file-extended-attributes fails, fall back on
5090 ;; set-file-modes.
5091 (unless
5092 (with-demoted-errors
5093 (set-file-extended-attributes buffer-file-name
5094 (nth 1 setmodes)))
5095 (set-file-modes buffer-file-name
5096 (logior (car setmodes) 128))))))
5097 (let (success)
5098 (unwind-protect
5099 (progn
5100 ;; Pass in nil&nil rather than point-min&max to indicate
5101 ;; we're saving the buffer rather than just a region.
5102 ;; write-region-annotate-functions may make us of it.
5103 (write-region nil nil
5104 buffer-file-name nil t buffer-file-truename)
5105 (when save-silently (message nil))
5106 (setq success t))
5107 ;; If we get an error writing the new file, and we made
5108 ;; the backup by renaming, undo the backing-up.
5109 (and setmodes (not success)
5110 (progn
5111 (rename-file (nth 2 setmodes) buffer-file-name t)
5112 (setq buffer-backed-up nil))))))
5113 setmodes))
5115 (declare-function diff-no-select "diff"
5116 (old new &optional switches no-async buf))
5118 (defvar save-some-buffers-action-alist
5119 `((?\C-r
5120 ,(lambda (buf)
5121 (if (not enable-recursive-minibuffers)
5122 (progn (display-buffer buf)
5123 (setq other-window-scroll-buffer buf))
5124 (view-buffer buf (lambda (_) (exit-recursive-edit)))
5125 (recursive-edit))
5126 ;; Return nil to ask about BUF again.
5127 nil)
5128 ,(purecopy "view this buffer"))
5129 (?d ,(lambda (buf)
5130 (if (null (buffer-file-name buf))
5131 (message "Not applicable: no file")
5132 (require 'diff) ;for diff-no-select.
5133 (let ((diffbuf (diff-no-select (buffer-file-name buf) buf
5134 nil 'noasync)))
5135 (if (not enable-recursive-minibuffers)
5136 (progn (display-buffer diffbuf)
5137 (setq other-window-scroll-buffer diffbuf))
5138 (view-buffer diffbuf (lambda (_) (exit-recursive-edit)))
5139 (recursive-edit))))
5140 ;; Return nil to ask about BUF again.
5141 nil)
5142 ,(purecopy "view changes in this buffer")))
5143 "ACTION-ALIST argument used in call to `map-y-or-n-p'.")
5144 (put 'save-some-buffers-action-alist 'risky-local-variable t)
5146 (defvar buffer-save-without-query nil
5147 "Non-nil means `save-some-buffers' should save this buffer without asking.")
5148 (make-variable-buffer-local 'buffer-save-without-query)
5150 (defcustom save-some-buffers-default-predicate nil
5151 "Default predicate for `save-some-buffers'.
5152 This allows you to stop `save-some-buffers' from asking
5153 about certain files that you'd usually rather not save."
5154 :group 'auto-save
5155 :type 'function
5156 :version "26.1")
5158 (defun save-some-buffers (&optional arg pred)
5159 "Save some modified file-visiting buffers. Asks user about each one.
5160 You can answer `y' to save, `n' not to save, `C-r' to look at the
5161 buffer in question with `view-buffer' before deciding or `d' to
5162 view the differences using `diff-buffer-with-file'.
5164 This command first saves any buffers where `buffer-save-without-query' is
5165 non-nil, without asking.
5167 Optional argument (the prefix) non-nil means save all with no questions.
5168 Optional second argument PRED determines which buffers are considered:
5169 If PRED is nil, all the file-visiting buffers are considered.
5170 If PRED is t, then certain non-file buffers will also be considered.
5171 If PRED is a zero-argument function, it indicates for each buffer whether
5172 to consider it or not when called with that buffer current.
5173 PRED defaults to the value of `save-some-buffers-default-predicate'.
5175 See `save-some-buffers-action-alist' if you want to
5176 change the additional actions you can take on files."
5177 (interactive "P")
5178 (unless pred
5179 (setq pred save-some-buffers-default-predicate))
5180 (save-window-excursion
5181 (let* (queried autosaved-buffers
5182 files-done abbrevs-done)
5183 (dolist (buffer (buffer-list))
5184 ;; First save any buffers that we're supposed to save unconditionally.
5185 ;; That way the following code won't ask about them.
5186 (with-current-buffer buffer
5187 (when (and buffer-save-without-query (buffer-modified-p))
5188 (push (buffer-name) autosaved-buffers)
5189 (save-buffer))))
5190 ;; Ask about those buffers that merit it,
5191 ;; and record the number thus saved.
5192 (setq files-done
5193 (map-y-or-n-p
5194 (lambda (buffer)
5195 ;; Note that killing some buffers may kill others via
5196 ;; hooks (e.g. Rmail and its viewing buffer).
5197 (and (buffer-live-p buffer)
5198 (buffer-modified-p buffer)
5199 (not (buffer-base-buffer buffer))
5201 (buffer-file-name buffer)
5202 (and pred
5203 (progn
5204 (set-buffer buffer)
5205 (and buffer-offer-save (> (buffer-size) 0)))))
5206 (or (not (functionp pred))
5207 (with-current-buffer buffer (funcall pred)))
5208 (if arg
5210 (setq queried t)
5211 (if (buffer-file-name buffer)
5212 (format "Save file %s? "
5213 (buffer-file-name buffer))
5214 (format "Save buffer %s? "
5215 (buffer-name buffer))))))
5216 (lambda (buffer)
5217 (with-current-buffer buffer
5218 (save-buffer)))
5219 (buffer-list)
5220 '("buffer" "buffers" "save")
5221 save-some-buffers-action-alist))
5222 ;; Maybe to save abbrevs, and record whether
5223 ;; we either saved them or asked to.
5224 (and save-abbrevs abbrevs-changed
5225 (progn
5226 (if (or arg
5227 (eq save-abbrevs 'silently)
5228 (y-or-n-p (format "Save abbrevs in %s? " abbrev-file-name)))
5229 (write-abbrev-file nil))
5230 ;; Don't keep bothering user if he says no.
5231 (setq abbrevs-changed nil)
5232 (setq abbrevs-done t)))
5233 (or queried (> files-done 0) abbrevs-done
5234 (cond
5235 ((null autosaved-buffers)
5236 (when (called-interactively-p 'any)
5237 (files--message "(No files need saving)")))
5238 ((= (length autosaved-buffers) 1)
5239 (files--message "(Saved %s)" (car autosaved-buffers)))
5241 (files--message "(Saved %d files: %s)"
5242 (length autosaved-buffers)
5243 (mapconcat 'identity autosaved-buffers ", "))))))))
5245 (defun clear-visited-file-modtime ()
5246 "Clear out records of last mod time of visited file.
5247 Next attempt to save will not complain of a discrepancy."
5248 (set-visited-file-modtime 0))
5250 (defun not-modified (&optional arg)
5251 "Mark current buffer as unmodified, not needing to be saved.
5252 With prefix ARG, mark buffer as modified, so \\[save-buffer] will save.
5254 It is not a good idea to use this function in Lisp programs, because it
5255 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
5256 (declare (interactive-only set-buffer-modified-p))
5257 (interactive "P")
5258 (files--message (if arg "Modification-flag set"
5259 "Modification-flag cleared"))
5260 (set-buffer-modified-p arg))
5262 (defun toggle-read-only (&optional arg interactive)
5263 "Change whether this buffer is read-only."
5264 (declare (obsolete read-only-mode "24.3"))
5265 (interactive (list current-prefix-arg t))
5266 (if interactive
5267 (call-interactively 'read-only-mode)
5268 (read-only-mode (or arg 'toggle))))
5270 (defun insert-file (filename)
5271 "Insert contents of file FILENAME into buffer after point.
5272 Set mark after the inserted text.
5274 This function is meant for the user to run interactively.
5275 Don't call it from programs! Use `insert-file-contents' instead.
5276 \(Its calling sequence is different; see its documentation)."
5277 (declare (interactive-only insert-file-contents))
5278 (interactive "*fInsert file: ")
5279 (insert-file-1 filename #'insert-file-contents))
5281 (defun append-to-file (start end filename)
5282 "Append the contents of the region to the end of file FILENAME.
5283 When called from a function, expects three arguments,
5284 START, END and FILENAME. START and END are normally buffer positions
5285 specifying the part of the buffer to write.
5286 If START is nil, that means to use the entire buffer contents.
5287 If START is a string, then output that string to the file
5288 instead of any buffer contents; END is ignored.
5290 This does character code conversion and applies annotations
5291 like `write-region' does."
5292 (interactive "r\nFAppend to file: ")
5293 (prog1 (write-region start end filename t)
5294 (when save-silently (message nil))))
5296 (defun file-newest-backup (filename)
5297 "Return most recent backup file for FILENAME or nil if no backups exist."
5298 ;; `make-backup-file-name' will get us the right directory for
5299 ;; ordinary or numeric backups. It might create a directory for
5300 ;; backups as a side-effect, according to `backup-directory-alist'.
5301 (let* ((filename (file-name-sans-versions
5302 (make-backup-file-name (expand-file-name filename))))
5303 (file (file-name-nondirectory filename))
5304 (dir (file-name-directory filename))
5305 (comp (file-name-all-completions file dir))
5306 (newest nil)
5307 tem)
5308 (while comp
5309 (setq tem (pop comp))
5310 (cond ((and (backup-file-name-p tem)
5311 (string= (file-name-sans-versions tem) file))
5312 (setq tem (concat dir tem))
5313 (if (or (null newest)
5314 (file-newer-than-file-p tem newest))
5315 (setq newest tem)))))
5316 newest))
5318 (defun rename-uniquely ()
5319 "Rename current buffer to a similar name not already taken.
5320 This function is useful for creating multiple shell process buffers
5321 or multiple mail buffers, etc.
5323 Note that some commands, in particular those based on `compilation-mode'
5324 \(`compile', `grep', etc.) will reuse the current buffer if it has the
5325 appropriate mode even if it has been renamed. So as well as renaming
5326 the buffer, you also need to switch buffers before running another
5327 instance of such commands."
5328 (interactive)
5329 (save-match-data
5330 (let ((base-name (buffer-name)))
5331 (and (string-match "<[0-9]+>\\'" base-name)
5332 (not (and buffer-file-name
5333 (string= base-name
5334 (file-name-nondirectory buffer-file-name))))
5335 ;; If the existing buffer name has a <NNN>,
5336 ;; which isn't part of the file name (if any),
5337 ;; then get rid of that.
5338 (setq base-name (substring base-name 0 (match-beginning 0))))
5339 (rename-buffer (generate-new-buffer-name base-name))
5340 (force-mode-line-update))))
5342 (defun make-directory (dir &optional parents)
5343 "Create the directory DIR and optionally any nonexistent parent dirs.
5344 If DIR already exists as a directory, signal an error, unless
5345 PARENTS is non-nil.
5347 Interactively, the default choice of directory to create is the
5348 current buffer's default directory. That is useful when you have
5349 visited a file in a nonexistent directory.
5351 Noninteractively, the second (optional) argument PARENTS, if
5352 non-nil, says whether to create parent directories that don't
5353 exist. Interactively, this happens by default.
5355 If creating the directory or directories fail, an error will be
5356 raised."
5357 (interactive
5358 (list (read-file-name "Make directory: " default-directory default-directory
5359 nil nil)
5361 ;; If default-directory is a remote directory,
5362 ;; make sure we find its make-directory handler.
5363 (setq dir (expand-file-name dir))
5364 (let ((handler (find-file-name-handler dir 'make-directory)))
5365 (if handler
5366 (funcall handler 'make-directory dir parents)
5367 (if (not parents)
5368 (make-directory-internal dir)
5369 (let ((dir (directory-file-name (expand-file-name dir)))
5370 create-list)
5371 (while (and (not (file-exists-p dir))
5372 ;; If directory is its own parent, then we can't
5373 ;; keep looping forever
5374 (not (equal dir
5375 (directory-file-name
5376 (file-name-directory dir)))))
5377 (setq create-list (cons dir create-list)
5378 dir (directory-file-name (file-name-directory dir))))
5379 (while create-list
5380 (make-directory-internal (car create-list))
5381 (setq create-list (cdr create-list))))))))
5383 (defconst directory-files-no-dot-files-regexp
5384 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"
5385 "Regexp matching any file name except \".\" and \"..\".")
5387 (defun files--force (no-such fn &rest args)
5388 "Use NO-SUCH to affect behavior of function FN applied to list ARGS.
5389 This acts like (apply FN ARGS) except it returns NO-SUCH if it is
5390 non-nil and if FN fails due to a missing file or directory."
5391 (condition-case err
5392 (apply fn args)
5393 (file-missing (or no-such (signal (car err) (cdr err))))))
5395 (defun delete-directory (directory &optional recursive trash)
5396 "Delete the directory named DIRECTORY. Does not follow symlinks.
5397 If RECURSIVE is non-nil, delete files in DIRECTORY as well, with
5398 no error if something else is simultaneously deleting them.
5399 TRASH non-nil means to trash the directory instead, provided
5400 `delete-by-moving-to-trash' is non-nil.
5402 When called interactively, TRASH is nil if and only if a prefix
5403 argument is given, and a further prompt asks the user for
5404 RECURSIVE if DIRECTORY is nonempty."
5405 (interactive
5406 (let* ((trashing (and delete-by-moving-to-trash
5407 (null current-prefix-arg)))
5408 (dir (expand-file-name
5409 (read-directory-name
5410 (if trashing
5411 "Move directory to trash: "
5412 "Delete directory: ")
5413 default-directory default-directory nil nil))))
5414 (list dir
5415 (if (directory-files dir nil directory-files-no-dot-files-regexp)
5416 (y-or-n-p
5417 (format-message "Directory `%s' is not empty, really %s? "
5418 dir (if trashing "trash" "delete")))
5419 nil)
5420 (null current-prefix-arg))))
5421 ;; If default-directory is a remote directory, make sure we find its
5422 ;; delete-directory handler.
5423 (setq directory (directory-file-name (expand-file-name directory)))
5424 (let ((handler (find-file-name-handler directory 'delete-directory)))
5425 (cond
5426 (handler
5427 (funcall handler 'delete-directory directory recursive))
5428 ((and delete-by-moving-to-trash trash)
5429 ;; Only move non-empty dir to trash if recursive deletion was
5430 ;; requested. This mimics the non-`delete-by-moving-to-trash'
5431 ;; case, where the operation fails in delete-directory-internal.
5432 ;; As `move-file-to-trash' trashes directories (empty or
5433 ;; otherwise) as a unit, we do not need to recurse here.
5434 (if (and (not recursive)
5435 ;; Check if directory is empty apart from "." and "..".
5436 (directory-files
5437 directory 'full directory-files-no-dot-files-regexp))
5438 (error "Directory is not empty, not moving to trash")
5439 (move-file-to-trash directory)))
5440 ;; Otherwise, call ourselves recursively if needed.
5442 (when (or (not recursive) (file-symlink-p directory)
5443 (let* ((files
5444 (files--force t #'directory-files directory 'full
5445 directory-files-no-dot-files-regexp))
5446 (directory-exists (listp files)))
5447 (when directory-exists
5448 (mapc (lambda (file)
5449 ;; This test is equivalent to but more efficient
5450 ;; than (and (file-directory-p fn)
5451 ;; (not (file-symlink-p fn))).
5452 (if (eq t (car (file-attributes file)))
5453 (delete-directory file recursive)
5454 (files--force t #'delete-file file)))
5455 files))
5456 directory-exists))
5457 (files--force recursive #'delete-directory-internal directory))))))
5459 (defun file-equal-p (file1 file2)
5460 "Return non-nil if files FILE1 and FILE2 name the same file.
5461 If FILE1 or FILE2 does not exist, the return value is unspecified."
5462 (let ((handler (or (find-file-name-handler file1 'file-equal-p)
5463 (find-file-name-handler file2 'file-equal-p))))
5464 (if handler
5465 (funcall handler 'file-equal-p file1 file2)
5466 (let (f1-attr f2-attr)
5467 (and (setq f1-attr (file-attributes (file-truename file1)))
5468 (setq f2-attr (file-attributes (file-truename file2)))
5469 (equal f1-attr f2-attr))))))
5471 (defun file-in-directory-p (file dir)
5472 "Return non-nil if FILE is in DIR or a subdirectory of DIR.
5473 A directory is considered to be \"in\" itself.
5474 Return nil if DIR is not an existing directory."
5475 (let ((handler (or (find-file-name-handler file 'file-in-directory-p)
5476 (find-file-name-handler dir 'file-in-directory-p))))
5477 (if handler
5478 (funcall handler 'file-in-directory-p file dir)
5479 (when (file-directory-p dir) ; DIR must exist.
5480 (setq file (file-truename file)
5481 dir (file-truename dir))
5482 (let ((ls1 (split-string file "/" t))
5483 (ls2 (split-string dir "/" t))
5484 (root
5485 (cond
5486 ;; A UNC on Windows systems, or a "super-root" on Apollo.
5487 ((string-match "\\`//" file) "//")
5488 ((string-match "\\`/" file) "/")
5489 (t "")))
5490 (mismatch nil))
5491 (while (and ls1 ls2 (not mismatch))
5492 (if (string-equal (car ls1) (car ls2))
5493 (setq root (concat root (car ls1) "/"))
5494 (setq mismatch t))
5495 (setq ls1 (cdr ls1)
5496 ls2 (cdr ls2)))
5497 (unless mismatch
5498 (file-equal-p root dir)))))))
5500 (defun copy-directory (directory newname &optional keep-time parents copy-contents)
5501 "Copy DIRECTORY to NEWNAME. Both args must be strings.
5502 This function always sets the file modes of the output files to match
5503 the corresponding input file.
5505 The third arg KEEP-TIME non-nil means give the output files the same
5506 last-modified time as the old ones. (This works on only some systems.)
5508 A prefix arg makes KEEP-TIME non-nil.
5510 Noninteractively, the last argument PARENTS says whether to
5511 create parent directories if they don't exist. Interactively,
5512 this happens by default.
5514 If NEWNAME names an existing directory, copy DIRECTORY as a
5515 subdirectory there. However, if called from Lisp with a non-nil
5516 optional argument COPY-CONTENTS, copy the contents of DIRECTORY
5517 directly into NEWNAME instead."
5518 (interactive
5519 (let ((dir (read-directory-name
5520 "Copy directory: " default-directory default-directory t nil)))
5521 (list dir
5522 (read-directory-name
5523 (format "Copy directory %s to: " dir)
5524 default-directory default-directory nil nil)
5525 current-prefix-arg t nil)))
5526 (when (file-in-directory-p newname directory)
5527 (error "Cannot copy `%s' into its subdirectory `%s'"
5528 directory newname))
5529 ;; If default-directory is a remote directory, make sure we find its
5530 ;; copy-directory handler.
5531 (let ((handler (or (find-file-name-handler directory 'copy-directory)
5532 (find-file-name-handler newname 'copy-directory))))
5533 (if handler
5534 (funcall handler 'copy-directory directory
5535 newname keep-time parents copy-contents)
5537 ;; Compute target name.
5538 (setq directory (directory-file-name (expand-file-name directory))
5539 newname (directory-file-name (expand-file-name newname)))
5541 (cond ((not (file-directory-p newname))
5542 ;; If NEWNAME is not an existing directory, create it;
5543 ;; that is where we will copy the files of DIRECTORY.
5544 (make-directory newname parents))
5545 ;; If NEWNAME is an existing directory and COPY-CONTENTS
5546 ;; is nil, copy into NEWNAME/[DIRECTORY-BASENAME].
5547 ((not copy-contents)
5548 (setq newname (expand-file-name
5549 (file-name-nondirectory
5550 (directory-file-name directory))
5551 newname))
5552 (and (file-exists-p newname)
5553 (not (file-directory-p newname))
5554 (error "Cannot overwrite non-directory %s with a directory"
5555 newname))
5556 (make-directory newname t)))
5558 ;; Copy recursively.
5559 (dolist (file
5560 ;; We do not want to copy "." and "..".
5561 (directory-files directory 'full
5562 directory-files-no-dot-files-regexp))
5563 (let ((target (expand-file-name (file-name-nondirectory file) newname))
5564 (filetype (car (file-attributes file))))
5565 (cond
5566 ((eq filetype t) ; Directory but not a symlink.
5567 (copy-directory file newname keep-time parents))
5568 ((stringp filetype) ; Symbolic link
5569 (make-symbolic-link filetype target t))
5570 ((copy-file file target t keep-time)))))
5572 ;; Set directory attributes.
5573 (let ((modes (file-modes directory))
5574 (times (and keep-time (nth 5 (file-attributes directory)))))
5575 (if modes (set-file-modes newname modes))
5576 (if times (set-file-times newname times))))))
5579 ;; At time of writing, only info uses this.
5580 (defun prune-directory-list (dirs &optional keep reject)
5581 "Return a copy of DIRS with all non-existent directories removed.
5582 The optional argument KEEP is a list of directories to retain even if
5583 they don't exist, and REJECT is a list of directories to remove from
5584 DIRS, even if they exist; REJECT takes precedence over KEEP.
5586 Note that membership in REJECT and KEEP is checked using simple string
5587 comparison."
5588 (apply #'nconc
5589 (mapcar (lambda (dir)
5590 (and (not (member dir reject))
5591 (or (member dir keep) (file-directory-p dir))
5592 (list dir)))
5593 dirs)))
5596 (put 'revert-buffer-function 'permanent-local t)
5597 (defvar revert-buffer-function #'revert-buffer--default
5598 "Function to use to revert this buffer.
5599 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
5600 which are the arguments that `revert-buffer' received.
5601 It also has access to the `preserve-modes' argument of `revert-buffer'
5602 via the `revert-buffer-preserve-modes' dynamic variable.
5604 For historical reasons, a value of nil means to use the default function.
5605 This should not be relied upon.")
5607 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
5608 (defvar revert-buffer-insert-file-contents-function
5609 #'revert-buffer-insert-file-contents--default-function
5610 "Function to use to insert contents when reverting this buffer.
5611 The function receives two arguments: the first the nominal file name to use;
5612 the second is t if reading the auto-save file.
5614 The function is responsible for updating (or preserving) point.
5616 For historical reasons, a value of nil means to use the default function.
5617 This should not be relied upon.")
5619 (defun buffer-stale--default-function (&optional _noconfirm)
5620 "Default function to use for `buffer-stale-function'.
5621 This function ignores its argument.
5622 This returns non-nil if the current buffer is visiting a readable file
5623 whose modification time does not match that of the buffer.
5625 This function only handles buffers that are visiting files.
5626 Non-file buffers need a custom function"
5627 (and buffer-file-name
5628 (file-readable-p buffer-file-name)
5629 (not (buffer-modified-p (current-buffer)))
5630 (not (verify-visited-file-modtime (current-buffer)))))
5632 (defvar buffer-stale-function #'buffer-stale--default-function
5633 "Function to check whether a buffer needs reverting.
5634 This should be a function with one optional argument NOCONFIRM.
5635 Auto Revert Mode passes t for NOCONFIRM. The function should return
5636 non-nil if the buffer should be reverted. A return value of
5637 `fast' means that the need for reverting was not checked, but
5638 that reverting the buffer is fast. The buffer is current when
5639 this function is called.
5641 The idea behind the NOCONFIRM argument is that it should be
5642 non-nil if the buffer is going to be reverted without asking the
5643 user. In such situations, one has to be careful with potentially
5644 time consuming operations.
5646 For historical reasons, a value of nil means to use the default function.
5647 This should not be relied upon.
5649 For more information on how this variable is used by Auto Revert mode,
5650 see Info node `(emacs)Supporting additional buffers'.")
5652 (defvar before-revert-hook nil
5653 "Normal hook for `revert-buffer' to run before reverting.
5654 The function `revert-buffer--default' runs this.
5655 A customized `revert-buffer-function' need not run this hook.")
5657 (defvar after-revert-hook nil
5658 "Normal hook for `revert-buffer' to run after reverting.
5659 Note that the hook value that it runs is the value that was in effect
5660 before reverting; that makes a difference if you have buffer-local
5661 hook functions.
5663 The function `revert-buffer--default' runs this.
5664 A customized `revert-buffer-function' need not run this hook.")
5666 (defvar revert-buffer-in-progress-p nil
5667 "Non-nil if a `revert-buffer' operation is in progress, nil otherwise.")
5669 (defvar revert-buffer-internal-hook)
5671 ;; `revert-buffer-function' was defined long ago to be a function of only
5672 ;; 2 arguments, so we have to use a dynbind variable to pass the
5673 ;; `preserve-modes' argument of `revert-buffer'.
5674 (defvar revert-buffer-preserve-modes)
5676 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
5677 "Replace current buffer text with the text of the visited file on disk.
5678 This undoes all changes since the file was visited or saved.
5679 With a prefix argument, offer to revert from latest auto-save file, if
5680 that is more recent than the visited file.
5682 This command also implements an interface for special buffers
5683 that contain text which doesn't come from a file, but reflects
5684 some other data instead (e.g. Dired buffers, `buffer-list'
5685 buffers). This is done via the variable `revert-buffer-function'.
5686 In these cases, it should reconstruct the buffer contents from the
5687 appropriate data.
5689 When called from Lisp, the first argument is IGNORE-AUTO; only offer
5690 to revert from the auto-save file when this is nil. Note that the
5691 sense of this argument is the reverse of the prefix argument, for the
5692 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
5693 to nil.
5695 Optional second argument NOCONFIRM means don't ask for confirmation
5696 at all. (The variable `revert-without-query' offers another way to
5697 revert buffers without querying for confirmation.)
5699 Optional third argument PRESERVE-MODES non-nil means don't alter
5700 the files modes. Normally we reinitialize them using `normal-mode'.
5702 This function binds `revert-buffer-in-progress-p' non-nil while it operates.
5704 This function calls the function that `revert-buffer-function' specifies
5705 to do the work, with arguments IGNORE-AUTO and NOCONFIRM.
5706 The default function runs the hooks `before-revert-hook' and
5707 `after-revert-hook'."
5708 ;; I admit it's odd to reverse the sense of the prefix argument, but
5709 ;; there is a lot of code out there which assumes that the first
5710 ;; argument should be t to avoid consulting the auto-save file, and
5711 ;; there's no straightforward way to encourage authors to notice a
5712 ;; reversal of the argument sense. So I'm just changing the user
5713 ;; interface, but leaving the programmatic interface the same.
5714 (interactive (list (not current-prefix-arg)))
5715 (let ((revert-buffer-in-progress-p t)
5716 (revert-buffer-preserve-modes preserve-modes))
5717 (funcall (or revert-buffer-function #'revert-buffer--default)
5718 ignore-auto noconfirm)))
5720 (defun revert-buffer--default (ignore-auto noconfirm)
5721 "Default function for `revert-buffer'.
5722 The arguments IGNORE-AUTO and NOCONFIRM are as described for `revert-buffer'.
5723 Runs the hooks `before-revert-hook' and `after-revert-hook' at the
5724 start and end.
5726 Calls `revert-buffer-insert-file-contents-function' to reread the
5727 contents of the visited file, with two arguments: the first is the file
5728 name, the second is non-nil if reading an auto-save file.
5730 This function only handles buffers that are visiting files.
5731 Non-file buffers need a custom function."
5732 (with-current-buffer (or (buffer-base-buffer (current-buffer))
5733 (current-buffer))
5734 (let* ((auto-save-p (and (not ignore-auto)
5735 (recent-auto-save-p)
5736 buffer-auto-save-file-name
5737 (file-readable-p buffer-auto-save-file-name)
5738 (y-or-n-p
5739 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
5740 (file-name (if auto-save-p
5741 buffer-auto-save-file-name
5742 buffer-file-name)))
5743 (cond ((null file-name)
5744 (error "Buffer does not seem to be associated with any file"))
5745 ((or noconfirm
5746 (and (not (buffer-modified-p))
5747 (catch 'found
5748 (dolist (regexp revert-without-query)
5749 (when (string-match regexp file-name)
5750 (throw 'found t)))))
5751 (yes-or-no-p (format "Revert buffer from file %s? "
5752 file-name)))
5753 (run-hooks 'before-revert-hook)
5754 ;; If file was backed up but has changed since,
5755 ;; we should make another backup.
5756 (and (not auto-save-p)
5757 (not (verify-visited-file-modtime (current-buffer)))
5758 (setq buffer-backed-up nil))
5759 ;; Effectively copy the after-revert-hook status,
5760 ;; since after-find-file will clobber it.
5761 (let ((global-hook (default-value 'after-revert-hook))
5762 (local-hook (when (local-variable-p 'after-revert-hook)
5763 after-revert-hook))
5764 (inhibit-read-only t))
5765 ;; FIXME: Throw away undo-log when preserve-modes is nil?
5766 (funcall
5767 (or revert-buffer-insert-file-contents-function
5768 #'revert-buffer-insert-file-contents--default-function)
5769 file-name auto-save-p)
5770 ;; Recompute the truename in case changes in symlinks
5771 ;; have changed the truename.
5772 (setq buffer-file-truename
5773 (abbreviate-file-name (file-truename buffer-file-name)))
5774 (after-find-file nil nil t nil revert-buffer-preserve-modes)
5775 ;; Run after-revert-hook as it was before we reverted.
5776 (setq-default revert-buffer-internal-hook global-hook)
5777 (if local-hook
5778 (set (make-local-variable 'revert-buffer-internal-hook)
5779 local-hook)
5780 (kill-local-variable 'revert-buffer-internal-hook))
5781 (run-hooks 'revert-buffer-internal-hook))
5782 t)))))
5784 (defun revert-buffer-insert-file-contents--default-function (file-name auto-save-p)
5785 "Default function for `revert-buffer-insert-file-contents-function'.
5786 The function `revert-buffer--default' calls this.
5787 FILE-NAME is the name of the file. AUTO-SAVE-P is non-nil if this is
5788 an auto-save file."
5789 (cond
5790 ((not (file-exists-p file-name))
5791 (error (if buffer-file-number
5792 "File %s no longer exists!"
5793 "Cannot revert nonexistent file %s")
5794 file-name))
5795 ((not (file-readable-p file-name))
5796 (error (if buffer-file-number
5797 "File %s no longer readable!"
5798 "Cannot revert unreadable file %s")
5799 file-name))
5801 ;; Bind buffer-file-name to nil
5802 ;; so that we don't try to lock the file.
5803 (let ((buffer-file-name nil))
5804 (or auto-save-p
5805 (unlock-buffer)))
5806 (widen)
5807 (let ((coding-system-for-read
5808 ;; Auto-saved file should be read by Emacs's
5809 ;; internal coding.
5810 (if auto-save-p 'auto-save-coding
5811 (or coding-system-for-read
5812 (and
5813 buffer-file-coding-system-explicit
5814 (car buffer-file-coding-system-explicit))))))
5815 (if (and (not enable-multibyte-characters)
5816 coding-system-for-read
5817 (not (memq (coding-system-base
5818 coding-system-for-read)
5819 '(no-conversion raw-text))))
5820 ;; As a coding system suitable for multibyte
5821 ;; buffer is specified, make the current
5822 ;; buffer multibyte.
5823 (set-buffer-multibyte t))
5825 ;; This force after-insert-file-set-coding
5826 ;; (called from insert-file-contents) to set
5827 ;; buffer-file-coding-system to a proper value.
5828 (kill-local-variable 'buffer-file-coding-system)
5830 ;; Note that this preserves point in an intelligent way.
5831 (if revert-buffer-preserve-modes
5832 (let ((buffer-file-format buffer-file-format))
5833 (insert-file-contents file-name (not auto-save-p)
5834 nil nil t))
5835 (insert-file-contents file-name (not auto-save-p)
5836 nil nil t))))))
5838 (defun recover-this-file ()
5839 "Recover the visited file--get contents from its last auto-save file."
5840 (interactive)
5841 (or buffer-file-name
5842 (user-error "This buffer is not visiting a file"))
5843 (recover-file buffer-file-name))
5845 (defun recover-file (file)
5846 "Visit file FILE, but get contents from its last auto-save file."
5847 ;; Actually putting the file name in the minibuffer should be used
5848 ;; only rarely.
5849 ;; Not just because users often use the default.
5850 (interactive "FRecover file: ")
5851 (setq file (expand-file-name file))
5852 (if (auto-save-file-name-p (file-name-nondirectory file))
5853 (error "%s is an auto-save file" (abbreviate-file-name file)))
5854 (let ((file-name (let ((buffer-file-name file))
5855 (make-auto-save-file-name))))
5856 (cond ((if (file-exists-p file)
5857 (not (file-newer-than-file-p file-name file))
5858 (not (file-exists-p file-name)))
5859 (error "Auto-save file %s not current"
5860 (abbreviate-file-name file-name)))
5861 ((with-temp-buffer-window
5862 "*Directory*" nil
5863 #'(lambda (window _value)
5864 (with-selected-window window
5865 (unwind-protect
5866 (yes-or-no-p (format "Recover auto save file %s? " file-name))
5867 (when (window-live-p window)
5868 (quit-restore-window window 'kill)))))
5869 (with-current-buffer standard-output
5870 (let ((switches dired-listing-switches))
5871 (if (file-symlink-p file)
5872 (setq switches (concat switches " -L")))
5873 ;; Use insert-directory-safely, not insert-directory,
5874 ;; because these files might not exist. In particular,
5875 ;; FILE might not exist if the auto-save file was for
5876 ;; a buffer that didn't visit a file, such as "*mail*".
5877 ;; The code in v20.x called `ls' directly, so we need
5878 ;; to emulate what `ls' did in that case.
5879 (insert-directory-safely file switches)
5880 (insert-directory-safely file-name switches))))
5881 (switch-to-buffer (find-file-noselect file t))
5882 (let ((inhibit-read-only t)
5883 ;; Keep the current buffer-file-coding-system.
5884 (coding-system buffer-file-coding-system)
5885 ;; Auto-saved file should be read with special coding.
5886 (coding-system-for-read 'auto-save-coding))
5887 (erase-buffer)
5888 (insert-file-contents file-name nil)
5889 (set-buffer-file-coding-system coding-system))
5890 (after-find-file nil nil t))
5891 (t (user-error "Recover-file canceled")))))
5893 (defun recover-session ()
5894 "Recover auto save files from a previous Emacs session.
5895 This command first displays a Dired buffer showing you the
5896 previous sessions that you could recover from.
5897 To choose one, move point to the proper line and then type C-c C-c.
5898 Then you'll be asked about a number of files to recover."
5899 (interactive)
5900 (if (null auto-save-list-file-prefix)
5901 (error "You set `auto-save-list-file-prefix' to disable making session files"))
5902 (let ((dir (file-name-directory auto-save-list-file-prefix))
5903 (nd (file-name-nondirectory auto-save-list-file-prefix)))
5904 (unless (file-directory-p dir)
5905 (make-directory dir t))
5906 (unless (directory-files dir nil
5907 (if (string= "" nd)
5908 directory-files-no-dot-files-regexp
5909 (concat "\\`" (regexp-quote nd)))
5911 (error "No previous sessions to recover")))
5912 (let ((ls-lisp-support-shell-wildcards t))
5913 (dired (concat auto-save-list-file-prefix "*")
5914 (concat dired-listing-switches " -t")))
5915 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
5916 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish)
5917 (save-excursion
5918 (goto-char (point-min))
5919 (or (looking-at " Move to the session you want to recover,")
5920 (let ((inhibit-read-only t))
5921 ;; Each line starts with a space
5922 ;; so that Font Lock mode won't highlight the first character.
5923 (insert " To recover a session, move to it and type C-c C-c.\n"
5924 (substitute-command-keys
5925 " To delete a session file, type \
5926 \\[dired-flag-file-deletion] on its line to flag
5927 the file for deletion, then \\[dired-do-flagged-delete] to \
5928 delete flagged files.\n\n"))))))
5930 (defun recover-session-finish ()
5931 "Choose one saved session to recover auto-save files from.
5932 This command is used in the special Dired buffer created by
5933 \\[recover-session]."
5934 (interactive)
5935 ;; Get the name of the session file to recover from.
5936 (let ((file (dired-get-filename))
5937 files
5938 (buffer (get-buffer-create " *recover*")))
5939 (dired-unmark 1)
5940 (dired-do-flagged-delete t)
5941 (unwind-protect
5942 (with-current-buffer buffer
5943 ;; Read in the auto-save-list file.
5944 (erase-buffer)
5945 (insert-file-contents file)
5946 ;; Loop thru the text of that file
5947 ;; and get out the names of the files to recover.
5948 (while (not (eobp))
5949 (let (thisfile autofile)
5950 (if (eolp)
5951 ;; This is a pair of lines for a non-file-visiting buffer.
5952 ;; Get the auto-save file name and manufacture
5953 ;; a "visited file name" from that.
5954 (progn
5955 (forward-line 1)
5956 ;; If there is no auto-save file name, the
5957 ;; auto-save-list file is probably corrupted.
5958 (unless (eolp)
5959 (setq autofile
5960 (buffer-substring-no-properties
5961 (point)
5962 (line-end-position)))
5963 (setq thisfile
5964 (expand-file-name
5965 (substring
5966 (file-name-nondirectory autofile)
5967 1 -1)
5968 (file-name-directory autofile))))
5969 (forward-line 1))
5970 ;; This pair of lines is a file-visiting
5971 ;; buffer. Use the visited file name.
5972 (progn
5973 (setq thisfile
5974 (buffer-substring-no-properties
5975 (point) (progn (end-of-line) (point))))
5976 (forward-line 1)
5977 (setq autofile
5978 (buffer-substring-no-properties
5979 (point) (progn (end-of-line) (point))))
5980 (forward-line 1)))
5981 ;; Ignore a file if its auto-save file does not exist now.
5982 (if (and autofile (file-exists-p autofile))
5983 (setq files (cons thisfile files)))))
5984 (setq files (nreverse files))
5985 ;; The file contains a pair of line for each auto-saved buffer.
5986 ;; The first line of the pair contains the visited file name
5987 ;; or is empty if the buffer was not visiting a file.
5988 ;; The second line is the auto-save file name.
5989 (if files
5990 (map-y-or-n-p "Recover %s? "
5991 (lambda (file)
5992 (condition-case nil
5993 (save-excursion (recover-file file))
5994 (error
5995 "Failed to recover `%s'" file)))
5996 files
5997 '("file" "files" "recover"))
5998 (message "No files can be recovered from this session now")))
5999 (kill-buffer buffer))))
6001 (defun kill-buffer-ask (buffer)
6002 "Kill BUFFER if confirmed."
6003 (when (yes-or-no-p (format "Buffer %s %s. Kill? "
6004 (buffer-name buffer)
6005 (if (buffer-modified-p buffer)
6006 "HAS BEEN EDITED" "is unmodified")))
6007 (kill-buffer buffer)))
6009 (defun kill-some-buffers (&optional list)
6010 "Kill some buffers. Asks the user whether to kill each one of them.
6011 Non-interactively, if optional argument LIST is non-nil, it
6012 specifies the list of buffers to kill, asking for approval for each one."
6013 (interactive)
6014 (if (null list)
6015 (setq list (buffer-list)))
6016 (while list
6017 (let* ((buffer (car list))
6018 (name (buffer-name buffer)))
6019 (and name ; Can be nil for an indirect buffer
6020 ; if we killed the base buffer.
6021 (not (string-equal name ""))
6022 (/= (aref name 0) ?\s)
6023 (kill-buffer-ask buffer)))
6024 (setq list (cdr list))))
6026 (defun kill-matching-buffers (regexp &optional internal-too)
6027 "Kill buffers whose name matches the specified REGEXP.
6028 The optional second argument indicates whether to kill internal buffers too."
6029 (interactive "sKill buffers matching this regular expression: \nP")
6030 (dolist (buffer (buffer-list))
6031 (let ((name (buffer-name buffer)))
6032 (when (and name (not (string-equal name ""))
6033 (or internal-too (/= (aref name 0) ?\s))
6034 (string-match regexp name))
6035 (kill-buffer-ask buffer)))))
6038 (defun rename-auto-save-file ()
6039 "Adjust current buffer's auto save file name for current conditions.
6040 Also rename any existing auto save file, if it was made in this session."
6041 (let ((osave buffer-auto-save-file-name))
6042 (setq buffer-auto-save-file-name
6043 (make-auto-save-file-name))
6044 (if (and osave buffer-auto-save-file-name
6045 (not (string= buffer-auto-save-file-name buffer-file-name))
6046 (not (string= buffer-auto-save-file-name osave))
6047 (file-exists-p osave)
6048 (recent-auto-save-p))
6049 (rename-file osave buffer-auto-save-file-name t))))
6051 (defun make-auto-save-file-name ()
6052 "Return file name to use for auto-saves of current buffer.
6053 Does not consider `auto-save-visited-file-name' as that variable is checked
6054 before calling this function. You can redefine this for customization.
6055 See also `auto-save-file-name-p'."
6056 (if buffer-file-name
6057 (let ((handler (find-file-name-handler buffer-file-name
6058 'make-auto-save-file-name)))
6059 (if handler
6060 (funcall handler 'make-auto-save-file-name)
6061 (let ((list auto-save-file-name-transforms)
6062 (filename buffer-file-name)
6063 result uniq)
6064 ;; Apply user-specified translations
6065 ;; to the file name.
6066 (while (and list (not result))
6067 (if (string-match (car (car list)) filename)
6068 (setq result (replace-match (cadr (car list)) t nil
6069 filename)
6070 uniq (car (cddr (car list)))))
6071 (setq list (cdr list)))
6072 (if result
6073 (if uniq
6074 (setq filename (concat
6075 (file-name-directory result)
6076 (subst-char-in-string
6077 ?/ ?!
6078 (replace-regexp-in-string "!" "!!"
6079 filename))))
6080 (setq filename result)))
6081 (setq result
6082 (if (and (eq system-type 'ms-dos)
6083 (not (msdos-long-file-names)))
6084 ;; We truncate the file name to DOS 8+3 limits
6085 ;; before doing anything else, because the regexp
6086 ;; passed to string-match below cannot handle
6087 ;; extensions longer than 3 characters, multiple
6088 ;; dots, and other atrocities.
6089 (let ((fn (dos-8+3-filename
6090 (file-name-nondirectory buffer-file-name))))
6091 (string-match
6092 "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'"
6094 (concat (file-name-directory buffer-file-name)
6095 "#" (match-string 1 fn)
6096 "." (match-string 3 fn) "#"))
6097 (concat (file-name-directory filename)
6099 (file-name-nondirectory filename)
6100 "#")))
6101 ;; Make sure auto-save file names don't contain characters
6102 ;; invalid for the underlying filesystem.
6103 (if (and (memq system-type '(ms-dos windows-nt cygwin))
6104 ;; Don't modify remote filenames
6105 (not (file-remote-p result)))
6106 (convert-standard-filename result)
6107 result))))
6109 ;; Deal with buffers that don't have any associated files. (Mail
6110 ;; mode tends to create a good number of these.)
6112 (let ((buffer-name (buffer-name))
6113 (limit 0)
6114 file-name)
6115 ;; Restrict the characters used in the file name to those which
6116 ;; are known to be safe on all filesystems, url-encoding the
6117 ;; rest.
6118 ;; We do this on all platforms, because even if we are not
6119 ;; running on DOS/Windows, the current directory may be on a
6120 ;; mounted VFAT filesystem, such as a USB memory stick.
6121 (while (string-match "[^A-Za-z0-9-_.~#+]" buffer-name limit)
6122 (let* ((character (aref buffer-name (match-beginning 0)))
6123 (replacement
6124 ;; For multibyte characters, this will produce more than
6125 ;; 2 hex digits, so is not true URL encoding.
6126 (format "%%%02X" character)))
6127 (setq buffer-name (replace-match replacement t t buffer-name))
6128 (setq limit (1+ (match-end 0)))))
6129 ;; Generate the file name.
6130 (setq file-name
6131 (make-temp-file
6132 (let ((fname
6133 (expand-file-name
6134 (format "#%s#" buffer-name)
6135 ;; Try a few alternative directories, to get one we can
6136 ;; write it.
6137 (cond
6138 ((file-writable-p default-directory) default-directory)
6139 ((file-writable-p "/var/tmp/") "/var/tmp/")
6140 ("~/")))))
6141 (if (and (memq system-type '(ms-dos windows-nt cygwin))
6142 ;; Don't modify remote filenames
6143 (not (file-remote-p fname)))
6144 ;; The call to convert-standard-filename is in case
6145 ;; buffer-name includes characters not allowed by the
6146 ;; DOS/Windows filesystems. make-temp-file writes to the
6147 ;; file it creates, so we must fix the file name _before_
6148 ;; make-temp-file is called.
6149 (convert-standard-filename fname)
6150 fname))
6151 nil "#"))
6152 ;; make-temp-file creates the file,
6153 ;; but we don't want it to exist until we do an auto-save.
6154 (condition-case ()
6155 (delete-file file-name)
6156 (file-error nil))
6157 file-name)))
6159 (defun auto-save-file-name-p (filename)
6160 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
6161 FILENAME should lack slashes. You can redefine this for customization."
6162 (string-match "\\`#.*#\\'" filename))
6164 (defun wildcard-to-regexp (wildcard)
6165 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
6166 The generated regexp will match a filename only if the filename
6167 matches that wildcard according to shell rules. Only wildcards known
6168 by `sh' are supported."
6169 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
6170 ;; Copy the initial run of non-special characters.
6171 (result (substring wildcard 0 i))
6172 (len (length wildcard)))
6173 ;; If no special characters, we're almost done.
6174 (if i
6175 (while (< i len)
6176 (let ((ch (aref wildcard i))
6178 (setq
6179 result
6180 (concat result
6181 (cond
6182 ((and (eq ch ?\[)
6183 (< (1+ i) len)
6184 (eq (aref wildcard (1+ i)) ?\]))
6185 "\\[")
6186 ((eq ch ?\[) ; [...] maps to regexp char class
6187 (progn
6188 (setq i (1+ i))
6189 (concat
6190 (cond
6191 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
6192 (progn
6193 (setq i (1+ i))
6194 (if (eq (aref wildcard i) ?\])
6195 (progn
6196 (setq i (1+ i))
6197 "[^]")
6198 "[^")))
6199 ((eq (aref wildcard i) ?^)
6200 ;; Found "[^". Insert a `\0' character
6201 ;; (which cannot happen in a filename)
6202 ;; into the character class, so that `^'
6203 ;; is not the first character after `[',
6204 ;; and thus non-special in a regexp.
6205 (progn
6206 (setq i (1+ i))
6207 "[\000^"))
6208 ((eq (aref wildcard i) ?\])
6209 ;; I don't think `]' can appear in a
6210 ;; character class in a wildcard, but
6211 ;; let's be general here.
6212 (progn
6213 (setq i (1+ i))
6214 "[]"))
6215 (t "["))
6216 (prog1 ; copy everything upto next `]'.
6217 (substring wildcard
6219 (setq j (string-match
6220 "]" wildcard i)))
6221 (setq i (if j (1- j) (1- len)))))))
6222 ((eq ch ?.) "\\.")
6223 ((eq ch ?*) "[^\000]*")
6224 ((eq ch ?+) "\\+")
6225 ((eq ch ?^) "\\^")
6226 ((eq ch ?$) "\\$")
6227 ((eq ch ?\\) "\\\\") ; probably cannot happen...
6228 ((eq ch ??) "[^\000]")
6229 (t (char-to-string ch)))))
6230 (setq i (1+ i)))))
6231 ;; Shell wildcards should match the entire filename,
6232 ;; not its part. Make the regexp say so.
6233 (concat "\\`" result "\\'")))
6235 (defcustom list-directory-brief-switches
6236 (purecopy "-CF")
6237 "Switches for `list-directory' to pass to `ls' for brief listing."
6238 :type 'string
6239 :group 'dired)
6241 (defcustom list-directory-verbose-switches
6242 (purecopy "-l")
6243 "Switches for `list-directory' to pass to `ls' for verbose listing."
6244 :type 'string
6245 :group 'dired)
6247 (defun file-expand-wildcards (pattern &optional full)
6248 "Expand wildcard pattern PATTERN.
6249 This returns a list of file names which match the pattern.
6250 Files are sorted in `string<' order.
6252 If PATTERN is written as an absolute file name,
6253 the values are absolute also.
6255 If PATTERN is written as a relative file name, it is interpreted
6256 relative to the current default directory, `default-directory'.
6257 The file names returned are normally also relative to the current
6258 default directory. However, if FULL is non-nil, they are absolute."
6259 (save-match-data
6260 (let* ((nondir (file-name-nondirectory pattern))
6261 (dirpart (file-name-directory pattern))
6262 ;; A list of all dirs that DIRPART specifies.
6263 ;; This can be more than one dir
6264 ;; if DIRPART contains wildcards.
6265 (dirs (if (and dirpart
6266 (string-match "[[*?]" (file-local-name dirpart)))
6267 (mapcar 'file-name-as-directory
6268 (file-expand-wildcards (directory-file-name dirpart)))
6269 (list dirpart)))
6270 contents)
6271 (dolist (dir dirs)
6272 (when (or (null dir) ; Possible if DIRPART is not wild.
6273 (file-accessible-directory-p dir))
6274 (let ((this-dir-contents
6275 ;; Filter out "." and ".."
6276 (delq nil
6277 (mapcar #'(lambda (name)
6278 (unless (string-match "\\`\\.\\.?\\'"
6279 (file-name-nondirectory name))
6280 name))
6281 (directory-files (or dir ".") full
6282 (wildcard-to-regexp nondir))))))
6283 (setq contents
6284 (nconc
6285 (if (and dir (not full))
6286 (mapcar #'(lambda (name) (concat dir name))
6287 this-dir-contents)
6288 this-dir-contents)
6289 contents)))))
6290 contents)))
6292 ;; Let Tramp know that `file-expand-wildcards' does not need an advice.
6293 (provide 'files '(remote-wildcards))
6295 (defun list-directory (dirname &optional verbose)
6296 "Display a list of files in or matching DIRNAME, a la `ls'.
6297 DIRNAME is globbed by the shell if necessary.
6298 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
6299 Actions controlled by variables `list-directory-brief-switches'
6300 and `list-directory-verbose-switches'."
6301 (interactive (let ((pfx current-prefix-arg))
6302 (list (read-directory-name (if pfx "List directory (verbose): "
6303 "List directory (brief): ")
6304 nil default-directory nil)
6305 pfx)))
6306 (let ((switches (if verbose list-directory-verbose-switches
6307 list-directory-brief-switches))
6308 buffer)
6309 (or dirname (setq dirname default-directory))
6310 (setq dirname (expand-file-name dirname))
6311 (with-output-to-temp-buffer "*Directory*"
6312 (setq buffer standard-output)
6313 (buffer-disable-undo standard-output)
6314 (princ "Directory ")
6315 (princ dirname)
6316 (terpri)
6317 (with-current-buffer "*Directory*"
6318 (let ((wildcard (not (file-directory-p dirname))))
6319 (insert-directory dirname switches wildcard (not wildcard)))))
6320 ;; Finishing with-output-to-temp-buffer seems to clobber default-directory.
6321 (with-current-buffer buffer
6322 (setq default-directory
6323 (if (file-directory-p dirname)
6324 (file-name-as-directory dirname)
6325 (file-name-directory dirname))))))
6327 (defun shell-quote-wildcard-pattern (pattern)
6328 "Quote characters special to the shell in PATTERN, leave wildcards alone.
6330 PATTERN is assumed to represent a file-name wildcard suitable for the
6331 underlying filesystem. For Unix and GNU/Linux, each character from the
6332 set [ \\t\\n;<>&|()\\=`\\='\"#$] is quoted with a backslash; for DOS/Windows, all
6333 the parts of the pattern which don't include wildcard characters are
6334 quoted with double quotes.
6336 This function leaves alone existing quote characters (\\ on Unix and \"
6337 on Windows), so PATTERN can use them to quote wildcard characters that
6338 need to be passed verbatim to shell commands."
6339 (save-match-data
6340 (cond
6341 ((memq system-type '(ms-dos windows-nt cygwin))
6342 ;; DOS/Windows don't allow `"' in file names. So if the
6343 ;; argument has quotes, we can safely assume it is already
6344 ;; quoted by the caller.
6345 (if (or (string-match "[\"]" pattern)
6346 ;; We quote [&()#$`'] in case their shell is a port of a
6347 ;; Unixy shell. We quote [,=+] because stock DOS and
6348 ;; Windows shells require that in some cases, such as
6349 ;; passing arguments to batch files that use positional
6350 ;; arguments like %1.
6351 (not (string-match "[ \t;&()#$`',=+]" pattern)))
6352 pattern
6353 (let ((result "\"")
6354 (beg 0)
6355 end)
6356 (while (string-match "[*?]+" pattern beg)
6357 (setq end (match-beginning 0)
6358 result (concat result (substring pattern beg end)
6359 "\""
6360 (substring pattern end (match-end 0))
6361 "\"")
6362 beg (match-end 0)))
6363 (concat result (substring pattern beg) "\""))))
6365 (let ((beg 0))
6366 (while (string-match "[ \t\n;<>&|()`'\"#$]" pattern beg)
6367 (setq pattern
6368 (concat (substring pattern 0 (match-beginning 0))
6369 "\\"
6370 (substring pattern (match-beginning 0)))
6371 beg (1+ (match-end 0)))))
6372 pattern))))
6375 (defvar insert-directory-program (purecopy "ls")
6376 "Absolute or relative name of the `ls' program used by `insert-directory'.")
6378 (defcustom directory-free-space-program (purecopy "df")
6379 "Program to get the amount of free space on a file system.
6380 We assume the output has the format of `df'.
6381 The value of this variable must be just a command name or file name;
6382 if you want to specify options, use `directory-free-space-args'.
6384 A value of nil disables this feature.
6386 If the function `file-system-info' is defined, it is always used in
6387 preference to the program given by this variable."
6388 :type '(choice (string :tag "Program") (const :tag "None" nil))
6389 :group 'dired)
6391 (defcustom directory-free-space-args
6392 (purecopy (if (eq system-type 'darwin) "-k" "-Pk"))
6393 "Options to use when running `directory-free-space-program'."
6394 :type 'string
6395 :group 'dired)
6397 (defun get-free-disk-space (dir)
6398 "Return the amount of free space on directory DIR's file system.
6399 The return value is a string describing the amount of free
6400 space (normally, the number of free 1KB blocks).
6402 This function calls `file-system-info' if it is available, or
6403 invokes the program specified by `directory-free-space-program'
6404 and `directory-free-space-args'. If the system call or program
6405 is unsuccessful, or if DIR is a remote directory, this function
6406 returns nil."
6407 (unless (file-remote-p (expand-file-name dir))
6408 ;; Try to find the number of free blocks. Non-Posix systems don't
6409 ;; always have df, but might have an equivalent system call.
6410 (if (fboundp 'file-system-info)
6411 (let ((fsinfo (file-system-info dir)))
6412 (if fsinfo
6413 (format "%.0f" (/ (nth 2 fsinfo) 1024))))
6414 (setq dir (expand-file-name dir))
6415 (save-match-data
6416 (with-temp-buffer
6417 (when (and directory-free-space-program
6418 ;; Avoid failure if the default directory does
6419 ;; not exist (Bug#2631, Bug#3911).
6420 (let ((default-directory
6421 (locate-dominating-file dir 'file-directory-p)))
6422 (eq (process-file directory-free-space-program
6423 nil t nil
6424 directory-free-space-args
6425 (file-relative-name dir))
6426 0)))
6427 ;; Assume that the "available" column is before the
6428 ;; "capacity" column. Find the "%" and scan backward.
6429 (goto-char (point-min))
6430 (forward-line 1)
6431 (when (re-search-forward
6432 "[[:space:]]+[^[:space:]]+%[^%]*$"
6433 (line-end-position) t)
6434 (goto-char (match-beginning 0))
6435 (let ((endpt (point)))
6436 (skip-chars-backward "^[:space:]")
6437 (buffer-substring-no-properties (point) endpt)))))))))
6439 ;; The following expression replaces `dired-move-to-filename-regexp'.
6440 (defvar directory-listing-before-filename-regexp
6441 (let* ((l "\\([A-Za-z]\\|[^\0-\177]\\)")
6442 (l-or-quote "\\([A-Za-z']\\|[^\0-\177]\\)")
6443 ;; In some locales, month abbreviations are as short as 2 letters,
6444 ;; and they can be followed by ".".
6445 ;; In Breton, a month name can include a quote character.
6446 (month (concat l-or-quote l-or-quote "+\\.?"))
6447 (s " ")
6448 (yyyy "[0-9][0-9][0-9][0-9]")
6449 (dd "[ 0-3][0-9]")
6450 (HH:MM "[ 0-2][0-9][:.][0-5][0-9]")
6451 (seconds "[0-6][0-9]\\([.,][0-9]+\\)?")
6452 (zone "[-+][0-2][0-9][0-5][0-9]")
6453 (iso-mm-dd "[01][0-9]-[0-3][0-9]")
6454 (iso-time (concat HH:MM "\\(:" seconds "\\( ?" zone "\\)?\\)?"))
6455 (iso (concat "\\(\\(" yyyy "-\\)?" iso-mm-dd "[ T]" iso-time
6456 "\\|" yyyy "-" iso-mm-dd "\\)"))
6457 (western (concat "\\(" month s "+" dd "\\|" dd "\\.?" s month "\\)"
6458 s "+"
6459 "\\(" HH:MM "\\|" yyyy "\\)"))
6460 (western-comma (concat month s "+" dd "," s "+" yyyy))
6461 ;; Japanese MS-Windows ls-lisp has one-digit months, and
6462 ;; omits the Kanji characters after month and day-of-month.
6463 ;; On Mac OS X 10.3, the date format in East Asian locales is
6464 ;; day-of-month digits followed by month digits.
6465 (mm "[ 0-1]?[0-9]")
6466 (east-asian
6467 (concat "\\(" mm l "?" s dd l "?" s "+"
6468 "\\|" dd s mm s "+" "\\)"
6469 "\\(" HH:MM "\\|" yyyy l "?" "\\)")))
6470 ;; The "[0-9]" below requires the previous column to end in a digit.
6471 ;; This avoids recognizing `1 may 1997' as a date in the line:
6472 ;; -r--r--r-- 1 may 1997 1168 Oct 19 16:49 README
6474 ;; The "[BkKMGTPEZY]?" below supports "ls -alh" output.
6476 ;; For non-iso date formats, we add the ".*" in order to find
6477 ;; the last possible match. This avoids recognizing
6478 ;; `jservice 10 1024' as a date in the line:
6479 ;; drwxr-xr-x 3 jservice 10 1024 Jul 2 1997 esg-host
6481 ;; vc dired listings provide the state or blanks between file
6482 ;; permissions and date. The state is always surrounded by
6483 ;; parentheses:
6484 ;; -rw-r--r-- (modified) 2005-10-22 21:25 files.el
6485 ;; This is not supported yet.
6486 (purecopy (concat "\\([0-9][BkKMGTPEZY]? " iso
6487 "\\|.*[0-9][BkKMGTPEZY]? "
6488 "\\(" western "\\|" western-comma "\\|" east-asian "\\)"
6489 "\\) +")))
6490 "Regular expression to match up to the file name in a directory listing.
6491 The default value is designed to recognize dates and times
6492 regardless of the language.")
6494 (defvar insert-directory-ls-version 'unknown)
6496 ;; insert-directory
6497 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
6498 ;; FULL-DIRECTORY-P is nil.
6499 ;; The single line of output must display FILE's name as it was
6500 ;; given, namely, an absolute path name.
6501 ;; - must insert exactly one line for each file if WILDCARD or
6502 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
6503 ;; before the file lines, plus optional text after the file lines.
6504 ;; Lines are delimited by "\n", so filenames containing "\n" are not
6505 ;; allowed.
6506 ;; File lines should display the basename.
6507 ;; - must be consistent with
6508 ;; - functions dired-move-to-filename, (these two define what a file line is)
6509 ;; dired-move-to-end-of-filename,
6510 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
6511 ;; dired-insert-headerline
6512 ;; dired-after-subdir-garbage (defines what a "total" line is)
6513 ;; - variable dired-subdir-regexp
6514 ;; - may be passed "--dired" as the first argument in SWITCHES.
6515 ;; Filename handlers might have to remove this switch if their
6516 ;; "ls" command does not support it.
6517 (defun insert-directory (file switches &optional wildcard full-directory-p)
6518 "Insert directory listing for FILE, formatted according to SWITCHES.
6519 Leaves point after the inserted text.
6520 SWITCHES may be a string of options, or a list of strings
6521 representing individual options.
6522 Optional third arg WILDCARD means treat FILE as shell wildcard.
6523 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
6524 switches do not contain `d', so that a full listing is expected.
6526 This works by running a directory listing program
6527 whose name is in the variable `insert-directory-program'.
6528 If WILDCARD, it also runs the shell specified by `shell-file-name'.
6530 When SWITCHES contains the long `--dired' option, this function
6531 treats it specially, for the sake of dired. However, the
6532 normally equivalent short `-D' option is just passed on to
6533 `insert-directory-program', as any other option."
6534 ;; We need the directory in order to find the right handler.
6535 (let ((handler (find-file-name-handler (expand-file-name file)
6536 'insert-directory)))
6537 (if handler
6538 (funcall handler 'insert-directory file switches
6539 wildcard full-directory-p)
6540 (let (result (beg (point)))
6542 ;; Read the actual directory using `insert-directory-program'.
6543 ;; RESULT gets the status code.
6544 (let* (;; We at first read by no-conversion, then after
6545 ;; putting text property `dired-filename, decode one
6546 ;; bunch by one to preserve that property.
6547 (coding-system-for-read 'no-conversion)
6548 ;; This is to control encoding the arguments in call-process.
6549 (coding-system-for-write
6550 (and enable-multibyte-characters
6551 (or file-name-coding-system
6552 default-file-name-coding-system))))
6553 (setq result
6554 (if wildcard
6555 ;; Run ls in the directory part of the file pattern
6556 ;; using the last component as argument.
6557 (let ((default-directory
6558 (if (file-name-absolute-p file)
6559 (file-name-directory file)
6560 (file-name-directory (expand-file-name file))))
6561 (pattern (file-name-nondirectory file)))
6562 ;; NB since switches is passed to the shell, be
6563 ;; careful of malicious values, eg "-l;reboot".
6564 ;; See eg dired-safe-switches-p.
6565 (call-process
6566 shell-file-name nil t nil
6567 "-c"
6568 (concat (if (memq system-type '(ms-dos windows-nt))
6570 "\\") ; Disregard Unix shell aliases!
6571 insert-directory-program
6572 " -d "
6573 (if (stringp switches)
6574 switches
6575 (mapconcat 'identity switches " "))
6576 " -- "
6577 ;; Quote some characters that have
6578 ;; special meanings in shells; but
6579 ;; don't quote the wildcards--we want
6580 ;; them to be special. We also
6581 ;; currently don't quote the quoting
6582 ;; characters in case people want to
6583 ;; use them explicitly to quote
6584 ;; wildcard characters.
6585 (shell-quote-wildcard-pattern pattern))))
6586 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
6587 ;; directory if FILE is a symbolic link.
6588 (unless full-directory-p
6589 (setq switches
6590 (cond
6591 ((stringp switches) (concat switches " -d"))
6592 ((member "-d" switches) switches)
6593 (t (append switches '("-d"))))))
6594 (apply 'call-process
6595 insert-directory-program nil t nil
6596 (append
6597 (if (listp switches) switches
6598 (unless (equal switches "")
6599 ;; Split the switches at any spaces so we can
6600 ;; pass separate options as separate args.
6601 (split-string-and-unquote switches)))
6602 ;; Avoid lossage if FILE starts with `-'.
6603 '("--")
6604 (progn
6605 (if (string-match "\\`~" file)
6606 (setq file (expand-file-name file)))
6607 (list
6608 (if full-directory-p
6609 (concat (file-name-as-directory file) ".")
6610 file))))))))
6612 ;; If we got "//DIRED//" in the output, it means we got a real
6613 ;; directory listing, even if `ls' returned nonzero.
6614 ;; So ignore any errors.
6615 (when (if (stringp switches)
6616 (string-match "--dired\\>" switches)
6617 (member "--dired" switches))
6618 (save-excursion
6619 (forward-line -2)
6620 (when (looking-at "//SUBDIRED//")
6621 (forward-line -1))
6622 (if (looking-at "//DIRED//")
6623 (setq result 0))))
6625 (when (and (not (eq 0 result))
6626 (eq insert-directory-ls-version 'unknown))
6627 ;; The first time ls returns an error,
6628 ;; find the version numbers of ls,
6629 ;; and set insert-directory-ls-version
6630 ;; to > if it is more than 5.2.1, < if it is less, nil if it
6631 ;; is equal or if the info cannot be obtained.
6632 ;; (That can mean it isn't GNU ls.)
6633 (let ((version-out
6634 (with-temp-buffer
6635 (call-process "ls" nil t nil "--version")
6636 (buffer-string))))
6637 (if (string-match "ls (.*utils) \\([0-9.]*\\)$" version-out)
6638 (let* ((version (match-string 1 version-out))
6639 (split (split-string version "[.]"))
6640 (numbers (mapcar 'string-to-number split))
6641 (min '(5 2 1))
6642 comparison)
6643 (while (and (not comparison) (or numbers min))
6644 (cond ((null min)
6645 (setq comparison '>))
6646 ((null numbers)
6647 (setq comparison '<))
6648 ((> (car numbers) (car min))
6649 (setq comparison '>))
6650 ((< (car numbers) (car min))
6651 (setq comparison '<))
6653 (setq numbers (cdr numbers)
6654 min (cdr min)))))
6655 (setq insert-directory-ls-version (or comparison '=)))
6656 (setq insert-directory-ls-version nil))))
6658 ;; For GNU ls versions 5.2.2 and up, ignore minor errors.
6659 (when (and (eq 1 result) (eq insert-directory-ls-version '>))
6660 (setq result 0))
6662 ;; If `insert-directory-program' failed, signal an error.
6663 (unless (eq 0 result)
6664 ;; Delete the error message it may have output.
6665 (delete-region beg (point))
6666 ;; On non-Posix systems, we cannot open a directory, so
6667 ;; don't even try, because that will always result in
6668 ;; the ubiquitous "Access denied". Instead, show the
6669 ;; command line so the user can try to guess what went wrong.
6670 (if (and (file-directory-p file)
6671 (memq system-type '(ms-dos windows-nt)))
6672 (error
6673 "Reading directory: \"%s %s -- %s\" exited with status %s"
6674 insert-directory-program
6675 (if (listp switches) (concat switches) switches)
6676 file result)
6677 ;; Unix. Access the file to get a suitable error.
6678 (access-file file "Reading directory")
6679 (error "Listing directory failed but `access-file' worked")))
6681 (when (if (stringp switches)
6682 (string-match "--dired\\>" switches)
6683 (member "--dired" switches))
6684 ;; The following overshoots by one line for an empty
6685 ;; directory listed with "--dired", but without "-a"
6686 ;; switch, where the ls output contains a
6687 ;; "//DIRED-OPTIONS//" line, but no "//DIRED//" line.
6688 ;; We take care of that case later.
6689 (forward-line -2)
6690 (when (looking-at "//SUBDIRED//")
6691 (delete-region (point) (progn (forward-line 1) (point)))
6692 (forward-line -1))
6693 (if (looking-at "//DIRED//")
6694 (let ((end (line-end-position))
6695 (linebeg (point))
6696 error-lines)
6697 ;; Find all the lines that are error messages,
6698 ;; and record the bounds of each one.
6699 (goto-char beg)
6700 (while (< (point) linebeg)
6701 (or (eql (following-char) ?\s)
6702 (push (list (point) (line-end-position)) error-lines))
6703 (forward-line 1))
6704 (setq error-lines (nreverse error-lines))
6705 ;; Now read the numeric positions of file names.
6706 (goto-char linebeg)
6707 (forward-word-strictly 1)
6708 (forward-char 3)
6709 (while (< (point) end)
6710 (let ((start (insert-directory-adj-pos
6711 (+ beg (read (current-buffer)))
6712 error-lines))
6713 (end (insert-directory-adj-pos
6714 (+ beg (read (current-buffer)))
6715 error-lines)))
6716 (if (memq (char-after end) '(?\n ?\s))
6717 ;; End is followed by \n or by " -> ".
6718 (put-text-property start end 'dired-filename t)
6719 ;; It seems that we can't trust ls's output as to
6720 ;; byte positions of filenames.
6721 (put-text-property beg (point) 'dired-filename nil)
6722 (end-of-line))))
6723 (goto-char end)
6724 (beginning-of-line)
6725 (delete-region (point) (progn (forward-line 1) (point))))
6726 ;; Take care of the case where the ls output contains a
6727 ;; "//DIRED-OPTIONS//"-line, but no "//DIRED//"-line
6728 ;; and we went one line too far back (see above).
6729 (forward-line 1))
6730 (if (looking-at "//DIRED-OPTIONS//")
6731 (delete-region (point) (progn (forward-line 1) (point)))))
6733 ;; Now decode what read if necessary.
6734 (let ((coding (or coding-system-for-read
6735 file-name-coding-system
6736 default-file-name-coding-system
6737 'undecided))
6738 coding-no-eol
6739 val pos)
6740 (when (and enable-multibyte-characters
6741 (not (memq (coding-system-base coding)
6742 '(raw-text no-conversion))))
6743 ;; If no coding system is specified or detection is
6744 ;; requested, detect the coding.
6745 (if (eq (coding-system-base coding) 'undecided)
6746 (setq coding (detect-coding-region beg (point) t)))
6747 (if (not (eq (coding-system-base coding) 'undecided))
6748 (save-restriction
6749 (setq coding-no-eol
6750 (coding-system-change-eol-conversion coding 'unix))
6751 (narrow-to-region beg (point))
6752 (goto-char (point-min))
6753 (while (not (eobp))
6754 (setq pos (point)
6755 val (get-text-property (point) 'dired-filename))
6756 (goto-char (next-single-property-change
6757 (point) 'dired-filename nil (point-max)))
6758 ;; Force no eol conversion on a file name, so
6759 ;; that CR is preserved.
6760 (decode-coding-region pos (point)
6761 (if val coding-no-eol coding))
6762 (if val
6763 (put-text-property pos (point)
6764 'dired-filename t)))))))
6766 (if full-directory-p
6767 ;; Try to insert the amount of free space.
6768 (save-excursion
6769 (goto-char beg)
6770 ;; First find the line to put it on.
6771 (when (re-search-forward "^ *\\(total\\)" nil t)
6772 (let ((available (get-free-disk-space ".")))
6773 (when available
6774 ;; Replace "total" with "used", to avoid confusion.
6775 (replace-match "total used in directory" nil nil nil 1)
6776 (end-of-line)
6777 (insert " available " available))))))))))
6779 (defun insert-directory-adj-pos (pos error-lines)
6780 "Convert `ls --dired' file name position value POS to a buffer position.
6781 File name position values returned in ls --dired output
6782 count only stdout; they don't count the error messages sent to stderr.
6783 So this function converts to them to real buffer positions.
6784 ERROR-LINES is a list of buffer positions of error message lines,
6785 of the form (START END)."
6786 (while (and error-lines (< (caar error-lines) pos))
6787 (setq pos (+ pos (- (nth 1 (car error-lines)) (nth 0 (car error-lines)))))
6788 (pop error-lines))
6789 pos)
6791 (defun insert-directory-safely (file switches
6792 &optional wildcard full-directory-p)
6793 "Insert directory listing for FILE, formatted according to SWITCHES.
6795 Like `insert-directory', but if FILE does not exist, it inserts a
6796 message to that effect instead of signaling an error."
6797 (if (file-exists-p file)
6798 (insert-directory file switches wildcard full-directory-p)
6799 ;; Simulate the message printed by `ls'.
6800 (insert (format "%s: No such file or directory\n" file))))
6802 (defcustom kill-emacs-query-functions nil
6803 "Functions to call with no arguments to query about killing Emacs.
6804 If any of these functions returns nil, killing Emacs is canceled.
6805 `save-buffers-kill-emacs' calls these functions, but `kill-emacs',
6806 the low level primitive, does not. See also `kill-emacs-hook'."
6807 :type 'hook
6808 :version "26.1"
6809 :group 'convenience)
6811 (defcustom confirm-kill-emacs nil
6812 "How to ask for confirmation when leaving Emacs.
6813 If nil, the default, don't ask at all. If the value is non-nil, it should
6814 be a predicate function; for example `yes-or-no-p'."
6815 :type '(choice (const :tag "Ask with yes-or-no-p" yes-or-no-p)
6816 (const :tag "Ask with y-or-n-p" y-or-n-p)
6817 (const :tag "Don't confirm" nil)
6818 (function :tag "Predicate function"))
6819 :group 'convenience
6820 :version "21.1")
6822 (defcustom confirm-kill-processes t
6823 "Non-nil if Emacs should confirm killing processes on exit.
6824 If this variable is nil, the value of
6825 `process-query-on-exit-flag' is ignored. Otherwise, if there are
6826 processes with a non-nil `process-query-on-exit-flag', Emacs will
6827 prompt the user before killing them."
6828 :type 'boolean
6829 :group 'convenience
6830 :version "26.1")
6832 (defun save-buffers-kill-emacs (&optional arg)
6833 "Offer to save each buffer, then kill this Emacs process.
6834 With prefix ARG, silently save all file-visiting buffers without asking.
6835 If there are active processes where `process-query-on-exit-flag'
6836 returns non-nil and `confirm-kill-processes' is non-nil,
6837 asks whether processes should be killed.
6838 Runs the members of `kill-emacs-query-functions' in turn and stops
6839 if any returns nil. If `confirm-kill-emacs' is non-nil, calls it."
6840 (interactive "P")
6841 ;; Don't use save-some-buffers-default-predicate, because we want
6842 ;; to ask about all the buffers before killing Emacs.
6843 (save-some-buffers arg t)
6844 (let ((confirm confirm-kill-emacs))
6845 (and
6846 (or (not (memq t (mapcar (function
6847 (lambda (buf) (and (buffer-file-name buf)
6848 (buffer-modified-p buf))))
6849 (buffer-list))))
6850 (progn (setq confirm nil)
6851 (yes-or-no-p "Modified buffers exist; exit anyway? ")))
6852 (or (not (fboundp 'process-list))
6853 ;; process-list is not defined on MSDOS.
6854 (not confirm-kill-processes)
6855 (let ((processes (process-list))
6856 active)
6857 (while processes
6858 (and (memq (process-status (car processes)) '(run stop open listen))
6859 (process-query-on-exit-flag (car processes))
6860 (setq active t))
6861 (setq processes (cdr processes)))
6862 (or (not active)
6863 (with-current-buffer-window
6864 (get-buffer-create "*Process List*") nil
6865 #'(lambda (window _value)
6866 (with-selected-window window
6867 (unwind-protect
6868 (progn
6869 (setq confirm nil)
6870 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))
6871 (when (window-live-p window)
6872 (quit-restore-window window 'kill)))))
6873 (list-processes t)))))
6874 ;; Query the user for other things, perhaps.
6875 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
6876 (or (null confirm)
6877 (funcall confirm "Really exit Emacs? "))
6878 (kill-emacs))))
6880 (defun save-buffers-kill-terminal (&optional arg)
6881 "Offer to save each buffer, then kill the current connection.
6882 If the current frame has no client, kill Emacs itself using
6883 `save-buffers-kill-emacs'.
6885 With prefix ARG, silently save all file-visiting buffers, then kill.
6887 If emacsclient was started with a list of filenames to edit, then
6888 only these files will be asked to be saved."
6889 (interactive "P")
6890 (if (frame-parameter nil 'client)
6891 (server-save-buffers-kill-terminal arg)
6892 (save-buffers-kill-emacs arg)))
6894 ;; We use /: as a prefix to "quote" a file name
6895 ;; so that magic file name handlers will not apply to it.
6897 (setq file-name-handler-alist
6898 (cons (cons (purecopy "\\`/:") 'file-name-non-special)
6899 file-name-handler-alist))
6901 ;; We depend on being the last handler on the list,
6902 ;; so that anything else which does need handling
6903 ;; has been handled already.
6904 ;; So it is safe for us to inhibit *all* magic file name handlers.
6906 (defun file-name-non-special (operation &rest arguments)
6907 (let ((file-name-handler-alist nil)
6908 (default-directory
6909 (if (eq operation 'insert-directory)
6910 (directory-file-name
6911 (expand-file-name
6912 (unhandled-file-name-directory default-directory)))
6913 default-directory))
6914 ;; Get a list of the indices of the args which are file names.
6915 (file-arg-indices
6916 (cdr (or (assq operation
6917 ;; The first six are special because they
6918 ;; return a file name. We want to include the /:
6919 ;; in the return value.
6920 ;; So just avoid stripping it in the first place.
6921 '((expand-file-name . nil)
6922 (file-name-directory . nil)
6923 (file-name-as-directory . nil)
6924 (directory-file-name . nil)
6925 (file-name-sans-versions . nil)
6926 (find-backup-file-name . nil)
6927 ;; `identity' means just return the first arg
6928 ;; not stripped of its quoting.
6929 (substitute-in-file-name identity)
6930 ;; `add' means add "/:" to the result.
6931 (file-truename add 0)
6932 (insert-file-contents insert-file-contents 0)
6933 ;; `unquote-then-quote' means set buffer-file-name
6934 ;; temporarily to unquoted filename.
6935 (verify-visited-file-modtime unquote-then-quote)
6936 ;; List the arguments which are filenames.
6937 (file-name-completion 1)
6938 (file-name-all-completions 1)
6939 (write-region 2 5)
6940 (rename-file 0 1)
6941 (copy-file 0 1)
6942 (make-symbolic-link 0 1)
6943 (add-name-to-file 0 1)))
6944 ;; For all other operations, treat the first argument only
6945 ;; as the file name.
6946 '(nil 0))))
6947 method
6948 ;; Copy ARGUMENTS so we can replace elements in it.
6949 (arguments (copy-sequence arguments)))
6950 (if (symbolp (car file-arg-indices))
6951 (setq method (pop file-arg-indices)))
6952 ;; Strip off the /: from the file names that have it.
6953 (save-match-data
6954 (while (consp file-arg-indices)
6955 (let ((pair (nthcdr (car file-arg-indices) arguments)))
6956 (and (car pair)
6957 (string-match "\\`/:" (car pair))
6958 (setcar pair
6959 (if (= (length (car pair)) 2)
6961 (substring (car pair) 2)))))
6962 (setq file-arg-indices (cdr file-arg-indices))))
6963 (pcase method
6964 (`identity (car arguments))
6965 (`add (concat "/:" (apply operation arguments)))
6966 (`insert-file-contents
6967 (let ((visit (nth 1 arguments)))
6968 (unwind-protect
6969 (apply operation arguments)
6970 (when (and visit buffer-file-name)
6971 (setq buffer-file-name (concat "/:" buffer-file-name))))))
6972 (`unquote-then-quote
6973 (let ((buffer-file-name (substring buffer-file-name 2)))
6974 (apply operation arguments)))
6976 (apply operation arguments)))))
6978 (defsubst file-name-quoted-p (name)
6979 "Whether NAME is quoted with prefix \"/:\".
6980 If NAME is a remote file name, check the local part of NAME."
6981 (string-prefix-p "/:" (file-local-name name)))
6983 (defsubst file-name-quote (name)
6984 "Add the quotation prefix \"/:\" to file NAME.
6985 If NAME is a remote file name, the local part of NAME is quoted.
6986 If NAME is already a quoted file name, NAME is returned unchanged."
6987 (if (file-name-quoted-p name)
6988 name
6989 (concat (file-remote-p name) "/:" (file-local-name name))))
6991 (defsubst file-name-unquote (name)
6992 "Remove quotation prefix \"/:\" from file NAME, if any.
6993 If NAME is a remote file name, the local part of NAME is unquoted."
6994 (let ((localname (file-local-name name)))
6995 (when (file-name-quoted-p localname)
6996 (setq
6997 localname (if (= (length localname) 2) "/" (substring localname 2))))
6998 (concat (file-remote-p name) localname)))
7000 ;; Symbolic modes and read-file-modes.
7002 (defun file-modes-char-to-who (char)
7003 "Convert CHAR to a numeric bit-mask for extracting mode bits.
7004 CHAR is in [ugoa] and represents the category of users (Owner, Group,
7005 Others, or All) for whom to produce the mask.
7006 The bit-mask that is returned extracts from mode bits the access rights
7007 for the specified category of users."
7008 (cond ((= char ?u) #o4700)
7009 ((= char ?g) #o2070)
7010 ((= char ?o) #o1007)
7011 ((= char ?a) #o7777)
7012 (t (error "%c: bad `who' character" char))))
7014 (defun file-modes-char-to-right (char &optional from)
7015 "Convert CHAR to a numeric value of mode bits.
7016 CHAR is in [rwxXstugo] and represents symbolic access permissions.
7017 If CHAR is in [Xugo], the value is taken from FROM (or 0 if omitted)."
7018 (or from (setq from 0))
7019 (cond ((= char ?r) #o0444)
7020 ((= char ?w) #o0222)
7021 ((= char ?x) #o0111)
7022 ((= char ?s) #o6000)
7023 ((= char ?t) #o1000)
7024 ;; Rights relative to the previous file modes.
7025 ((= char ?X) (if (= (logand from #o111) 0) 0 #o0111))
7026 ((= char ?u) (let ((uright (logand #o4700 from)))
7027 (+ uright (/ uright #o10) (/ uright #o100))))
7028 ((= char ?g) (let ((gright (logand #o2070 from)))
7029 (+ gright (/ gright #o10) (* gright #o10))))
7030 ((= char ?o) (let ((oright (logand #o1007 from)))
7031 (+ oright (* oright #o10) (* oright #o100))))
7032 (t (error "%c: bad right character" char))))
7034 (defun file-modes-rights-to-number (rights who-mask &optional from)
7035 "Convert a symbolic mode string specification to an equivalent number.
7036 RIGHTS is the symbolic mode spec, it should match \"([+=-][rwxXstugo]*)+\".
7037 WHO-MASK is the bit-mask specifying the category of users to which to
7038 apply the access permissions. See `file-modes-char-to-who'.
7039 FROM (or 0 if nil) gives the mode bits on which to base permissions if
7040 RIGHTS request to add, remove, or set permissions based on existing ones,
7041 as in \"og+rX-w\"."
7042 (let* ((num-rights (or from 0))
7043 (list-rights (string-to-list rights))
7044 (op (pop list-rights)))
7045 (while (memq op '(?+ ?- ?=))
7046 (let ((num-right 0)
7047 char-right)
7048 (while (memq (setq char-right (pop list-rights))
7049 '(?r ?w ?x ?X ?s ?t ?u ?g ?o))
7050 (setq num-right
7051 (logior num-right
7052 (file-modes-char-to-right char-right num-rights))))
7053 (setq num-right (logand who-mask num-right)
7054 num-rights
7055 (cond ((= op ?+) (logior num-rights num-right))
7056 ((= op ?-) (logand num-rights (lognot num-right)))
7057 (t (logior (logand num-rights (lognot who-mask)) num-right)))
7058 op char-right)))
7059 num-rights))
7061 (defun file-modes-symbolic-to-number (modes &optional from)
7062 "Convert symbolic file modes to numeric file modes.
7063 MODES is the string to convert, it should match
7064 \"[ugoa]*([+-=][rwxXstugo]*)+,...\".
7065 See Info node `(coreutils)File permissions' for more information on this
7066 notation.
7067 FROM (or 0 if nil) gives the mode bits on which to base permissions if
7068 MODES request to add, remove, or set permissions based on existing ones,
7069 as in \"og+rX-w\"."
7070 (save-match-data
7071 (let ((case-fold-search nil)
7072 (num-modes (or from 0)))
7073 (while (/= (string-to-char modes) 0)
7074 (if (string-match "^\\([ugoa]*\\)\\([+=-][rwxXstugo]*\\)+\\(,\\|\\)" modes)
7075 (let ((num-who (apply 'logior 0
7076 (mapcar 'file-modes-char-to-who
7077 (match-string 1 modes)))))
7078 (when (= num-who 0)
7079 (setq num-who (logior #o7000 (default-file-modes))))
7080 (setq num-modes
7081 (file-modes-rights-to-number (substring modes (match-end 1))
7082 num-who num-modes)
7083 modes (substring modes (match-end 3))))
7084 (error "Parse error in modes near `%s'" (substring modes 0))))
7085 num-modes)))
7087 (defun read-file-modes (&optional prompt orig-file)
7088 "Read file modes in octal or symbolic notation and return its numeric value.
7089 PROMPT is used as the prompt, default to \"File modes (octal or symbolic): \".
7090 ORIG-FILE is the name of a file on whose mode bits to base returned
7091 permissions if what user types requests to add, remove, or set permissions
7092 based on existing mode bits, as in \"og+rX-w\"."
7093 (let* ((modes (or (if orig-file (file-modes orig-file) 0)
7094 (error "File not found")))
7095 (modestr (and (stringp orig-file)
7096 (nth 8 (file-attributes orig-file))))
7097 (default
7098 (and (stringp modestr)
7099 (string-match "^.\\(...\\)\\(...\\)\\(...\\)$" modestr)
7100 (replace-regexp-in-string
7101 "-" ""
7102 (format "u=%s,g=%s,o=%s"
7103 (match-string 1 modestr)
7104 (match-string 2 modestr)
7105 (match-string 3 modestr)))))
7106 (value (read-string (or prompt "File modes (octal or symbolic): ")
7107 nil nil default)))
7108 (save-match-data
7109 (if (string-match "^[0-7]+" value)
7110 (string-to-number value 8)
7111 (file-modes-symbolic-to-number value modes)))))
7113 (define-obsolete-variable-alias 'cache-long-line-scans
7114 'cache-long-scans "24.4")
7116 ;; Trashcan handling.
7117 (defcustom trash-directory nil
7118 "Directory for `move-file-to-trash' to move files and directories to.
7119 This directory is only used when the function `system-move-file-to-trash'
7120 is not defined.
7121 Relative paths are interpreted relative to `default-directory'.
7122 If the value is nil, Emacs uses a freedesktop.org-style trashcan."
7123 :type '(choice (const nil) directory)
7124 :group 'auto-save
7125 :version "23.2")
7127 (defvar trash--hexify-table)
7129 (declare-function system-move-file-to-trash "w32fns.c" (filename))
7131 (defun move-file-to-trash (filename)
7132 "Move the file (or directory) named FILENAME to the trash.
7133 When `delete-by-moving-to-trash' is non-nil, this function is
7134 called by `delete-file' and `delete-directory' instead of
7135 deleting files outright.
7137 If the function `system-move-file-to-trash' is defined, call it
7138 with FILENAME as an argument.
7139 Otherwise, if `trash-directory' is non-nil, move FILENAME to that
7140 directory.
7141 Otherwise, trash FILENAME using the freedesktop.org conventions,
7142 like the GNOME, KDE and XFCE desktop environments. Emacs only
7143 moves files to \"home trash\", ignoring per-volume trashcans."
7144 (interactive "fMove file to trash: ")
7145 (cond (trash-directory
7146 ;; If `trash-directory' is non-nil, move the file there.
7147 (let* ((trash-dir (expand-file-name trash-directory))
7148 (fn (directory-file-name (expand-file-name filename)))
7149 (new-fn (expand-file-name (file-name-nondirectory fn)
7150 trash-dir)))
7151 ;; We can't trash a parent directory of trash-directory.
7152 (if (string-prefix-p fn trash-dir)
7153 (error "Trash directory `%s' is a subdirectory of `%s'"
7154 trash-dir filename))
7155 (unless (file-directory-p trash-dir)
7156 (make-directory trash-dir t))
7157 ;; Ensure that the trashed file-name is unique.
7158 (if (file-exists-p new-fn)
7159 (let ((version-control t)
7160 (backup-directory-alist nil))
7161 (setq new-fn (car (find-backup-file-name new-fn)))))
7162 (let (delete-by-moving-to-trash)
7163 (rename-file fn new-fn))))
7164 ;; If `system-move-file-to-trash' is defined, use it.
7165 ((fboundp 'system-move-file-to-trash)
7166 (system-move-file-to-trash filename))
7167 ;; Otherwise, use the freedesktop.org method, as specified at
7168 ;; http://freedesktop.org/wiki/Specifications/trash-spec
7170 (let* ((xdg-data-dir
7171 (directory-file-name
7172 (expand-file-name "Trash"
7173 (or (getenv "XDG_DATA_HOME")
7174 "~/.local/share"))))
7175 (trash-files-dir (expand-file-name "files" xdg-data-dir))
7176 (trash-info-dir (expand-file-name "info" xdg-data-dir))
7177 (fn (directory-file-name (expand-file-name filename))))
7179 ;; Check if we have permissions to delete.
7180 (unless (file-writable-p (directory-file-name
7181 (file-name-directory fn)))
7182 (error "Cannot move %s to trash: Permission denied" filename))
7183 ;; The trashed file cannot be the trash dir or its parent.
7184 (if (string-prefix-p fn trash-files-dir)
7185 (error "The trash directory %s is a subdirectory of %s"
7186 trash-files-dir filename))
7187 (if (string-prefix-p fn trash-info-dir)
7188 (error "The trash directory %s is a subdirectory of %s"
7189 trash-info-dir filename))
7191 ;; Ensure that the trash directory exists; otherwise, create it.
7192 (with-file-modes #o700
7193 (unless (file-exists-p trash-files-dir)
7194 (make-directory trash-files-dir t))
7195 (unless (file-exists-p trash-info-dir)
7196 (make-directory trash-info-dir t)))
7198 ;; Try to move to trash with .trashinfo undo information
7199 (save-excursion
7200 (with-temp-buffer
7201 (set-buffer-file-coding-system 'utf-8-unix)
7202 (insert "[Trash Info]\nPath=")
7203 ;; Perform url-encoding on FN. For compatibility with
7204 ;; other programs (e.g. XFCE Thunar), allow literal "/"
7205 ;; for path separators.
7206 (unless (boundp 'trash--hexify-table)
7207 (setq trash--hexify-table (make-vector 256 nil))
7208 (let ((unreserved-chars
7209 (list ?/ ?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m
7210 ?n ?o ?p ?q ?r ?s ?t ?u ?v ?w ?x ?y ?z ?A
7211 ?B ?C ?D ?E ?F ?G ?H ?I ?J ?K ?L ?M ?N ?O
7212 ?P ?Q ?R ?S ?T ?U ?V ?W ?X ?Y ?Z ?0 ?1 ?2
7213 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?- ?_ ?. ?! ?~ ?* ?'
7214 ?\( ?\))))
7215 (dotimes (byte 256)
7216 (aset trash--hexify-table byte
7217 (if (memq byte unreserved-chars)
7218 (char-to-string byte)
7219 (format "%%%02x" byte))))))
7220 (mapc (lambda (byte)
7221 (insert (aref trash--hexify-table byte)))
7222 (if (multibyte-string-p fn)
7223 (encode-coding-string fn 'utf-8)
7224 fn))
7225 (insert "\nDeletionDate="
7226 (format-time-string "%Y-%m-%dT%T")
7227 "\n")
7229 ;; Attempt to make .trashinfo file, trying up to 5
7230 ;; times. The .trashinfo file is opened with O_EXCL,
7231 ;; as per trash-spec 0.7, even if that can be a problem
7232 ;; on old NFS versions...
7233 (let* ((tries 5)
7234 (base-fn (expand-file-name
7235 (file-name-nondirectory fn)
7236 trash-files-dir))
7237 (new-fn base-fn)
7238 success info-fn)
7239 (while (> tries 0)
7240 (setq info-fn (expand-file-name
7241 (concat (file-name-nondirectory new-fn)
7242 ".trashinfo")
7243 trash-info-dir))
7244 (unless (condition-case nil
7245 (progn
7246 (write-region nil nil info-fn nil
7247 'quiet info-fn 'excl)
7248 (setq tries 0 success t))
7249 (file-already-exists nil))
7250 (setq tries (1- tries))
7251 ;; Uniquify new-fn. (Some file managers do not
7252 ;; like Emacs-style backup file names---e.g. bug
7253 ;; 170956 in Konqueror bug tracker.)
7254 (setq new-fn (make-temp-name (concat base-fn "_")))))
7255 (unless success
7256 (error "Cannot move %s to trash: Lock failed" filename))
7258 ;; Finally, try to move the file to the trashcan.
7259 (let ((delete-by-moving-to-trash nil))
7260 (rename-file fn new-fn)))))))))
7262 (defsubst file-attribute-type (attributes)
7263 "The type field in ATTRIBUTES returned by `file-attributes'.
7264 The value is either t for directory, string (name linked to) for
7265 symbolic link, or nil."
7266 (nth 0 attributes))
7268 (defsubst file-attribute-link-number (attributes)
7269 "Return the number of links in ATTRIBUTES returned by `file-attributes'."
7270 (nth 1 attributes))
7272 (defsubst file-attribute-user-id (attributes)
7273 "The UID field in ATTRIBUTES returned by `file-attributes'.
7274 This is either a string or a number. If a string value cannot be
7275 looked up, a numeric value, either an integer or a float, is
7276 returned."
7277 (nth 2 attributes))
7279 (defsubst file-attribute-group-id (attributes)
7280 "The GID field in ATTRIBUTES returned by `file-attributes'.
7281 This is either a string or a number. If a string value cannot be
7282 looked up, a numeric value, either an integer or a float, is
7283 returned."
7284 (nth 3 attributes))
7286 (defsubst file-attribute-access-time (attributes)
7287 "The last access time in ATTRIBUTES returned by `file-attributes'.
7288 This a list of integers (HIGH LOW USEC PSEC) in the same style
7289 as (current-time)."
7290 (nth 4 attributes))
7292 (defsubst file-attribute-modification-time (attributes)
7293 "The modification time in ATTRIBUTES returned by `file-attributes'.
7294 This is the time of the last change to the file's contents, and
7295 is a list of integers (HIGH LOW USEC PSEC) in the same style
7296 as (current-time)."
7297 (nth 5 attributes))
7299 (defsubst file-attribute-status-change-time (attributes)
7300 "The status modification time in ATTRIBUTES returned by `file-attributes'.
7301 This is the time of last change to the file's attributes: owner
7302 and group, access mode bits, etc, and is a list of integers (HIGH
7303 LOW USEC PSEC) in the same style as (current-time)."
7304 (nth 6 attributes))
7306 (defsubst file-attribute-size (attributes)
7307 "The size (in bytes) in ATTRIBUTES returned by `file-attributes'.
7308 This is a floating point number if the size is too large for an integer."
7309 (nth 7 attributes))
7311 (defsubst file-attribute-modes (attributes)
7312 "The file modes in ATTRIBUTES returned by `file-attributes'.
7313 This is a string of ten letters or dashes as in ls -l."
7314 (nth 8 attributes))
7316 (defsubst file-attribute-inode-number (attributes)
7317 "The inode number in ATTRIBUTES returned by `file-attributes'.
7318 If it is larger than what an Emacs integer can hold, this is of
7319 the form (HIGH . LOW): first the high bits, then the low 16 bits.
7320 If even HIGH is too large for an Emacs integer, this is instead
7321 of the form (HIGH MIDDLE . LOW): first the high bits, then the
7322 middle 24 bits, and finally the low 16 bits."
7323 (nth 10 attributes))
7325 (defsubst file-attribute-device-number (attributes)
7326 "The file system device number in ATTRIBUTES returned by `file-attributes'.
7327 If it is larger than what an Emacs integer can hold, this is of
7328 the form (HIGH . LOW): first the high bits, then the low 16 bits.
7329 If even HIGH is too large for an Emacs integer, this is instead
7330 of the form (HIGH MIDDLE . LOW): first the high bits, then the
7331 middle 24 bits, and finally the low 16 bits."
7332 (nth 11 attributes))
7334 (defun file-attribute-collect (attributes &rest attr-names)
7335 "Return a sublist of ATTRIBUTES returned by `file-attributes'.
7336 ATTR-NAMES are symbols with the selected attribute names.
7338 Valid attribute names are: type, link-number, user-id, group-id,
7339 access-time, modification-time, status-change-time, size, modes,
7340 inode-number and device-number."
7341 (let ((all '(type link-number user-id group-id access-time
7342 modification-time status-change-time
7343 size modes inode-number device-number))
7344 result)
7345 (while attr-names
7346 (let ((attr (pop attr-names)))
7347 (if (memq attr all)
7348 (push (funcall
7349 (intern (format "file-attribute-%s" (symbol-name attr)))
7350 attributes)
7351 result)
7352 (error "Wrong attribute name '%S'" attr))))
7353 (nreverse result)))
7355 (define-key ctl-x-map "\C-f" 'find-file)
7356 (define-key ctl-x-map "\C-r" 'find-file-read-only)
7357 (define-key ctl-x-map "\C-v" 'find-alternate-file)
7358 (define-key ctl-x-map "\C-s" 'save-buffer)
7359 (define-key ctl-x-map "s" 'save-some-buffers)
7360 (define-key ctl-x-map "\C-w" 'write-file)
7361 (define-key ctl-x-map "i" 'insert-file)
7362 (define-key esc-map "~" 'not-modified)
7363 (define-key ctl-x-map "\C-d" 'list-directory)
7364 (define-key ctl-x-map "\C-c" 'save-buffers-kill-terminal)
7365 (define-key ctl-x-map "\C-q" 'read-only-mode)
7367 (define-key ctl-x-4-map "f" 'find-file-other-window)
7368 (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
7369 (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
7370 (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
7371 (define-key ctl-x-4-map "\C-o" 'display-buffer)
7373 (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
7374 (define-key ctl-x-5-map "f" 'find-file-other-frame)
7375 (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
7376 (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
7377 (define-key ctl-x-5-map "\C-o" 'display-buffer-other-frame)
7379 ;;; files.el ends here