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