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