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