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