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