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