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