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