]> code.delx.au - gnu-emacs/blob - lisp/files.el
Correct spalling.
[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 ((locals-file (locate-dominating-file file dir-locals-file))
3279 (dir-elt nil))
3280 ;; `locate-dominating-file' may have abbreviated the name.
3281 (when locals-file
3282 (setq locals-file (expand-file-name dir-locals-file locals-file)))
3283 (dolist (elt dir-locals-directory-alist)
3284 (when (and (eq t (compare-strings file nil (length (car elt))
3285 (car elt) nil nil))
3286 (> (length (car elt)) (length (car dir-elt))))
3287 (setq dir-elt elt)))
3288 (if (and locals-file dir-elt)
3289 (if (> (length (file-name-directory locals-file))
3290 (length (car dir-elt)))
3291 locals-file
3292 dir-elt)
3293 (or locals-file dir-elt))))
3294
3295 (defun dir-locals-read-from-file (file)
3296 "Load a variables FILE and register a new class and instance.
3297 FILE is the name of the file holding the variables to apply.
3298 The new class name is the same as the directory in which FILE
3299 is found. Returns the new class name."
3300 (with-temp-buffer
3301 ;; We should probably store the modtime of FILE and then
3302 ;; reload it whenever it changes.
3303 (insert-file-contents file)
3304 (let* ((dir-name (file-name-directory file))
3305 (class-name (intern dir-name))
3306 (variables (read (current-buffer))))
3307 (dir-locals-set-class-variables class-name variables)
3308 (dir-locals-set-directory-class dir-name class-name)
3309 class-name)))
3310
3311 (declare-function c-postprocess-file-styles "cc-mode" ())
3312
3313 (defun hack-dir-local-variables ()
3314 "Read per-directory local variables for the current buffer.
3315 Store the directory-local variables in `file-local-variables-alist',
3316 without applying them."
3317 (when (and enable-local-variables
3318 (buffer-file-name)
3319 (not (file-remote-p (buffer-file-name))))
3320 ;; Find the variables file.
3321 (let ((variables-file (dir-locals-find-file (buffer-file-name)))
3322 (class nil)
3323 (dir-name nil))
3324 (cond
3325 ((stringp variables-file)
3326 (setq dir-name (file-name-directory (buffer-file-name)))
3327 (setq class (dir-locals-read-from-file variables-file)))
3328 ((consp variables-file)
3329 (setq dir-name (car variables-file))
3330 (setq class (cdr variables-file))))
3331 (when class
3332 (let ((variables
3333 (dir-locals-collect-variables
3334 (dir-locals-get-class-variables class) dir-name nil)))
3335 (when variables
3336 (hack-local-variables-filter variables dir-name)))))))
3337
3338 \f
3339 (defcustom change-major-mode-with-file-name t
3340 "Non-nil means \\[write-file] should set the major mode from the file name.
3341 However, the mode will not be changed if
3342 \(1) a local variables list or the `-*-' line specifies a major mode, or
3343 \(2) the current major mode is a \"special\" mode,
3344 \ not suitable for ordinary files, or
3345 \(3) the new file name does not particularly specify any mode."
3346 :type 'boolean
3347 :group 'editing-basics)
3348
3349 (defun set-visited-file-name (filename &optional no-query along-with-file)
3350 "Change name of file visited in current buffer to FILENAME.
3351 This also renames the buffer to correspond to the new file.
3352 The next time the buffer is saved it will go in the newly specified file.
3353 FILENAME nil or an empty string means mark buffer as not visiting any file.
3354 Remember to delete the initial contents of the minibuffer
3355 if you wish to pass an empty string as the argument.
3356
3357 The optional second argument NO-QUERY, if non-nil, inhibits asking for
3358 confirmation in the case where another buffer is already visiting FILENAME.
3359
3360 The optional third argument ALONG-WITH-FILE, if non-nil, means that
3361 the old visited file has been renamed to the new name FILENAME."
3362 (interactive "FSet visited file name: ")
3363 (if (buffer-base-buffer)
3364 (error "An indirect buffer cannot visit a file"))
3365 (let (truename)
3366 (if filename
3367 (setq filename
3368 (if (string-equal filename "")
3369 nil
3370 (expand-file-name filename))))
3371 (if filename
3372 (progn
3373 (setq truename (file-truename filename))
3374 (if find-file-visit-truename
3375 (setq filename truename))))
3376 (if filename
3377 (let ((new-name (file-name-nondirectory filename)))
3378 (if (string= new-name "")
3379 (error "Empty file name"))))
3380 (let ((buffer (and filename (find-buffer-visiting filename))))
3381 (and buffer (not (eq buffer (current-buffer)))
3382 (not no-query)
3383 (not (y-or-n-p (format "A buffer is visiting %s; proceed? "
3384 filename)))
3385 (error "Aborted")))
3386 (or (equal filename buffer-file-name)
3387 (progn
3388 (and filename (lock-buffer filename))
3389 (unlock-buffer)))
3390 (setq buffer-file-name filename)
3391 (if filename ; make buffer name reflect filename.
3392 (let ((new-name (file-name-nondirectory buffer-file-name)))
3393 (setq default-directory (file-name-directory buffer-file-name))
3394 ;; If new-name == old-name, renaming would add a spurious <2>
3395 ;; and it's considered as a feature in rename-buffer.
3396 (or (string= new-name (buffer-name))
3397 (rename-buffer new-name t))))
3398 (setq buffer-backed-up nil)
3399 (or along-with-file
3400 (clear-visited-file-modtime))
3401 ;; Abbreviate the file names of the buffer.
3402 (if truename
3403 (progn
3404 (setq buffer-file-truename (abbreviate-file-name truename))
3405 (if find-file-visit-truename
3406 (setq buffer-file-name truename))))
3407 (setq buffer-file-number
3408 (if filename
3409 (nthcdr 10 (file-attributes buffer-file-name))
3410 nil)))
3411 ;; write-file-functions is normally used for things like ftp-find-file
3412 ;; that visit things that are not local files as if they were files.
3413 ;; Changing to visit an ordinary local file instead should flush the hook.
3414 (kill-local-variable 'write-file-functions)
3415 (kill-local-variable 'local-write-file-hooks)
3416 (kill-local-variable 'revert-buffer-function)
3417 (kill-local-variable 'backup-inhibited)
3418 ;; If buffer was read-only because of version control,
3419 ;; that reason is gone now, so make it writable.
3420 (if vc-mode
3421 (setq buffer-read-only nil))
3422 (kill-local-variable 'vc-mode)
3423 ;; Turn off backup files for certain file names.
3424 ;; Since this is a permanent local, the major mode won't eliminate it.
3425 (and buffer-file-name
3426 backup-enable-predicate
3427 (not (funcall backup-enable-predicate buffer-file-name))
3428 (progn
3429 (make-local-variable 'backup-inhibited)
3430 (setq backup-inhibited t)))
3431 (let ((oauto buffer-auto-save-file-name))
3432 ;; If auto-save was not already on, turn it on if appropriate.
3433 (if (not buffer-auto-save-file-name)
3434 (and buffer-file-name auto-save-default
3435 (auto-save-mode t))
3436 ;; If auto save is on, start using a new name.
3437 ;; We deliberately don't rename or delete the old auto save
3438 ;; for the old visited file name. This is because perhaps
3439 ;; the user wants to save the new state and then compare with the
3440 ;; previous state from the auto save file.
3441 (setq buffer-auto-save-file-name
3442 (make-auto-save-file-name)))
3443 ;; Rename the old auto save file if any.
3444 (and oauto buffer-auto-save-file-name
3445 (file-exists-p oauto)
3446 (rename-file oauto buffer-auto-save-file-name t)))
3447 (and buffer-file-name
3448 (not along-with-file)
3449 (set-buffer-modified-p t))
3450 ;; Update the major mode, if the file name determines it.
3451 (condition-case nil
3452 ;; Don't change the mode if it is special.
3453 (or (not change-major-mode-with-file-name)
3454 (get major-mode 'mode-class)
3455 ;; Don't change the mode if the local variable list specifies it.
3456 (hack-local-variables t)
3457 (set-auto-mode t))
3458 (error nil)))
3459
3460 (defun write-file (filename &optional confirm)
3461 "Write current buffer into file FILENAME.
3462 This makes the buffer visit that file, and marks it as not modified.
3463
3464 If you specify just a directory name as FILENAME, that means to use
3465 the default file name but in that directory. You can also yank
3466 the default file name into the minibuffer to edit it, using \\<minibuffer-local-map>\\[next-history-element].
3467
3468 If the buffer is not already visiting a file, the default file name
3469 for the output file is the buffer name.
3470
3471 If optional second arg CONFIRM is non-nil, this function
3472 asks for confirmation before overwriting an existing file.
3473 Interactively, confirmation is required unless you supply a prefix argument."
3474 ;; (interactive "FWrite file: ")
3475 (interactive
3476 (list (if buffer-file-name
3477 (read-file-name "Write file: "
3478 nil nil nil nil)
3479 (read-file-name "Write file: " default-directory
3480 (expand-file-name
3481 (file-name-nondirectory (buffer-name))
3482 default-directory)
3483 nil nil))
3484 (not current-prefix-arg)))
3485 (or (null filename) (string-equal filename "")
3486 (progn
3487 ;; If arg is just a directory,
3488 ;; use the default file name, but in that directory.
3489 (if (file-directory-p filename)
3490 (setq filename (concat (file-name-as-directory filename)
3491 (file-name-nondirectory
3492 (or buffer-file-name (buffer-name))))))
3493 (and confirm
3494 (file-exists-p filename)
3495 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
3496 (error "Canceled")))
3497 (set-visited-file-name filename (not confirm))))
3498 (set-buffer-modified-p t)
3499 ;; Make buffer writable if file is writable.
3500 (and buffer-file-name
3501 (file-writable-p buffer-file-name)
3502 (setq buffer-read-only nil))
3503 (save-buffer)
3504 ;; It's likely that the VC status at the new location is different from
3505 ;; the one at the old location.
3506 (vc-find-file-hook))
3507 \f
3508 (defun backup-buffer ()
3509 "Make a backup of the disk file visited by the current buffer, if appropriate.
3510 This is normally done before saving the buffer the first time.
3511
3512 A backup may be done by renaming or by copying; see documentation of
3513 variable `make-backup-files'. If it's done by renaming, then the file is
3514 no longer accessible under its old name.
3515
3516 The value is non-nil after a backup was made by renaming.
3517 It has the form (MODES . BACKUPNAME).
3518 MODES is the result of `file-modes' on the original
3519 file; this means that the caller, after saving the buffer, should change
3520 the modes of the new file to agree with the old modes.
3521 BACKUPNAME is the backup file name, which is the old file renamed."
3522 (if (and make-backup-files (not backup-inhibited)
3523 (not buffer-backed-up)
3524 (file-exists-p buffer-file-name)
3525 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
3526 '(?- ?l)))
3527 (let ((real-file-name buffer-file-name)
3528 backup-info backupname targets setmodes)
3529 ;; If specified name is a symbolic link, chase it to the target.
3530 ;; Thus we make the backups in the directory where the real file is.
3531 (setq real-file-name (file-chase-links real-file-name))
3532 (setq backup-info (find-backup-file-name real-file-name)
3533 backupname (car backup-info)
3534 targets (cdr backup-info))
3535 ;; (if (file-directory-p buffer-file-name)
3536 ;; (error "Cannot save buffer in directory %s" buffer-file-name))
3537 (if backup-info
3538 (condition-case ()
3539 (let ((delete-old-versions
3540 ;; If have old versions to maybe delete,
3541 ;; ask the user to confirm now, before doing anything.
3542 ;; But don't actually delete til later.
3543 (and targets
3544 (or (eq delete-old-versions t) (eq delete-old-versions nil))
3545 (or delete-old-versions
3546 (y-or-n-p (format "Delete excess backup versions of %s? "
3547 real-file-name)))))
3548 (modes (file-modes buffer-file-name)))
3549 ;; Actually write the back up file.
3550 (condition-case ()
3551 (if (or file-precious-flag
3552 ; (file-symlink-p buffer-file-name)
3553 backup-by-copying
3554 ;; Don't rename a suid or sgid file.
3555 (and modes (< 0 (logand modes #o6000)))
3556 (not (file-writable-p (file-name-directory real-file-name)))
3557 (and backup-by-copying-when-linked
3558 (> (file-nlinks real-file-name) 1))
3559 (and (or backup-by-copying-when-mismatch
3560 (integerp backup-by-copying-when-privileged-mismatch))
3561 (let ((attr (file-attributes real-file-name)))
3562 (and (or backup-by-copying-when-mismatch
3563 (and (integerp (nth 2 attr))
3564 (integerp backup-by-copying-when-privileged-mismatch)
3565 (<= (nth 2 attr) backup-by-copying-when-privileged-mismatch)))
3566 (or (nth 9 attr)
3567 (not (file-ownership-preserved-p real-file-name)))))))
3568 (backup-buffer-copy real-file-name backupname modes)
3569 ;; rename-file should delete old backup.
3570 (rename-file real-file-name backupname t)
3571 (setq setmodes (cons modes backupname)))
3572 (file-error
3573 ;; If trouble writing the backup, write it in ~.
3574 (setq backupname (expand-file-name
3575 (convert-standard-filename
3576 "~/%backup%~")))
3577 (message "Cannot write backup file; backing up in %s"
3578 backupname)
3579 (sleep-for 1)
3580 (backup-buffer-copy real-file-name backupname modes)))
3581 (setq buffer-backed-up t)
3582 ;; Now delete the old versions, if desired.
3583 (if delete-old-versions
3584 (while targets
3585 (condition-case ()
3586 (delete-file (car targets))
3587 (file-error nil))
3588 (setq targets (cdr targets))))
3589 setmodes)
3590 (file-error nil))))))
3591
3592 (defun backup-buffer-copy (from-name to-name modes)
3593 (let ((umask (default-file-modes)))
3594 (unwind-protect
3595 (progn
3596 ;; Create temp files with strict access rights. It's easy to
3597 ;; loosen them later, whereas it's impossible to close the
3598 ;; time-window of loose permissions otherwise.
3599 (set-default-file-modes ?\700)
3600 (when (condition-case nil
3601 ;; Try to overwrite old backup first.
3602 (copy-file from-name to-name t t t)
3603 (error t))
3604 (while (condition-case nil
3605 (progn
3606 (when (file-exists-p to-name)
3607 (delete-file to-name))
3608 (copy-file from-name to-name nil t t)
3609 nil)
3610 (file-already-exists t))
3611 ;; The file was somehow created by someone else between
3612 ;; `delete-file' and `copy-file', so let's try again.
3613 ;; rms says "I think there is also a possible race
3614 ;; condition for making backup files" (emacs-devel 20070821).
3615 nil)))
3616 ;; Reset the umask.
3617 (set-default-file-modes umask)))
3618 (and modes
3619 (set-file-modes to-name (logand modes #o1777))))
3620
3621 (defun file-name-sans-versions (name &optional keep-backup-version)
3622 "Return file NAME sans backup versions or strings.
3623 This is a separate procedure so your site-init or startup file can
3624 redefine it.
3625 If the optional argument KEEP-BACKUP-VERSION is non-nil,
3626 we do not remove backup version numbers, only true file version numbers."
3627 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
3628 (if handler
3629 (funcall handler 'file-name-sans-versions name keep-backup-version)
3630 (substring name 0
3631 (if keep-backup-version
3632 (length name)
3633 (or (string-match "\\.~[-[:alnum:]:#@^._]+~\\'" name)
3634 (string-match "~\\'" name)
3635 (length name)))))))
3636
3637 (defun file-ownership-preserved-p (file)
3638 "Return t if deleting FILE and rewriting it would preserve the owner."
3639 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
3640 (if handler
3641 (funcall handler 'file-ownership-preserved-p file)
3642 (let ((attributes (file-attributes file)))
3643 ;; Return t if the file doesn't exist, since it's true that no
3644 ;; information would be lost by an (attempted) delete and create.
3645 (or (null attributes)
3646 (= (nth 2 attributes) (user-uid)))))))
3647
3648 (defun file-name-sans-extension (filename)
3649 "Return FILENAME sans final \"extension\".
3650 The extension, in a file name, is the part that follows the last `.',
3651 except that a leading `.', if any, doesn't count."
3652 (save-match-data
3653 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
3654 directory)
3655 (if (and (string-match "\\.[^.]*\\'" file)
3656 (not (eq 0 (match-beginning 0))))
3657 (if (setq directory (file-name-directory filename))
3658 ;; Don't use expand-file-name here; if DIRECTORY is relative,
3659 ;; we don't want to expand it.
3660 (concat directory (substring file 0 (match-beginning 0)))
3661 (substring file 0 (match-beginning 0)))
3662 filename))))
3663
3664 (defun file-name-extension (filename &optional period)
3665 "Return FILENAME's final \"extension\".
3666 The extension, in a file name, is the part that follows the last `.',
3667 excluding version numbers and backup suffixes,
3668 except that a leading `.', if any, doesn't count.
3669 Return nil for extensionless file names such as `foo'.
3670 Return the empty string for file names such as `foo.'.
3671
3672 If PERIOD is non-nil, then the returned value includes the period
3673 that delimits the extension, and if FILENAME has no extension,
3674 the value is \"\"."
3675 (save-match-data
3676 (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
3677 (if (and (string-match "\\.[^.]*\\'" file)
3678 (not (eq 0 (match-beginning 0))))
3679 (substring file (+ (match-beginning 0) (if period 0 1)))
3680 (if period
3681 "")))))
3682
3683 (defcustom make-backup-file-name-function nil
3684 "A function to use instead of the default `make-backup-file-name'.
3685 A value of nil gives the default `make-backup-file-name' behavior.
3686
3687 This could be buffer-local to do something special for specific
3688 files. If you define it, you may need to change `backup-file-name-p'
3689 and `file-name-sans-versions' too.
3690
3691 See also `backup-directory-alist'."
3692 :group 'backup
3693 :type '(choice (const :tag "Default" nil)
3694 (function :tag "Your function")))
3695
3696 (defcustom backup-directory-alist nil
3697 "Alist of filename patterns and backup directory names.
3698 Each element looks like (REGEXP . DIRECTORY). Backups of files with
3699 names matching REGEXP will be made in DIRECTORY. DIRECTORY may be
3700 relative or absolute. If it is absolute, so that all matching files
3701 are backed up into the same directory, the file names in this
3702 directory will be the full name of the file backed up with all
3703 directory separators changed to `!' to prevent clashes. This will not
3704 work correctly if your filesystem truncates the resulting name.
3705
3706 For the common case of all backups going into one directory, the alist
3707 should contain a single element pairing \".\" with the appropriate
3708 directory name.
3709
3710 If this variable is nil, or it fails to match a filename, the backup
3711 is made in the original file's directory.
3712
3713 On MS-DOS filesystems without long names this variable is always
3714 ignored."
3715 :group 'backup
3716 :type '(repeat (cons (regexp :tag "Regexp matching filename")
3717 (directory :tag "Backup directory name"))))
3718
3719 (defun normal-backup-enable-predicate (name)
3720 "Default `backup-enable-predicate' function.
3721 Checks for files in `temporary-file-directory',
3722 `small-temporary-file-directory', and /tmp."
3723 (not (or (let ((comp (compare-strings temporary-file-directory 0 nil
3724 name 0 nil)))
3725 ;; Directory is under temporary-file-directory.
3726 (and (not (eq comp t))
3727 (< comp (- (length temporary-file-directory)))))
3728 (let ((comp (compare-strings "/tmp" 0 nil
3729 name 0 nil)))
3730 ;; Directory is under /tmp.
3731 (and (not (eq comp t))
3732 (< comp (- (length "/tmp")))))
3733 (if small-temporary-file-directory
3734 (let ((comp (compare-strings small-temporary-file-directory
3735 0 nil
3736 name 0 nil)))
3737 ;; Directory is under small-temporary-file-directory.
3738 (and (not (eq comp t))
3739 (< comp (- (length small-temporary-file-directory)))))))))
3740
3741 (defun make-backup-file-name (file)
3742 "Create the non-numeric backup file name for FILE.
3743 Normally this will just be the file's name with `~' appended.
3744 Customization hooks are provided as follows.
3745
3746 If the variable `make-backup-file-name-function' is non-nil, its value
3747 should be a function which will be called with FILE as its argument;
3748 the resulting name is used.
3749
3750 Otherwise a match for FILE is sought in `backup-directory-alist'; see
3751 the documentation of that variable. If the directory for the backup
3752 doesn't exist, it is created."
3753 (if make-backup-file-name-function
3754 (funcall make-backup-file-name-function file)
3755 (if (and (eq system-type 'ms-dos)
3756 (not (msdos-long-file-names)))
3757 (let ((fn (file-name-nondirectory file)))
3758 (concat (file-name-directory file)
3759 (or (and (string-match "\\`[^.]+\\'" fn)
3760 (concat (match-string 0 fn) ".~"))
3761 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
3762 (concat (match-string 0 fn) "~")))))
3763 (concat (make-backup-file-name-1 file) "~"))))
3764
3765 (defun make-backup-file-name-1 (file)
3766 "Subroutine of `make-backup-file-name' and `find-backup-file-name'."
3767 (let ((alist backup-directory-alist)
3768 elt backup-directory abs-backup-directory)
3769 (while alist
3770 (setq elt (pop alist))
3771 (if (string-match (car elt) file)
3772 (setq backup-directory (cdr elt)
3773 alist nil)))
3774 ;; If backup-directory is relative, it should be relative to the
3775 ;; file's directory. By expanding explicitly here, we avoid
3776 ;; depending on default-directory.
3777 (if backup-directory
3778 (setq abs-backup-directory
3779 (expand-file-name backup-directory
3780 (file-name-directory file))))
3781 (if (and abs-backup-directory (not (file-exists-p abs-backup-directory)))
3782 (condition-case nil
3783 (make-directory abs-backup-directory 'parents)
3784 (file-error (setq backup-directory nil
3785 abs-backup-directory nil))))
3786 (if (null backup-directory)
3787 file
3788 (if (file-name-absolute-p backup-directory)
3789 (progn
3790 (when (memq system-type '(windows-nt ms-dos cygwin))
3791 ;; Normalize DOSish file names: downcase the drive
3792 ;; letter, if any, and replace the leading "x:" with
3793 ;; "/drive_x".
3794 (or (file-name-absolute-p file)
3795 (setq file (expand-file-name file))) ; make defaults explicit
3796 ;; Replace any invalid file-name characters (for the
3797 ;; case of backing up remote files).
3798 (setq file (expand-file-name (convert-standard-filename file)))
3799 (if (eq (aref file 1) ?:)
3800 (setq file (concat "/"
3801 "drive_"
3802 (char-to-string (downcase (aref file 0)))
3803 (if (eq (aref file 2) ?/)
3804 ""
3805 "/")
3806 (substring file 2)))))
3807 ;; Make the name unique by substituting directory
3808 ;; separators. It may not really be worth bothering about
3809 ;; doubling `!'s in the original name...
3810 (expand-file-name
3811 (subst-char-in-string
3812 ?/ ?!
3813 (replace-regexp-in-string "!" "!!" file))
3814 backup-directory))
3815 (expand-file-name (file-name-nondirectory file)
3816 (file-name-as-directory abs-backup-directory))))))
3817
3818 (defun backup-file-name-p (file)
3819 "Return non-nil if FILE is a backup file name (numeric or not).
3820 This is a separate function so you can redefine it for customization.
3821 You may need to redefine `file-name-sans-versions' as well."
3822 (string-match "~\\'" file))
3823
3824 (defvar backup-extract-version-start)
3825
3826 ;; This is used in various files.
3827 ;; The usage of backup-extract-version-start is not very clean,
3828 ;; but I can't see a good alternative, so as of now I am leaving it alone.
3829 (defun backup-extract-version (fn)
3830 "Given the name of a numeric backup file, FN, return the backup number.
3831 Uses the free variable `backup-extract-version-start', whose value should be
3832 the index in the name where the version number begins."
3833 (if (and (string-match "[0-9]+~/?$" fn backup-extract-version-start)
3834 (= (match-beginning 0) backup-extract-version-start))
3835 (string-to-number (substring fn backup-extract-version-start -1))
3836 0))
3837
3838 (defun find-backup-file-name (fn)
3839 "Find a file name for a backup file FN, and suggestions for deletions.
3840 Value is a list whose car is the name for the backup file
3841 and whose cdr is a list of old versions to consider deleting now.
3842 If the value is nil, don't make a backup.
3843 Uses `backup-directory-alist' in the same way as does
3844 `make-backup-file-name'."
3845 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
3846 ;; Run a handler for this function so that ange-ftp can refuse to do it.
3847 (if handler
3848 (funcall handler 'find-backup-file-name fn)
3849 (if (or (eq version-control 'never)
3850 ;; We don't support numbered backups on plain MS-DOS
3851 ;; when long file names are unavailable.
3852 (and (eq system-type 'ms-dos)
3853 (not (msdos-long-file-names))))
3854 (list (make-backup-file-name fn))
3855 (let* ((basic-name (make-backup-file-name-1 fn))
3856 (base-versions (concat (file-name-nondirectory basic-name)
3857 ".~"))
3858 (backup-extract-version-start (length base-versions))
3859 (high-water-mark 0)
3860 (number-to-delete 0)
3861 possibilities deserve-versions-p versions)
3862 (condition-case ()
3863 (setq possibilities (file-name-all-completions
3864 base-versions
3865 (file-name-directory basic-name))
3866 versions (sort (mapcar #'backup-extract-version
3867 possibilities)
3868 #'<)
3869 high-water-mark (apply 'max 0 versions)
3870 deserve-versions-p (or version-control
3871 (> high-water-mark 0))
3872 number-to-delete (- (length versions)
3873 kept-old-versions
3874 kept-new-versions
3875 -1))
3876 (file-error (setq possibilities nil)))
3877 (if (not deserve-versions-p)
3878 (list (make-backup-file-name fn))
3879 (cons (format "%s.~%d~" basic-name (1+ high-water-mark))
3880 (if (and (> number-to-delete 0)
3881 ;; Delete nothing if there is overflow
3882 ;; in the number of versions to keep.
3883 (>= (+ kept-new-versions kept-old-versions -1) 0))
3884 (mapcar (lambda (n)
3885 (format "%s.~%d~" basic-name n))
3886 (let ((v (nthcdr kept-old-versions versions)))
3887 (rplacd (nthcdr (1- number-to-delete) v) ())
3888 v))))))))))
3889
3890 (defun file-nlinks (filename)
3891 "Return number of names file FILENAME has."
3892 (car (cdr (file-attributes filename))))
3893
3894 ;; (defun file-relative-name (filename &optional directory)
3895 ;; "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
3896 ;; This function returns a relative file name which is equivalent to FILENAME
3897 ;; when used with that default directory as the default.
3898 ;; If this is impossible (which can happen on MSDOS and Windows
3899 ;; when the file name and directory use different drive names)
3900 ;; then it returns FILENAME."
3901 ;; (save-match-data
3902 ;; (let ((fname (expand-file-name filename)))
3903 ;; (setq directory (file-name-as-directory
3904 ;; (expand-file-name (or directory default-directory))))
3905 ;; ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
3906 ;; ;; drive names, they can't be relative, so return the absolute name.
3907 ;; (if (and (or (eq system-type 'ms-dos)
3908 ;; (eq system-type 'cygwin)
3909 ;; (eq system-type 'windows-nt))
3910 ;; (not (string-equal (substring fname 0 2)
3911 ;; (substring directory 0 2))))
3912 ;; filename
3913 ;; (let ((ancestor ".")
3914 ;; (fname-dir (file-name-as-directory fname)))
3915 ;; (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
3916 ;; (not (string-match (concat "^" (regexp-quote directory)) fname)))
3917 ;; (setq directory (file-name-directory (substring directory 0 -1))
3918 ;; ancestor (if (equal ancestor ".")
3919 ;; ".."
3920 ;; (concat "../" ancestor))))
3921 ;; ;; Now ancestor is empty, or .., or ../.., etc.
3922 ;; (if (string-match (concat "^" (regexp-quote directory)) fname)
3923 ;; ;; We matched within FNAME's directory part.
3924 ;; ;; Add the rest of FNAME onto ANCESTOR.
3925 ;; (let ((rest (substring fname (match-end 0))))
3926 ;; (if (and (equal ancestor ".")
3927 ;; (not (equal rest "")))
3928 ;; ;; But don't bother with ANCESTOR if it would give us `./'.
3929 ;; rest
3930 ;; (concat (file-name-as-directory ancestor) rest)))
3931 ;; ;; We matched FNAME's directory equivalent.
3932 ;; ancestor))))))
3933
3934 (defun file-relative-name (filename &optional directory)
3935 "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
3936 This function returns a relative file name which is equivalent to FILENAME
3937 when used with that default directory as the default.
3938 If FILENAME and DIRECTORY lie on different machines or on different drives
3939 on a DOS/Windows machine, it returns FILENAME in expanded form."
3940 (save-match-data
3941 (setq directory
3942 (file-name-as-directory (expand-file-name (or directory
3943 default-directory))))
3944 (setq filename (expand-file-name filename))
3945 (let ((fremote (file-remote-p filename))
3946 (dremote (file-remote-p directory)))
3947 (if ;; Conditions for separate trees
3948 (or
3949 ;; Test for different drives on DOS/Windows
3950 (and
3951 ;; Should `cygwin' really be included here? --stef
3952 (memq system-type '(ms-dos cygwin windows-nt))
3953 (not (eq t (compare-strings filename 0 2 directory 0 2))))
3954 ;; Test for different remote file system identification
3955 (not (equal fremote dremote)))
3956 filename
3957 (let ((ancestor ".")
3958 (filename-dir (file-name-as-directory filename)))
3959 (while (not
3960 (or
3961 (eq t (compare-strings filename-dir nil (length directory)
3962 directory nil nil case-fold-search))
3963 (eq t (compare-strings filename nil (length directory)
3964 directory nil nil case-fold-search))))
3965 (setq directory (file-name-directory (substring directory 0 -1))
3966 ancestor (if (equal ancestor ".")
3967 ".."
3968 (concat "../" ancestor))))
3969 ;; Now ancestor is empty, or .., or ../.., etc.
3970 (if (eq t (compare-strings filename nil (length directory)
3971 directory nil nil case-fold-search))
3972 ;; We matched within FILENAME's directory part.
3973 ;; Add the rest of FILENAME onto ANCESTOR.
3974 (let ((rest (substring filename (length directory))))
3975 (if (and (equal ancestor ".") (not (equal rest "")))
3976 ;; But don't bother with ANCESTOR if it would give us `./'.
3977 rest
3978 (concat (file-name-as-directory ancestor) rest)))
3979 ;; We matched FILENAME's directory equivalent.
3980 ancestor))))))
3981 \f
3982 (defun save-buffer (&optional args)
3983 "Save current buffer in visited file if modified.
3984 Variations are described below.
3985
3986 By default, makes the previous version into a backup file
3987 if previously requested or if this is the first save.
3988 Prefixed with one \\[universal-argument], marks this version
3989 to become a backup when the next save is done.
3990 Prefixed with two \\[universal-argument]'s,
3991 unconditionally makes the previous version into a backup file.
3992 Prefixed with three \\[universal-argument]'s, marks this version
3993 to become a backup when the next save is done,
3994 and unconditionally makes the previous version into a backup file.
3995
3996 With a numeric argument of 0, never make the previous version
3997 into a backup file.
3998
3999 If a file's name is FOO, the names of its numbered backup versions are
4000 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
4001 Numeric backups (rather than FOO~) will be made if value of
4002 `version-control' is not the atom `never' and either there are already
4003 numeric versions of the file being backed up, or `version-control' is
4004 non-nil.
4005 We don't want excessive versions piling up, so there are variables
4006 `kept-old-versions', which tells Emacs how many oldest versions to keep,
4007 and `kept-new-versions', which tells how many newest versions to keep.
4008 Defaults are 2 old versions and 2 new.
4009 `dired-kept-versions' controls dired's clean-directory (.) command.
4010 If `delete-old-versions' is nil, system will query user
4011 before trimming versions. Otherwise it does it silently.
4012
4013 If `vc-make-backup-files' is nil, which is the default,
4014 no backup files are made for files managed by version control.
4015 (This is because the version control system itself records previous versions.)
4016
4017 See the subroutine `basic-save-buffer' for more information."
4018 (interactive "p")
4019 (let ((modp (buffer-modified-p))
4020 (large (> (buffer-size) 50000))
4021 (make-backup-files (or (and make-backup-files (not (eq args 0)))
4022 (memq args '(16 64)))))
4023 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
4024 (if (and modp large (buffer-file-name))
4025 (message "Saving file %s..." (buffer-file-name)))
4026 (basic-save-buffer)
4027 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
4028
4029 (defun delete-auto-save-file-if-necessary (&optional force)
4030 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
4031 Normally delete only if the file was written by this Emacs since
4032 the last real save, but optional arg FORCE non-nil means delete anyway."
4033 (and buffer-auto-save-file-name delete-auto-save-files
4034 (not (string= buffer-file-name buffer-auto-save-file-name))
4035 (or force (recent-auto-save-p))
4036 (progn
4037 (condition-case ()
4038 (delete-file buffer-auto-save-file-name)
4039 (file-error nil))
4040 (set-buffer-auto-saved))))
4041
4042 (defvar auto-save-hook nil
4043 "Normal hook run just before auto-saving.")
4044
4045 (defcustom before-save-hook nil
4046 "Normal hook that is run before a buffer is saved to its file."
4047 :options '(copyright-update time-stamp)
4048 :type 'hook
4049 :group 'files)
4050
4051 (defcustom after-save-hook nil
4052 "Normal hook that is run after a buffer is saved to its file."
4053 :options '(executable-make-buffer-file-executable-if-script-p)
4054 :type 'hook
4055 :group 'files)
4056
4057 (defvar save-buffer-coding-system nil
4058 "If non-nil, use this coding system for saving the buffer.
4059 More precisely, use this coding system in place of the
4060 value of `buffer-file-coding-system', when saving the buffer.
4061 Calling `write-region' for any purpose other than saving the buffer
4062 will still use `buffer-file-coding-system'; this variable has no effect
4063 in such cases.")
4064
4065 (make-variable-buffer-local 'save-buffer-coding-system)
4066 (put 'save-buffer-coding-system 'permanent-local t)
4067
4068 (defun basic-save-buffer ()
4069 "Save the current buffer in its visited file, if it has been modified.
4070 The hooks `write-contents-functions' and `write-file-functions' get a chance
4071 to do the job of saving; if they do not, then the buffer is saved in
4072 the visited file in the usual way.
4073 Before and after saving the buffer, this function runs
4074 `before-save-hook' and `after-save-hook', respectively."
4075 (interactive)
4076 (save-current-buffer
4077 ;; In an indirect buffer, save its base buffer instead.
4078 (if (buffer-base-buffer)
4079 (set-buffer (buffer-base-buffer)))
4080 (if (buffer-modified-p)
4081 (let ((recent-save (recent-auto-save-p))
4082 setmodes)
4083 ;; If buffer has no file name, ask user for one.
4084 (or buffer-file-name
4085 (let ((filename
4086 (expand-file-name
4087 (read-file-name "File to save in: ") nil)))
4088 (if (file-exists-p filename)
4089 (if (file-directory-p filename)
4090 ;; Signal an error if the user specified the name of an
4091 ;; existing directory.
4092 (error "%s is a directory" filename)
4093 (unless (y-or-n-p (format "File `%s' exists; overwrite? "
4094 filename))
4095 (error "Canceled")))
4096 ;; Signal an error if the specified name refers to a
4097 ;; non-existing directory.
4098 (let ((dir (file-name-directory filename)))
4099 (unless (file-directory-p dir)
4100 (if (file-exists-p dir)
4101 (error "%s is not a directory" dir)
4102 (error "%s: no such directory" dir)))))
4103 (set-visited-file-name filename)))
4104 (or (verify-visited-file-modtime (current-buffer))
4105 (not (file-exists-p buffer-file-name))
4106 (yes-or-no-p
4107 (format "%s has changed since visited or saved. Save anyway? "
4108 (file-name-nondirectory buffer-file-name)))
4109 (error "Save not confirmed"))
4110 (save-restriction
4111 (widen)
4112 (save-excursion
4113 (and (> (point-max) (point-min))
4114 (not find-file-literally)
4115 (/= (char-after (1- (point-max))) ?\n)
4116 (not (and (eq selective-display t)
4117 (= (char-after (1- (point-max))) ?\r)))
4118 (or (eq require-final-newline t)
4119 (eq require-final-newline 'visit-save)
4120 (and require-final-newline
4121 (y-or-n-p
4122 (format "Buffer %s does not end in newline. Add one? "
4123 (buffer-name)))))
4124 (save-excursion
4125 (goto-char (point-max))
4126 (insert ?\n))))
4127 ;; Support VC version backups.
4128 (vc-before-save)
4129 (run-hooks 'before-save-hook)
4130 (or (run-hook-with-args-until-success 'write-contents-functions)
4131 (run-hook-with-args-until-success 'local-write-file-hooks)
4132 (run-hook-with-args-until-success 'write-file-functions)
4133 ;; If a hook returned t, file is already "written".
4134 ;; Otherwise, write it the usual way now.
4135 (setq setmodes (basic-save-buffer-1)))
4136 ;; Now we have saved the current buffer. Let's make sure
4137 ;; that buffer-file-coding-system is fixed to what
4138 ;; actually used for saving by binding it locally.
4139 (if save-buffer-coding-system
4140 (setq save-buffer-coding-system last-coding-system-used)
4141 (setq buffer-file-coding-system last-coding-system-used))
4142 (setq buffer-file-number
4143 (nthcdr 10 (file-attributes buffer-file-name)))
4144 (if setmodes
4145 (condition-case ()
4146 (set-file-modes buffer-file-name (car setmodes))
4147 (error nil))))
4148 ;; If the auto-save file was recent before this command,
4149 ;; delete it now.
4150 (delete-auto-save-file-if-necessary recent-save)
4151 ;; Support VC `implicit' locking.
4152 (vc-after-save)
4153 (run-hooks 'after-save-hook))
4154 (message "(No changes need to be saved)"))))
4155
4156 ;; This does the "real job" of writing a buffer into its visited file
4157 ;; and making a backup file. This is what is normally done
4158 ;; but inhibited if one of write-file-functions returns non-nil.
4159 ;; It returns a value (MODES . BACKUPNAME), like backup-buffer.
4160 (defun basic-save-buffer-1 ()
4161 (prog1
4162 (if save-buffer-coding-system
4163 (let ((coding-system-for-write save-buffer-coding-system))
4164 (basic-save-buffer-2))
4165 (basic-save-buffer-2))
4166 (setq buffer-file-coding-system-explicit last-coding-system-used)))
4167
4168 ;; This returns a value (MODES . BACKUPNAME), like backup-buffer.
4169 (defun basic-save-buffer-2 ()
4170 (let (tempsetmodes setmodes)
4171 (if (not (file-writable-p buffer-file-name))
4172 (let ((dir (file-name-directory buffer-file-name)))
4173 (if (not (file-directory-p dir))
4174 (if (file-exists-p dir)
4175 (error "%s is not a directory" dir)
4176 (error "%s: no such directory" dir))
4177 (if (not (file-exists-p buffer-file-name))
4178 (error "Directory %s write-protected" dir)
4179 (if (yes-or-no-p
4180 (format "File %s is write-protected; try to save anyway? "
4181 (file-name-nondirectory
4182 buffer-file-name)))
4183 (setq tempsetmodes t)
4184 (error "Attempt to save to a file which you aren't allowed to write"))))))
4185 (or buffer-backed-up
4186 (setq setmodes (backup-buffer)))
4187 (let* ((dir (file-name-directory buffer-file-name))
4188 (dir-writable (file-writable-p dir)))
4189 (if (or (and file-precious-flag dir-writable)
4190 (and break-hardlink-on-save
4191 (> (file-nlinks buffer-file-name) 1)
4192 (or dir-writable
4193 (error (concat (format
4194 "Directory %s write-protected; " dir)
4195 "cannot break hardlink when saving")))))
4196 ;; Write temp name, then rename it.
4197 ;; This requires write access to the containing dir,
4198 ;; which is why we don't try it if we don't have that access.
4199 (let ((realname buffer-file-name)
4200 tempname succeed
4201 (umask (default-file-modes))
4202 (old-modtime (visited-file-modtime)))
4203 ;; Create temp files with strict access rights. It's easy to
4204 ;; loosen them later, whereas it's impossible to close the
4205 ;; time-window of loose permissions otherwise.
4206 (unwind-protect
4207 (progn
4208 (clear-visited-file-modtime)
4209 (set-default-file-modes ?\700)
4210 ;; Try various temporary names.
4211 ;; This code follows the example of make-temp-file,
4212 ;; but it calls write-region in the appropriate way
4213 ;; for saving the buffer.
4214 (while (condition-case ()
4215 (progn
4216 (setq tempname
4217 (make-temp-name
4218 (expand-file-name "tmp" dir)))
4219 ;; Pass in nil&nil rather than point-min&max
4220 ;; cause we're saving the whole buffer.
4221 ;; write-region-annotate-functions may use it.
4222 (write-region nil nil
4223 tempname nil realname
4224 buffer-file-truename 'excl)
4225 nil)
4226 (file-already-exists t))
4227 ;; The file was somehow created by someone else between
4228 ;; `make-temp-name' and `write-region', let's try again.
4229 nil)
4230 (setq succeed t))
4231 ;; Reset the umask.
4232 (set-default-file-modes umask)
4233 ;; If we failed, restore the buffer's modtime.
4234 (unless succeed
4235 (set-visited-file-modtime old-modtime)))
4236 ;; Since we have created an entirely new file,
4237 ;; make sure it gets the right permission bits set.
4238 (setq setmodes (or setmodes
4239 (cons (or (file-modes buffer-file-name)
4240 (logand ?\666 umask))
4241 buffer-file-name)))
4242 ;; We succeeded in writing the temp file,
4243 ;; so rename it.
4244 (rename-file tempname buffer-file-name t))
4245 ;; If file not writable, see if we can make it writable
4246 ;; temporarily while we write it.
4247 ;; But no need to do so if we have just backed it up
4248 ;; (setmodes is set) because that says we're superseding.
4249 (cond ((and tempsetmodes (not setmodes))
4250 ;; Change the mode back, after writing.
4251 (setq setmodes (cons (file-modes buffer-file-name) buffer-file-name))
4252 (set-file-modes buffer-file-name (logior (car setmodes) 128))))
4253 (let (success)
4254 (unwind-protect
4255 (progn
4256 ;; Pass in nil&nil rather than point-min&max to indicate
4257 ;; we're saving the buffer rather than just a region.
4258 ;; write-region-annotate-functions may make us of it.
4259 (write-region nil nil
4260 buffer-file-name nil t buffer-file-truename)
4261 (setq success t))
4262 ;; If we get an error writing the new file, and we made
4263 ;; the backup by renaming, undo the backing-up.
4264 (and setmodes (not success)
4265 (progn
4266 (rename-file (cdr setmodes) buffer-file-name t)
4267 (setq buffer-backed-up nil)))))))
4268 setmodes))
4269
4270 (defun diff-buffer-with-file (&optional buffer)
4271 "View the differences between BUFFER and its associated file.
4272 This requires the external program `diff' to be in your `exec-path'."
4273 (interactive "bBuffer: ")
4274 (with-current-buffer (get-buffer (or buffer (current-buffer)))
4275 (if (and buffer-file-name
4276 (file-exists-p buffer-file-name))
4277 (let ((tempfile (make-temp-file "buffer-content-")))
4278 (unwind-protect
4279 (progn
4280 (write-region nil nil tempfile nil 'nomessage)
4281 (diff buffer-file-name tempfile nil t)
4282 (sit-for 0))
4283 (when (file-exists-p tempfile)
4284 (delete-file tempfile))))
4285 (message "Buffer %s has no associated file on disc" (buffer-name))
4286 ;; Display that message for 1 second so that user can read it
4287 ;; in the minibuffer.
4288 (sit-for 1)))
4289 ;; return always nil, so that save-buffers-kill-emacs will not move
4290 ;; over to the next unsaved buffer when calling `d'.
4291 nil)
4292
4293 (defvar save-some-buffers-action-alist
4294 `((?\C-r
4295 ,(lambda (buf)
4296 (if (not enable-recursive-minibuffers)
4297 (progn (display-buffer buf)
4298 (setq other-window-scroll-buffer buf))
4299 (view-buffer buf (lambda (_) (exit-recursive-edit)))
4300 (recursive-edit))
4301 ;; Return nil to ask about BUF again.
4302 nil)
4303 "view this buffer")
4304 (?d ,(lambda (buf)
4305 (if (null buffer-file-name)
4306 (message "Not applicable: no file")
4307 (save-window-excursion (diff-buffer-with-file buf))
4308 (if (not enable-recursive-minibuffers)
4309 (progn (display-buffer (get-buffer-create "*Diff*"))
4310 (setq other-window-scroll-buffer "*Diff*"))
4311 (view-buffer (get-buffer-create "*Diff*")
4312 (lambda (_) (exit-recursive-edit)))
4313 (recursive-edit)))
4314 ;; Return nil to ask about BUF again.
4315 nil)
4316 "view changes in this buffer"))
4317 "ACTION-ALIST argument used in call to `map-y-or-n-p'.")
4318
4319 (defvar buffer-save-without-query nil
4320 "Non-nil means `save-some-buffers' should save this buffer without asking.")
4321 (make-variable-buffer-local 'buffer-save-without-query)
4322
4323 (defun save-some-buffers (&optional arg pred)
4324 "Save some modified file-visiting buffers. Asks user about each one.
4325 You can answer `y' to save, `n' not to save, `C-r' to look at the
4326 buffer in question with `view-buffer' before deciding or `d' to
4327 view the differences using `diff-buffer-with-file'.
4328
4329 Optional argument (the prefix) non-nil means save all with no questions.
4330 Optional second argument PRED determines which buffers are considered:
4331 If PRED is nil, all the file-visiting buffers are considered.
4332 If PRED is t, then certain non-file buffers will also be considered.
4333 If PRED is a zero-argument function, it indicates for each buffer whether
4334 to consider it or not when called with that buffer current.
4335
4336 See `save-some-buffers-action-alist' if you want to
4337 change the additional actions you can take on files."
4338 (interactive "P")
4339 (save-window-excursion
4340 (let* (queried some-automatic
4341 files-done abbrevs-done)
4342 (dolist (buffer (buffer-list))
4343 ;; First save any buffers that we're supposed to save unconditionally.
4344 ;; That way the following code won't ask about them.
4345 (with-current-buffer buffer
4346 (when (and buffer-save-without-query (buffer-modified-p))
4347 (setq some-automatic t)
4348 (save-buffer))))
4349 ;; Ask about those buffers that merit it,
4350 ;; and record the number thus saved.
4351 (setq files-done
4352 (map-y-or-n-p
4353 (lambda (buffer)
4354 (and (buffer-modified-p buffer)
4355 (not (buffer-base-buffer buffer))
4356 (or
4357 (buffer-file-name buffer)
4358 (and pred
4359 (progn
4360 (set-buffer buffer)
4361 (and buffer-offer-save (> (buffer-size) 0)))))
4362 (or (not (functionp pred))
4363 (with-current-buffer buffer (funcall pred)))
4364 (if arg
4365 t
4366 (setq queried t)
4367 (if (buffer-file-name buffer)
4368 (format "Save file %s? "
4369 (buffer-file-name buffer))
4370 (format "Save buffer %s? "
4371 (buffer-name buffer))))))
4372 (lambda (buffer)
4373 (with-current-buffer buffer
4374 (save-buffer)))
4375 (buffer-list)
4376 '("buffer" "buffers" "save")
4377 save-some-buffers-action-alist))
4378 ;; Maybe to save abbrevs, and record whether
4379 ;; we either saved them or asked to.
4380 (and save-abbrevs abbrevs-changed
4381 (progn
4382 (if (or arg
4383 (eq save-abbrevs 'silently)
4384 (y-or-n-p (format "Save abbrevs in %s? "
4385 abbrev-file-name)))
4386 (write-abbrev-file nil))
4387 ;; Don't keep bothering user if he says no.
4388 (setq abbrevs-changed nil)
4389 (setq abbrevs-done t)))
4390 (or queried (> files-done 0) abbrevs-done
4391 (message (if some-automatic
4392 "(Some special files were saved without asking)"
4393 "(No files need saving)"))))))
4394 \f
4395 (defun not-modified (&optional arg)
4396 "Mark current buffer as unmodified, not needing to be saved.
4397 With prefix ARG, mark buffer as modified, so \\[save-buffer] will save.
4398
4399 It is not a good idea to use this function in Lisp programs, because it
4400 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
4401 (interactive "P")
4402 (message (if arg "Modification-flag set"
4403 "Modification-flag cleared"))
4404 (set-buffer-modified-p arg))
4405
4406 (defun toggle-read-only (&optional arg)
4407 "Change whether this buffer is visiting its file read-only.
4408 With prefix argument ARG, make the buffer read-only if ARG is
4409 positive, otherwise make it writable. If visiting file read-only
4410 and `view-read-only' is non-nil, enter view mode."
4411 (interactive "P")
4412 (if (and arg
4413 (if (> (prefix-numeric-value arg) 0) buffer-read-only
4414 (not buffer-read-only))) ; If buffer-read-only is set correctly,
4415 nil ; do nothing.
4416 ;; Toggle.
4417 (cond
4418 ((and buffer-read-only view-mode)
4419 (View-exit-and-edit)
4420 (make-local-variable 'view-read-only)
4421 (setq view-read-only t)) ; Must leave view mode.
4422 ((and (not buffer-read-only) view-read-only
4423 ;; If view-mode is already active, `view-mode-enter' is a nop.
4424 (not view-mode)
4425 (not (eq (get major-mode 'mode-class) 'special)))
4426 (view-mode-enter))
4427 (t (setq buffer-read-only (not buffer-read-only))
4428 (force-mode-line-update)))
4429 (if (vc-backend buffer-file-name)
4430 (message "%s" (substitute-command-keys
4431 (concat "File is under version-control; "
4432 "use \\[vc-next-action] to check in/out"))))))
4433
4434 (defun insert-file (filename)
4435 "Insert contents of file FILENAME into buffer after point.
4436 Set mark after the inserted text.
4437
4438 This function is meant for the user to run interactively.
4439 Don't call it from programs! Use `insert-file-contents' instead.
4440 \(Its calling sequence is different; see its documentation)."
4441 (interactive "*fInsert file: ")
4442 (insert-file-1 filename #'insert-file-contents))
4443
4444 (defun append-to-file (start end filename)
4445 "Append the contents of the region to the end of file FILENAME.
4446 When called from a function, expects three arguments,
4447 START, END and FILENAME. START and END are buffer positions
4448 saying what text to write."
4449 (interactive "r\nFAppend to file: ")
4450 (write-region start end filename t))
4451
4452 (defun file-newest-backup (filename)
4453 "Return most recent backup file for FILENAME or nil if no backups exist."
4454 ;; `make-backup-file-name' will get us the right directory for
4455 ;; ordinary or numeric backups. It might create a directory for
4456 ;; backups as a side-effect, according to `backup-directory-alist'.
4457 (let* ((filename (file-name-sans-versions
4458 (make-backup-file-name (expand-file-name filename))))
4459 (file (file-name-nondirectory filename))
4460 (dir (file-name-directory filename))
4461 (comp (file-name-all-completions file dir))
4462 (newest nil)
4463 tem)
4464 (while comp
4465 (setq tem (pop comp))
4466 (cond ((and (backup-file-name-p tem)
4467 (string= (file-name-sans-versions tem) file))
4468 (setq tem (concat dir tem))
4469 (if (or (null newest)
4470 (file-newer-than-file-p tem newest))
4471 (setq newest tem)))))
4472 newest))
4473
4474 (defun rename-uniquely ()
4475 "Rename current buffer to a similar name not already taken.
4476 This function is useful for creating multiple shell process buffers
4477 or multiple mail buffers, etc."
4478 (interactive)
4479 (save-match-data
4480 (let ((base-name (buffer-name)))
4481 (and (string-match "<[0-9]+>\\'" base-name)
4482 (not (and buffer-file-name
4483 (string= base-name
4484 (file-name-nondirectory buffer-file-name))))
4485 ;; If the existing buffer name has a <NNN>,
4486 ;; which isn't part of the file name (if any),
4487 ;; then get rid of that.
4488 (setq base-name (substring base-name 0 (match-beginning 0))))
4489 (rename-buffer (generate-new-buffer-name base-name))
4490 (force-mode-line-update))))
4491
4492 (defun make-directory (dir &optional parents)
4493 "Create the directory DIR and any nonexistent parent dirs.
4494 If DIR already exists as a directory, signal an error, unless PARENTS is set.
4495
4496 Interactively, the default choice of directory to create
4497 is the current default directory for file names.
4498 That is useful when you have visited a file in a nonexistent directory.
4499
4500 Noninteractively, the second (optional) argument PARENTS says whether
4501 to create parent directories if they don't exist. Interactively,
4502 this happens by default."
4503 (interactive
4504 (list (read-file-name "Make directory: " default-directory default-directory
4505 nil nil)
4506 t))
4507 ;; If default-directory is a remote directory,
4508 ;; make sure we find its make-directory handler.
4509 (setq dir (expand-file-name dir))
4510 (let ((handler (find-file-name-handler dir 'make-directory)))
4511 (if handler
4512 (funcall handler 'make-directory dir parents)
4513 (if (not parents)
4514 (make-directory-internal dir)
4515 (let ((dir (directory-file-name (expand-file-name dir)))
4516 create-list)
4517 (while (not (file-exists-p dir))
4518 (setq create-list (cons dir create-list)
4519 dir (directory-file-name (file-name-directory dir))))
4520 (while create-list
4521 (make-directory-internal (car create-list))
4522 (setq create-list (cdr create-list))))))))
4523 \f
4524 (put 'revert-buffer-function 'permanent-local t)
4525 (defvar revert-buffer-function nil
4526 "Function to use to revert this buffer, or nil to do the default.
4527 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
4528 which are the arguments that `revert-buffer' received.")
4529
4530 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
4531 (defvar revert-buffer-insert-file-contents-function nil
4532 "Function to use to insert contents when reverting this buffer.
4533 Gets two args, first the nominal file name to use,
4534 and second, t if reading the auto-save file.
4535
4536 The function you specify is responsible for updating (or preserving) point.")
4537
4538 (defvar buffer-stale-function nil
4539 "Function to check whether a non-file buffer needs reverting.
4540 This should be a function with one optional argument NOCONFIRM.
4541 Auto Revert Mode passes t for NOCONFIRM. The function should return
4542 non-nil if the buffer should be reverted. A return value of
4543 `fast' means that the need for reverting was not checked, but
4544 that reverting the buffer is fast. The buffer is current when
4545 this function is called.
4546
4547 The idea behind the NOCONFIRM argument is that it should be
4548 non-nil if the buffer is going to be reverted without asking the
4549 user. In such situations, one has to be careful with potentially
4550 time consuming operations.
4551
4552 For more information on how this variable is used by Auto Revert mode,
4553 see Info node `(emacs)Supporting additional buffers'.")
4554
4555 (defvar before-revert-hook nil
4556 "Normal hook for `revert-buffer' to run before reverting.
4557 If `revert-buffer-function' is used to override the normal revert
4558 mechanism, this hook is not used.")
4559
4560 (defvar after-revert-hook nil
4561 "Normal hook for `revert-buffer' to run after reverting.
4562 Note that the hook value that it runs is the value that was in effect
4563 before reverting; that makes a difference if you have buffer-local
4564 hook functions.
4565
4566 If `revert-buffer-function' is used to override the normal revert
4567 mechanism, this hook is not used.")
4568
4569 (defvar revert-buffer-internal-hook)
4570
4571 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
4572 "Replace current buffer text with the text of the visited file on disk.
4573 This undoes all changes since the file was visited or saved.
4574 With a prefix argument, offer to revert from latest auto-save file, if
4575 that is more recent than the visited file.
4576
4577 This command also implements an interface for special buffers
4578 that contain text which doesn't come from a file, but reflects
4579 some other data instead (e.g. Dired buffers, `buffer-list'
4580 buffers). This is done via the variable `revert-buffer-function'.
4581 In these cases, it should reconstruct the buffer contents from the
4582 appropriate data.
4583
4584 When called from Lisp, the first argument is IGNORE-AUTO; only offer
4585 to revert from the auto-save file when this is nil. Note that the
4586 sense of this argument is the reverse of the prefix argument, for the
4587 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
4588 to nil.
4589
4590 Optional second argument NOCONFIRM means don't ask for confirmation
4591 at all. \(The variable `revert-without-query' offers another way to
4592 revert buffers without querying for confirmation.)
4593
4594 Optional third argument PRESERVE-MODES non-nil means don't alter
4595 the files modes. Normally we reinitialize them using `normal-mode'.
4596
4597 If the value of `revert-buffer-function' is non-nil, it is called to
4598 do all the work for this command. Otherwise, the hooks
4599 `before-revert-hook' and `after-revert-hook' are run at the beginning
4600 and the end, and if `revert-buffer-insert-file-contents-function' is
4601 non-nil, it is called instead of rereading visited file contents."
4602
4603 ;; I admit it's odd to reverse the sense of the prefix argument, but
4604 ;; there is a lot of code out there which assumes that the first
4605 ;; argument should be t to avoid consulting the auto-save file, and
4606 ;; there's no straightforward way to encourage authors to notice a
4607 ;; reversal of the argument sense. So I'm just changing the user
4608 ;; interface, but leaving the programmatic interface the same.
4609 (interactive (list (not current-prefix-arg)))
4610 (if revert-buffer-function
4611 (funcall revert-buffer-function ignore-auto noconfirm)
4612 (with-current-buffer (or (buffer-base-buffer (current-buffer))
4613 (current-buffer))
4614 (let* ((auto-save-p (and (not ignore-auto)
4615 (recent-auto-save-p)
4616 buffer-auto-save-file-name
4617 (file-readable-p buffer-auto-save-file-name)
4618 (y-or-n-p
4619 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
4620 (file-name (if auto-save-p
4621 buffer-auto-save-file-name
4622 buffer-file-name)))
4623 (cond ((null file-name)
4624 (error "Buffer does not seem to be associated with any file"))
4625 ((or noconfirm
4626 (and (not (buffer-modified-p))
4627 (catch 'found
4628 (dolist (regexp revert-without-query)
4629 (when (string-match regexp file-name)
4630 (throw 'found t)))))
4631 (yes-or-no-p (format "Revert buffer from file %s? "
4632 file-name)))
4633 (run-hooks 'before-revert-hook)
4634 ;; If file was backed up but has changed since,
4635 ;; we shd make another backup.
4636 (and (not auto-save-p)
4637 (not (verify-visited-file-modtime (current-buffer)))
4638 (setq buffer-backed-up nil))
4639 ;; Effectively copy the after-revert-hook status,
4640 ;; since after-find-file will clobber it.
4641 (let ((global-hook (default-value 'after-revert-hook))
4642 (local-hook (when (local-variable-p 'after-revert-hook)
4643 after-revert-hook))
4644 (inhibit-read-only t))
4645 (cond
4646 (revert-buffer-insert-file-contents-function
4647 (unless (eq buffer-undo-list t)
4648 ;; Get rid of all undo records for this buffer.
4649 (setq buffer-undo-list nil))
4650 ;; Don't make undo records for the reversion.
4651 (let ((buffer-undo-list t))
4652 (funcall revert-buffer-insert-file-contents-function
4653 file-name auto-save-p)))
4654 ((not (file-exists-p file-name))
4655 (error (if buffer-file-number
4656 "File %s no longer exists!"
4657 "Cannot revert nonexistent file %s")
4658 file-name))
4659 ((not (file-readable-p file-name))
4660 (error (if buffer-file-number
4661 "File %s no longer readable!"
4662 "Cannot revert unreadable file %s")
4663 file-name))
4664 (t
4665 ;; Bind buffer-file-name to nil
4666 ;; so that we don't try to lock the file.
4667 (let ((buffer-file-name nil))
4668 (or auto-save-p
4669 (unlock-buffer)))
4670 (widen)
4671 (let ((coding-system-for-read
4672 ;; Auto-saved file should be read by Emacs'
4673 ;; internal coding.
4674 (if auto-save-p 'auto-save-coding
4675 (or coding-system-for-read
4676 buffer-file-coding-system-explicit))))
4677 (if (and (not enable-multibyte-characters)
4678 coding-system-for-read
4679 (not (memq (coding-system-base
4680 coding-system-for-read)
4681 '(no-conversion raw-text))))
4682 ;; As a coding system suitable for multibyte
4683 ;; buffer is specified, make the current
4684 ;; buffer multibyte.
4685 (set-buffer-multibyte t))
4686
4687 ;; This force after-insert-file-set-coding
4688 ;; (called from insert-file-contents) to set
4689 ;; buffer-file-coding-system to a proper value.
4690 (kill-local-variable 'buffer-file-coding-system)
4691
4692 ;; Note that this preserves point in an intelligent way.
4693 (if preserve-modes
4694 (let ((buffer-file-format buffer-file-format))
4695 (insert-file-contents file-name (not auto-save-p)
4696 nil nil t))
4697 (insert-file-contents file-name (not auto-save-p)
4698 nil nil t)))))
4699 ;; Recompute the truename in case changes in symlinks
4700 ;; have changed the truename.
4701 (setq buffer-file-truename
4702 (abbreviate-file-name (file-truename buffer-file-name)))
4703 (after-find-file nil nil t t preserve-modes)
4704 ;; Run after-revert-hook as it was before we reverted.
4705 (setq-default revert-buffer-internal-hook global-hook)
4706 (if local-hook
4707 (set (make-local-variable 'revert-buffer-internal-hook)
4708 local-hook)
4709 (kill-local-variable 'revert-buffer-internal-hook))
4710 (run-hooks 'revert-buffer-internal-hook))
4711 t))))))
4712
4713 (defun recover-this-file ()
4714 "Recover the visited file--get contents from its last auto-save file."
4715 (interactive)
4716 (recover-file buffer-file-name))
4717
4718 (defun recover-file (file)
4719 "Visit file FILE, but get contents from its last auto-save file."
4720 ;; Actually putting the file name in the minibuffer should be used
4721 ;; only rarely.
4722 ;; Not just because users often use the default.
4723 (interactive "FRecover file: ")
4724 (setq file (expand-file-name file))
4725 (if (auto-save-file-name-p (file-name-nondirectory file))
4726 (error "%s is an auto-save file" (abbreviate-file-name file)))
4727 (let ((file-name (let ((buffer-file-name file))
4728 (make-auto-save-file-name))))
4729 (cond ((if (file-exists-p file)
4730 (not (file-newer-than-file-p file-name file))
4731 (not (file-exists-p file-name)))
4732 (error "Auto-save file %s not current"
4733 (abbreviate-file-name file-name)))
4734 ((save-window-excursion
4735 (with-output-to-temp-buffer "*Directory*"
4736 (buffer-disable-undo standard-output)
4737 (save-excursion
4738 (let ((switches dired-listing-switches))
4739 (if (file-symlink-p file)
4740 (setq switches (concat switches "L")))
4741 (set-buffer standard-output)
4742 ;; Use insert-directory-safely, not insert-directory,
4743 ;; because these files might not exist. In particular,
4744 ;; FILE might not exist if the auto-save file was for
4745 ;; a buffer that didn't visit a file, such as "*mail*".
4746 ;; The code in v20.x called `ls' directly, so we need
4747 ;; to emulate what `ls' did in that case.
4748 (insert-directory-safely file switches)
4749 (insert-directory-safely file-name switches))))
4750 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
4751 (switch-to-buffer (find-file-noselect file t))
4752 (let ((inhibit-read-only t)
4753 ;; Keep the current buffer-file-coding-system.
4754 (coding-system buffer-file-coding-system)
4755 ;; Auto-saved file should be read with special coding.
4756 (coding-system-for-read 'auto-save-coding))
4757 (erase-buffer)
4758 (insert-file-contents file-name nil)
4759 (set-buffer-file-coding-system coding-system))
4760 (after-find-file nil nil t))
4761 (t (error "Recover-file cancelled")))))
4762
4763 (defun recover-session ()
4764 "Recover auto save files from a previous Emacs session.
4765 This command first displays a Dired buffer showing you the
4766 previous sessions that you could recover from.
4767 To choose one, move point to the proper line and then type C-c C-c.
4768 Then you'll be asked about a number of files to recover."
4769 (interactive)
4770 (if (null auto-save-list-file-prefix)
4771 (error "You set `auto-save-list-file-prefix' to disable making session files"))
4772 (let ((dir (file-name-directory auto-save-list-file-prefix)))
4773 (unless (file-directory-p dir)
4774 (make-directory dir t))
4775 (unless (directory-files dir nil
4776 (concat "\\`" (regexp-quote
4777 (file-name-nondirectory
4778 auto-save-list-file-prefix)))
4779 t)
4780 (error "No previous sessions to recover")))
4781 (let ((ls-lisp-support-shell-wildcards t))
4782 (dired (concat auto-save-list-file-prefix "*")
4783 (concat dired-listing-switches "t")))
4784 (save-excursion
4785 (goto-char (point-min))
4786 (or (looking-at " Move to the session you want to recover,")
4787 (let ((inhibit-read-only t))
4788 ;; Each line starts with a space
4789 ;; so that Font Lock mode won't highlight the first character.
4790 (insert " Move to the session you want to recover,\n"
4791 " then type C-c C-c to select it.\n\n"
4792 " You can also delete some of these files;\n"
4793 " type d on a line to mark that file for deletion.\n\n"))))
4794 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
4795 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
4796
4797 (defun recover-session-finish ()
4798 "Choose one saved session to recover auto-save files from.
4799 This command is used in the special Dired buffer created by
4800 \\[recover-session]."
4801 (interactive)
4802 ;; Get the name of the session file to recover from.
4803 (let ((file (dired-get-filename))
4804 files
4805 (buffer (get-buffer-create " *recover*")))
4806 (dired-unmark 1)
4807 (dired-do-flagged-delete t)
4808 (unwind-protect
4809 (save-excursion
4810 ;; Read in the auto-save-list file.
4811 (set-buffer buffer)
4812 (erase-buffer)
4813 (insert-file-contents file)
4814 ;; Loop thru the text of that file
4815 ;; and get out the names of the files to recover.
4816 (while (not (eobp))
4817 (let (thisfile autofile)
4818 (if (eolp)
4819 ;; This is a pair of lines for a non-file-visiting buffer.
4820 ;; Get the auto-save file name and manufacture
4821 ;; a "visited file name" from that.
4822 (progn
4823 (forward-line 1)
4824 ;; If there is no auto-save file name, the
4825 ;; auto-save-list file is probably corrupted.
4826 (unless (eolp)
4827 (setq autofile
4828 (buffer-substring-no-properties
4829 (point)
4830 (line-end-position)))
4831 (setq thisfile
4832 (expand-file-name
4833 (substring
4834 (file-name-nondirectory autofile)
4835 1 -1)
4836 (file-name-directory autofile))))
4837 (forward-line 1))
4838 ;; This pair of lines is a file-visiting
4839 ;; buffer. Use the visited file name.
4840 (progn
4841 (setq thisfile
4842 (buffer-substring-no-properties
4843 (point) (progn (end-of-line) (point))))
4844 (forward-line 1)
4845 (setq autofile
4846 (buffer-substring-no-properties
4847 (point) (progn (end-of-line) (point))))
4848 (forward-line 1)))
4849 ;; Ignore a file if its auto-save file does not exist now.
4850 (if (and autofile (file-exists-p autofile))
4851 (setq files (cons thisfile files)))))
4852 (setq files (nreverse files))
4853 ;; The file contains a pair of line for each auto-saved buffer.
4854 ;; The first line of the pair contains the visited file name
4855 ;; or is empty if the buffer was not visiting a file.
4856 ;; The second line is the auto-save file name.
4857 (if files
4858 (map-y-or-n-p "Recover %s? "
4859 (lambda (file)
4860 (condition-case nil
4861 (save-excursion (recover-file file))
4862 (error
4863 "Failed to recover `%s'" file)))
4864 files
4865 '("file" "files" "recover"))
4866 (message "No files can be recovered from this session now")))
4867 (kill-buffer buffer))))
4868
4869 (defun kill-buffer-ask (buffer)
4870 "Kill BUFFER if confirmed."
4871 (when (yes-or-no-p
4872 (format "Buffer %s %s. Kill? " (buffer-name buffer)
4873 (if (buffer-modified-p buffer)
4874 "HAS BEEN EDITED" "is unmodified")))
4875 (kill-buffer buffer)))
4876
4877 (defun kill-some-buffers (&optional list)
4878 "Kill some buffers. Asks the user whether to kill each one of them.
4879 Non-interactively, if optional argument LIST is non-nil, it
4880 specifies the list of buffers to kill, asking for approval for each one."
4881 (interactive)
4882 (if (null list)
4883 (setq list (buffer-list)))
4884 (while list
4885 (let* ((buffer (car list))
4886 (name (buffer-name buffer)))
4887 (and name ; Can be nil for an indirect buffer
4888 ; if we killed the base buffer.
4889 (not (string-equal name ""))
4890 (/= (aref name 0) ?\s)
4891 (kill-buffer-ask buffer)))
4892 (setq list (cdr list))))
4893
4894 (defun kill-matching-buffers (regexp &optional internal-too)
4895 "Kill buffers whose name matches the specified REGEXP.
4896 The optional second argument indicates whether to kill internal buffers too."
4897 (interactive "sKill buffers matching this regular expression: \nP")
4898 (dolist (buffer (buffer-list))
4899 (let ((name (buffer-name buffer)))
4900 (when (and name (not (string-equal name ""))
4901 (or internal-too (/= (aref name 0) ?\s))
4902 (string-match regexp name))
4903 (kill-buffer-ask buffer)))))
4904
4905 \f
4906 (defun auto-save-mode (arg)
4907 "Toggle auto-saving of contents of current buffer.
4908 With prefix argument ARG, turn auto-saving on if positive, else off."
4909 (interactive "P")
4910 (setq buffer-auto-save-file-name
4911 (and (if (null arg)
4912 (or (not buffer-auto-save-file-name)
4913 ;; If auto-save is off because buffer has shrunk,
4914 ;; then toggling should turn it on.
4915 (< buffer-saved-size 0))
4916 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
4917 (if (and buffer-file-name auto-save-visited-file-name
4918 (not buffer-read-only))
4919 buffer-file-name
4920 (make-auto-save-file-name))))
4921 ;; If -1 was stored here, to temporarily turn off saving,
4922 ;; turn it back on.
4923 (and (< buffer-saved-size 0)
4924 (setq buffer-saved-size 0))
4925 (if (interactive-p)
4926 (message "Auto-save %s (in this buffer)"
4927 (if buffer-auto-save-file-name "on" "off")))
4928 buffer-auto-save-file-name)
4929
4930 (defun rename-auto-save-file ()
4931 "Adjust current buffer's auto save file name for current conditions.
4932 Also rename any existing auto save file, if it was made in this session."
4933 (let ((osave buffer-auto-save-file-name))
4934 (setq buffer-auto-save-file-name
4935 (make-auto-save-file-name))
4936 (if (and osave buffer-auto-save-file-name
4937 (not (string= buffer-auto-save-file-name buffer-file-name))
4938 (not (string= buffer-auto-save-file-name osave))
4939 (file-exists-p osave)
4940 (recent-auto-save-p))
4941 (rename-file osave buffer-auto-save-file-name t))))
4942
4943 (defun make-auto-save-file-name ()
4944 "Return file name to use for auto-saves of current buffer.
4945 Does not consider `auto-save-visited-file-name' as that variable is checked
4946 before calling this function. You can redefine this for customization.
4947 See also `auto-save-file-name-p'."
4948 (if buffer-file-name
4949 (let ((handler (find-file-name-handler buffer-file-name
4950 'make-auto-save-file-name)))
4951 (if handler
4952 (funcall handler 'make-auto-save-file-name)
4953 (let ((list auto-save-file-name-transforms)
4954 (filename buffer-file-name)
4955 result uniq)
4956 ;; Apply user-specified translations
4957 ;; to the file name.
4958 (while (and list (not result))
4959 (if (string-match (car (car list)) filename)
4960 (setq result (replace-match (cadr (car list)) t nil
4961 filename)
4962 uniq (car (cddr (car list)))))
4963 (setq list (cdr list)))
4964 (if result
4965 (if uniq
4966 (setq filename (concat
4967 (file-name-directory result)
4968 (subst-char-in-string
4969 ?/ ?!
4970 (replace-regexp-in-string "!" "!!"
4971 filename))))
4972 (setq filename result)))
4973 (setq result
4974 (if (and (eq system-type 'ms-dos)
4975 (not (msdos-long-file-names)))
4976 ;; We truncate the file name to DOS 8+3 limits
4977 ;; before doing anything else, because the regexp
4978 ;; passed to string-match below cannot handle
4979 ;; extensions longer than 3 characters, multiple
4980 ;; dots, and other atrocities.
4981 (let ((fn (dos-8+3-filename
4982 (file-name-nondirectory buffer-file-name))))
4983 (string-match
4984 "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'"
4985 fn)
4986 (concat (file-name-directory buffer-file-name)
4987 "#" (match-string 1 fn)
4988 "." (match-string 3 fn) "#"))
4989 (concat (file-name-directory filename)
4990 "#"
4991 (file-name-nondirectory filename)
4992 "#")))
4993 ;; Make sure auto-save file names don't contain characters
4994 ;; invalid for the underlying filesystem.
4995 (if (and (memq system-type '(ms-dos windows-nt cygwin))
4996 ;; Don't modify remote (ange-ftp) filenames
4997 (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" result)))
4998 (convert-standard-filename result)
4999 result))))
5000
5001 ;; Deal with buffers that don't have any associated files. (Mail
5002 ;; mode tends to create a good number of these.)
5003
5004 (let ((buffer-name (buffer-name))
5005 (limit 0)
5006 file-name)
5007 ;; Restrict the characters used in the file name to those which
5008 ;; are known to be safe on all filesystems, url-encoding the
5009 ;; rest.
5010 ;; We do this on all platforms, because even if we are not
5011 ;; running on DOS/Windows, the current directory may be on a
5012 ;; mounted VFAT filesystem, such as a USB memory stick.
5013 (while (string-match "[^A-Za-z0-9-_.~#+]" buffer-name limit)
5014 (let* ((character (aref buffer-name (match-beginning 0)))
5015 (replacement
5016 ;; For multibyte characters, this will produce more than
5017 ;; 2 hex digits, so is not true URL encoding.
5018 (format "%%%02X" character)))
5019 (setq buffer-name (replace-match replacement t t buffer-name))
5020 (setq limit (1+ (match-end 0)))))
5021 ;; Generate the file name.
5022 (setq file-name
5023 (make-temp-file
5024 (let ((fname
5025 (expand-file-name
5026 (format "#%s#" buffer-name)
5027 ;; Try a few alternative directories, to get one we can
5028 ;; write it.
5029 (cond
5030 ((file-writable-p default-directory) default-directory)
5031 ((file-writable-p "/var/tmp/") "/var/tmp/")
5032 ("~/")))))
5033 (if (and (memq system-type '(ms-dos windows-nt cygwin))
5034 ;; Don't modify remote (ange-ftp) filenames
5035 (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" fname)))
5036 ;; The call to convert-standard-filename is in case
5037 ;; buffer-name includes characters not allowed by the
5038 ;; DOS/Windows filesystems. make-temp-file writes to the
5039 ;; file it creates, so we must fix the file name _before_
5040 ;; make-temp-file is called.
5041 (convert-standard-filename fname)
5042 fname))
5043 nil "#"))
5044 ;; make-temp-file creates the file,
5045 ;; but we don't want it to exist until we do an auto-save.
5046 (condition-case ()
5047 (delete-file file-name)
5048 (file-error nil))
5049 file-name)))
5050
5051 (defun auto-save-file-name-p (filename)
5052 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
5053 FILENAME should lack slashes. You can redefine this for customization."
5054 (string-match "^#.*#$" filename))
5055 \f
5056 (defun wildcard-to-regexp (wildcard)
5057 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
5058 The generated regexp will match a filename only if the filename
5059 matches that wildcard according to shell rules. Only wildcards known
5060 by `sh' are supported."
5061 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
5062 ;; Copy the initial run of non-special characters.
5063 (result (substring wildcard 0 i))
5064 (len (length wildcard)))
5065 ;; If no special characters, we're almost done.
5066 (if i
5067 (while (< i len)
5068 (let ((ch (aref wildcard i))
5069 j)
5070 (setq
5071 result
5072 (concat result
5073 (cond
5074 ((and (eq ch ?\[)
5075 (< (1+ i) len)
5076 (eq (aref wildcard (1+ i)) ?\]))
5077 "\\[")
5078 ((eq ch ?\[) ; [...] maps to regexp char class
5079 (progn
5080 (setq i (1+ i))
5081 (concat
5082 (cond
5083 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
5084 (progn
5085 (setq i (1+ i))
5086 (if (eq (aref wildcard i) ?\])
5087 (progn
5088 (setq i (1+ i))
5089 "[^]")
5090 "[^")))
5091 ((eq (aref wildcard i) ?^)
5092 ;; Found "[^". Insert a `\0' character
5093 ;; (which cannot happen in a filename)
5094 ;; into the character class, so that `^'
5095 ;; is not the first character after `[',
5096 ;; and thus non-special in a regexp.
5097 (progn
5098 (setq i (1+ i))
5099 "[\000^"))
5100 ((eq (aref wildcard i) ?\])
5101 ;; I don't think `]' can appear in a
5102 ;; character class in a wildcard, but
5103 ;; let's be general here.
5104 (progn
5105 (setq i (1+ i))
5106 "[]"))
5107 (t "["))
5108 (prog1 ; copy everything upto next `]'.
5109 (substring wildcard
5110 i
5111 (setq j (string-match
5112 "]" wildcard i)))
5113 (setq i (if j (1- j) (1- len)))))))
5114 ((eq ch ?.) "\\.")
5115 ((eq ch ?*) "[^\000]*")
5116 ((eq ch ?+) "\\+")
5117 ((eq ch ?^) "\\^")
5118 ((eq ch ?$) "\\$")
5119 ((eq ch ?\\) "\\\\") ; probably cannot happen...
5120 ((eq ch ??) "[^\000]")
5121 (t (char-to-string ch)))))
5122 (setq i (1+ i)))))
5123 ;; Shell wildcards should match the entire filename,
5124 ;; not its part. Make the regexp say so.
5125 (concat "\\`" result "\\'")))
5126 \f
5127 (defcustom list-directory-brief-switches
5128 "-CF"
5129 "Switches for `list-directory' to pass to `ls' for brief listing."
5130 :type 'string
5131 :group 'dired)
5132
5133 (defcustom list-directory-verbose-switches
5134 "-l"
5135 "Switches for `list-directory' to pass to `ls' for verbose listing."
5136 :type 'string
5137 :group 'dired)
5138
5139 (defun file-expand-wildcards (pattern &optional full)
5140 "Expand wildcard pattern PATTERN.
5141 This returns a list of file names which match the pattern.
5142
5143 If PATTERN is written as an absolute file name,
5144 the values are absolute also.
5145
5146 If PATTERN is written as a relative file name, it is interpreted
5147 relative to the current default directory, `default-directory'.
5148 The file names returned are normally also relative to the current
5149 default directory. However, if FULL is non-nil, they are absolute."
5150 (save-match-data
5151 (let* ((nondir (file-name-nondirectory pattern))
5152 (dirpart (file-name-directory pattern))
5153 ;; A list of all dirs that DIRPART specifies.
5154 ;; This can be more than one dir
5155 ;; if DIRPART contains wildcards.
5156 (dirs (if (and dirpart (string-match "[[*?]" dirpart))
5157 (mapcar 'file-name-as-directory
5158 (file-expand-wildcards (directory-file-name dirpart)))
5159 (list dirpart)))
5160 contents)
5161 (while dirs
5162 (when (or (null (car dirs)) ; Possible if DIRPART is not wild.
5163 (file-directory-p (directory-file-name (car dirs))))
5164 (let ((this-dir-contents
5165 ;; Filter out "." and ".."
5166 (delq nil
5167 (mapcar #'(lambda (name)
5168 (unless (string-match "\\`\\.\\.?\\'"
5169 (file-name-nondirectory name))
5170 name))
5171 (directory-files (or (car dirs) ".") full
5172 (wildcard-to-regexp nondir))))))
5173 (setq contents
5174 (nconc
5175 (if (and (car dirs) (not full))
5176 (mapcar (function (lambda (name) (concat (car dirs) name)))
5177 this-dir-contents)
5178 this-dir-contents)
5179 contents))))
5180 (setq dirs (cdr dirs)))
5181 contents)))
5182
5183 (defun list-directory (dirname &optional verbose)
5184 "Display a list of files in or matching DIRNAME, a la `ls'.
5185 DIRNAME is globbed by the shell if necessary.
5186 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
5187 Actions controlled by variables `list-directory-brief-switches'
5188 and `list-directory-verbose-switches'."
5189 (interactive (let ((pfx current-prefix-arg))
5190 (list (read-file-name (if pfx "List directory (verbose): "
5191 "List directory (brief): ")
5192 nil default-directory nil)
5193 pfx)))
5194 (let ((switches (if verbose list-directory-verbose-switches
5195 list-directory-brief-switches))
5196 buffer)
5197 (or dirname (setq dirname default-directory))
5198 (setq dirname (expand-file-name dirname))
5199 (with-output-to-temp-buffer "*Directory*"
5200 (setq buffer standard-output)
5201 (buffer-disable-undo standard-output)
5202 (princ "Directory ")
5203 (princ dirname)
5204 (terpri)
5205 (save-excursion
5206 (set-buffer "*Directory*")
5207 (let ((wildcard (not (file-directory-p dirname))))
5208 (insert-directory dirname switches wildcard (not wildcard)))))
5209 ;; Finishing with-output-to-temp-buffer seems to clobber default-directory.
5210 (with-current-buffer buffer
5211 (setq default-directory
5212 (if (file-directory-p dirname)
5213 (file-name-as-directory dirname)
5214 (file-name-directory dirname))))))
5215
5216 (defun shell-quote-wildcard-pattern (pattern)
5217 "Quote characters special to the shell in PATTERN, leave wildcards alone.
5218
5219 PATTERN is assumed to represent a file-name wildcard suitable for the
5220 underlying filesystem. For Unix and GNU/Linux, the characters from the
5221 set [ \\t\\n;<>&|()'\"#$] are quoted with a backslash; for DOS/Windows, all
5222 the parts of the pattern which don't include wildcard characters are
5223 quoted with double quotes.
5224 Existing quote characters in PATTERN are left alone, so you can pass
5225 PATTERN that already quotes some of the special characters."
5226 (save-match-data
5227 (cond
5228 ((memq system-type '(ms-dos windows-nt cygwin))
5229 ;; DOS/Windows don't allow `"' in file names. So if the
5230 ;; argument has quotes, we can safely assume it is already
5231 ;; quoted by the caller.
5232 (if (or (string-match "[\"]" pattern)
5233 ;; We quote [&()#$'] in case their shell is a port of a
5234 ;; Unixy shell. We quote [,=+] because stock DOS and
5235 ;; Windows shells require that in some cases, such as
5236 ;; passing arguments to batch files that use positional
5237 ;; arguments like %1.
5238 (not (string-match "[ \t;&()#$',=+]" pattern)))
5239 pattern
5240 (let ((result "\"")
5241 (beg 0)
5242 end)
5243 (while (string-match "[*?]+" pattern beg)
5244 (setq end (match-beginning 0)
5245 result (concat result (substring pattern beg end)
5246 "\""
5247 (substring pattern end (match-end 0))
5248 "\"")
5249 beg (match-end 0)))
5250 (concat result (substring pattern beg) "\""))))
5251 (t
5252 (let ((beg 0))
5253 (while (string-match "[ \t\n;<>&|()'\"#$]" pattern beg)
5254 (setq pattern
5255 (concat (substring pattern 0 (match-beginning 0))
5256 "\\"
5257 (substring pattern (match-beginning 0)))
5258 beg (1+ (match-end 0)))))
5259 pattern))))
5260
5261
5262 (defvar insert-directory-program "ls"
5263 "Absolute or relative name of the `ls' program used by `insert-directory'.")
5264
5265 (defcustom directory-free-space-program "df"
5266 "Program to get the amount of free space on a file system.
5267 We assume the output has the format of `df'.
5268 The value of this variable must be just a command name or file name;
5269 if you want to specify options, use `directory-free-space-args'.
5270
5271 A value of nil disables this feature.
5272
5273 If the function `file-system-info' is defined, it is always used in
5274 preference to the program given by this variable."
5275 :type '(choice (string :tag "Program") (const :tag "None" nil))
5276 :group 'dired)
5277
5278 (defcustom directory-free-space-args
5279 (if (eq system-type 'darwin) "-k" "-Pk")
5280 "Options to use when running `directory-free-space-program'."
5281 :type 'string
5282 :group 'dired)
5283
5284 (defun get-free-disk-space (dir)
5285 "Return the amount of free space on directory DIR's file system.
5286 The result is a string that gives the number of free 1KB blocks,
5287 or nil if the system call or the program which retrieve the information
5288 fail. It returns also nil when DIR is a remote directory.
5289
5290 This function calls `file-system-info' if it is available, or invokes the
5291 program specified by `directory-free-space-program' if that is non-nil."
5292 (when (not (file-remote-p dir))
5293 ;; Try to find the number of free blocks. Non-Posix systems don't
5294 ;; always have df, but might have an equivalent system call.
5295 (if (fboundp 'file-system-info)
5296 (let ((fsinfo (file-system-info dir)))
5297 (if fsinfo
5298 (format "%.0f" (/ (nth 2 fsinfo) 1024))))
5299 (save-match-data
5300 (with-temp-buffer
5301 (when (and directory-free-space-program
5302 (eq 0 (call-process directory-free-space-program
5303 nil t nil
5304 directory-free-space-args
5305 dir)))
5306 ;; Usual format is a header line followed by a line of
5307 ;; numbers.
5308 (goto-char (point-min))
5309 (forward-line 1)
5310 (if (not (eobp))
5311 (progn
5312 ;; Move to the end of the "available blocks" number.
5313 (skip-chars-forward "^ \t")
5314 (forward-word 3)
5315 ;; Copy it into AVAILABLE.
5316 (let ((end (point)))
5317 (forward-word -1)
5318 (buffer-substring (point) end))))))))))
5319
5320 ;; The following expression replaces `dired-move-to-filename-regexp'.
5321 (defvar directory-listing-before-filename-regexp
5322 (let* ((l "\\([A-Za-z]\\|[^\0-\177]\\)")
5323 (l-or-quote "\\([A-Za-z']\\|[^\0-\177]\\)")
5324 ;; In some locales, month abbreviations are as short as 2 letters,
5325 ;; and they can be followed by ".".
5326 ;; In Breton, a month name can include a quote character.
5327 (month (concat l-or-quote l-or-quote "+\\.?"))
5328 (s " ")
5329 (yyyy "[0-9][0-9][0-9][0-9]")
5330 (dd "[ 0-3][0-9]")
5331 (HH:MM "[ 0-2][0-9][:.][0-5][0-9]")
5332 (seconds "[0-6][0-9]\\([.,][0-9]+\\)?")
5333 (zone "[-+][0-2][0-9][0-5][0-9]")
5334 (iso-mm-dd "[01][0-9]-[0-3][0-9]")
5335 (iso-time (concat HH:MM "\\(:" seconds "\\( ?" zone "\\)?\\)?"))
5336 (iso (concat "\\(\\(" yyyy "-\\)?" iso-mm-dd "[ T]" iso-time
5337 "\\|" yyyy "-" iso-mm-dd "\\)"))
5338 (western (concat "\\(" month s "+" dd "\\|" dd "\\.?" s month "\\)"
5339 s "+"
5340 "\\(" HH:MM "\\|" yyyy "\\)"))
5341 (western-comma (concat month s "+" dd "," s "+" yyyy))
5342 ;; Japanese MS-Windows ls-lisp has one-digit months, and
5343 ;; omits the Kanji characters after month and day-of-month.
5344 ;; On Mac OS X 10.3, the date format in East Asian locales is
5345 ;; day-of-month digits followed by month digits.
5346 (mm "[ 0-1]?[0-9]")
5347 (east-asian
5348 (concat "\\(" mm l "?" s dd l "?" s "+"
5349 "\\|" dd s mm s "+" "\\)"
5350 "\\(" HH:MM "\\|" yyyy l "?" "\\)")))
5351 ;; The "[0-9]" below requires the previous column to end in a digit.
5352 ;; This avoids recognizing `1 may 1997' as a date in the line:
5353 ;; -r--r--r-- 1 may 1997 1168 Oct 19 16:49 README
5354
5355 ;; The "[BkKMGTPEZY]?" below supports "ls -alh" output.
5356 ;; The ".*" below finds the last match if there are multiple matches.
5357 ;; This avoids recognizing `jservice 10 1024' as a date in the line:
5358 ;; drwxr-xr-x 3 jservice 10 1024 Jul 2 1997 esg-host
5359
5360 ;; vc dired listings provide the state or blanks between file
5361 ;; permissions and date. The state is always surrounded by
5362 ;; parantheses:
5363 ;; -rw-r--r-- (modified) 2005-10-22 21:25 files.el
5364 ;; This is not supported yet.
5365 (concat ".*[0-9][BkKMGTPEZY]?" s
5366 "\\(" western "\\|" western-comma "\\|" east-asian "\\|" iso "\\)"
5367 s "+"))
5368 "Regular expression to match up to the file name in a directory listing.
5369 The default value is designed to recognize dates and times
5370 regardless of the language.")
5371
5372 (defvar insert-directory-ls-version 'unknown)
5373
5374 ;; insert-directory
5375 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
5376 ;; FULL-DIRECTORY-P is nil.
5377 ;; The single line of output must display FILE's name as it was
5378 ;; given, namely, an absolute path name.
5379 ;; - must insert exactly one line for each file if WILDCARD or
5380 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
5381 ;; before the file lines, plus optional text after the file lines.
5382 ;; Lines are delimited by "\n", so filenames containing "\n" are not
5383 ;; allowed.
5384 ;; File lines should display the basename.
5385 ;; - must be consistent with
5386 ;; - functions dired-move-to-filename, (these two define what a file line is)
5387 ;; dired-move-to-end-of-filename,
5388 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
5389 ;; dired-insert-headerline
5390 ;; dired-after-subdir-garbage (defines what a "total" line is)
5391 ;; - variable dired-subdir-regexp
5392 ;; - may be passed "--dired" as the first argument in SWITCHES.
5393 ;; Filename handlers might have to remove this switch if their
5394 ;; "ls" command does not support it.
5395 (defun insert-directory (file switches &optional wildcard full-directory-p)
5396 "Insert directory listing for FILE, formatted according to SWITCHES.
5397 Leaves point after the inserted text.
5398 SWITCHES may be a string of options, or a list of strings
5399 representing individual options.
5400 Optional third arg WILDCARD means treat FILE as shell wildcard.
5401 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
5402 switches do not contain `d', so that a full listing is expected.
5403
5404 This works by running a directory listing program
5405 whose name is in the variable `insert-directory-program'.
5406 If WILDCARD, it also runs the shell specified by `shell-file-name'.
5407
5408 When SWITCHES contains the long `--dired' option, this function
5409 treats it specially, for the sake of dired. However, the
5410 normally equivalent short `-D' option is just passed on to
5411 `insert-directory-program', as any other option."
5412 ;; We need the directory in order to find the right handler.
5413 (let ((handler (find-file-name-handler (expand-file-name file)
5414 'insert-directory)))
5415 (if handler
5416 (funcall handler 'insert-directory file switches
5417 wildcard full-directory-p)
5418 (let (result (beg (point)))
5419
5420 ;; Read the actual directory using `insert-directory-program'.
5421 ;; RESULT gets the status code.
5422 (let* (;; We at first read by no-conversion, then after
5423 ;; putting text property `dired-filename, decode one
5424 ;; bunch by one to preserve that property.
5425 (coding-system-for-read 'no-conversion)
5426 ;; This is to control encoding the arguments in call-process.
5427 (coding-system-for-write
5428 (and enable-multibyte-characters
5429 (or file-name-coding-system
5430 default-file-name-coding-system))))
5431 (setq result
5432 (if wildcard
5433 ;; Run ls in the directory part of the file pattern
5434 ;; using the last component as argument.
5435 (let ((default-directory
5436 (if (file-name-absolute-p file)
5437 (file-name-directory file)
5438 (file-name-directory (expand-file-name file))))
5439 (pattern (file-name-nondirectory file)))
5440 (call-process
5441 shell-file-name nil t nil
5442 "-c"
5443 (concat (if (memq system-type '(ms-dos windows-nt))
5444 ""
5445 "\\") ; Disregard Unix shell aliases!
5446 insert-directory-program
5447 " -d "
5448 (if (stringp switches)
5449 switches
5450 (mapconcat 'identity switches " "))
5451 " -- "
5452 ;; Quote some characters that have
5453 ;; special meanings in shells; but
5454 ;; don't quote the wildcards--we want
5455 ;; them to be special. We also
5456 ;; currently don't quote the quoting
5457 ;; characters in case people want to
5458 ;; use them explicitly to quote
5459 ;; wildcard characters.
5460 (shell-quote-wildcard-pattern pattern))))
5461 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
5462 ;; directory if FILE is a symbolic link.
5463 (apply 'call-process
5464 insert-directory-program nil t nil
5465 (append
5466 (if (listp switches) switches
5467 (unless (equal switches "")
5468 ;; Split the switches at any spaces so we can
5469 ;; pass separate options as separate args.
5470 (split-string switches)))
5471 ;; Avoid lossage if FILE starts with `-'.
5472 '("--")
5473 (progn
5474 (if (string-match "\\`~" file)
5475 (setq file (expand-file-name file)))
5476 (list
5477 (if full-directory-p
5478 (concat (file-name-as-directory file) ".")
5479 file))))))))
5480
5481 ;; If we got "//DIRED//" in the output, it means we got a real
5482 ;; directory listing, even if `ls' returned nonzero.
5483 ;; So ignore any errors.
5484 (when (if (stringp switches)
5485 (string-match "--dired\\>" switches)
5486 (member "--dired" switches))
5487 (save-excursion
5488 (forward-line -2)
5489 (when (looking-at "//SUBDIRED//")
5490 (forward-line -1))
5491 (if (looking-at "//DIRED//")
5492 (setq result 0))))
5493
5494 (when (and (not (eq 0 result))
5495 (eq insert-directory-ls-version 'unknown))
5496 ;; The first time ls returns an error,
5497 ;; find the version numbers of ls,
5498 ;; and set insert-directory-ls-version
5499 ;; to > if it is more than 5.2.1, < if it is less, nil if it
5500 ;; is equal or if the info cannot be obtained.
5501 ;; (That can mean it isn't GNU ls.)
5502 (let ((version-out
5503 (with-temp-buffer
5504 (call-process "ls" nil t nil "--version")
5505 (buffer-string))))
5506 (if (string-match "ls (.*utils) \\([0-9.]*\\)$" version-out)
5507 (let* ((version (match-string 1 version-out))
5508 (split (split-string version "[.]"))
5509 (numbers (mapcar 'string-to-number split))
5510 (min '(5 2 1))
5511 comparison)
5512 (while (and (not comparison) (or numbers min))
5513 (cond ((null min)
5514 (setq comparison '>))
5515 ((null numbers)
5516 (setq comparison '<))
5517 ((> (car numbers) (car min))
5518 (setq comparison '>))
5519 ((< (car numbers) (car min))
5520 (setq comparison '<))
5521 (t
5522 (setq numbers (cdr numbers)
5523 min (cdr min)))))
5524 (setq insert-directory-ls-version (or comparison '=)))
5525 (setq insert-directory-ls-version nil))))
5526
5527 ;; For GNU ls versions 5.2.2 and up, ignore minor errors.
5528 (when (and (eq 1 result) (eq insert-directory-ls-version '>))
5529 (setq result 0))
5530
5531 ;; If `insert-directory-program' failed, signal an error.
5532 (unless (eq 0 result)
5533 ;; Delete the error message it may have output.
5534 (delete-region beg (point))
5535 ;; On non-Posix systems, we cannot open a directory, so
5536 ;; don't even try, because that will always result in
5537 ;; the ubiquitous "Access denied". Instead, show the
5538 ;; command line so the user can try to guess what went wrong.
5539 (if (and (file-directory-p file)
5540 (memq system-type '(ms-dos windows-nt)))
5541 (error
5542 "Reading directory: \"%s %s -- %s\" exited with status %s"
5543 insert-directory-program
5544 (if (listp switches) (concat switches) switches)
5545 file result)
5546 ;; Unix. Access the file to get a suitable error.
5547 (access-file file "Reading directory")
5548 (error "Listing directory failed but `access-file' worked")))
5549
5550 (when (if (stringp switches)
5551 (string-match "--dired\\>" switches)
5552 (member "--dired" switches))
5553 ;; The following overshoots by one line for an empty
5554 ;; directory listed with "--dired", but without "-a"
5555 ;; switch, where the ls output contains a
5556 ;; "//DIRED-OPTIONS//" line, but no "//DIRED//" line.
5557 ;; We take care of that case later.
5558 (forward-line -2)
5559 (when (looking-at "//SUBDIRED//")
5560 (delete-region (point) (progn (forward-line 1) (point)))
5561 (forward-line -1))
5562 (if (looking-at "//DIRED//")
5563 (let ((end (line-end-position))
5564 (linebeg (point))
5565 error-lines)
5566 ;; Find all the lines that are error messages,
5567 ;; and record the bounds of each one.
5568 (goto-char beg)
5569 (while (< (point) linebeg)
5570 (or (eql (following-char) ?\s)
5571 (push (list (point) (line-end-position)) error-lines))
5572 (forward-line 1))
5573 (setq error-lines (nreverse error-lines))
5574 ;; Now read the numeric positions of file names.
5575 (goto-char linebeg)
5576 (forward-word 1)
5577 (forward-char 3)
5578 (while (< (point) end)
5579 (let ((start (insert-directory-adj-pos
5580 (+ beg (read (current-buffer)))
5581 error-lines))
5582 (end (insert-directory-adj-pos
5583 (+ beg (read (current-buffer)))
5584 error-lines)))
5585 (if (memq (char-after end) '(?\n ?\s))
5586 ;; End is followed by \n or by " -> ".
5587 (put-text-property start end 'dired-filename t)
5588 ;; It seems that we can't trust ls's output as to
5589 ;; byte positions of filenames.
5590 (put-text-property beg (point) 'dired-filename nil)
5591 (end-of-line))))
5592 (goto-char end)
5593 (beginning-of-line)
5594 (delete-region (point) (progn (forward-line 1) (point))))
5595 ;; Take care of the case where the ls output contains a
5596 ;; "//DIRED-OPTIONS//"-line, but no "//DIRED//"-line
5597 ;; and we went one line too far back (see above).
5598 (forward-line 1))
5599 (if (looking-at "//DIRED-OPTIONS//")
5600 (delete-region (point) (progn (forward-line 1) (point)))))
5601
5602 ;; Now decode what read if necessary.
5603 (let ((coding (or coding-system-for-read
5604 file-name-coding-system
5605 default-file-name-coding-system
5606 'undecided))
5607 coding-no-eol
5608 val pos)
5609 (when (and enable-multibyte-characters
5610 (not (memq (coding-system-base coding)
5611 '(raw-text no-conversion))))
5612 ;; If no coding system is specified or detection is
5613 ;; requested, detect the coding.
5614 (if (eq (coding-system-base coding) 'undecided)
5615 (setq coding (detect-coding-region beg (point) t)))
5616 (if (not (eq (coding-system-base coding) 'undecided))
5617 (save-restriction
5618 (setq coding-no-eol
5619 (coding-system-change-eol-conversion coding 'unix))
5620 (narrow-to-region beg (point))
5621 (goto-char (point-min))
5622 (while (not (eobp))
5623 (setq pos (point)
5624 val (get-text-property (point) 'dired-filename))
5625 (goto-char (next-single-property-change
5626 (point) 'dired-filename nil (point-max)))
5627 ;; Force no eol conversion on a file name, so
5628 ;; that CR is preserved.
5629 (decode-coding-region pos (point)
5630 (if val coding-no-eol coding))
5631 (if val
5632 (put-text-property pos (point)
5633 'dired-filename t)))))))
5634
5635 (if full-directory-p
5636 ;; Try to insert the amount of free space.
5637 (save-excursion
5638 (goto-char beg)
5639 ;; First find the line to put it on.
5640 (when (re-search-forward "^ *\\(total\\)" nil t)
5641 (let ((available (get-free-disk-space ".")))
5642 (when available
5643 ;; Replace "total" with "used", to avoid confusion.
5644 (replace-match "total used in directory" nil nil nil 1)
5645 (end-of-line)
5646 (insert " available " available))))))))))
5647
5648 (defun insert-directory-adj-pos (pos error-lines)
5649 "Convert `ls --dired' file name position value POS to a buffer position.
5650 File name position values returned in ls --dired output
5651 count only stdout; they don't count the error messages sent to stderr.
5652 So this function converts to them to real buffer positions.
5653 ERROR-LINES is a list of buffer positions of error message lines,
5654 of the form (START END)."
5655 (while (and error-lines (< (caar error-lines) pos))
5656 (setq pos (+ pos (- (nth 1 (car error-lines)) (nth 0 (car error-lines)))))
5657 (pop error-lines))
5658 pos)
5659
5660 (defun insert-directory-safely (file switches
5661 &optional wildcard full-directory-p)
5662 "Insert directory listing for FILE, formatted according to SWITCHES.
5663
5664 Like `insert-directory', but if FILE does not exist, it inserts a
5665 message to that effect instead of signaling an error."
5666 (if (file-exists-p file)
5667 (insert-directory file switches wildcard full-directory-p)
5668 ;; Simulate the message printed by `ls'.
5669 (insert (format "%s: No such file or directory\n" file))))
5670
5671 (defvar kill-emacs-query-functions nil
5672 "Functions to call with no arguments to query about killing Emacs.
5673 If any of these functions returns nil, killing Emacs is cancelled.
5674 `save-buffers-kill-emacs' calls these functions, but `kill-emacs',
5675 the low level primitive, does not. See also `kill-emacs-hook'.")
5676
5677 (defcustom confirm-kill-emacs nil
5678 "How to ask for confirmation when leaving Emacs.
5679 If nil, the default, don't ask at all. If the value is non-nil, it should
5680 be a predicate function such as `yes-or-no-p'."
5681 :type '(choice (const :tag "Ask with yes-or-no-p" yes-or-no-p)
5682 (const :tag "Ask with y-or-n-p" y-or-n-p)
5683 (const :tag "Don't confirm" nil))
5684 :group 'convenience
5685 :version "21.1")
5686
5687 (defun save-buffers-kill-emacs (&optional arg)
5688 "Offer to save each buffer, then kill this Emacs process.
5689 With prefix ARG, silently save all file-visiting buffers, then kill."
5690 (interactive "P")
5691 (save-some-buffers arg t)
5692 (and (or (not (memq t (mapcar (function
5693 (lambda (buf) (and (buffer-file-name buf)
5694 (buffer-modified-p buf))))
5695 (buffer-list))))
5696 (yes-or-no-p "Modified buffers exist; exit anyway? "))
5697 (or (not (fboundp 'process-list))
5698 ;; process-list is not defined on MSDOS.
5699 (let ((processes (process-list))
5700 active)
5701 (while processes
5702 (and (memq (process-status (car processes)) '(run stop open listen))
5703 (process-query-on-exit-flag (car processes))
5704 (setq active t))
5705 (setq processes (cdr processes)))
5706 (or (not active)
5707 (list-processes t)
5708 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
5709 ;; Query the user for other things, perhaps.
5710 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
5711 (or (null confirm-kill-emacs)
5712 (funcall confirm-kill-emacs "Really exit Emacs? "))
5713 (kill-emacs)))
5714
5715 (defun save-buffers-kill-terminal (&optional arg)
5716 "Offer to save each buffer, then kill the current connection.
5717 If the current frame has no client, kill Emacs itself.
5718
5719 With prefix ARG, silently save all file-visiting buffers, then kill.
5720
5721 If emacsclient was started with a list of filenames to edit, then
5722 only these files will be asked to be saved."
5723 (interactive "P")
5724 (let ((proc (frame-parameter (selected-frame) 'client))
5725 (frame (selected-frame)))
5726 (if (null proc)
5727 (save-buffers-kill-emacs)
5728 (server-save-buffers-kill-terminal proc arg))))
5729
5730 \f
5731 ;; We use /: as a prefix to "quote" a file name
5732 ;; so that magic file name handlers will not apply to it.
5733
5734 (setq file-name-handler-alist
5735 (cons '("\\`/:" . file-name-non-special)
5736 file-name-handler-alist))
5737
5738 ;; We depend on being the last handler on the list,
5739 ;; so that anything else which does need handling
5740 ;; has been handled already.
5741 ;; So it is safe for us to inhibit *all* magic file name handlers.
5742
5743 (defun file-name-non-special (operation &rest arguments)
5744 (let ((file-name-handler-alist nil)
5745 (default-directory
5746 (if (eq operation 'insert-directory)
5747 (directory-file-name
5748 (expand-file-name
5749 (unhandled-file-name-directory default-directory)))
5750 default-directory))
5751 ;; Get a list of the indices of the args which are file names.
5752 (file-arg-indices
5753 (cdr (or (assq operation
5754 ;; The first six are special because they
5755 ;; return a file name. We want to include the /:
5756 ;; in the return value.
5757 ;; So just avoid stripping it in the first place.
5758 '((expand-file-name . nil)
5759 (file-name-directory . nil)
5760 (file-name-as-directory . nil)
5761 (directory-file-name . nil)
5762 (file-name-sans-versions . nil)
5763 (find-backup-file-name . nil)
5764 ;; `identity' means just return the first arg
5765 ;; not stripped of its quoting.
5766 (substitute-in-file-name identity)
5767 ;; `add' means add "/:" to the result.
5768 (file-truename add 0)
5769 ;; `quote' means add "/:" to buffer-file-name.
5770 (insert-file-contents quote 0)
5771 ;; `unquote-then-quote' means set buffer-file-name
5772 ;; temporarily to unquoted filename.
5773 (verify-visited-file-modtime unquote-then-quote)
5774 ;; List the arguments which are filenames.
5775 (file-name-completion 1)
5776 (file-name-all-completions 1)
5777 (write-region 2 5)
5778 (rename-file 0 1)
5779 (copy-file 0 1)
5780 (make-symbolic-link 0 1)
5781 (add-name-to-file 0 1)))
5782 ;; For all other operations, treat the first argument only
5783 ;; as the file name.
5784 '(nil 0))))
5785 method
5786 ;; Copy ARGUMENTS so we can replace elements in it.
5787 (arguments (copy-sequence arguments)))
5788 (if (symbolp (car file-arg-indices))
5789 (setq method (pop file-arg-indices)))
5790 ;; Strip off the /: from the file names that have it.
5791 (save-match-data
5792 (while (consp file-arg-indices)
5793 (let ((pair (nthcdr (car file-arg-indices) arguments)))
5794 (and (car pair)
5795 (string-match "\\`/:" (car pair))
5796 (setcar pair
5797 (if (= (length (car pair)) 2)
5798 "/"
5799 (substring (car pair) 2)))))
5800 (setq file-arg-indices (cdr file-arg-indices))))
5801 (cond ((eq method 'identity)
5802 (car arguments))
5803 ((eq method 'add)
5804 (concat "/:" (apply operation arguments)))
5805 ((eq method 'quote)
5806 (unwind-protect
5807 (apply operation arguments)
5808 (setq buffer-file-name (concat "/:" buffer-file-name))))
5809 ((eq method 'unquote-then-quote)
5810 (let (res)
5811 (setq buffer-file-name (substring buffer-file-name 2))
5812 (setq res (apply operation arguments))
5813 (setq buffer-file-name (concat "/:" buffer-file-name))
5814 res))
5815 (t
5816 (apply operation arguments)))))
5817 \f
5818 ;; Symbolic modes and read-file-modes.
5819
5820 (defun file-modes-char-to-who (char)
5821 "Convert CHAR to a numeric bit-mask for extracting mode bits.
5822 CHAR is in [ugoa] and represents the category of users (Owner, Group,
5823 Others, or All) for whom to produce the mask.
5824 The bit-mask that is returned extracts from mode bits the access rights
5825 for the specified category of users."
5826 (cond ((= char ?u) #o4700)
5827 ((= char ?g) #o2070)
5828 ((= char ?o) #o1007)
5829 ((= char ?a) #o7777)
5830 (t (error "%c: bad `who' character" char))))
5831
5832 (defun file-modes-char-to-right (char &optional from)
5833 "Convert CHAR to a numeric value of mode bits.
5834 CHAR is in [rwxXstugo] and represents symbolic access permissions.
5835 If CHAR is in [Xugo], the value is taken from FROM (or 0 if omitted)."
5836 (or from (setq from 0))
5837 (cond ((= char ?r) #o0444)
5838 ((= char ?w) #o0222)
5839 ((= char ?x) #o0111)
5840 ((= char ?s) #o1000)
5841 ((= char ?t) #o6000)
5842 ;; Rights relative to the previous file modes.
5843 ((= char ?X) (if (= (logand from #o111) 0) 0 #o0111))
5844 ((= char ?u) (let ((uright (logand #o4700 from)))
5845 (+ uright (/ uright #o10) (/ uright #o100))))
5846 ((= char ?g) (let ((gright (logand #o2070 from)))
5847 (+ gright (/ gright #o10) (* gright #o10))))
5848 ((= char ?o) (let ((oright (logand #o1007 from)))
5849 (+ oright (* oright #o10) (* oright #o100))))
5850 (t (error "%c: bad right character" char))))
5851
5852 (defun file-modes-rights-to-number (rights who-mask &optional from)
5853 "Convert a symbolic mode string specification to an equivalent number.
5854 RIGHTS is the symbolic mode spec, it should match \"([+=-][rwxXstugo]+)+\".
5855 WHO-MASK is the bit-mask specifying the category of users to which to
5856 apply the access permissions. See `file-modes-char-to-who'.
5857 FROM (or 0 if nil) gives the mode bits on which to base permissions if
5858 RIGHTS request to add, remove, or set permissions based on existing ones,
5859 as in \"og+rX-w\"."
5860 (let* ((num-rights (or from 0))
5861 (list-rights (string-to-list rights))
5862 (op (pop list-rights)))
5863 (while (memq op '(?+ ?- ?=))
5864 (let ((num-right 0)
5865 char-right)
5866 (while (memq (setq char-right (pop list-rights))
5867 '(?r ?w ?x ?X ?s ?t ?u ?g ?o))
5868 (setq num-right
5869 (logior num-right
5870 (file-modes-char-to-right char-right num-rights))))
5871 (setq num-right (logand who-mask num-right)
5872 num-rights
5873 (cond ((= op ?+) (logior num-rights num-right))
5874 ((= op ?-) (logand num-rights (lognot num-right)))
5875 (t (logior (logand num-rights (lognot who-mask)) num-right)))
5876 op char-right)))
5877 num-rights))
5878
5879 (defun file-modes-symbolic-to-number (modes &optional from)
5880 "Convert symbolic file modes to numeric file modes.
5881 MODES is the string to convert, it should match
5882 \"[ugoa]*([+-=][rwxXstugo]+)+,...\".
5883 See (info \"(coreutils)File permissions\") for more information on this
5884 notation.
5885 FROM (or 0 if nil) gives the mode bits on which to base permissions if
5886 MODES request to add, remove, or set permissions based on existing ones,
5887 as in \"og+rX-w\"."
5888 (save-match-data
5889 (let ((case-fold-search nil)
5890 (num-modes (or from 0)))
5891 (while (/= (string-to-char modes) 0)
5892 (if (string-match "^\\([ugoa]*\\)\\([+=-][rwxXstugo]+\\)+\\(,\\|\\)" modes)
5893 (let ((num-who (apply 'logior 0
5894 (mapcar 'file-modes-char-to-who
5895 (match-string 1 modes)))))
5896 (when (= num-who 0)
5897 (setq num-who (default-file-modes)))
5898 (setq num-modes
5899 (file-modes-rights-to-number (substring modes (match-end 1))
5900 num-who num-modes)
5901 modes (substring modes (match-end 3))))
5902 (error "Parse error in modes near `%s'" (substring modes 0))))
5903 num-modes)))
5904
5905 (defun read-file-modes (&optional prompt orig-file)
5906 "Read file modes in octal or symbolic notation and return its numeric value.
5907 PROMPT is used as the prompt, default to `File modes (octal or symbolic): '.
5908 ORIG-FILE is the name of a file on whose mode bits to base returned
5909 permissions if what user types requests to add, remove, or set permissions
5910 based on existing mode bits, as in \"og+rX-w\"."
5911 (let* ((modes (or (if orig-file (file-modes orig-file) 0)
5912 (error "File not found")))
5913 (modestr (and (stringp orig-file)
5914 (nth 8 (file-attributes orig-file))))
5915 (default
5916 (and (stringp modestr)
5917 (string-match "^.\\(...\\)\\(...\\)\\(...\\)$" modestr)
5918 (replace-regexp-in-string
5919 "-" ""
5920 (format "u=%s,g=%s,o=%s"
5921 (match-string 1 modestr)
5922 (match-string 2 modestr)
5923 (match-string 3 modestr)))))
5924 (value (read-string (or prompt "File modes (octal or symbolic): ")
5925 nil nil default)))
5926 (save-match-data
5927 (if (string-match "^[0-7]+" value)
5928 (string-to-number value 8)
5929 (file-modes-symbolic-to-number value modes)))))
5930
5931 \f
5932 ;; Trashcan handling.
5933 (defcustom trash-directory (convert-standard-filename "~/.Trash")
5934 "Directory for `move-file-to-trash' to move files and directories to.
5935 This directory is only used when the function `system-move-file-to-trash' is
5936 not defined. Relative paths are interpreted relative to `default-directory'.
5937 See also `delete-by-moving-to-trash'."
5938 :type 'directory
5939 :group 'auto-save
5940 :version "23.1")
5941
5942 (declare-function system-move-file-to-trash "w32fns.c" (filename))
5943
5944 (defun move-file-to-trash (filename)
5945 "Move file (or directory) name FILENAME to the trash.
5946 This function is called by `delete-file' and `delete-directory' when
5947 `delete-by-moving-to-trash' is non-nil. On platforms that define
5948 `system-move-file-to-trash', that function is used to move FILENAME to the
5949 system trash, otherwise FILENAME is moved to `trash-directory'.
5950 Returns nil on success."
5951 (interactive "fMove file to trash: ")
5952 (cond
5953 ((fboundp 'system-move-file-to-trash)
5954 (system-move-file-to-trash filename))
5955 (t
5956 (let* ((trash-dir (expand-file-name trash-directory))
5957 (fn (directory-file-name (expand-file-name filename)))
5958 (fn-nondir (file-name-nondirectory fn))
5959 (new-fn (expand-file-name fn-nondir trash-dir)))
5960 (or (file-directory-p trash-dir)
5961 (make-directory trash-dir t))
5962 (and (file-exists-p new-fn)
5963 ;; make new-fn unique.
5964 ;; example: "~/.Trash/abc.txt" -> "~/.Trash/abc.txt.~1~"
5965 (let ((version-control t))
5966 (setq new-fn (car (find-backup-file-name new-fn)))))
5967 ;; stop processing if fn is same or parent directory of trash-dir.
5968 (and (string-match fn trash-dir)
5969 (error "Filename `%s' is same or parent directory of trash-directory"
5970 filename))
5971 (let ((delete-by-moving-to-trash nil))
5972 (rename-file fn new-fn))))))
5973
5974 \f
5975 (define-key ctl-x-map "\C-f" 'find-file)
5976 (define-key ctl-x-map "\C-r" 'find-file-read-only)
5977 (define-key ctl-x-map "\C-v" 'find-alternate-file)
5978 (define-key ctl-x-map "\C-s" 'save-buffer)
5979 (define-key ctl-x-map "s" 'save-some-buffers)
5980 (define-key ctl-x-map "\C-w" 'write-file)
5981 (define-key ctl-x-map "i" 'insert-file)
5982 (define-key esc-map "~" 'not-modified)
5983 (define-key ctl-x-map "\C-d" 'list-directory)
5984 (define-key ctl-x-map "\C-c" 'save-buffers-kill-terminal)
5985 (define-key ctl-x-map "\C-q" 'toggle-read-only)
5986
5987 (define-key ctl-x-4-map "f" 'find-file-other-window)
5988 (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
5989 (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
5990 (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
5991 (define-key ctl-x-4-map "\C-o" 'display-buffer)
5992
5993 (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
5994 (define-key ctl-x-5-map "f" 'find-file-other-frame)
5995 (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
5996 (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
5997 (define-key ctl-x-5-map "\C-o" 'display-buffer-other-frame)
5998
5999 ;; arch-tag: bc68d3ea-19ca-468b-aac6-3a4a7766101f
6000 ;;; files.el ends here