]> code.delx.au - gnu-emacs/blob - lisp/files.el
(file-name-invalid-regexp): Add control characters for DOS/Windows
[gnu-emacs] / lisp / files.el
1 ;;; files.el --- file input and output commands for Emacs
2
3 ;; Copyright (C) 1985, 86, 87, 92, 93,
4 ;; 94, 95, 96, 97, 1998 Free Software Foundation, Inc.
5
6 ;; Maintainer: FSF
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; Defines most of Emacs's file- and directory-handling functions,
28 ;; including basic file visiting, backup generation, link handling,
29 ;; ITS-id version control, load- and write-hook handling, and the like.
30
31 ;;; Code:
32
33 (defgroup backup nil
34 "Backups of edited data files."
35 :group 'files)
36
37 (defgroup find-file nil
38 "Finding files."
39 :group 'files)
40
41
42 (defcustom delete-auto-save-files t
43 "*Non-nil means delete auto-save file when a buffer is saved or killed.
44
45 Note that auto-save file will not be deleted if the buffer is killed
46 when it has unsaved changes."
47 :type 'boolean
48 :group 'auto-save)
49
50 (defcustom directory-abbrev-alist
51 nil
52 "*Alist of abbreviations for file directories.
53 A list of elements of the form (FROM . TO), each meaning to replace
54 FROM with TO when it appears in a directory name. This replacement is
55 done when setting up the default directory of a newly visited file.
56 *Every* FROM string should start with `^'.
57
58 Do not use `~' in the TO strings.
59 They should be ordinary absolute directory names.
60
61 Use this feature when you have directories which you normally refer to
62 via absolute symbolic links. Make TO the name of the link, and FROM
63 the name it is linked to."
64 :type '(repeat (cons :format "%v"
65 :value ("" . "")
66 (regexp :tag "From")
67 (regexp :tag "To")))
68 :group 'abbrev
69 :group 'find-file)
70
71 ;;; Turn off backup files on VMS since it has version numbers.
72 (defcustom make-backup-files (not (eq system-type 'vax-vms))
73 "*Non-nil means make a backup of a file the first time it is saved.
74 This can be done by renaming the file or by copying.
75
76 Renaming means that Emacs renames the existing file so that it is a
77 backup file, then writes the buffer into a new file. Any other names
78 that the old file had will now refer to the backup file. The new file
79 is owned by you and its group is defaulted.
80
81 Copying means that Emacs copies the existing file into the backup
82 file, then writes the buffer on top of the existing file. Any other
83 names that the old file had will now refer to the new (edited) file.
84 The file's owner and group are unchanged.
85
86 The choice of renaming or copying is controlled by the variables
87 `backup-by-copying', `backup-by-copying-when-linked' and
88 `backup-by-copying-when-mismatch'. See also `backup-inhibited'."
89 :type 'boolean
90 :group 'backup)
91
92 ;; Do this so that local variables based on the file name
93 ;; are not overridden by the major mode.
94 (defvar backup-inhibited nil
95 "Non-nil means don't make a backup, regardless of the other parameters.
96 This variable is intended for use by making it local to a buffer.
97 But it is local only if you make it local.")
98 (put 'backup-inhibited 'permanent-local t)
99
100 (defcustom backup-by-copying nil
101 "*Non-nil means always use copying to create backup files.
102 See documentation of variable `make-backup-files'."
103 :type 'boolean
104 :group 'backup)
105
106 (defcustom backup-by-copying-when-linked nil
107 "*Non-nil means use copying to create backups for files with multiple names.
108 This causes the alternate names to refer to the latest version as edited.
109 This variable is relevant only if `backup-by-copying' is nil."
110 :type 'boolean
111 :group 'backup)
112
113 (defcustom backup-by-copying-when-mismatch nil
114 "*Non-nil means create backups by copying if this preserves owner or group.
115 Renaming may still be used (subject to control of other variables)
116 when it would not result in changing the owner or group of the file;
117 that is, for files which are owned by you and whose group matches
118 the default for a new file created there by you.
119 This variable is relevant only if `backup-by-copying' is nil."
120 :type 'boolean
121 :group 'backup)
122
123 (defvar backup-enable-predicate
124 '(lambda (name)
125 (or (< (length name) 5)
126 (not (string-equal "/tmp/" (substring name 0 5)))))
127 "Predicate that looks at a file name and decides whether to make backups.
128 Called with an absolute file name as argument, it returns t to enable backup.")
129
130 (defcustom buffer-offer-save nil
131 "*Non-nil in a buffer means offer to save the buffer on exit
132 even if the buffer is not visiting a file.
133 Automatically local in all buffers."
134 :type 'boolean
135 :group 'backup)
136 (make-variable-buffer-local 'buffer-offer-save)
137
138 (defcustom find-file-existing-other-name t
139 "*Non-nil means find a file under alternative names, in existing buffers.
140 This means if any existing buffer is visiting the file you want
141 under another name, you get the existing buffer instead of a new buffer."
142 :type 'boolean
143 :group 'find-file)
144
145 (defcustom find-file-visit-truename nil
146 "*Non-nil means visit a file under its truename.
147 The truename of a file is found by chasing all links
148 both at the file level and at the levels of the containing directories."
149 :type 'boolean
150 :group 'find-file)
151
152 (defcustom revert-without-query
153 nil
154 "*Specify which files should be reverted without query.
155 The value is a list of regular expressions.
156 If the file name matches one of these regular expressions,
157 then `revert-buffer' reverts the file without querying
158 if the file has changed on disk and you have not edited the buffer."
159 :type '(repeat regexp)
160 :group 'find-file)
161
162 (defvar buffer-file-number nil
163 "The device number and file number of the file visited in the current buffer.
164 The value is a list of the form (FILENUM DEVNUM).
165 This pair of numbers uniquely identifies the file.
166 If the buffer is visiting a new file, the value is nil.")
167 (make-variable-buffer-local 'buffer-file-number)
168 (put 'buffer-file-number 'permanent-local t)
169
170 (defvar buffer-file-numbers-unique (not (memq system-type '(windows-nt)))
171 "Non-nil means that buffer-file-number uniquely identifies files.")
172
173 (defvar file-name-invalid-regexp
174 (cond ((and (eq system-type 'ms-dos) (not (msdos-long-file-names)))
175 (concat "\\(^\\([A-z]:\\)?/?.*:\\)\\|" ; colon except after drive
176 "[+, ;=|<>\"?*]\\|\\[\\|\\]\\|" ; invalid characters
177 "[\000-\031]|" ; control characters
178 "\\(/\\.\\.?[^/]\\)\\|" ; leading dots
179 "\\(/[^/.]+\\.[^/.]*\\.\\)")) ; more than a single dot
180 ((memq system-type '(ms-dos windows-nt))
181 (concat "\\(^\\([A-z]:\\)?/?.*:\\)\\|" ; colon except after drive
182 "[|<>\"?*\000-\031]")) ; invalid characters
183 (t "[\000]"))
184 "Regexp recognizing file names which aren't allowed by the filesystem.")
185
186 (defcustom file-precious-flag nil
187 "*Non-nil means protect against I/O errors while saving files.
188 Some modes set this non-nil in particular buffers.
189
190 This feature works by writing the new contents into a temporary file
191 and then renaming the temporary file to replace the original.
192 In this way, any I/O error in writing leaves the original untouched,
193 and there is never any instant where the file is nonexistent.
194
195 Note that this feature forces backups to be made by copying.
196 Yet, at the same time, saving a precious file
197 breaks any hard links between it and other files."
198 :type 'boolean
199 :group 'backup)
200
201 (defcustom version-control nil
202 "*Control use of version numbers for backup files.
203 t means make numeric backup versions unconditionally.
204 nil means make them for files that have some already.
205 `never' means do not make them."
206 :type 'boolean
207 :group 'backup
208 :group 'vc)
209
210 (defcustom dired-kept-versions 2
211 "*When cleaning directory, number of versions to keep."
212 :type 'integer
213 :group 'backup
214 :group 'dired)
215
216 (defcustom delete-old-versions nil
217 "*If t, delete excess backup versions silently.
218 If nil, ask confirmation. Any other value prevents any trimming."
219 :type '(choice (const :tag "Delete" t)
220 (const :tag "Ask" nil)
221 (sexp :tag "Leave" :format "%t\n" other))
222 :group 'backup)
223
224 (defcustom kept-old-versions 2
225 "*Number of oldest versions to keep when a new numbered backup is made."
226 :type 'integer
227 :group 'backup)
228
229 (defcustom kept-new-versions 2
230 "*Number of newest versions to keep when a new numbered backup is made.
231 Includes the new backup. Must be > 0"
232 :type 'integer
233 :group 'backup)
234
235 (defcustom require-final-newline nil
236 "*Value of t says silently ensure a file ends in a newline when it is saved.
237 Non-nil but not t says ask user whether to add a newline when there isn't one.
238 nil means don't add newlines."
239 :type '(choice (const :tag "Off" nil)
240 (const :tag "Add" t)
241 (sexp :tag "Ask" :format "%t\n" ask))
242 :group 'editing-basics)
243
244 (defcustom auto-save-default t
245 "*Non-nil says by default do auto-saving of every file-visiting buffer."
246 :type 'boolean
247 :group 'auto-save)
248
249 (defcustom auto-save-visited-file-name nil
250 "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
251 Normally auto-save files are written under other names."
252 :type 'boolean
253 :group 'auto-save)
254
255 (defcustom save-abbrevs nil
256 "*Non-nil means save word abbrevs too when files are saved.
257 Loading an abbrev file sets this to t."
258 :type 'boolean
259 :group 'abbrev)
260
261 (defcustom find-file-run-dired t
262 "*Non-nil says run dired if `find-file' is given the name of a directory."
263 :type 'boolean
264 :group 'find-file)
265
266 ;;;It is not useful to make this a local variable.
267 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
268 (defvar find-file-not-found-hooks nil
269 "List of functions to be called for `find-file' on nonexistent file.
270 These functions are called as soon as the error is detected.
271 `buffer-file-name' is already set up.
272 The functions are called in the order given until one of them returns non-nil.")
273
274 ;;;It is not useful to make this a local variable.
275 ;;;(put 'find-file-hooks 'permanent-local t)
276 (defvar find-file-hooks nil
277 "List of functions to be called after a buffer is loaded from a file.
278 The buffer's local variables (if any) will have been processed before the
279 functions are called.")
280
281 (defvar write-file-hooks nil
282 "List of functions to be called before writing out a buffer to a file.
283 If one of them returns non-nil, the file is considered already written
284 and the rest are not called.
285 These hooks are considered to pertain to the visited file.
286 So this list is cleared if you change the visited file name.
287
288 Don't make this variable buffer-local; instead, use `local-write-file-hooks'.
289 See also `write-contents-hooks'.")
290 ;;; However, in case someone does make it local...
291 (put 'write-file-hooks 'permanent-local t)
292
293 (defvar local-write-file-hooks nil
294 "Just like `write-file-hooks', except intended for per-buffer use.
295 The functions in this list are called before the ones in
296 `write-file-hooks'.
297
298 This variable is meant to be used for hooks that have to do with a
299 particular visited file. Therefore, it is a permanent local, so that
300 changing the major mode does not clear it. However, calling
301 `set-visited-file-name' does clear it.")
302 (make-variable-buffer-local 'local-write-file-hooks)
303 (put 'local-write-file-hooks 'permanent-local t)
304
305 (defvar write-contents-hooks nil
306 "List of functions to be called before writing out a buffer to a file.
307 If one of them returns non-nil, the file is considered already written
308 and the rest are not called.
309
310 This variable is meant to be used for hooks that pertain to the
311 buffer's contents, not to the particular visited file; thus,
312 `set-visited-file-name' does not clear this variable; but changing the
313 major mode does clear it.
314
315 This variable automatically becomes buffer-local whenever it is set.
316 If you use `add-hook' to add elements to the list, use nil for the
317 LOCAL argument.
318
319 See also `write-file-hooks'.")
320 (make-variable-buffer-local 'write-contents-hooks)
321
322 (defcustom enable-local-variables t
323 "*Control use of local variables in files you visit.
324 The value can be t, nil or something else.
325 A value of t means file local variables specifications are obeyed;
326 nil means they are ignored; anything else means query.
327
328 The command \\[normal-mode] always obeys file local variable
329 specifications and ignores this variable."
330 :type '(choice (const :tag "Obey" t)
331 (const :tag "Ignore" nil)
332 (sexp :tag "Query" :format "%t\n" other))
333 :group 'find-file)
334
335 (defvar local-enable-local-variables t
336 "Like `enable-local-variables' but meant for buffer-local bindings.
337 If a major mode sets this to nil, buffer-locally, then any local
338 variables list in the file will be ignored.")
339
340 (defcustom enable-local-eval 'maybe
341 "*Control processing of the \"variable\" `eval' in a file's local variables.
342 The value can be t, nil or something else.
343 A value of t means obey `eval' variables;
344 nil means ignore them; anything else means query.
345
346 The command \\[normal-mode] always obeys local-variables lists
347 and ignores this variable."
348 :type '(choice (const :tag "Obey" t)
349 (const :tag "Ignore" nil)
350 (sexp :tag "Query" :format "%t\n" other))
351 :group 'find-file)
352
353 ;; Avoid losing in versions where CLASH_DETECTION is disabled.
354 (or (fboundp 'lock-buffer)
355 (defalias 'lock-buffer 'ignore))
356 (or (fboundp 'unlock-buffer)
357 (defalias 'unlock-buffer 'ignore))
358 (or (fboundp 'file-locked-p)
359 (defalias 'file-locked-p 'ignore))
360
361 (defvar view-read-only nil
362 "*Non-nil means buffers visiting files read-only, do it in view mode.")
363
364 (defvar temporary-file-directory
365 (file-name-as-directory
366 (cond ((memq system-type '(ms-dos windows-nt))
367 (or (getenv "TEMP") (getenv "TMPDIR") (getenv "TMP") "c:/temp"))
368 ((memq system-type '(vax-vms axp-vms))
369 (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "SYS$SCRATCH:"))
370 (t
371 (or (getenv "TMPDIR") (getenv "TMP") (getenv "TEMP") "/tmp"))))
372 "The directory for writing temporary files.")
373
374 ;; The system null device. (Should reference NULL_DEVICE from C.)
375 (defvar null-device "/dev/null" "The system null device.")
376
377 ;; This hook function provides support for ange-ftp host name
378 ;; completion. It runs the usual ange-ftp hook, but only for
379 ;; completion operations. Having this here avoids the need
380 ;; to load ange-ftp when it's not really in use.
381 (defun ange-ftp-completion-hook-function (op &rest args)
382 (if (memq op '(file-name-completion file-name-all-completions))
383 (apply 'ange-ftp-hook-function op args)
384 (let ((inhibit-file-name-handlers
385 (cons 'ange-ftp-completion-hook-function
386 (and (eq inhibit-file-name-operation op)
387 inhibit-file-name-handlers)))
388 (inhibit-file-name-operation op))
389 (apply op args))))
390
391 (defun convert-standard-filename (filename)
392 "Convert a standard file's name to something suitable for the current OS.
393 This function's standard definition is trivial; it just returns the argument.
394 However, on some systems, the function is redefined
395 with a definition that really does change some file names."
396 filename)
397 \f
398 (defun pwd ()
399 "Show the current default directory."
400 (interactive nil)
401 (message "Directory %s" default-directory))
402
403 (defvar cd-path nil
404 "Value of the CDPATH environment variable, as a list.
405 Not actually set up until the first time you you use it.")
406
407 (defun parse-colon-path (cd-path)
408 "Explode a colon-separated search path into a list of directory names."
409 (and cd-path
410 (let (cd-prefix cd-list (cd-start 0) cd-colon)
411 (setq cd-path (concat cd-path path-separator))
412 (while (setq cd-colon (string-match path-separator cd-path cd-start))
413 (setq cd-list
414 (nconc cd-list
415 (list (if (= cd-start cd-colon)
416 nil
417 (substitute-in-file-name
418 (file-name-as-directory
419 (substring cd-path cd-start cd-colon)))))))
420 (setq cd-start (+ cd-colon 1)))
421 cd-list)))
422
423 (defun cd-absolute (dir)
424 "Change current directory to given absolute file name DIR."
425 ;; Put the name into directory syntax now,
426 ;; because otherwise expand-file-name may give some bad results.
427 (if (not (eq system-type 'vax-vms))
428 (setq dir (file-name-as-directory dir)))
429 (setq dir (abbreviate-file-name (expand-file-name dir)))
430 (if (not (file-directory-p dir))
431 (if (file-exists-p dir)
432 (error "%s is not a directory" dir)
433 (error "%s: no such directory" dir))
434 (if (file-executable-p dir)
435 (setq default-directory dir)
436 (error "Cannot cd to %s: Permission denied" dir))))
437
438 (defun cd (dir)
439 "Make DIR become the current buffer's default directory.
440 If your environment includes a `CDPATH' variable, try each one of that
441 colon-separated list of directories when resolving a relative directory name."
442 (interactive
443 (list (read-file-name "Change default directory: "
444 default-directory default-directory
445 (and (member cd-path '(nil ("./")))
446 (null (getenv "CDPATH"))))))
447 (if (file-name-absolute-p dir)
448 (cd-absolute (expand-file-name dir))
449 (if (null cd-path)
450 (let ((trypath (parse-colon-path (getenv "CDPATH"))))
451 (setq cd-path (or trypath (list "./")))))
452 (if (not (catch 'found
453 (mapcar
454 (function (lambda (x)
455 (let ((f (expand-file-name (concat x dir))))
456 (if (file-directory-p f)
457 (progn
458 (cd-absolute f)
459 (throw 'found t))))))
460 cd-path)
461 nil))
462 (error "No such directory found via CDPATH environment variable"))))
463
464 (defun load-file (file)
465 "Load the Lisp file named FILE."
466 (interactive "fLoad file: ")
467 (load (expand-file-name file) nil nil t))
468
469 (defun load-library (library)
470 "Load the library named LIBRARY.
471 This is an interface to the function `load'."
472 (interactive "sLoad library: ")
473 (load library))
474
475 (defun file-local-copy (file &optional buffer)
476 "Copy the file FILE into a temporary file on this machine.
477 Returns the name of the local copy, or nil, if FILE is directly
478 accessible."
479 (let ((handler (find-file-name-handler file 'file-local-copy)))
480 (if handler
481 (funcall handler 'file-local-copy file)
482 nil)))
483
484 (defun file-truename (filename &optional counter prev-dirs)
485 "Return the truename of FILENAME, which should be absolute.
486 The truename of a file name is found by chasing symbolic links
487 both at the level of the file and at the level of the directories
488 containing it, until no links are left at any level.
489
490 The arguments COUNTER and PREV-DIRS are used only in recursive calls.
491 Do not specify them in other calls."
492 ;; COUNTER can be a cons cell whose car is the count of how many more links
493 ;; to chase before getting an error.
494 ;; PREV-DIRS can be a cons cell whose car is an alist
495 ;; of truenames we've just recently computed.
496
497 ;; The last test looks dubious, maybe `+' is meant here? --simon.
498 (if (or (string= filename "") (string= filename "~")
499 (and (string= (substring filename 0 1) "~")
500 (string-match "~[^/]*" filename)))
501 (progn
502 (setq filename (expand-file-name filename))
503 (if (string= filename "")
504 (setq filename "/"))))
505 (or counter (setq counter (list 100)))
506 (let (done
507 ;; For speed, remove the ange-ftp completion handler from the list.
508 ;; We know it's not needed here.
509 ;; For even more speed, do this only on the outermost call.
510 (file-name-handler-alist
511 (if prev-dirs file-name-handler-alist
512 (let ((tem (copy-sequence file-name-handler-alist)))
513 (delq (rassq 'ange-ftp-completion-hook-function tem) tem)))))
514 (or prev-dirs (setq prev-dirs (list nil)))
515
516 ;; andrewi@harlequin.co.uk - none of the following code (except for
517 ;; invoking the file-name handler) currently applies on Windows
518 ;; (ie. there are no native symlinks), but there is an issue with
519 ;; case differences being ignored by the OS, and short "8.3 DOS"
520 ;; name aliases existing for all files. (The short names are not
521 ;; reported by directory-files, but can be used to refer to files.)
522 ;; It seems appropriate for file-truename to resolve these issues in
523 ;; the most natural way, which on Windows is to call the function
524 ;; `w32-long-file-name' - this returns the exact name of a file as
525 ;; it is stored on disk (expanding short name aliases with the full
526 ;; name in the process).
527 (if (eq system-type 'windows-nt)
528 (let ((handler (find-file-name-handler filename 'file-truename))
529 newname)
530 ;; For file name that has a special handler, call handler.
531 ;; This is so that ange-ftp can save time by doing a no-op.
532 (if handler
533 (setq filename (funcall handler 'file-truename filename))
534 ;; If filename contains a wildcard, newname will be the old name.
535 (if (string-match "[*?]" filename)
536 (setq newname filename)
537 ;; If filename doesn't exist, newname will be nil.
538 (setq newname (w32-long-file-name filename)))
539 (setq filename (or newname filename)))
540 (setq done t)))
541
542 ;; If this file directly leads to a link, process that iteratively
543 ;; so that we don't use lots of stack.
544 (while (not done)
545 (setcar counter (1- (car counter)))
546 (if (< (car counter) 0)
547 (error "Apparent cycle of symbolic links for %s" filename))
548 (let ((handler (find-file-name-handler filename 'file-truename)))
549 ;; For file name that has a special handler, call handler.
550 ;; This is so that ange-ftp can save time by doing a no-op.
551 (if handler
552 (setq filename (funcall handler 'file-truename filename)
553 done t)
554 (let ((dir (or (file-name-directory filename) default-directory))
555 target dirfile)
556 ;; Get the truename of the directory.
557 (setq dirfile (directory-file-name dir))
558 ;; If these are equal, we have the (or a) root directory.
559 (or (string= dir dirfile)
560 ;; If this is the same dir we last got the truename for,
561 ;; save time--don't recalculate.
562 (if (assoc dir (car prev-dirs))
563 (setq dir (cdr (assoc dir (car prev-dirs))))
564 (let ((old dir)
565 (new (file-name-as-directory (file-truename dirfile counter prev-dirs))))
566 (setcar prev-dirs (cons (cons old new) (car prev-dirs)))
567 (setq dir new))))
568 (if (equal ".." (file-name-nondirectory filename))
569 (setq filename
570 (directory-file-name (file-name-directory (directory-file-name dir)))
571 done t)
572 (if (equal "." (file-name-nondirectory filename))
573 (setq filename (directory-file-name dir)
574 done t)
575 ;; Put it back on the file name.
576 (setq filename (concat dir (file-name-nondirectory filename)))
577 ;; Is the file name the name of a link?
578 (setq target (file-symlink-p filename))
579 (if target
580 ;; Yes => chase that link, then start all over
581 ;; since the link may point to a directory name that uses links.
582 ;; We can't safely use expand-file-name here
583 ;; since target might look like foo/../bar where foo
584 ;; is itself a link. Instead, we handle . and .. above.
585 (setq filename
586 (if (file-name-absolute-p target)
587 target
588 (concat dir target))
589 done nil)
590 ;; No, we are done!
591 (setq done t))))))))
592 filename))
593
594 (defun file-chase-links (filename)
595 "Chase links in FILENAME until a name that is not a link.
596 Does not examine containing directories for links,
597 unlike `file-truename'."
598 (let (tem (count 100) (newname filename))
599 (while (setq tem (file-symlink-p newname))
600 (save-match-data
601 (if (= count 0)
602 (error "Apparent cycle of symbolic links for %s" filename))
603 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
604 (while (string-match "//+" tem)
605 (setq tem (replace-match "/" nil nil tem)))
606 ;; Handle `..' by hand, since it needs to work in the
607 ;; target of any directory symlink.
608 ;; This code is not quite complete; it does not handle
609 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
610 (while (string-match "\\`\\.\\./" tem)
611 (setq tem (substring tem 3))
612 (setq newname (expand-file-name newname))
613 ;; Chase links in the default dir of the symlink.
614 (setq newname
615 (file-chase-links
616 (directory-file-name (file-name-directory newname))))
617 ;; Now find the parent of that dir.
618 (setq newname (file-name-directory newname)))
619 (setq newname (expand-file-name tem (file-name-directory newname)))
620 (setq count (1- count))))
621 newname))
622 \f
623 (defun switch-to-buffer-other-window (buffer &optional norecord)
624 "Select buffer BUFFER in another window.
625 Optional second arg NORECORD non-nil means
626 do not put this buffer at the front of the list of recently selected ones."
627 (interactive "BSwitch to buffer in other window: ")
628 (let ((pop-up-windows t))
629 (pop-to-buffer buffer t norecord)))
630
631 (defun switch-to-buffer-other-frame (buffer &optional norecord)
632 "Switch to buffer BUFFER in another frame.
633 Optional second arg NORECORD non-nil means
634 do not put this buffer at the front of the list of recently selected ones."
635 (interactive "BSwitch to buffer in other frame: ")
636 (let ((pop-up-frames t))
637 (pop-to-buffer buffer t norecord)
638 (raise-frame (window-frame (selected-window)))))
639
640 (defun find-file (filename)
641 "Edit file FILENAME.
642 Switch to a buffer visiting file FILENAME,
643 creating one if none already exists."
644 (interactive "FFind file: ")
645 (switch-to-buffer (find-file-noselect filename)))
646
647 (defun find-file-other-window (filename)
648 "Edit file FILENAME, in another window.
649 May create a new window, or reuse an existing one.
650 See the function `display-buffer'."
651 (interactive "FFind file in other window: ")
652 (switch-to-buffer-other-window (find-file-noselect filename)))
653
654 (defun find-file-other-frame (filename)
655 "Edit file FILENAME, in another frame.
656 May create a new frame, or reuse an existing one.
657 See the function `display-buffer'."
658 (interactive "FFind file in other frame: ")
659 (switch-to-buffer-other-frame (find-file-noselect filename)))
660
661 (defun find-file-read-only (filename)
662 "Edit file FILENAME but don't allow changes.
663 Like \\[find-file] but marks buffer as read-only.
664 Use \\[toggle-read-only] to permit editing."
665 (interactive "fFind file read-only: ")
666 (find-file filename)
667 (toggle-read-only 1)
668 (current-buffer))
669
670 (defun find-file-read-only-other-window (filename)
671 "Edit file FILENAME in another window but don't allow changes.
672 Like \\[find-file-other-window] but marks buffer as read-only.
673 Use \\[toggle-read-only] to permit editing."
674 (interactive "fFind file read-only other window: ")
675 (find-file-other-window filename)
676 (toggle-read-only 1)
677 (current-buffer))
678
679 (defun find-file-read-only-other-frame (filename)
680 "Edit file FILENAME in another frame but don't allow changes.
681 Like \\[find-file-other-frame] but marks buffer as read-only.
682 Use \\[toggle-read-only] to permit editing."
683 (interactive "fFind file read-only other frame: ")
684 (find-file-other-frame filename)
685 (toggle-read-only 1)
686 (current-buffer))
687
688 (defun find-alternate-file-other-window (filename)
689 "Find file FILENAME as a replacement for the file in the next window.
690 This command does not select that window."
691 (interactive
692 (save-selected-window
693 (other-window 1)
694 (let ((file buffer-file-name)
695 (file-name nil)
696 (file-dir nil))
697 (and file
698 (setq file-name (file-name-nondirectory file)
699 file-dir (file-name-directory file)))
700 (list (read-file-name
701 "Find alternate file: " file-dir nil nil file-name)))))
702 (if (one-window-p)
703 (find-file-other-window filename)
704 (save-selected-window
705 (other-window 1)
706 (find-alternate-file filename))))
707
708 (defun find-alternate-file (filename)
709 "Find file FILENAME, select its buffer, kill previous buffer.
710 If the current buffer now contains an empty file that you just visited
711 \(presumably by mistake), use this command to visit the file you really want."
712 (interactive
713 (let ((file buffer-file-name)
714 (file-name nil)
715 (file-dir nil))
716 (and file
717 (setq file-name (file-name-nondirectory file)
718 file-dir (file-name-directory file)))
719 (list (read-file-name
720 "Find alternate file: " file-dir nil nil file-name))))
721 (and (buffer-modified-p) (buffer-file-name)
722 ;; (not buffer-read-only)
723 (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
724 (buffer-name))))
725 (error "Aborted"))
726 (let ((obuf (current-buffer))
727 (ofile buffer-file-name)
728 (onum buffer-file-number)
729 (otrue buffer-file-truename)
730 (oname (buffer-name)))
731 (if (get-buffer " **lose**")
732 (kill-buffer " **lose**"))
733 (rename-buffer " **lose**")
734 (unwind-protect
735 (progn
736 (unlock-buffer)
737 (setq buffer-file-name nil)
738 (setq buffer-file-number nil)
739 (setq buffer-file-truename nil)
740 (find-file filename))
741 (cond ((eq obuf (current-buffer))
742 (setq buffer-file-name ofile)
743 (setq buffer-file-number onum)
744 (setq buffer-file-truename otrue)
745 (lock-buffer)
746 (rename-buffer oname))))
747 (or (eq (current-buffer) obuf)
748 (kill-buffer obuf))))
749 \f
750 (defun create-file-buffer (filename)
751 "Create a suitably named buffer for visiting FILENAME, and return it.
752 FILENAME (sans directory) is used unchanged if that name is free;
753 otherwise a string <2> or <3> or ... is appended to get an unused name."
754 (let ((lastname (file-name-nondirectory filename)))
755 (if (string= lastname "")
756 (setq lastname filename))
757 (generate-new-buffer lastname)))
758
759 (defun generate-new-buffer (name)
760 "Create and return a buffer with a name based on NAME.
761 Choose the buffer's name using `generate-new-buffer-name'."
762 (get-buffer-create (generate-new-buffer-name name)))
763
764 (defvar automount-dir-prefix "^/tmp_mnt/"
765 "Regexp to match the automounter prefix in a directory name.")
766
767 (defvar abbreviated-home-dir nil
768 "The user's homedir abbreviated according to `directory-abbrev-list'.")
769
770 (defun abbreviate-file-name (filename)
771 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
772 This also substitutes \"~\" for the user's home directory.
773 Type \\[describe-variable] directory-abbrev-alist RET for more information."
774 ;; Get rid of the prefixes added by the automounter.
775 (if (and automount-dir-prefix
776 (string-match automount-dir-prefix filename)
777 (file-exists-p (file-name-directory
778 (substring filename (1- (match-end 0))))))
779 (setq filename (substring filename (1- (match-end 0)))))
780 (let ((tail directory-abbrev-alist))
781 ;; If any elt of directory-abbrev-alist matches this name,
782 ;; abbreviate accordingly.
783 (while tail
784 (if (string-match (car (car tail)) filename)
785 (setq filename
786 (concat (cdr (car tail)) (substring filename (match-end 0)))))
787 (setq tail (cdr tail)))
788 ;; Compute and save the abbreviated homedir name.
789 ;; We defer computing this until the first time it's needed, to
790 ;; give time for directory-abbrev-alist to be set properly.
791 ;; We include a slash at the end, to avoid spurious matches
792 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
793 (or abbreviated-home-dir
794 (setq abbreviated-home-dir
795 (let ((abbreviated-home-dir "$foo"))
796 (concat "^" (abbreviate-file-name (expand-file-name "~"))
797 "\\(/\\|$\\)"))))
798
799 ;; If FILENAME starts with the abbreviated homedir,
800 ;; make it start with `~' instead.
801 (if (and (string-match abbreviated-home-dir filename)
802 ;; If the home dir is just /, don't change it.
803 (not (and (= (match-end 0) 1)
804 (= (aref filename 0) ?/)))
805 ;; MS-DOS root directories can come with a drive letter;
806 ;; Novell Netware allows drive letters beyond `Z:'.
807 (not (and (or (eq system-type 'ms-dos)
808 (eq system-type 'windows-nt))
809 (save-match-data
810 (string-match "^[a-zA-`]:/$" filename)))))
811 (setq filename
812 (concat "~"
813 (substring filename (match-beginning 1) (match-end 1))
814 (substring filename (match-end 0)))))
815 filename))
816
817 (defcustom find-file-not-true-dirname-list nil
818 "*List of logical names for which visiting shouldn't save the true dirname.
819 On VMS, when you visit a file using a logical name that searches a path,
820 you may or may not want the visited file name to record the specific
821 directory where the file was found. If you *do not* want that, add the logical
822 name to this list as a string."
823 :type '(repeat (string :tag "Name"))
824 :group 'find-file)
825
826 (defun find-buffer-visiting (filename)
827 "Return the buffer visiting file FILENAME (a string).
828 This is like `get-file-buffer', except that it checks for any buffer
829 visiting the same file, possibly under a different name.
830 If there is no such live buffer, return nil."
831 (let ((buf (get-file-buffer filename))
832 (truename (abbreviate-file-name (file-truename filename))))
833 (or buf
834 (let ((list (buffer-list)) found)
835 (while (and (not found) list)
836 (save-excursion
837 (set-buffer (car list))
838 (if (and buffer-file-name
839 (string= buffer-file-truename truename))
840 (setq found (car list))))
841 (setq list (cdr list)))
842 found)
843 (let ((number (nthcdr 10 (file-attributes truename)))
844 (list (buffer-list)) found)
845 (and buffer-file-numbers-unique
846 number
847 (while (and (not found) list)
848 (save-excursion
849 (set-buffer (car list))
850 (if (and buffer-file-name
851 (equal buffer-file-number number)
852 ;; Verify this buffer's file number
853 ;; still belongs to its file.
854 (file-exists-p buffer-file-name)
855 (equal (nthcdr 10 (file-attributes buffer-file-name))
856 number))
857 (setq found (car list))))
858 (setq list (cdr list))))
859 found))))
860 \f
861 (defun find-file-noselect (filename &optional nowarn rawfile)
862 "Read file FILENAME into a buffer and return the buffer.
863 If a buffer exists visiting FILENAME, return that one, but
864 verify that the file has not changed since visited or saved.
865 The buffer is not selected, just returned to the caller.
866 Optional first arg NOWARN non-nil means suppress any warning messages.
867 Optional second arg RAWFILE non-nil means the file is read literally."
868 (setq filename
869 (abbreviate-file-name
870 (expand-file-name filename)))
871 (if (file-directory-p filename)
872 (if find-file-run-dired
873 (dired-noselect (if find-file-visit-truename
874 (abbreviate-file-name (file-truename filename))
875 filename))
876 (error "%s is a directory" filename))
877 (let* ((buf (get-file-buffer filename))
878 (truename (abbreviate-file-name (file-truename filename)))
879 (number (nthcdr 10 (file-attributes truename)))
880 ;; Find any buffer for a file which has same truename.
881 (other (and (not buf) (find-buffer-visiting filename))))
882 ;; Let user know if there is a buffer with the same truename.
883 (if other
884 (progn
885 (or nowarn
886 (string-equal filename (buffer-file-name other))
887 (message "%s and %s are the same file"
888 filename (buffer-file-name other)))
889 ;; Optionally also find that buffer.
890 (if (or find-file-existing-other-name find-file-visit-truename)
891 (setq buf other))))
892 (if buf
893 (progn
894 (or nowarn
895 (verify-visited-file-modtime buf)
896 (cond ((not (file-exists-p filename))
897 (error "File %s no longer exists!" filename))
898 ;; Certain files should be reverted automatically
899 ;; if they have changed on disk and not in the buffer.
900 ((and (not (buffer-modified-p buf))
901 (let ((tail revert-without-query)
902 (found nil))
903 (while tail
904 (if (string-match (car tail) filename)
905 (setq found t))
906 (setq tail (cdr tail)))
907 found))
908 (with-current-buffer buf
909 (message "Reverting file %s..." filename)
910 (revert-buffer t t)
911 (message "Reverting file %s...done" filename)))
912 ((yes-or-no-p
913 (if (string= (file-name-nondirectory filename)
914 (buffer-name buf))
915 (format
916 (if (buffer-modified-p buf)
917 "File %s changed on disk. Discard your edits? "
918 "File %s changed on disk. Reread from disk? ")
919 (file-name-nondirectory filename))
920 (format
921 (if (buffer-modified-p buf)
922 "File %s changed on disk. Discard your edits in %s? "
923 "File %s changed on disk. Reread from disk into %s? ")
924 (file-name-nondirectory filename)
925 (buffer-name buf))))
926 (with-current-buffer buf
927 (revert-buffer t t)))))
928 (when (not (eq rawfile (not (null find-file-literally))))
929 (with-current-buffer buf
930 (if (buffer-modified-p)
931 (if (y-or-n-p (if rawfile
932 "Save file and revisit literally? "
933 "Save file and revisit non-literally? "))
934 (progn
935 (save-buffer)
936 (find-file-noselect-1 buf filename nowarn
937 rawfile truename number))
938 (if (y-or-n-p (if rawfile
939 "Discard your edits and revisit file literally? "
940 "Discard your edits and revisit file non-literally? "))
941 (find-file-noselect-1 buf filename nowarn
942 rawfile truename number)
943 (error (if rawfile "File already visited non-literally"
944 "File already visited literally"))))
945 (if (y-or-n-p (if rawfile
946 "Revisit file literally? "
947 "Revisit file non-literally? "))
948 (find-file-noselect-1 buf filename nowarn
949 rawfile truename number)
950 (error (if rawfile "File already visited non-literally"
951 "File already visited literally")))))))
952 (progn
953 (setq buf (create-file-buffer filename))
954 (set-buffer-major-mode buf)
955 (find-file-noselect-1 buf filename nowarn rawfile truename number)))
956 buf)))
957
958 (defun find-file-noselect-1 (buf filename nowarn rawfile truename number)
959 (let ((inhibit-read-only t)
960 error)
961 (with-current-buffer buf
962 (kill-local-variable 'find-file-literally)
963 (setq buffer-file-coding-system nil)
964 (erase-buffer)
965 (and (default-value 'enable-multibyte-characters)
966 (not rawfile)
967 (set-buffer-multibyte t))
968 (if rawfile
969 (condition-case ()
970 (insert-file-contents-literally filename t)
971 (file-error
972 (when (and (file-exists-p filename)
973 (not (file-readable-p filename)))
974 (kill-buffer buf)
975 (signal 'file-error (list "File is not readable"
976 filename)))
977 ;; Unconditionally set error
978 (setq error t)))
979 (condition-case ()
980 (insert-file-contents filename t)
981 (file-error
982 (when (and (file-exists-p filename)
983 (not (file-readable-p filename)))
984 (kill-buffer buf)
985 (signal 'file-error (list "File is not readable"
986 filename)))
987 ;; Run find-file-not-found-hooks until one returns non-nil.
988 (or (run-hook-with-args-until-success 'find-file-not-found-hooks)
989 ;; If they fail too, set error.
990 (setq error t)))))
991 ;; Find the file's truename, and maybe use that as visited name.
992 (setq buffer-file-truename truename)
993 (setq buffer-file-number number)
994 ;; On VMS, we may want to remember which directory in a search list
995 ;; the file was found in.
996 (and (eq system-type 'vax-vms)
997 (let (logical)
998 (if (string-match ":" (file-name-directory filename))
999 (setq logical (substring (file-name-directory filename)
1000 0 (match-beginning 0))))
1001 (not (member logical find-file-not-true-dirname-list)))
1002 (setq buffer-file-name buffer-file-truename))
1003 (if find-file-visit-truename
1004 (setq buffer-file-name
1005 (setq filename
1006 (expand-file-name buffer-file-truename))))
1007 ;; Set buffer's default directory to that of the file.
1008 (setq default-directory (file-name-directory filename))
1009 ;; Turn off backup files for certain file names. Since
1010 ;; this is a permanent local, the major mode won't eliminate it.
1011 (and (not (funcall backup-enable-predicate buffer-file-name))
1012 (progn
1013 (make-local-variable 'backup-inhibited)
1014 (setq backup-inhibited t)))
1015 (if rawfile
1016 (progn
1017 (set-buffer-multibyte nil)
1018 (setq buffer-file-coding-system 'no-conversion)
1019 (make-local-variable 'find-file-literally)
1020 (setq find-file-literally t))
1021 (after-find-file error (not nowarn))
1022 (setq buf (current-buffer))))))
1023 \f
1024 (defun insert-file-contents-literally (filename &optional visit beg end replace)
1025 "Like `insert-file-contents', but only reads in the file literally.
1026 A buffer may be modified in several ways after reading into the buffer,
1027 to Emacs features such as format decoding, character code
1028 conversion, find-file-hooks, automatic uncompression, etc.
1029
1030 This function ensures that none of these modifications will take place."
1031 (let ((format-alist nil)
1032 (after-insert-file-functions nil)
1033 (coding-system-for-read 'no-conversion)
1034 (coding-system-for-write 'no-conversion)
1035 (jka-compr-compression-info-list nil)
1036 (find-buffer-file-type-function
1037 (if (fboundp 'find-buffer-file-type)
1038 (symbol-function 'find-buffer-file-type)
1039 nil)))
1040 (unwind-protect
1041 (progn
1042 (fset 'find-buffer-file-type (lambda (filename) t))
1043 (insert-file-contents filename visit beg end replace))
1044 (if find-buffer-file-type-function
1045 (fset 'find-buffer-file-type find-buffer-file-type-function)
1046 (fmakunbound 'find-buffer-file-type)))))
1047
1048 (defun insert-file-literally (filename)
1049 "Insert contents of file FILENAME into buffer after point with no conversion.
1050
1051 This function is meant for the user to run interactively.
1052 Don't call it from programs! Use `insert-file-contents-literally' instead.
1053 \(Its calling sequence is different; see its documentation)."
1054 (interactive "*fInsert file literally: ")
1055 (if (file-directory-p filename)
1056 (signal 'file-error (list "Opening input file" "file is a directory"
1057 filename)))
1058 (let ((tem (insert-file-contents-literally filename)))
1059 (push-mark (+ (point) (car (cdr tem))))))
1060
1061 (defvar find-file-literally nil
1062 "Non-nil if this buffer was made by `find-file-literally' or equivalent.
1063 This is a permanent local.")
1064 (put 'find-file-literally 'permanent-local t)
1065
1066 (defun find-file-literally (filename)
1067 "Visit file FILENAME with no conversion of any kind.
1068 Format conversion and character code conversion are both disabled,
1069 and multibyte characters are disabled in the resulting buffer.
1070 The major mode used is Fundamental mode regardless of the file name,
1071 and local variable specifications in the file are ignored.
1072 Automatic uncompression is also disabled.
1073
1074 You cannot absolutely rely on this function to result in
1075 visiting the file literally. If Emacs already has a buffer
1076 which is visiting the file, you get the existing buffer,
1077 regardless of whether it was created literally or not.
1078
1079 In a Lisp program, if you want to be sure of accessing a file's
1080 contents literally, you should create a temporary buffer and then read
1081 the file contents into it using `insert-file-contents-literally'."
1082 (interactive "FFind file literally: ")
1083 (switch-to-buffer (find-file-noselect filename nil t)))
1084 \f
1085 (defvar after-find-file-from-revert-buffer nil)
1086
1087 (defun after-find-file (&optional error warn noauto
1088 after-find-file-from-revert-buffer
1089 nomodes)
1090 "Called after finding a file and by the default revert function.
1091 Sets buffer mode, parses local variables.
1092 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
1093 error in reading the file. WARN non-nil means warn if there
1094 exists an auto-save file more recent than the visited file.
1095 NOAUTO means don't mess with auto-save mode.
1096 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
1097 means this call was from `revert-buffer'.
1098 Fifth arg NOMODES non-nil means don't alter the file's modes.
1099 Finishes by calling the functions in `find-file-hooks'
1100 unless NOMODES is non-nil."
1101 (setq buffer-read-only (not (file-writable-p buffer-file-name)))
1102 (if noninteractive
1103 nil
1104 (let* (not-serious
1105 (msg
1106 (cond ((and error (file-attributes buffer-file-name))
1107 (setq buffer-read-only t)
1108 "File exists, but cannot be read.")
1109 ((not buffer-read-only)
1110 (if (and warn
1111 (file-newer-than-file-p (make-auto-save-file-name)
1112 buffer-file-name))
1113 (format "%s has auto save data; consider M-x recover-file"
1114 (file-name-nondirectory buffer-file-name))
1115 (setq not-serious t)
1116 (if error "(New file)" nil)))
1117 ((not error)
1118 (setq not-serious t)
1119 "Note: file is write protected")
1120 ((file-attributes (directory-file-name default-directory))
1121 "File not found and directory write-protected")
1122 ((file-exists-p (file-name-directory buffer-file-name))
1123 (setq buffer-read-only nil))
1124 (t
1125 (setq buffer-read-only nil)
1126 (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
1127 "Use M-x make-dir RET RET to create the directory"
1128 "Use C-u M-x make-dir RET RET to create directory and its parents")))))
1129 (if msg
1130 (progn
1131 (message msg)
1132 (or not-serious (sit-for 1 nil t)))))
1133 (if (and auto-save-default (not noauto))
1134 (auto-save-mode t)))
1135 (if nomodes
1136 nil
1137 (normal-mode t)
1138 (if (and buffer-read-only view-read-only
1139 (not (eq (get major-mode 'mode-class) 'special)))
1140 (view-mode-enter))
1141 (run-hooks 'find-file-hooks)))
1142
1143 (defun normal-mode (&optional find-file)
1144 "Choose the major mode for this buffer automatically.
1145 Also sets up any specified local variables of the file.
1146 Uses the visited file name, the -*- line, and the local variables spec.
1147
1148 This function is called automatically from `find-file'. In that case,
1149 we may set up specified local variables depending on the value of
1150 `enable-local-variables': if it is t, we do; if it is nil, we don't;
1151 otherwise, we query. `enable-local-variables' is ignored if you
1152 run `normal-mode' explicitly."
1153 (interactive)
1154 (or find-file (funcall (or default-major-mode 'fundamental-mode)))
1155 (condition-case err
1156 (set-auto-mode)
1157 (error (message "File mode specification error: %s"
1158 (prin1-to-string err))))
1159 (condition-case err
1160 (let ((enable-local-variables (or (not find-file)
1161 enable-local-variables)))
1162 (hack-local-variables))
1163 (error (message "File local-variables error: %s"
1164 (prin1-to-string err)))))
1165
1166 (defvar auto-mode-alist
1167 '(("\\.te?xt\\'" . text-mode)
1168 ("\\.c\\'" . c-mode)
1169 ("\\.h\\'" . c-mode)
1170 ("\\.tex\\'" . tex-mode)
1171 ("\\.ltx\\'" . latex-mode)
1172 ("\\.el\\'" . emacs-lisp-mode)
1173 ("\\.mm\\'" . nroff-mode)
1174 ("\\.me\\'" . nroff-mode)
1175 ("\\.ms\\'" . nroff-mode)
1176 ("\\.man\\'" . nroff-mode)
1177 ("\\.scm\\'" . scheme-mode)
1178 ("\\.l\\'" . lisp-mode)
1179 ("\\.lisp\\'" . lisp-mode)
1180 ("\\.f\\'" . fortran-mode)
1181 ("\\.F\\'" . fortran-mode)
1182 ("\\.for\\'" . fortran-mode)
1183 ("\\.p\\'" . pascal-mode)
1184 ("\\.pas\\'" . pascal-mode)
1185 ("\\.ad[abs]\\'" . ada-mode)
1186 ("\\.\\([pP][Llm]\\|al\\)\\'" . perl-mode)
1187 ("\\.s?html?\\'" . html-mode)
1188 ("\\.cc\\'" . c++-mode)
1189 ("\\.hh\\'" . c++-mode)
1190 ("\\.hpp\\'" . c++-mode)
1191 ("\\.C\\'" . c++-mode)
1192 ("\\.H\\'" . c++-mode)
1193 ("\\.cpp\\'" . c++-mode)
1194 ("\\.cxx\\'" . c++-mode)
1195 ("\\.hxx\\'" . c++-mode)
1196 ("\\.c\\+\\+\\'" . c++-mode)
1197 ("\\.h\\+\\+\\'" . c++-mode)
1198 ("\\.m\\'" . objc-mode)
1199 ("\\.java\\'" . java-mode)
1200 ("\\.mk\\'" . makefile-mode)
1201 ("\\(M\\|m\\|GNUm\\)akefile\\(.in\\)?\\'" . makefile-mode)
1202 ("\\.am\\'" . makefile-mode) ;For Automake.
1203 ;;; Less common extensions come here
1204 ;;; so more common ones above are found faster.
1205 ("\\.texinfo\\'" . texinfo-mode)
1206 ("\\.te?xi\\'" . texinfo-mode)
1207 ("\\.s\\'" . asm-mode)
1208 ("\\.S\\'" . asm-mode)
1209 ("\\.asm\\'" . asm-mode)
1210 ("ChangeLog\\'" . change-log-mode)
1211 ("change.log\\'" . change-log-mode)
1212 ("changelo\\'" . change-log-mode)
1213 ("ChangeLog.[0-9]+\\'" . change-log-mode)
1214 ;; for MSDOS and MS-Windows (which are case-insensitive)
1215 ("changelog\\'" . change-log-mode)
1216 ("changelog.[0-9]+\\'" . change-log-mode)
1217 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
1218 ("\\.scm\\.[0-9]*\\'" . scheme-mode)
1219 ("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode)
1220 ("/\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode)
1221 ("/\\.\\(bash_logout\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode)
1222 ("/\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
1223 ;;; The following should come after the ChangeLog pattern
1224 ;;; for the sake of ChangeLog.1, etc.
1225 ;;; and after the .scm.[0-9] pattern too.
1226 ("\\.[12345678]\\'" . nroff-mode)
1227 ("\\.TeX\\'" . tex-mode)
1228 ("\\.sty\\'" . latex-mode)
1229 ("\\.cls\\'" . latex-mode) ;LaTeX 2e class
1230 ("\\.clo\\'" . latex-mode) ;LaTeX 2e class option
1231 ("\\.bbl\\'" . latex-mode)
1232 ("\\.bib\\'" . bibtex-mode)
1233 ("\\.m4\\'" . m4-mode)
1234 ("\\.mc\\'" . m4-mode)
1235 ("\\.mf\\'" . metafont-mode)
1236 ("\\.mp\\'" . metapost-mode)
1237 ("\\.vhdl?\\'" . vhdl-mode)
1238 ("\\.article\\'" . text-mode)
1239 ("\\.letter\\'" . text-mode)
1240 ("\\.tcl\\'" . tcl-mode)
1241 ("\\.exp\\'" . tcl-mode)
1242 ("\\.itcl\\'" . tcl-mode)
1243 ("\\.itk\\'" . tcl-mode)
1244 ("\\.icn\\'" . icon-mode)
1245 ("\\.sim\\'" . simula-mode)
1246 ("\\.mss\\'" . scribe-mode)
1247 ("\\.f90\\'" . f90-mode)
1248 ("\\.lsp\\'" . lisp-mode)
1249 ("\\.awk\\'" . awk-mode)
1250 ("\\.prolog\\'" . prolog-mode)
1251 ("\\.tar\\'" . tar-mode)
1252 ("\\.\\(arc\\|zip\\|lzh\\|zoo\\|jar\\)\\'" . archive-mode)
1253 ("\\.\\(ARC\\|ZIP\\|LZH\\|ZOO\\|JAR\\)\\'" . archive-mode)
1254 ;; Mailer puts message to be edited in
1255 ;; /tmp/Re.... or Message
1256 ("\\`/tmp/Re" . text-mode)
1257 ("/Message[0-9]*\\'" . text-mode)
1258 ("/drafts/[0-9]+\\'" . mh-letter-mode)
1259 ("\\.zone\\'" . zone-mode)
1260 ;; some news reader is reported to use this
1261 ("\\`/tmp/fol/" . text-mode)
1262 ("\\.y\\'" . c-mode)
1263 ("\\.lex\\'" . c-mode)
1264 ("\\.oak\\'" . scheme-mode)
1265 ("\\.sgml?\\'" . sgml-mode)
1266 ("\\.dtd\\'" . sgml-mode)
1267 ("\\.ds\\(ss\\)?l\\'" . dsssl-mode)
1268 ;; .emacs following a directory delimiter
1269 ;; in Unix, MSDOG or VMS syntax.
1270 ("[]>:/\\]\\..*emacs\\'" . emacs-lisp-mode)
1271 ;; _emacs following a directory delimiter
1272 ;; in MsDos syntax
1273 ("[:/]_emacs\\'" . emacs-lisp-mode)
1274 ("\\.ml\\'" . lisp-mode))
1275 "\
1276 Alist of filename patterns vs corresponding major mode functions.
1277 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
1278 \(NON-NIL stands for anything that is not nil; the value does not matter.)
1279 Visiting a file whose name matches REGEXP specifies FUNCTION as the
1280 mode function to use. FUNCTION will be called, unless it is nil.
1281
1282 If the element has the form (REGEXP FUNCTION NON-NIL), then after
1283 calling FUNCTION (if it's not nil), we delete the suffix that matched
1284 REGEXP and search the list again for another match.")
1285
1286
1287 (defvar interpreter-mode-alist
1288 '(("perl" . perl-mode)
1289 ("perl5" . perl-mode)
1290 ("miniperl" . perl-mode)
1291 ("wish" . tcl-mode)
1292 ("wishx" . tcl-mode)
1293 ("tcl" . tcl-mode)
1294 ("tclsh" . tcl-mode)
1295 ("awk" . awk-mode)
1296 ("mawk" . awk-mode)
1297 ("nawk" . awk-mode)
1298 ("gawk" . awk-mode)
1299 ("scm" . scheme-mode)
1300 ("ash" . sh-mode)
1301 ("bash" . sh-mode)
1302 ("csh" . sh-mode)
1303 ("dtksh" . sh-mode)
1304 ("es" . sh-mode)
1305 ("itcsh" . sh-mode)
1306 ("jsh" . sh-mode)
1307 ("ksh" . sh-mode)
1308 ("oash" . sh-mode)
1309 ("pdksh" . sh-mode)
1310 ("rc" . sh-mode)
1311 ("sh" . sh-mode)
1312 ("sh5" . sh-mode)
1313 ("tcsh" . sh-mode)
1314 ("wksh" . sh-mode)
1315 ("wsh" . sh-mode)
1316 ("zsh" . sh-mode)
1317 ("tail" . text-mode)
1318 ("more" . text-mode)
1319 ("less" . text-mode)
1320 ("pg" . text-mode))
1321 "Alist mapping interpreter names to major modes.
1322 This alist applies to files whose first line starts with `#!'.
1323 Each element looks like (INTERPRETER . MODE).
1324 The car of each element is compared with
1325 the name of the interpreter specified in the first line.
1326 If it matches, mode MODE is selected.")
1327
1328 (defvar inhibit-first-line-modes-regexps '("\\.tar\\'" "\\.tgz\\'")
1329 "List of regexps; if one matches a file name, don't look for `-*-'.")
1330
1331 (defvar inhibit-first-line-modes-suffixes nil
1332 "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
1333 When checking `inhibit-first-line-modes-regexps', we first discard
1334 from the end of the file name anything that matches one of these regexps.")
1335
1336 (defvar user-init-file nil
1337 "File name, including directory, of user's initialization file.")
1338
1339 (defun set-auto-mode (&optional just-from-file-name)
1340 "Select major mode appropriate for current buffer.
1341 This checks for a -*- mode tag in the buffer's text,
1342 compares the filename against the entries in `auto-mode-alist',
1343 or checks the interpreter that runs this file against
1344 `interpreter-mode-alist'.
1345
1346 It does not check for the `mode:' local variable in the
1347 Local Variables section of the file; for that, use `hack-local-variables'.
1348
1349 If `enable-local-variables' is nil, this function does not check for a
1350 -*- mode tag.
1351
1352 If the optional argument JUST-FROM-FILE-NAME is non-nil,
1353 then we do not set anything but the major mode,
1354 and we don't even do that unless it would come from the file name."
1355 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
1356 (let (beg end done modes)
1357 (save-excursion
1358 (goto-char (point-min))
1359 (skip-chars-forward " \t\n")
1360 (and enable-local-variables
1361 local-enable-local-variables
1362 ;; Don't look for -*- if this file name matches any
1363 ;; of the regexps in inhibit-first-line-modes-regexps.
1364 (let ((temp inhibit-first-line-modes-regexps)
1365 (name (if buffer-file-name
1366 (file-name-sans-versions buffer-file-name)
1367 (buffer-name))))
1368 (while (let ((sufs inhibit-first-line-modes-suffixes))
1369 (while (and sufs (not (string-match (car sufs) name)))
1370 (setq sufs (cdr sufs)))
1371 sufs)
1372 (setq name (substring name 0 (match-beginning 0))))
1373 (while (and temp
1374 (not (string-match (car temp) name)))
1375 (setq temp (cdr temp)))
1376 (not temp))
1377 (search-forward "-*-" (save-excursion
1378 ;; If the file begins with "#!"
1379 ;; (exec interpreter magic), look
1380 ;; for mode frobs in the first two
1381 ;; lines. You cannot necessarily
1382 ;; put them in the first line of
1383 ;; such a file without screwing up
1384 ;; the interpreter invocation.
1385 (end-of-line (and (looking-at "^#!") 2))
1386 (point)) t)
1387 (progn
1388 (skip-chars-forward " \t")
1389 (setq beg (point))
1390 (search-forward "-*-"
1391 (save-excursion (end-of-line) (point))
1392 t))
1393 (progn
1394 (forward-char -3)
1395 (skip-chars-backward " \t")
1396 (setq end (point))
1397 (goto-char beg)
1398 (if (save-excursion (search-forward ":" end t))
1399 ;; Find all specifications for the `mode:' variable
1400 ;; and execute them left to right.
1401 (while (let ((case-fold-search t))
1402 (or (and (looking-at "mode:")
1403 (goto-char (match-end 0)))
1404 (re-search-forward "[ \t;]mode:" end t)))
1405 (skip-chars-forward " \t")
1406 (setq beg (point))
1407 (if (search-forward ";" end t)
1408 (forward-char -1)
1409 (goto-char end))
1410 (skip-chars-backward " \t")
1411 (setq modes (cons (intern (concat (downcase (buffer-substring beg (point))) "-mode"))
1412 modes)))
1413 ;; Simple -*-MODE-*- case.
1414 (setq modes (cons (intern (concat (downcase (buffer-substring beg end))
1415 "-mode"))
1416 modes))))))
1417 ;; If we found modes to use, invoke them now,
1418 ;; outside the save-excursion.
1419 (when modes
1420 (unless just-from-file-name
1421 (mapcar 'funcall (nreverse modes)))
1422 (setq done t))
1423 ;; If we didn't find a mode from a -*- line, try using the file name.
1424 (if (and (not done) buffer-file-name)
1425 (let ((name buffer-file-name)
1426 (keep-going t))
1427 ;; Remove backup-suffixes from file name.
1428 (setq name (file-name-sans-versions name))
1429 (while keep-going
1430 (setq keep-going nil)
1431 (let ((alist auto-mode-alist)
1432 (mode nil))
1433 ;; Find first matching alist entry.
1434 (let ((case-fold-search
1435 (memq system-type '(vax-vms windows-nt))))
1436 (while (and (not mode) alist)
1437 (if (string-match (car (car alist)) name)
1438 (if (and (consp (cdr (car alist)))
1439 (nth 2 (car alist)))
1440 (progn
1441 (setq mode (car (cdr (car alist)))
1442 name (substring name 0 (match-beginning 0))
1443 keep-going t))
1444 (setq mode (cdr (car alist))
1445 keep-going nil)))
1446 (setq alist (cdr alist))))
1447 (if mode
1448 ;; When JUST-FROM-FILE-NAME is set,
1449 ;; we are working on behalf of set-visited-file-name.
1450 ;; In that case, if the major mode specified is the
1451 ;; same one we already have, don't actually reset it.
1452 ;; We don't want to lose minor modes such as Font Lock.
1453 (unless (and just-from-file-name (eq mode major-mode))
1454 (funcall mode))
1455 ;; If we can't deduce a mode from the file name,
1456 ;; look for an interpreter specified in the first line.
1457 ;; As a special case, allow for things like "#!/bin/env perl",
1458 ;; which finds the interpreter anywhere in $PATH.
1459 (let ((interpreter
1460 (save-excursion
1461 (goto-char (point-min))
1462 (if (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1463 (buffer-substring (match-beginning 2)
1464 (match-end 2))
1465 "")))
1466 elt)
1467 ;; Map interpreter name to a mode.
1468 (setq elt (assoc (file-name-nondirectory interpreter)
1469 interpreter-mode-alist))
1470 (unless just-from-file-name
1471 (if elt
1472 (funcall (cdr elt))))))))))))
1473
1474 (defun hack-local-variables-prop-line ()
1475 ;; Set local variables specified in the -*- line.
1476 ;; Ignore any specification for `mode:' and `coding:';
1477 ;; set-auto-mode should already have handled `mode:',
1478 ;; set-auto-coding should already have handled `coding:'.
1479 (save-excursion
1480 (goto-char (point-min))
1481 (let ((result nil)
1482 (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point))))
1483 ;; Parse the -*- line into the `result' alist.
1484 (cond ((not (search-forward "-*-" end t))
1485 ;; doesn't have one.
1486 nil)
1487 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
1488 ;; Simple form: "-*- MODENAME -*-". Already handled.
1489 nil)
1490 (t
1491 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
1492 ;; (last ";" is optional).
1493 (save-excursion
1494 (if (search-forward "-*-" end t)
1495 (setq end (- (point) 3))
1496 (error "-*- not terminated before end of line")))
1497 (while (< (point) end)
1498 (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
1499 (error "malformed -*- line"))
1500 (goto-char (match-end 0))
1501 ;; There used to be a downcase here,
1502 ;; but the manual didn't say so,
1503 ;; and people want to set var names that aren't all lc.
1504 (let ((key (intern (buffer-substring
1505 (match-beginning 1)
1506 (match-end 1))))
1507 (val (save-restriction
1508 (narrow-to-region (point) end)
1509 (read (current-buffer)))))
1510 ;; It is traditional to ignore
1511 ;; case when checking for `mode' in set-auto-mode,
1512 ;; so we must do that here as well.
1513 ;; That is inconsistent, but we're stuck with it.
1514 ;; The same can be said for `coding' in set-auto-coding.
1515 (or (equal (downcase (symbol-name key)) "mode")
1516 (equal (downcase (symbol-name key)) "coding")
1517 (setq result (cons (cons key val) result)))
1518 (skip-chars-forward " \t;")))
1519 (setq result (nreverse result))))
1520
1521 (if (and result
1522 (or (eq enable-local-variables t)
1523 (and enable-local-variables
1524 (save-window-excursion
1525 (condition-case nil
1526 (switch-to-buffer (current-buffer))
1527 (error
1528 ;; If we fail to switch in the selected window,
1529 ;; it is probably a minibuffer.
1530 ;; So try another window.
1531 (condition-case nil
1532 (switch-to-buffer-other-window (current-buffer))
1533 (error
1534 (switch-to-buffer-other-frame (current-buffer))))))
1535 (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
1536 (file-name-nondirectory buffer-file-name)))))))
1537 (let ((enable-local-eval enable-local-eval))
1538 (while result
1539 (hack-one-local-variable (car (car result)) (cdr (car result)))
1540 (setq result (cdr result))))))))
1541
1542 (defvar hack-local-variables-hook nil
1543 "Normal hook run after processing a file's local variables specs.
1544 Major modes can use this to examine user-specified local variables
1545 in order to initialize other data structure based on them.")
1546
1547 (defun hack-local-variables (&optional mode-only)
1548 "Parse and put into effect this buffer's local variables spec.
1549 If MODE-ONLY is non-nil, all we do is check whether the major mode
1550 is specified, returning t if it is specified."
1551 (unless mode-only
1552 (hack-local-variables-prop-line))
1553 ;; Look for "Local variables:" line in last page.
1554 (let (mode-specified)
1555 (save-excursion
1556 (goto-char (point-max))
1557 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
1558 (if (let ((case-fold-search t))
1559 (and (search-forward "Local Variables:" nil t)
1560 (or (eq enable-local-variables t)
1561 mode-only
1562 (and enable-local-variables
1563 (save-window-excursion
1564 (switch-to-buffer (current-buffer))
1565 (save-excursion
1566 (beginning-of-line)
1567 (set-window-start (selected-window) (point)))
1568 (y-or-n-p (format "Set local variables as specified at end of %s? "
1569 (if buffer-file-name
1570 (file-name-nondirectory
1571 buffer-file-name)
1572 (concat "buffer "
1573 (buffer-name))))))))))
1574 (let ((continue t)
1575 prefix prefixlen suffix beg
1576 mode-specified
1577 (enable-local-eval enable-local-eval))
1578 ;; The prefix is what comes before "local variables:" in its line.
1579 ;; The suffix is what comes after "local variables:" in its line.
1580 (skip-chars-forward " \t")
1581 (or (eolp)
1582 (setq suffix (buffer-substring (point)
1583 (progn (end-of-line) (point)))))
1584 (goto-char (match-beginning 0))
1585 (or (bolp)
1586 (setq prefix
1587 (buffer-substring (point)
1588 (progn (beginning-of-line) (point)))))
1589
1590 (if prefix (setq prefixlen (length prefix)
1591 prefix (regexp-quote prefix)))
1592 (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
1593 (while continue
1594 ;; Look at next local variable spec.
1595 (if selective-display (re-search-forward "[\n\C-m]")
1596 (forward-line 1))
1597 ;; Skip the prefix, if any.
1598 (if prefix
1599 (if (looking-at prefix)
1600 (forward-char prefixlen)
1601 (error "Local variables entry is missing the prefix")))
1602 ;; Find the variable name; strip whitespace.
1603 (skip-chars-forward " \t")
1604 (setq beg (point))
1605 (skip-chars-forward "^:\n")
1606 (if (eolp) (error "Missing colon in local variables entry"))
1607 (skip-chars-backward " \t")
1608 (let* ((str (buffer-substring beg (point)))
1609 (var (read str))
1610 val)
1611 ;; Setting variable named "end" means end of list.
1612 (if (string-equal (downcase str) "end")
1613 (setq continue nil)
1614 ;; Otherwise read the variable value.
1615 (skip-chars-forward "^:")
1616 (forward-char 1)
1617 (setq val (read (current-buffer)))
1618 (skip-chars-backward "\n")
1619 (skip-chars-forward " \t")
1620 (or (if suffix (looking-at suffix) (eolp))
1621 (error "Local variables entry is terminated incorrectly"))
1622 (if mode-only
1623 (if (eq var 'mode)
1624 (setq mode-specified t))
1625 ;; Set the variable. "Variables" mode and eval are funny.
1626 (hack-one-local-variable var val))))))))
1627 (unless mode-only
1628 (run-hooks 'hack-local-variables-hook))
1629 mode-specified))
1630
1631 (defvar ignored-local-variables
1632 '(enable-local-eval)
1633 "Variables to be ignored in a file's local variable spec.")
1634
1635 ;; Get confirmation before setting these variables as locals in a file.
1636 (put 'debugger 'risky-local-variable t)
1637 (put 'enable-local-eval 'risky-local-variable t)
1638 (put 'ignored-local-variables 'risky-local-variable t)
1639 (put 'eval 'risky-local-variable t)
1640 (put 'file-name-handler-alist 'risky-local-variable t)
1641 (put 'minor-mode-map-alist 'risky-local-variable t)
1642 (put 'after-load-alist 'risky-local-variable t)
1643 (put 'buffer-file-name 'risky-local-variable t)
1644 (put 'buffer-auto-save-file-name 'risky-local-variable t)
1645 (put 'buffer-file-truename 'risky-local-variable t)
1646 (put 'exec-path 'risky-local-variable t)
1647 (put 'load-path 'risky-local-variable t)
1648 (put 'exec-directory 'risky-local-variable t)
1649 (put 'process-environment 'risky-local-variable t)
1650 (put 'dabbrev-case-fold-search 'risky-local-variable t)
1651 (put 'dabbrev-case-replace 'risky-local-variable t)
1652 ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
1653 (put 'outline-level 'risky-local-variable t)
1654 (put 'rmail-output-file-alist 'risky-local-variable t)
1655
1656 ;; This one is safe because the user gets to check it before it is used.
1657 (put 'compile-command 'safe-local-variable t)
1658
1659 (defun hack-one-local-variable-quotep (exp)
1660 (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
1661
1662 ;; "Set" one variable in a local variables spec.
1663 ;; A few variable names are treated specially.
1664 (defun hack-one-local-variable (var val)
1665 (cond ((eq var 'mode)
1666 (funcall (intern (concat (downcase (symbol-name val))
1667 "-mode"))))
1668 ((eq var 'coding)
1669 ;; We have already handled coding: tag in set-auto-coding.
1670 nil)
1671 ((memq var ignored-local-variables)
1672 nil)
1673 ;; "Setting" eval means either eval it or do nothing.
1674 ;; Likewise for setting hook variables.
1675 ((or (get var 'risky-local-variable)
1676 (and
1677 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$\\|-predicate$"
1678 (symbol-name var))
1679 (not (get var 'safe-local-variable))))
1680 ;; Permit evalling a put of a harmless property.
1681 ;; if the args do nothing tricky.
1682 (if (or (and (eq var 'eval)
1683 (consp val)
1684 (eq (car val) 'put)
1685 (hack-one-local-variable-quotep (nth 1 val))
1686 (hack-one-local-variable-quotep (nth 2 val))
1687 ;; Only allow safe values of lisp-indent-hook;
1688 ;; not functions.
1689 (or (numberp (nth 3 val))
1690 (equal (nth 3 val) ''defun))
1691 (memq (nth 1 (nth 2 val))
1692 '(lisp-indent-hook)))
1693 ;; Permit eval if not root and user says ok.
1694 (and (not (zerop (user-uid)))
1695 (or (eq enable-local-eval t)
1696 (and enable-local-eval
1697 (save-window-excursion
1698 (switch-to-buffer (current-buffer))
1699 (save-excursion
1700 (beginning-of-line)
1701 (set-window-start (selected-window) (point)))
1702 (setq enable-local-eval
1703 (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
1704 (file-name-nondirectory buffer-file-name)))))))))
1705 (if (eq var 'eval)
1706 (save-excursion (eval val))
1707 (make-local-variable var)
1708 (set var val))
1709 (message "Ignoring `eval:' in file's local variables")))
1710 ;; Ordinary variable, really set it.
1711 (t (make-local-variable var)
1712 (set var val))))
1713
1714 \f
1715 (defcustom change-major-mode-with-file-name t
1716 "*Non-nil means \\[write-file] should set the major mode from the file name.
1717 However, the mode will not be changed if
1718 \(1) a local variables list or the `-*-' line specifies a major mode, or
1719 \(2) the current major mode is a \"special\" mode,
1720 \ not suitable for ordinary files, or
1721 \(3) the new file name does not particularly specify any mode."
1722 :type 'boolean
1723 :group 'editing-basics)
1724
1725 (defun set-visited-file-name (filename &optional no-query along-with-file)
1726 "Change name of file visited in current buffer to FILENAME.
1727 The next time the buffer is saved it will go in the newly specified file.
1728 nil or empty string as argument means make buffer not be visiting any file.
1729 Remember to delete the initial contents of the minibuffer
1730 if you wish to pass an empty string as the argument.
1731
1732 The optional second argument NO-QUERY, if non-nil, inhibits asking for
1733 confirmation in the case where another buffer is already visiting FILENAME.
1734
1735 The optional third argument ALONG-WITH-FILE, if non-nil, means that
1736 the old visited file has been renamed to the new name FILENAME."
1737 (interactive "FSet visited file name: ")
1738 (if (buffer-base-buffer)
1739 (error "An indirect buffer cannot visit a file"))
1740 (let (truename)
1741 (if filename
1742 (setq filename
1743 (if (string-equal filename "")
1744 nil
1745 (expand-file-name filename))))
1746 (if filename
1747 (progn
1748 (setq truename (file-truename filename))
1749 (if find-file-visit-truename
1750 (setq filename truename))))
1751 (let ((buffer (and filename (find-buffer-visiting filename))))
1752 (and buffer (not (eq buffer (current-buffer)))
1753 (not no-query)
1754 (not (y-or-n-p (message "A buffer is visiting %s; proceed? "
1755 filename)))
1756 (error "Aborted")))
1757 (or (equal filename buffer-file-name)
1758 (progn
1759 (and filename (lock-buffer filename))
1760 (unlock-buffer)))
1761 (setq buffer-file-name filename)
1762 (if filename ; make buffer name reflect filename.
1763 (let ((new-name (file-name-nondirectory buffer-file-name)))
1764 (if (string= new-name "")
1765 (error "Empty file name"))
1766 (if (eq system-type 'vax-vms)
1767 (setq new-name (downcase new-name)))
1768 (setq default-directory (file-name-directory buffer-file-name))
1769 (or (string= new-name (buffer-name))
1770 (rename-buffer new-name t))))
1771 (setq buffer-backed-up nil)
1772 (or along-with-file
1773 (clear-visited-file-modtime))
1774 ;; Abbreviate the file names of the buffer.
1775 (if truename
1776 (progn
1777 (setq buffer-file-truename (abbreviate-file-name truename))
1778 (if find-file-visit-truename
1779 (setq buffer-file-name buffer-file-truename))))
1780 (setq buffer-file-number
1781 (if filename
1782 (nthcdr 10 (file-attributes buffer-file-name))
1783 nil)))
1784 ;; write-file-hooks is normally used for things like ftp-find-file
1785 ;; that visit things that are not local files as if they were files.
1786 ;; Changing to visit an ordinary local file instead should flush the hook.
1787 (kill-local-variable 'write-file-hooks)
1788 (kill-local-variable 'local-write-file-hooks)
1789 (kill-local-variable 'revert-buffer-function)
1790 (kill-local-variable 'backup-inhibited)
1791 ;; If buffer was read-only because of version control,
1792 ;; that reason is gone now, so make it writable.
1793 (if vc-mode
1794 (setq buffer-read-only nil))
1795 (kill-local-variable 'vc-mode)
1796 ;; Turn off backup files for certain file names.
1797 ;; Since this is a permanent local, the major mode won't eliminate it.
1798 (and buffer-file-name
1799 (not (funcall backup-enable-predicate buffer-file-name))
1800 (progn
1801 (make-local-variable 'backup-inhibited)
1802 (setq backup-inhibited t)))
1803 (let ((oauto buffer-auto-save-file-name))
1804 ;; If auto-save was not already on, turn it on if appropriate.
1805 (if (not buffer-auto-save-file-name)
1806 (and buffer-file-name auto-save-default
1807 (auto-save-mode t))
1808 ;; If auto save is on, start using a new name.
1809 ;; We deliberately don't rename or delete the old auto save
1810 ;; for the old visited file name. This is because perhaps
1811 ;; the user wants to save the new state and then compare with the
1812 ;; previous state from the auto save file.
1813 (setq buffer-auto-save-file-name
1814 (make-auto-save-file-name)))
1815 ;; Rename the old auto save file if any.
1816 (and oauto buffer-auto-save-file-name
1817 (file-exists-p oauto)
1818 (rename-file oauto buffer-auto-save-file-name t)))
1819 (and buffer-file-name
1820 (not along-with-file)
1821 (set-buffer-modified-p t))
1822 ;; Update the major mode, if the file name determines it.
1823 (condition-case nil
1824 ;; Don't change the mode if it is special.
1825 (or (not change-major-mode-with-file-name)
1826 (get major-mode 'mode-class)
1827 ;; Don't change the mode if the local variable list specifies it.
1828 (hack-local-variables t)
1829 (set-auto-mode t))
1830 (error nil)))
1831
1832 (defun write-file (filename &optional confirm)
1833 "Write current buffer into file FILENAME.
1834 Makes buffer visit that file, and marks it not modified.
1835 If the buffer is already visiting a file, you can specify
1836 a directory name as FILENAME, to write a file of the same
1837 old name in that directory.
1838
1839 If optional second arg CONFIRM is non-nil,
1840 ask for confirmation for overwriting an existing file.
1841 Interactively, confirmation is required unless you supply a prefix argument."
1842 ;; (interactive "FWrite file: ")
1843 (interactive
1844 (list (if buffer-file-name
1845 (read-file-name "Write file: "
1846 nil nil nil nil)
1847 (read-file-name "Write file: "
1848 (cdr (assq 'default-directory
1849 (buffer-local-variables)))
1850 nil nil (file-name-nondirectory (buffer-name))))
1851 (not current-prefix-arg)))
1852 (or (null filename) (string-equal filename "")
1853 (progn
1854 ;; If arg is just a directory,
1855 ;; use same file name, but in that directory.
1856 (if (and (file-directory-p filename) buffer-file-name)
1857 (setq filename (concat (file-name-as-directory filename)
1858 (file-name-nondirectory buffer-file-name))))
1859 (and confirm
1860 (file-exists-p filename)
1861 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
1862 (error "Canceled")))
1863 (set-visited-file-name filename (not confirm))))
1864 (set-buffer-modified-p t)
1865 ;; Make buffer writable if file is writable.
1866 (and buffer-file-name
1867 (file-writable-p buffer-file-name)
1868 (setq buffer-read-only nil))
1869 (save-buffer))
1870 \f
1871 (defun backup-buffer ()
1872 "Make a backup of the disk file visited by the current buffer, if appropriate.
1873 This is normally done before saving the buffer the first time.
1874 If the value is non-nil, it is the result of `file-modes' on the original
1875 file; this means that the caller, after saving the buffer, should change
1876 the modes of the new file to agree with the old modes.
1877
1878 A backup may be done by renaming or by copying; see documentation of
1879 variable `make-backup-files'. If it's done by renaming, then the file is
1880 no longer accessible under its old name."
1881 (if (and make-backup-files (not backup-inhibited)
1882 (not buffer-backed-up)
1883 (file-exists-p buffer-file-name)
1884 (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
1885 '(?- ?l)))
1886 (let ((real-file-name buffer-file-name)
1887 backup-info backupname targets setmodes)
1888 ;; If specified name is a symbolic link, chase it to the target.
1889 ;; Thus we make the backups in the directory where the real file is.
1890 (setq real-file-name (file-chase-links real-file-name))
1891 (setq backup-info (find-backup-file-name real-file-name)
1892 backupname (car backup-info)
1893 targets (cdr backup-info))
1894 ;;; (if (file-directory-p buffer-file-name)
1895 ;;; (error "Cannot save buffer in directory %s" buffer-file-name))
1896 (if backup-info
1897 (condition-case ()
1898 (let ((delete-old-versions
1899 ;; If have old versions to maybe delete,
1900 ;; ask the user to confirm now, before doing anything.
1901 ;; But don't actually delete til later.
1902 (and targets
1903 (or (eq delete-old-versions t) (eq delete-old-versions nil))
1904 (or delete-old-versions
1905 (y-or-n-p (format "Delete excess backup versions of %s? "
1906 real-file-name))))))
1907 ;; Actually write the back up file.
1908 (condition-case ()
1909 (if (or file-precious-flag
1910 ; (file-symlink-p buffer-file-name)
1911 backup-by-copying
1912 (and backup-by-copying-when-linked
1913 (> (file-nlinks real-file-name) 1))
1914 (and backup-by-copying-when-mismatch
1915 (let ((attr (file-attributes real-file-name)))
1916 (or (nth 9 attr)
1917 (not (file-ownership-preserved-p real-file-name))))))
1918 (condition-case ()
1919 (copy-file real-file-name backupname t t)
1920 (file-error
1921 ;; If copying fails because file BACKUPNAME
1922 ;; is not writable, delete that file and try again.
1923 (if (and (file-exists-p backupname)
1924 (not (file-writable-p backupname)))
1925 (delete-file backupname))
1926 (copy-file real-file-name backupname t t)))
1927 ;; rename-file should delete old backup.
1928 (rename-file real-file-name backupname t)
1929 (setq setmodes (file-modes backupname)))
1930 (file-error
1931 ;; If trouble writing the backup, write it in ~.
1932 (setq backupname (expand-file-name
1933 (convert-standard-filename
1934 "~/%backup%~")))
1935 (message "Cannot write backup file; backing up in %s"
1936 (file-name-nondirectory backupname))
1937 (sleep-for 1)
1938 (condition-case ()
1939 (copy-file real-file-name backupname t t)
1940 (file-error
1941 ;; If copying fails because file BACKUPNAME
1942 ;; is not writable, delete that file and try again.
1943 (if (and (file-exists-p backupname)
1944 (not (file-writable-p backupname)))
1945 (delete-file backupname))
1946 (copy-file real-file-name backupname t t)))))
1947 (setq buffer-backed-up t)
1948 ;; Now delete the old versions, if desired.
1949 (if delete-old-versions
1950 (while targets
1951 (condition-case ()
1952 (delete-file (car targets))
1953 (file-error nil))
1954 (setq targets (cdr targets))))
1955 setmodes)
1956 (file-error nil))))))
1957
1958 (defun file-name-sans-versions (name &optional keep-backup-version)
1959 "Return FILENAME sans backup versions or strings.
1960 This is a separate procedure so your site-init or startup file can
1961 redefine it.
1962 If the optional argument KEEP-BACKUP-VERSION is non-nil,
1963 we do not remove backup version numbers, only true file version numbers."
1964 (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
1965 (if handler
1966 (funcall handler 'file-name-sans-versions name keep-backup-version)
1967 (substring name 0
1968 (if (eq system-type 'vax-vms)
1969 ;; VMS version number is (a) semicolon, optional
1970 ;; sign, zero or more digits or (b) period, option
1971 ;; sign, zero or more digits, provided this is the
1972 ;; second period encountered outside of the
1973 ;; device/directory part of the file name.
1974 (or (string-match ";[-+]?[0-9]*\\'" name)
1975 (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
1976 name)
1977 (match-beginning 1))
1978 (length name))
1979 (if keep-backup-version
1980 (length name)
1981 (or (string-match "\\.~[0-9.]+~\\'" name)
1982 (string-match "~\\'" name)
1983 (length name))))))))
1984
1985 (defun file-ownership-preserved-p (file)
1986 "Returns t if deleting FILE and rewriting it would preserve the owner."
1987 (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
1988 (if handler
1989 (funcall handler 'file-ownership-preserved-p file)
1990 (let ((attributes (file-attributes file)))
1991 ;; Return t if the file doesn't exist, since it's true that no
1992 ;; information would be lost by an (attempted) delete and create.
1993 (or (null attributes)
1994 (= (nth 2 attributes) (user-uid)))))))
1995
1996 (defun file-name-sans-extension (filename)
1997 "Return FILENAME sans final \"extension\".
1998 The extension, in a file name, is the part that follows the last `.'."
1999 (save-match-data
2000 (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
2001 directory)
2002 (if (string-match "\\.[^.]*\\'" file)
2003 (if (setq directory (file-name-directory filename))
2004 (expand-file-name (substring file 0 (match-beginning 0))
2005 directory)
2006 (substring file 0 (match-beginning 0)))
2007 filename))))
2008
2009 (defun file-name-extension (filename &optional period)
2010 "Return FILENAME's final \"extension\".
2011 The extension, in a file name, is the part that follows the last `.'.
2012 Return nil for extensionless file names such as `foo'.
2013 Return the empty string for file names such as `foo.'.
2014
2015 If PERIOD is non-nil, then the returned value includes the period
2016 that delimits the extension, and if FILENAME has no extension,
2017 the value is \"\"."
2018 (save-match-data
2019 (let ((file (file-name-sans-versions (file-name-nondirectory filename))))
2020 (if (string-match "\\.[^.]*\\'" file)
2021 (substring file (+ (match-beginning 0) (if period 0 1)))
2022 (if period
2023 "")))))
2024
2025 (defun make-backup-file-name (file)
2026 "Create the non-numeric backup file name for FILE.
2027 This is a separate function so you can redefine it for customization."
2028 (if (and (eq system-type 'ms-dos)
2029 (not (msdos-long-file-names)))
2030 (let ((fn (file-name-nondirectory file)))
2031 (concat (file-name-directory file)
2032 (or
2033 (and (string-match "\\`[^.]+\\'" fn)
2034 (concat (match-string 0 fn) ".~"))
2035 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
2036 (concat (match-string 0 fn) "~")))))
2037 (concat file "~")))
2038
2039 (defun backup-file-name-p (file)
2040 "Return non-nil if FILE is a backup file name (numeric or not).
2041 This is a separate function so you can redefine it for customization.
2042 You may need to redefine `file-name-sans-versions' as well."
2043 (string-match "~\\'" file))
2044
2045 (defvar backup-extract-version-start)
2046
2047 ;; This is used in various files.
2048 ;; The usage of bv-length is not very clean,
2049 ;; but I can't see a good alternative,
2050 ;; so as of now I am leaving it alone.
2051 (defun backup-extract-version (fn)
2052 "Given the name of a numeric backup file, return the backup number.
2053 Uses the free variable `backup-extract-version-start', whose value should be
2054 the index in the name where the version number begins."
2055 (if (and (string-match "[0-9]+~$" fn backup-extract-version-start)
2056 (= (match-beginning 0) backup-extract-version-start))
2057 (string-to-int (substring fn backup-extract-version-start -1))
2058 0))
2059
2060 ;; I believe there is no need to alter this behavior for VMS;
2061 ;; since backup files are not made on VMS, it should not get called.
2062 (defun find-backup-file-name (fn)
2063 "Find a file name for a backup file, and suggestions for deletions.
2064 Value is a list whose car is the name for the backup file
2065 and whose cdr is a list of old versions to consider deleting now.
2066 If the value is nil, don't make a backup."
2067 (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
2068 ;; Run a handler for this function so that ange-ftp can refuse to do it.
2069 (if handler
2070 (funcall handler 'find-backup-file-name fn)
2071 (if (eq version-control 'never)
2072 (list (make-backup-file-name fn))
2073 (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
2074 (backup-extract-version-start (length base-versions))
2075 possibilities
2076 (versions nil)
2077 (high-water-mark 0)
2078 (deserve-versions-p nil)
2079 (number-to-delete 0))
2080 (condition-case ()
2081 (setq possibilities (file-name-all-completions
2082 base-versions
2083 (file-name-directory fn))
2084 versions (sort (mapcar
2085 (function backup-extract-version)
2086 possibilities)
2087 '<)
2088 high-water-mark (apply 'max 0 versions)
2089 deserve-versions-p (or version-control
2090 (> high-water-mark 0))
2091 number-to-delete (- (length versions)
2092 kept-old-versions kept-new-versions -1))
2093 (file-error
2094 (setq possibilities nil)))
2095 (if (not deserve-versions-p)
2096 (list (make-backup-file-name fn))
2097 (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
2098 (if (and (> number-to-delete 0)
2099 ;; Delete nothing if there is overflow
2100 ;; in the number of versions to keep.
2101 (>= (+ kept-new-versions kept-old-versions -1) 0))
2102 (mapcar (function (lambda (n)
2103 (concat fn ".~" (int-to-string n) "~")))
2104 (let ((v (nthcdr kept-old-versions versions)))
2105 (rplacd (nthcdr (1- number-to-delete) v) ())
2106 v))))))))))
2107
2108 (defun file-nlinks (filename)
2109 "Return number of names file FILENAME has."
2110 (car (cdr (file-attributes filename))))
2111
2112 (defun file-relative-name (filename &optional directory)
2113 "Convert FILENAME to be relative to DIRECTORY (default: default-directory).
2114 This function returns a relative file name which is equivalent to FILENAME
2115 when used with that default directory as the default.
2116 If this is impossible (which can happen on MSDOS and Windows
2117 when the file name and directory use different drive names)
2118 then it returns FILENAME."
2119 (save-match-data
2120 (let ((fname (expand-file-name filename)))
2121 (setq directory (file-name-as-directory
2122 (expand-file-name (or directory default-directory))))
2123 ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
2124 ;; drive names, they can't be relative, so return the absolute name.
2125 (if (and (or (eq system-type 'ms-dos)
2126 (eq system-type 'windows-nt))
2127 (not (string-equal (substring fname 0 2)
2128 (substring directory 0 2))))
2129 filename
2130 (let ((ancestor ".")
2131 (fname-dir (file-name-as-directory fname)))
2132 (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
2133 (not (string-match (concat "^" (regexp-quote directory)) fname)))
2134 (setq directory (file-name-directory (substring directory 0 -1))
2135 ancestor (if (equal ancestor ".")
2136 ".."
2137 (concat "../" ancestor))))
2138 ;; Now ancestor is empty, or .., or ../.., etc.
2139 (if (string-match (concat "^" (regexp-quote directory)) fname)
2140 ;; We matched within FNAME's directory part.
2141 ;; Add the rest of FNAME onto ANCESTOR.
2142 (let ((rest (substring fname (match-end 0))))
2143 (if (and (equal ancestor ".")
2144 (not (equal rest "")))
2145 ;; But don't bother with ANCESTOR if it would give us `./'.
2146 rest
2147 (concat (file-name-as-directory ancestor) rest)))
2148 ;; We matched FNAME's directory equivalent.
2149 ancestor))))))
2150 \f
2151 (defun save-buffer (&optional args)
2152 "Save current buffer in visited file if modified. Versions described below.
2153 By default, makes the previous version into a backup file
2154 if previously requested or if this is the first save.
2155 With 1 \\[universal-argument], marks this version
2156 to become a backup when the next save is done.
2157 With 2 \\[universal-argument]'s,
2158 unconditionally makes the previous version into a backup file.
2159 With 3 \\[universal-argument]'s, marks this version
2160 to become a backup when the next save is done,
2161 and unconditionally makes the previous version into a backup file.
2162
2163 With argument of 0, never makes the previous version into a backup file.
2164
2165 If a file's name is FOO, the names of its numbered backup versions are
2166 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
2167 Numeric backups (rather than FOO~) will be made if value of
2168 `version-control' is not the atom `never' and either there are already
2169 numeric versions of the file being backed up, or `version-control' is
2170 non-nil.
2171 We don't want excessive versions piling up, so there are variables
2172 `kept-old-versions', which tells Emacs how many oldest versions to keep,
2173 and `kept-new-versions', which tells how many newest versions to keep.
2174 Defaults are 2 old versions and 2 new.
2175 `dired-kept-versions' controls dired's clean-directory (.) command.
2176 If `delete-old-versions' is nil, system will query user
2177 before trimming versions. Otherwise it does it silently."
2178 (interactive "p")
2179 (let ((modp (buffer-modified-p))
2180 (large (> (buffer-size) 50000))
2181 (make-backup-files (or (and make-backup-files (not (eq args 0)))
2182 (memq args '(16 64)))))
2183 (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
2184 (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
2185 (basic-save-buffer)
2186 (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
2187
2188 (defun delete-auto-save-file-if-necessary (&optional force)
2189 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
2190 Normally delete only if the file was written by this Emacs since
2191 the last real save, but optional arg FORCE non-nil means delete anyway."
2192 (and buffer-auto-save-file-name delete-auto-save-files
2193 (not (string= buffer-file-name buffer-auto-save-file-name))
2194 (or force (recent-auto-save-p))
2195 (progn
2196 (condition-case ()
2197 (delete-file buffer-auto-save-file-name)
2198 (file-error nil))
2199 (set-buffer-auto-saved))))
2200
2201 (defvar after-save-hook nil
2202 "Normal hook that is run after a buffer is saved to its file.")
2203
2204 (defvar save-buffer-coding-system nil
2205 "If non-nil, use this coding system for saving the buffer.
2206 More precisely, use this coding system in place of the
2207 value of `buffer-file-coding-system', when saving the buffer.
2208 Calling `write-region' for any purpose other than saving the buffer
2209 will still use `buffer-file-coding-system'; this variable has no effect
2210 in such cases.")
2211
2212 (defun basic-save-buffer ()
2213 "Save the current buffer in its visited file, if it has been modified.
2214 After saving the buffer, run `after-save-hook'."
2215 (interactive)
2216 (save-current-buffer
2217 ;; In an indirect buffer, save its base buffer instead.
2218 (if (buffer-base-buffer)
2219 (set-buffer (buffer-base-buffer)))
2220 (if (buffer-modified-p)
2221 (let ((recent-save (recent-auto-save-p))
2222 setmodes tempsetmodes)
2223 ;; On VMS, rename file and buffer to get rid of version number.
2224 (if (and (eq system-type 'vax-vms)
2225 (not (string= buffer-file-name
2226 (file-name-sans-versions buffer-file-name))))
2227 (let (buffer-new-name)
2228 ;; Strip VMS version number before save.
2229 (setq buffer-file-name
2230 (file-name-sans-versions buffer-file-name))
2231 ;; Construct a (unique) buffer name to correspond.
2232 (let ((buf (create-file-buffer (downcase buffer-file-name))))
2233 (setq buffer-new-name (buffer-name buf))
2234 (kill-buffer buf))
2235 (rename-buffer buffer-new-name)))
2236 ;; If buffer has no file name, ask user for one.
2237 (or buffer-file-name
2238 (let ((filename
2239 (expand-file-name
2240 (read-file-name "File to save in: ") nil)))
2241 (and (file-exists-p filename)
2242 (or (y-or-n-p (format "File `%s' exists; overwrite? "
2243 filename))
2244 (error "Canceled")))
2245 (set-visited-file-name filename)))
2246 (or (verify-visited-file-modtime (current-buffer))
2247 (not (file-exists-p buffer-file-name))
2248 (yes-or-no-p
2249 (format "%s has changed since visited or saved. Save anyway? "
2250 (file-name-nondirectory buffer-file-name)))
2251 (error "Save not confirmed"))
2252 (save-restriction
2253 (widen)
2254 (save-excursion
2255 (and (> (point-max) 1)
2256 (/= (char-after (1- (point-max))) ?\n)
2257 (not (and (eq selective-display t)
2258 (= (char-after (1- (point-max))) ?\r)))
2259 (or (eq require-final-newline t)
2260 (and require-final-newline
2261 (y-or-n-p
2262 (format "Buffer %s does not end in newline. Add one? "
2263 (buffer-name)))))
2264 (save-excursion
2265 (goto-char (point-max))
2266 (insert ?\n))))
2267 (or (run-hook-with-args-until-success 'write-contents-hooks)
2268 (run-hook-with-args-until-success 'local-write-file-hooks)
2269 (run-hook-with-args-until-success 'write-file-hooks)
2270 ;; If a hook returned t, file is already "written".
2271 ;; Otherwise, write it the usual way now.
2272 (setq setmodes (basic-save-buffer-1)))
2273 ;; Now we have saved the current buffer. Let's make sure
2274 ;; that buffer-file-coding-system is fixed to what
2275 ;; actually used for saving by binding it locally.
2276 (if save-buffer-coding-system
2277 (setq save-buffer-coding-system last-coding-system-used)
2278 (setq buffer-file-coding-system last-coding-system-used))
2279 (setq buffer-file-number
2280 (nthcdr 10 (file-attributes buffer-file-name)))
2281 (if setmodes
2282 (condition-case ()
2283 (set-file-modes buffer-file-name setmodes)
2284 (error nil))))
2285 ;; If the auto-save file was recent before this command,
2286 ;; delete it now.
2287 (delete-auto-save-file-if-necessary recent-save)
2288 ;; Support VC `implicit' locking.
2289 (vc-after-save)
2290 (run-hooks 'after-save-hook))
2291 (message "(No changes need to be saved)"))))
2292
2293 ;; This does the "real job" of writing a buffer into its visited file
2294 ;; and making a backup file. This is what is normally done
2295 ;; but inhibited if one of write-file-hooks returns non-nil.
2296 ;; It returns a value to store in setmodes.
2297 (defun basic-save-buffer-1 ()
2298 (let ((buffer-file-coding-system
2299 (or save-buffer-coding-system
2300 buffer-file-coding-system))
2301 tempsetmodes setmodes)
2302 (if (not (file-writable-p buffer-file-name))
2303 (let ((dir (file-name-directory buffer-file-name)))
2304 (if (not (file-directory-p dir))
2305 (if (file-exists-p dir)
2306 (error "%s is not a directory" dir)
2307 (error "%s: no such directory" buffer-file-name))
2308 (if (not (file-exists-p buffer-file-name))
2309 (error "Directory %s write-protected" dir)
2310 (if (yes-or-no-p
2311 (format "File %s is write-protected; try to save anyway? "
2312 (file-name-nondirectory
2313 buffer-file-name)))
2314 (setq tempsetmodes t)
2315 (error "Attempt to save to a file which you aren't allowed to write"))))))
2316 (or buffer-backed-up
2317 (setq setmodes (backup-buffer)))
2318 (let ((dir (file-name-directory buffer-file-name)))
2319 (if (and file-precious-flag
2320 (file-writable-p dir))
2321 ;; If file is precious, write temp name, then rename it.
2322 ;; This requires write access to the containing dir,
2323 ;; which is why we don't try it if we don't have that access.
2324 (let ((realname buffer-file-name)
2325 tempname temp nogood i succeed
2326 (old-modtime (visited-file-modtime)))
2327 (setq i 0)
2328 (setq nogood t)
2329 ;; Find the temporary name to write under.
2330 (while nogood
2331 (setq tempname (format
2332 (if (and (eq system-type 'ms-dos)
2333 (not (msdos-long-file-names)))
2334 "%s#%d.tm#" ; MSDOS limits files to 8+3
2335 "%s#tmp#%d")
2336 dir i))
2337 (setq nogood (file-exists-p tempname))
2338 (setq i (1+ i)))
2339 (unwind-protect
2340 (progn (clear-visited-file-modtime)
2341 (write-region (point-min) (point-max)
2342 tempname nil realname
2343 buffer-file-truename)
2344 (setq succeed t))
2345 ;; If writing the temp file fails,
2346 ;; delete the temp file.
2347 (or succeed
2348 (progn
2349 (delete-file tempname)
2350 (set-visited-file-modtime old-modtime))))
2351 ;; Since we have created an entirely new file
2352 ;; and renamed it, make sure it gets the
2353 ;; right permission bits set.
2354 (setq setmodes (file-modes buffer-file-name))
2355 ;; We succeeded in writing the temp file,
2356 ;; so rename it.
2357 (rename-file tempname buffer-file-name t))
2358 ;; If file not writable, see if we can make it writable
2359 ;; temporarily while we write it.
2360 ;; But no need to do so if we have just backed it up
2361 ;; (setmodes is set) because that says we're superseding.
2362 (cond ((and tempsetmodes (not setmodes))
2363 ;; Change the mode back, after writing.
2364 (setq setmodes (file-modes buffer-file-name))
2365 (set-file-modes buffer-file-name 511)))
2366 (write-region (point-min) (point-max)
2367 buffer-file-name nil t buffer-file-truename)))
2368 setmodes))
2369
2370 (defun save-some-buffers (&optional arg exiting)
2371 "Save some modified file-visiting buffers. Asks user about each one.
2372 Optional argument (the prefix) non-nil means save all with no questions.
2373 Optional second argument EXITING means ask about certain non-file buffers
2374 as well as about file buffers."
2375 (interactive "P")
2376 (save-window-excursion
2377 (let* ((queried nil)
2378 (files-done
2379 (map-y-or-n-p
2380 (function
2381 (lambda (buffer)
2382 (and (buffer-modified-p buffer)
2383 (not (buffer-base-buffer buffer))
2384 (or
2385 (buffer-file-name buffer)
2386 (and exiting
2387 (progn
2388 (set-buffer buffer)
2389 (and buffer-offer-save (> (buffer-size) 0)))))
2390 (if arg
2391 t
2392 (setq queried t)
2393 (if (buffer-file-name buffer)
2394 (format "Save file %s? "
2395 (buffer-file-name buffer))
2396 (format "Save buffer %s? "
2397 (buffer-name buffer)))))))
2398 (function
2399 (lambda (buffer)
2400 (set-buffer buffer)
2401 (save-buffer)))
2402 (buffer-list)
2403 '("buffer" "buffers" "save")
2404 (list (list ?\C-r (lambda (buf)
2405 (view-buffer buf
2406 (function
2407 (lambda (ignore)
2408 (exit-recursive-edit))))
2409 (recursive-edit)
2410 ;; Return nil to ask about BUF again.
2411 nil)
2412 "display the current buffer"))))
2413 (abbrevs-done
2414 (and save-abbrevs abbrevs-changed
2415 (progn
2416 (if (or arg
2417 (y-or-n-p (format "Save abbrevs in %s? "
2418 abbrev-file-name)))
2419 (write-abbrev-file nil))
2420 ;; Don't keep bothering user if he says no.
2421 (setq abbrevs-changed nil)
2422 t))))
2423 (or queried (> files-done 0) abbrevs-done
2424 (message "(No files need saving)")))))
2425 \f
2426 (defun not-modified (&optional arg)
2427 "Mark current buffer as unmodified, not needing to be saved.
2428 With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
2429
2430 It is not a good idea to use this function in Lisp programs, because it
2431 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
2432 (interactive "P")
2433 (message (if arg "Modification-flag set"
2434 "Modification-flag cleared"))
2435 (set-buffer-modified-p arg))
2436
2437 (defun toggle-read-only (&optional arg)
2438 "Change whether this buffer is visiting its file read-only.
2439 With arg, set read-only iff arg is positive.
2440 If visiting file read-only and `view-read-only' is non-nil, enter view mode."
2441 (interactive "P")
2442 (cond
2443 ((and arg (if (> (prefix-numeric-value arg) 0) buffer-read-only
2444 (not buffer-read-only))) ; If buffer-read-only is set correctly,
2445 nil) ; do nothing.
2446 ;; Toggle.
2447 ((and buffer-read-only view-mode)
2448 (View-exit-and-edit)
2449 (make-local-variable 'view-read-only)
2450 (setq view-read-only t)) ; Must leave view mode.
2451 ((and (not buffer-read-only) view-read-only
2452 (not (eq (get major-mode 'mode-class) 'special)))
2453 (view-mode-enter))
2454 (t (setq buffer-read-only (not buffer-read-only))
2455 (force-mode-line-update))))
2456
2457 (defun insert-file (filename)
2458 "Insert contents of file FILENAME into buffer after point.
2459 Set mark after the inserted text.
2460
2461 This function is meant for the user to run interactively.
2462 Don't call it from programs! Use `insert-file-contents' instead.
2463 \(Its calling sequence is different; see its documentation)."
2464 (interactive "*fInsert file: ")
2465 (if (file-directory-p filename)
2466 (signal 'file-error (list "Opening input file" "file is a directory"
2467 filename)))
2468 (let ((tem (insert-file-contents filename)))
2469 (push-mark (+ (point) (car (cdr tem))))))
2470
2471 (defun append-to-file (start end filename)
2472 "Append the contents of the region to the end of file FILENAME.
2473 When called from a function, expects three arguments,
2474 START, END and FILENAME. START and END are buffer positions
2475 saying what text to write."
2476 (interactive "r\nFAppend to file: ")
2477 (write-region start end filename t))
2478
2479 (defun file-newest-backup (filename)
2480 "Return most recent backup file for FILENAME or nil if no backups exist."
2481 (let* ((filename (expand-file-name filename))
2482 (file (file-name-nondirectory filename))
2483 (dir (file-name-directory filename))
2484 (comp (file-name-all-completions file dir))
2485 (newest nil)
2486 tem)
2487 (while comp
2488 (setq tem (car comp)
2489 comp (cdr comp))
2490 (cond ((and (backup-file-name-p tem)
2491 (string= (file-name-sans-versions tem) file))
2492 (setq tem (concat dir tem))
2493 (if (or (null newest)
2494 (file-newer-than-file-p tem newest))
2495 (setq newest tem)))))
2496 newest))
2497
2498 (defun rename-uniquely ()
2499 "Rename current buffer to a similar name not already taken.
2500 This function is useful for creating multiple shell process buffers
2501 or multiple mail buffers, etc."
2502 (interactive)
2503 (save-match-data
2504 (let ((base-name (buffer-name)))
2505 (and (string-match "<[0-9]+>\\'" base-name)
2506 (not (and buffer-file-name
2507 (string= base-name
2508 (file-name-nondirectory buffer-file-name))))
2509 ;; If the existing buffer name has a <NNN>,
2510 ;; which isn't part of the file name (if any),
2511 ;; then get rid of that.
2512 (setq base-name (substring base-name 0 (match-beginning 0))))
2513 (rename-buffer (generate-new-buffer-name base-name))
2514 (force-mode-line-update))))
2515
2516 (defun make-directory (dir &optional parents)
2517 "Create the directory DIR and any nonexistent parent dirs.
2518 Interactively, the default choice of directory to create
2519 is the current default directory for file names.
2520 That is useful when you have visited a file in a nonexistent directory.
2521
2522 Noninteractively, the second (optional) argument PARENTS says whether
2523 to create parent directories if they don't exist."
2524 (interactive
2525 (list (read-file-name "Make directory: " default-directory default-directory
2526 nil nil)
2527 t))
2528 (let ((handler (find-file-name-handler dir 'make-directory)))
2529 (if handler
2530 (funcall handler 'make-directory dir parents)
2531 (if (not parents)
2532 (make-directory-internal dir)
2533 (let ((dir (directory-file-name (expand-file-name dir)))
2534 create-list)
2535 (while (not (file-exists-p dir))
2536 (setq create-list (cons dir create-list)
2537 dir (directory-file-name (file-name-directory dir))))
2538 (while create-list
2539 (make-directory-internal (car create-list))
2540 (setq create-list (cdr create-list))))))))
2541 \f
2542 (put 'revert-buffer-function 'permanent-local t)
2543 (defvar revert-buffer-function nil
2544 "Function to use to revert this buffer, or nil to do the default.
2545 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
2546 which are the arguments that `revert-buffer' received.")
2547
2548 (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
2549 (defvar revert-buffer-insert-file-contents-function nil
2550 "Function to use to insert contents when reverting this buffer.
2551 Gets two args, first the nominal file name to use,
2552 and second, t if reading the auto-save file.")
2553
2554 (defvar before-revert-hook nil
2555 "Normal hook for `revert-buffer' to run before reverting.
2556 If `revert-buffer-function' is used to override the normal revert
2557 mechanism, this hook is not used.")
2558
2559 (defvar after-revert-hook nil
2560 "Normal hook for `revert-buffer' to run after reverting.
2561 Note that the hook value that it runs is the value that was in effect
2562 before reverting; that makes a difference if you have buffer-local
2563 hook functions.
2564
2565 If `revert-buffer-function' is used to override the normal revert
2566 mechanism, this hook is not used.")
2567
2568 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
2569 "Replace current buffer text with the text of the visited file on disk.
2570 This undoes all changes since the file was visited or saved.
2571 With a prefix argument, offer to revert from latest auto-save file, if
2572 that is more recent than the visited file.
2573
2574 This command also works for special buffers that contain text which
2575 doesn't come from a file, but reflects some other data base instead:
2576 for example, Dired buffers and buffer-list buffers. In these cases,
2577 it reconstructs the buffer contents from the appropriate data base.
2578
2579 When called from Lisp, the first argument is IGNORE-AUTO; only offer
2580 to revert from the auto-save file when this is nil. Note that the
2581 sense of this argument is the reverse of the prefix argument, for the
2582 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
2583 to nil.
2584
2585 Optional second argument NOCONFIRM means don't ask for confirmation at
2586 all.
2587
2588 Optional third argument PRESERVE-MODES non-nil means don't alter
2589 the files modes. Normally we reinitialize them using `normal-mode'.
2590
2591 If the value of `revert-buffer-function' is non-nil, it is called to
2592 do all the work for this command. Otherwise, the hooks
2593 `before-revert-hook' and `after-revert-hook' are run at the beginning
2594 and the end, and if `revert-buffer-insert-file-contents-function' is
2595 non-nil, it is called instead of rereading visited file contents."
2596
2597 ;; I admit it's odd to reverse the sense of the prefix argument, but
2598 ;; there is a lot of code out there which assumes that the first
2599 ;; argument should be t to avoid consulting the auto-save file, and
2600 ;; there's no straightforward way to encourage authors to notice a
2601 ;; reversal of the argument sense. So I'm just changing the user
2602 ;; interface, but leaving the programmatic interface the same.
2603 (interactive (list (not current-prefix-arg)))
2604 (if revert-buffer-function
2605 (funcall revert-buffer-function ignore-auto noconfirm)
2606 (let* ((opoint (point))
2607 (auto-save-p (and (not ignore-auto)
2608 (recent-auto-save-p)
2609 buffer-auto-save-file-name
2610 (file-readable-p buffer-auto-save-file-name)
2611 (y-or-n-p
2612 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
2613 (file-name (if auto-save-p
2614 buffer-auto-save-file-name
2615 buffer-file-name)))
2616 (cond ((null file-name)
2617 (error "Buffer does not seem to be associated with any file"))
2618 ((or noconfirm
2619 (and (not (buffer-modified-p))
2620 (let ((tail revert-without-query)
2621 (found nil))
2622 (while tail
2623 (if (string-match (car tail) file-name)
2624 (setq found t))
2625 (setq tail (cdr tail)))
2626 found))
2627 (yes-or-no-p (format "Revert buffer from file %s? "
2628 file-name)))
2629 (run-hooks 'before-revert-hook)
2630 ;; If file was backed up but has changed since,
2631 ;; we shd make another backup.
2632 (and (not auto-save-p)
2633 (not (verify-visited-file-modtime (current-buffer)))
2634 (setq buffer-backed-up nil))
2635 ;; Get rid of all undo records for this buffer.
2636 (or (eq buffer-undo-list t)
2637 (setq buffer-undo-list nil))
2638 ;; Effectively copy the after-revert-hook status,
2639 ;; since after-find-file will clobber it.
2640 (let ((global-hook (default-value 'after-revert-hook))
2641 (local-hook-p (local-variable-p 'after-revert-hook))
2642 (local-hook (and (local-variable-p 'after-revert-hook)
2643 after-revert-hook)))
2644 (let (buffer-read-only
2645 ;; Don't make undo records for the reversion.
2646 (buffer-undo-list t))
2647 (if revert-buffer-insert-file-contents-function
2648 (funcall revert-buffer-insert-file-contents-function
2649 file-name auto-save-p)
2650 (if (not (file-exists-p file-name))
2651 (error "File %s no longer exists!" file-name))
2652 ;; Bind buffer-file-name to nil
2653 ;; so that we don't try to lock the file.
2654 (let ((buffer-file-name nil))
2655 (or auto-save-p
2656 (unlock-buffer)))
2657 (widen)
2658 (let ((coding-system-for-read
2659 ;; Auto-saved file shoule be read without
2660 ;; any code conversion.
2661 (if auto-save-p 'no-conversion
2662 coding-system-for-read)))
2663 (insert-file-contents file-name (not auto-save-p)
2664 nil nil t))))
2665 (goto-char (min opoint (point-max)))
2666 ;; Recompute the truename in case changes in symlinks
2667 ;; have changed the truename.
2668 (setq buffer-file-truename
2669 (abbreviate-file-name (file-truename buffer-file-name)))
2670 (after-find-file nil nil t t preserve-modes)
2671 ;; Run after-revert-hook as it was before we reverted.
2672 (setq-default revert-buffer-internal-hook global-hook)
2673 (if local-hook-p
2674 (progn
2675 (make-local-variable 'revert-buffer-internal-hook)
2676 (setq revert-buffer-internal-hook local-hook))
2677 (kill-local-variable 'revert-buffer-internal-hook))
2678 (run-hooks 'revert-buffer-internal-hook))
2679 t)))))
2680
2681 (defun recover-file (file)
2682 "Visit file FILE, but get contents from its last auto-save file."
2683 ;; Actually putting the file name in the minibuffer should be used
2684 ;; only rarely.
2685 ;; Not just because users often use the default.
2686 (interactive "FRecover file: ")
2687 (setq file (expand-file-name file))
2688 (if (auto-save-file-name-p (file-name-nondirectory file))
2689 (error "%s is an auto-save file" file))
2690 (let ((file-name (let ((buffer-file-name file))
2691 (make-auto-save-file-name))))
2692 (cond ((if (file-exists-p file)
2693 (not (file-newer-than-file-p file-name file))
2694 (not (file-exists-p file-name)))
2695 (error "Auto-save file %s not current" file-name))
2696 ((save-window-excursion
2697 (if (not (memq system-type '(vax-vms windows-nt)))
2698 (with-output-to-temp-buffer "*Directory*"
2699 (buffer-disable-undo standard-output)
2700 (call-process "ls" nil standard-output nil
2701 (if (file-symlink-p file) "-lL" "-l")
2702 file file-name)))
2703 (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2704 (switch-to-buffer (find-file-noselect file t))
2705 (let ((buffer-read-only nil)
2706 ;; Auto-saved file shoule be read without any code conversion.
2707 (coding-system-for-read 'no-conversion))
2708 (erase-buffer)
2709 (insert-file-contents file-name nil))
2710 (after-find-file nil nil t))
2711 (t (error "Recover-file cancelled")))))
2712
2713 (defun recover-session ()
2714 "Recover auto save files from a previous Emacs session.
2715 This command first displays a Dired buffer showing you the
2716 previous sessions that you could recover from.
2717 To choose one, move point to the proper line and then type C-c C-c.
2718 Then you'll be asked about a number of files to recover."
2719 (interactive)
2720 (if (null auto-save-list-file-prefix)
2721 (error "You set `auto-save-list-file-prefix' to disable making session files"))
2722 (let ((ls-lisp-support-shell-wildcards t))
2723 (dired (concat auto-save-list-file-prefix "*")
2724 (concat dired-listing-switches "t")))
2725 (goto-char (point-min))
2726 (or (looking-at "Move to the session you want to recover,")
2727 (let ((inhibit-read-only t))
2728 (insert "Move to the session you want to recover,\n"
2729 "then type C-c C-c to select it.\n\n"
2730 "You can also delete some of these files;\n"
2731 "type d on a line to mark that file for deletion.\n\n")))
2732 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
2733 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
2734
2735 (defun recover-session-finish ()
2736 "Choose one saved session to recover auto-save files from.
2737 This command is used in the special Dired buffer created by
2738 \\[recover-session]."
2739 (interactive)
2740 ;; Get the name of the session file to recover from.
2741 (let ((file (dired-get-filename))
2742 files
2743 (buffer (get-buffer-create " *recover*")))
2744 (dired-unmark 1)
2745 (dired-do-flagged-delete t)
2746 (unwind-protect
2747 (save-excursion
2748 ;; Read in the auto-save-list file.
2749 (set-buffer buffer)
2750 (erase-buffer)
2751 (insert-file-contents file)
2752 ;; Loop thru the text of that file
2753 ;; and get out the names of the files to recover.
2754 (while (not (eobp))
2755 (let (thisfile autofile)
2756 (if (eolp)
2757 ;; This is a pair of lines for a non-file-visiting buffer.
2758 ;; Get the auto-save file name and manufacture
2759 ;; a "visited file name" from that.
2760 (progn
2761 (forward-line 1)
2762 (setq autofile
2763 (buffer-substring-no-properties
2764 (point)
2765 (save-excursion
2766 (end-of-line)
2767 (point))))
2768 (setq thisfile
2769 (expand-file-name
2770 (substring
2771 (file-name-nondirectory autofile)
2772 1 -1)
2773 (file-name-directory autofile)))
2774 (forward-line 1))
2775 ;; This pair of lines is a file-visiting
2776 ;; buffer. Use the visited file name.
2777 (progn
2778 (setq thisfile
2779 (buffer-substring-no-properties
2780 (point) (progn (end-of-line) (point))))
2781 (forward-line 1)
2782 (setq autofile
2783 (buffer-substring-no-properties
2784 (point) (progn (end-of-line) (point))))
2785 (forward-line 1)))
2786 ;; Ignore a file if its auto-save file does not exist now.
2787 (if (file-exists-p autofile)
2788 (setq files (cons thisfile files)))))
2789 (setq files (nreverse files))
2790 ;; The file contains a pair of line for each auto-saved buffer.
2791 ;; The first line of the pair contains the visited file name
2792 ;; or is empty if the buffer was not visiting a file.
2793 ;; The second line is the auto-save file name.
2794 (if files
2795 (map-y-or-n-p "Recover %s? "
2796 (lambda (file)
2797 (condition-case nil
2798 (save-excursion (recover-file file))
2799 (error
2800 "Failed to recover `%s'" file)))
2801 files
2802 '("file" "files" "recover"))
2803 (message "No files can be recovered from this session now")))
2804 (kill-buffer buffer))))
2805
2806 (defun kill-some-buffers (&optional list)
2807 "For each buffer in LIST, ask whether to kill it.
2808 LIST defaults to all existing live buffers."
2809 (interactive)
2810 (if (null list)
2811 (setq list (buffer-list)))
2812 (while list
2813 (let* ((buffer (car list))
2814 (name (buffer-name buffer)))
2815 (and (not (string-equal name ""))
2816 (/= (aref name 0) ? )
2817 (yes-or-no-p
2818 (format "Buffer %s %s. Kill? "
2819 name
2820 (if (buffer-modified-p buffer)
2821 "HAS BEEN EDITED" "is unmodified")))
2822 (kill-buffer buffer)))
2823 (setq list (cdr list))))
2824 \f
2825 (defun auto-save-mode (arg)
2826 "Toggle auto-saving of contents of current buffer.
2827 With prefix argument ARG, turn auto-saving on if positive, else off."
2828 (interactive "P")
2829 (setq buffer-auto-save-file-name
2830 (and (if (null arg)
2831 (or (not buffer-auto-save-file-name)
2832 ;; If autosave is off because buffer has shrunk,
2833 ;; then toggling should turn it on.
2834 (< buffer-saved-size 0))
2835 (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
2836 (if (and buffer-file-name auto-save-visited-file-name
2837 (not buffer-read-only))
2838 buffer-file-name
2839 (make-auto-save-file-name))))
2840 ;; If -1 was stored here, to temporarily turn off saving,
2841 ;; turn it back on.
2842 (and (< buffer-saved-size 0)
2843 (setq buffer-saved-size 0))
2844 (if (interactive-p)
2845 (message "Auto-save %s (in this buffer)"
2846 (if buffer-auto-save-file-name "on" "off")))
2847 buffer-auto-save-file-name)
2848
2849 (defun rename-auto-save-file ()
2850 "Adjust current buffer's auto save file name for current conditions.
2851 Also rename any existing auto save file, if it was made in this session."
2852 (let ((osave buffer-auto-save-file-name))
2853 (setq buffer-auto-save-file-name
2854 (make-auto-save-file-name))
2855 (if (and osave buffer-auto-save-file-name
2856 (not (string= buffer-auto-save-file-name buffer-file-name))
2857 (not (string= buffer-auto-save-file-name osave))
2858 (file-exists-p osave)
2859 (recent-auto-save-p))
2860 (rename-file osave buffer-auto-save-file-name t))))
2861
2862 (defun make-auto-save-file-name ()
2863 "Return file name to use for auto-saves of current buffer.
2864 Does not consider `auto-save-visited-file-name' as that variable is checked
2865 before calling this function. You can redefine this for customization.
2866 See also `auto-save-file-name-p'."
2867 (if buffer-file-name
2868 (if (and (eq system-type 'ms-dos)
2869 (not (msdos-long-file-names)))
2870 (let ((fn (file-name-nondirectory buffer-file-name)))
2871 (string-match "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'" fn)
2872 (concat (file-name-directory buffer-file-name)
2873 "#" (match-string 1 fn)
2874 "." (match-string 3 fn) "#"))
2875 (concat (file-name-directory buffer-file-name)
2876 "#"
2877 (file-name-nondirectory buffer-file-name)
2878 "#"))
2879
2880 ;; Deal with buffers that don't have any associated files. (Mail
2881 ;; mode tends to create a good number of these.)
2882
2883 (let ((buffer-name (buffer-name))
2884 (limit 0))
2885 ;; Eliminate all slashes and backslashes by
2886 ;; replacing them with sequences that start with %.
2887 ;; Quote % also, to keep distinct names distinct.
2888 (while (string-match "[/\\%]" buffer-name limit)
2889 (let* ((character (aref buffer-name (match-beginning 0)))
2890 (replacement
2891 (cond ((eq character ?%) "%%")
2892 ((eq character ?/) "%+")
2893 ((eq character ?\\) "%-"))))
2894 (setq buffer-name (replace-match replacement t t buffer-name))
2895 (setq limit (1+ (match-end 0)))))
2896 ;; Generate the file name.
2897 (expand-file-name
2898 (format "#%s#%s#" buffer-name (make-temp-name ""))
2899 ;; Try a few alternative directories, to get one we can write it.
2900 (cond
2901 ((file-writable-p default-directory) default-directory)
2902 ((file-writable-p "/var/tmp/") "/var/tmp/")
2903 ("~/"))))))
2904
2905 (defun auto-save-file-name-p (filename)
2906 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
2907 FILENAME should lack slashes. You can redefine this for customization."
2908 (string-match "^#.*#$" filename))
2909 \f
2910 (defun wildcard-to-regexp (wildcard)
2911 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
2912 The generated regexp will match a filename iff the filename
2913 matches that wildcard according to shell rules. Only wildcards known
2914 by `sh' are supported."
2915 (let* ((i (string-match "[[.*+\\^$?]" wildcard))
2916 ;; Copy the initial run of non-special characters.
2917 (result (substring wildcard 0 i))
2918 (len (length wildcard)))
2919 ;; If no special characters, we're almost done.
2920 (if i
2921 (while (< i len)
2922 (let ((ch (aref wildcard i))
2923 j)
2924 (setq
2925 result
2926 (concat result
2927 (cond
2928 ((and (eq ch ?\[)
2929 (< (1+ i) len)
2930 (eq (aref wildcard (1+ i)) ?\]))
2931 "\\[")
2932 ((eq ch ?\[) ; [...] maps to regexp char class
2933 (progn
2934 (setq i (1+ i))
2935 (concat
2936 (cond
2937 ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
2938 (progn
2939 (setq i (1+ i))
2940 (if (eq (aref wildcard i) ?\])
2941 (progn
2942 (setq i (1+ i))
2943 "[^]")
2944 "[^")))
2945 ((eq (aref wildcard i) ?^)
2946 ;; Found "[^". Insert a `\0' character
2947 ;; (which cannot happen in a filename)
2948 ;; into the character class, so that `^'
2949 ;; is not the first character after `[',
2950 ;; and thus non-special in a regexp.
2951 (progn
2952 (setq i (1+ i))
2953 "[\000^"))
2954 ((eq (aref wildcard i) ?\])
2955 ;; I don't think `]' can appear in a
2956 ;; character class in a wildcard, but
2957 ;; let's be general here.
2958 (progn
2959 (setq i (1+ i))
2960 "[]"))
2961 (t "["))
2962 (prog1 ; copy everything upto next `]'.
2963 (substring wildcard
2964 i
2965 (setq j (string-match
2966 "]" wildcard i)))
2967 (setq i (if j (1- j) (1- len)))))))
2968 ((eq ch ?.) "\\.")
2969 ((eq ch ?*) "[^\000]*")
2970 ((eq ch ?+) "\\+")
2971 ((eq ch ?^) "\\^")
2972 ((eq ch ?$) "\\$")
2973 ((eq ch ?\\) "\\\\") ; probably cannot happen...
2974 ((eq ch ??) "[^\000]")
2975 (t (char-to-string ch)))))
2976 (setq i (1+ i)))))
2977 ;; Shell wildcards should match the entire filename,
2978 ;; not its part. Make the regexp say so.
2979 (concat "\\`" result "\\'")))
2980 \f
2981 (defcustom list-directory-brief-switches
2982 (if (eq system-type 'vax-vms) "" "-CF")
2983 "*Switches for list-directory to pass to `ls' for brief listing,"
2984 :type 'string
2985 :group 'dired)
2986
2987 (defcustom list-directory-verbose-switches
2988 (if (eq system-type 'vax-vms)
2989 "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
2990 "-l")
2991 "*Switches for list-directory to pass to `ls' for verbose listing,"
2992 :type 'string
2993 :group 'dired)
2994
2995 (defun list-directory (dirname &optional verbose)
2996 "Display a list of files in or matching DIRNAME, a la `ls'.
2997 DIRNAME is globbed by the shell if necessary.
2998 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
2999 Actions controlled by variables `list-directory-brief-switches'
3000 and `list-directory-verbose-switches'."
3001 (interactive (let ((pfx current-prefix-arg))
3002 (list (read-file-name (if pfx "List directory (verbose): "
3003 "List directory (brief): ")
3004 nil default-directory nil)
3005 pfx)))
3006 (let ((switches (if verbose list-directory-verbose-switches
3007 list-directory-brief-switches)))
3008 (or dirname (setq dirname default-directory))
3009 (setq dirname (expand-file-name dirname))
3010 (with-output-to-temp-buffer "*Directory*"
3011 (buffer-disable-undo standard-output)
3012 (princ "Directory ")
3013 (princ dirname)
3014 (terpri)
3015 (save-excursion
3016 (set-buffer "*Directory*")
3017 (setq default-directory
3018 (if (file-directory-p dirname)
3019 (file-name-as-directory dirname)
3020 (file-name-directory dirname)))
3021 (let ((wildcard (not (file-directory-p dirname))))
3022 (insert-directory dirname switches wildcard (not wildcard)))))))
3023
3024 (defvar insert-directory-program "ls"
3025 "Absolute or relative name of the `ls' program used by `insert-directory'.")
3026
3027 ;; insert-directory
3028 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
3029 ;; FULL-DIRECTORY-P is nil.
3030 ;; The single line of output must display FILE's name as it was
3031 ;; given, namely, an absolute path name.
3032 ;; - must insert exactly one line for each file if WILDCARD or
3033 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
3034 ;; before the file lines, plus optional text after the file lines.
3035 ;; Lines are delimited by "\n", so filenames containing "\n" are not
3036 ;; allowed.
3037 ;; File lines should display the basename.
3038 ;; - must be consistent with
3039 ;; - functions dired-move-to-filename, (these two define what a file line is)
3040 ;; dired-move-to-end-of-filename,
3041 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
3042 ;; dired-insert-headerline
3043 ;; dired-after-subdir-garbage (defines what a "total" line is)
3044 ;; - variable dired-subdir-regexp
3045 (defun insert-directory (file switches &optional wildcard full-directory-p)
3046 "Insert directory listing for FILE, formatted according to SWITCHES.
3047 Leaves point after the inserted text.
3048 SWITCHES may be a string of options, or a list of strings.
3049 Optional third arg WILDCARD means treat FILE as shell wildcard.
3050 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
3051 switches do not contain `d', so that a full listing is expected.
3052
3053 This works by running a directory listing program
3054 whose name is in the variable `insert-directory-program'.
3055 If WILDCARD, it also runs the shell specified by `shell-file-name'."
3056 ;; We need the directory in order to find the right handler.
3057 (let ((handler (find-file-name-handler (expand-file-name file)
3058 'insert-directory)))
3059 (if handler
3060 (funcall handler 'insert-directory file switches
3061 wildcard full-directory-p)
3062 (if (eq system-type 'vax-vms)
3063 (vms-read-directory file switches (current-buffer))
3064 (let* ((coding-system-for-read
3065 (and enable-multibyte-characters
3066 (or file-name-coding-system
3067 default-file-name-coding-system)))
3068 ;; This is to control encoding the arguments in call-process.
3069 (coding-system-for-write coding-system-for-read)
3070 (result
3071 (if wildcard
3072 ;; Run ls in the directory of the file pattern we asked for.
3073 (let ((default-directory
3074 (if (file-name-absolute-p file)
3075 (file-name-directory file)
3076 (file-name-directory (expand-file-name file))))
3077 (pattern (file-name-nondirectory file))
3078 (beg 0))
3079 ;; Quote some characters that have special meanings in shells;
3080 ;; but don't quote the wildcards--we want them to be special.
3081 ;; We also currently don't quote the quoting characters
3082 ;; in case people want to use them explicitly to quote
3083 ;; wildcard characters.
3084 (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
3085 (setq pattern
3086 (concat (substring pattern 0 (match-beginning 0))
3087 "\\"
3088 (substring pattern (match-beginning 0)))
3089 beg (1+ (match-end 0))))
3090 (call-process shell-file-name nil t nil
3091 "-c" (concat "\\";; Disregard shell aliases!
3092 insert-directory-program
3093 " -d "
3094 (if (stringp switches)
3095 switches
3096 (mapconcat 'identity switches " "))
3097 " -- "
3098 pattern)))
3099 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
3100 ;; directory if FILE is a symbolic link.
3101 (apply 'call-process
3102 insert-directory-program nil t nil
3103 (let (list)
3104 (if (listp switches)
3105 (setq list switches)
3106 (if (not (equal switches ""))
3107 (progn
3108 ;; Split the switches at any spaces
3109 ;; so we can pass separate options as separate args.
3110 (while (string-match " " switches)
3111 (setq list (cons (substring switches 0 (match-beginning 0))
3112 list)
3113 switches (substring switches (match-end 0))))
3114 (setq list (nreverse (cons switches list))))))
3115 (append list
3116 ;; Avoid lossage if FILE starts with `-'.
3117 '("--")
3118 (progn
3119 (if (string-match "\\`~" file)
3120 (setq file (expand-file-name file)))
3121 (list
3122 (if full-directory-p
3123 (concat (file-name-as-directory file) ".")
3124 file)))))))))
3125 (if (/= result 0)
3126 ;; We get here if ls failed.
3127 ;; Access the file to get a suitable error.
3128 (access-file file "Reading directory")))))))
3129
3130 (defvar kill-emacs-query-functions nil
3131 "Functions to call with no arguments to query about killing Emacs.
3132 If any of these functions returns nil, killing Emacs is cancelled.
3133 `save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
3134 but `kill-emacs', the low level primitive, does not.
3135 See also `kill-emacs-hook'.")
3136
3137 (defun save-buffers-kill-emacs (&optional arg)
3138 "Offer to save each buffer, then kill this Emacs process.
3139 With prefix arg, silently save all file-visiting buffers, then kill."
3140 (interactive "P")
3141 (save-some-buffers arg t)
3142 (and (or (not (memq t (mapcar (function
3143 (lambda (buf) (and (buffer-file-name buf)
3144 (buffer-modified-p buf))))
3145 (buffer-list))))
3146 (yes-or-no-p "Modified buffers exist; exit anyway? "))
3147 (or (not (fboundp 'process-list))
3148 ;; process-list is not defined on VMS.
3149 (let ((processes (process-list))
3150 active)
3151 (while processes
3152 (and (memq (process-status (car processes)) '(run stop open))
3153 (let ((val (process-kill-without-query (car processes))))
3154 (process-kill-without-query (car processes) val)
3155 val)
3156 (setq active t))
3157 (setq processes (cdr processes)))
3158 (or (not active)
3159 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
3160 ;; Query the user for other things, perhaps.
3161 (run-hook-with-args-until-failure 'kill-emacs-query-functions)
3162 (kill-emacs)))
3163 \f
3164 ;; We use /: as a prefix to "quote" a file name
3165 ;; so that magic file name handlers will not apply to it.
3166
3167 (setq file-name-handler-alist
3168 (cons '("\\`/:" . file-name-non-special)
3169 file-name-handler-alist))
3170
3171 ;; We depend on being the last handler on the list,
3172 ;; so that anything else which does need handling
3173 ;; has been handled already.
3174 ;; So it is safe for us to inhibit *all* magic file name handlers.
3175
3176 (defun file-name-non-special (operation &rest arguments)
3177 (let ((file-name-handler-alist nil)
3178 (default-directory
3179 (if (eq operation 'insert-directory)
3180 (directory-file-name
3181 (expand-file-name
3182 (unhandled-file-name-directory default-directory)))
3183 default-directory))
3184 ;; Get a list of the indices of the args which are file names.
3185 (file-arg-indices
3186 (cdr (or (assq operation
3187 ;; The first four are special because they
3188 ;; return a file name. We want to include the /:
3189 ;; in the return value.
3190 ;; So just avoid stripping it in the first place.
3191 '((expand-file-name . nil)
3192 ;; `identity' means just return the first arg
3193 ;; as stripped of its quoting.
3194 (substitute-in-file-name . identity)
3195 (file-name-directory . nil)
3196 (file-name-as-directory . nil)
3197 (directory-file-name . nil)
3198 (file-name-completion 0 1)
3199 (file-name-all-completions 0 1)
3200 (rename-file 0 1)
3201 (copy-file 0 1)
3202 (make-symbolic-link 0 1)
3203 (add-name-to-file 0 1)))
3204 ;; For all other operations, treat the first argument only
3205 ;; as the file name.
3206 '(nil 0))))
3207 ;; Copy ARGUMENTS so we can replace elements in it.
3208 (arguments (copy-sequence arguments)))
3209 ;; Strip off the /: from the file names that have this handler.
3210 (save-match-data
3211 (while (consp file-arg-indices)
3212 (let ((pair (nthcdr (car file-arg-indices) arguments)))
3213 (and (car pair)
3214 (string-match "\\`/:" (car pair))
3215 (setcar pair
3216 (if (= (length (car pair)) 2)
3217 "/"
3218 (substring (car pair) 2)))))
3219 (setq file-arg-indices (cdr file-arg-indices))))
3220 (if (eq file-arg-indices 'identity)
3221 (car arguments)
3222 (apply operation arguments))))
3223 \f
3224 (define-key ctl-x-map "\C-f" 'find-file)
3225 (define-key ctl-x-map "\C-r" 'find-file-read-only)
3226 (define-key ctl-x-map "\C-v" 'find-alternate-file)
3227 (define-key ctl-x-map "\C-s" 'save-buffer)
3228 (define-key ctl-x-map "s" 'save-some-buffers)
3229 (define-key ctl-x-map "\C-w" 'write-file)
3230 (define-key ctl-x-map "i" 'insert-file)
3231 (define-key esc-map "~" 'not-modified)
3232 (define-key ctl-x-map "\C-d" 'list-directory)
3233 (define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
3234
3235 (define-key ctl-x-4-map "f" 'find-file-other-window)
3236 (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
3237 (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
3238 (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
3239 (define-key ctl-x-4-map "\C-o" 'display-buffer)
3240
3241 (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
3242 (define-key ctl-x-5-map "f" 'find-file-other-frame)
3243 (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
3244 (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
3245
3246 ;;; files.el ends here