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