1 ;;; files.el --- file input and output commands for Emacs
3 ;; Copyright (C) 1985-1987, 1992-2013 Free Software Foundation, Inc.
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; Defines most of Emacs's file- and directory-handling functions,
26 ;; including basic file visiting, backup generation, link handling,
27 ;; ITS-id version control, load- and write-hook handling, and the like.
31 (defvar font-lock-keywords
)
34 "Backups of edited data files."
37 (defgroup find-file nil
42 (defcustom delete-auto-save-files t
43 "Non-nil means delete auto-save file when a buffer is saved or killed.
45 Note that the auto-save file will not be deleted if the buffer is killed
46 when it has unsaved changes."
50 (defcustom directory-abbrev-alist
52 "Alist of abbreviations for file directories.
53 A list of elements of the form (FROM . TO), each meaning to replace
54 FROM with TO when it appears in a directory name. This replacement is
55 done when setting up the default directory of a newly visited file.
57 FROM is matched against directory names anchored at the first
58 character, so it should start with a \"\\\\`\", or, if directory
59 names cannot have embedded newlines, with a \"^\".
61 FROM and TO should be equivalent names, which refer to the
62 same directory. Do not use `~' in the TO strings;
63 they should be ordinary absolute directory names.
65 Use this feature when you have directories which you normally refer to
66 via absolute symbolic links. Make TO the name of the link, and FROM
67 the name it is linked to."
68 :type
'(repeat (cons :format
"%v"
75 (defcustom make-backup-files t
76 "Non-nil means make a backup of a file the first time it is saved.
77 This can be done by renaming the file or by copying.
79 Renaming means that Emacs renames the existing file so that it is a
80 backup file, then writes the buffer into a new file. Any other names
81 that the old file had will now refer to the backup file. The new file
82 is owned by you and its group is defaulted.
84 Copying means that Emacs copies the existing file into the backup
85 file, then writes the buffer on top of the existing file. Any other
86 names that the old file had will now refer to the new (edited) file.
87 The file's owner and group are unchanged.
89 The choice of renaming or copying is controlled by the variables
90 `backup-by-copying', `backup-by-copying-when-linked',
91 `backup-by-copying-when-mismatch' and
92 `backup-by-copying-when-privileged-mismatch'. See also `backup-inhibited'."
96 ;; Do this so that local variables based on the file name
97 ;; are not overridden by the major mode.
98 (defvar backup-inhibited nil
99 "Non-nil means don't make a backup, regardless of the other parameters.
100 This variable is intended for use by making it local to a buffer.
101 But it is local only if you make it local.")
102 (put 'backup-inhibited
'permanent-local t
)
104 (defcustom backup-by-copying nil
105 "Non-nil means always use copying to create backup files.
106 See documentation of variable `make-backup-files'."
110 (defcustom backup-by-copying-when-linked nil
111 "Non-nil means use copying to create backups for files with multiple names.
112 This causes the alternate names to refer to the latest version as edited.
113 This variable is relevant only if `backup-by-copying' is nil."
117 (defcustom backup-by-copying-when-mismatch t
118 "Non-nil means create backups by copying if this preserves owner or group.
119 Renaming may still be used (subject to control of other variables)
120 when it would not result in changing the owner or group of the file;
121 that is, for files which are owned by you and whose group matches
122 the default for a new file created there by you.
123 This variable is relevant only if `backup-by-copying' is nil."
127 (put 'backup-by-copying-when-mismatch
'permanent-local t
)
129 (defcustom backup-by-copying-when-privileged-mismatch
200
130 "Non-nil means create backups by copying to preserve a privileged owner.
131 Renaming may still be used (subject to control of other variables)
132 when it would not result in changing the owner of the file or if the owner
133 has a user id greater than the value of this variable. This is useful
134 when low-numbered uid's are used for special system users (such as root)
135 that must maintain ownership of certain files.
136 This variable is relevant only if `backup-by-copying' and
137 `backup-by-copying-when-mismatch' are nil."
138 :type
'(choice (const nil
) integer
)
141 (defvar backup-enable-predicate
'normal-backup-enable-predicate
142 "Predicate that looks at a file name and decides whether to make backups.
143 Called with an absolute file name as argument, it returns t to enable backup.")
145 (defcustom buffer-offer-save nil
146 "Non-nil in a buffer means always offer to save buffer on exit.
147 Do so even if the buffer is not visiting a file.
148 Automatically local in all buffers."
151 (make-variable-buffer-local 'buffer-offer-save
)
152 (put 'buffer-offer-save
'permanent-local t
)
154 (defcustom find-file-existing-other-name t
155 "Non-nil means find a file under alternative names, in existing buffers.
156 This means if any existing buffer is visiting the file you want
157 under another name, you get the existing buffer instead of a new buffer."
161 (defcustom find-file-visit-truename nil
162 "Non-nil means visit a file under its truename.
163 The truename of a file is found by chasing all links
164 both at the file level and at the levels of the containing directories."
167 (put 'find-file-visit-truename
'safe-local-variable
'booleanp
)
169 (defcustom revert-without-query nil
170 "Specify which files should be reverted without query.
171 The value is a list of regular expressions.
172 If the file name matches one of these regular expressions,
173 then `revert-buffer' reverts the file without querying
174 if the file has changed on disk and you have not edited the buffer."
175 :type
'(repeat regexp
)
178 (defvar buffer-file-number nil
179 "The device number and file number of the file visited in the current buffer.
180 The value is a list of the form (FILENUM DEVNUM).
181 This pair of numbers uniquely identifies the file.
182 If the buffer is visiting a new file, the value is nil.")
183 (make-variable-buffer-local 'buffer-file-number
)
184 (put 'buffer-file-number
'permanent-local t
)
186 (defvar buffer-file-numbers-unique
(not (memq system-type
'(windows-nt)))
187 "Non-nil means that `buffer-file-number' uniquely identifies files.")
189 (defvar buffer-file-read-only nil
190 "Non-nil if visited file was read-only when visited.")
191 (make-variable-buffer-local 'buffer-file-read-only
)
193 (defcustom small-temporary-file-directory
194 (if (eq system-type
'ms-dos
) (getenv "TMPDIR"))
195 "The directory for writing small temporary files.
196 If non-nil, this directory is used instead of `temporary-file-directory'
197 by programs that create small temporary files. This is for systems that
198 have fast storage with limited space, such as a RAM disk."
200 :initialize
'custom-initialize-delay
201 :type
'(choice (const nil
) directory
))
203 ;; The system null device. (Should reference NULL_DEVICE from C.)
204 (defvar null-device
(purecopy "/dev/null") "The system null device.")
206 (declare-function msdos-long-file-names
"msdos.c")
207 (declare-function w32-long-file-name
"w32proc.c")
208 (declare-function dired-get-filename
"dired" (&optional localp no-error-if-not-filep
))
209 (declare-function dired-unmark
"dired" (arg))
210 (declare-function dired-do-flagged-delete
"dired" (&optional nomessage
))
211 (declare-function dos-8
+3-filename
"dos-fns" (filename))
212 (declare-function dosified-file-name
"dos-fns" (file-name))
214 (defvar file-name-invalid-regexp
215 (cond ((and (eq system-type
'ms-dos
) (not (msdos-long-file-names)))
217 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
218 "[+, ;=|<>\"?*]\\|\\[\\|\\]\\|" ; invalid characters
219 "[\000-\037]\\|" ; control characters
220 "\\(/\\.\\.?[^/]\\)\\|" ; leading dots
221 "\\(/[^/.]+\\.[^/.]*\\.\\)"))) ; more than a single dot
222 ((memq system-type
'(ms-dos windows-nt cygwin
))
224 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
225 "[|<>\"?*\000-\037]"))) ; invalid characters
226 (t (purecopy "[\000]")))
227 "Regexp recognizing file names which aren't allowed by the filesystem.")
229 (defcustom file-precious-flag nil
230 "Non-nil means protect against I/O errors while saving files.
231 Some modes set this non-nil in particular buffers.
233 This feature works by writing the new contents into a temporary file
234 and then renaming the temporary file to replace the original.
235 In this way, any I/O error in writing leaves the original untouched,
236 and there is never any instant where the file is nonexistent.
238 Note that this feature forces backups to be made by copying.
239 Yet, at the same time, saving a precious file
240 breaks any hard links between it and other files.
242 This feature is advisory: for example, if the directory in which the
243 file is being saved is not writable, Emacs may ignore a non-nil value
244 of `file-precious-flag' and write directly into the file.
246 See also: `break-hardlink-on-save'."
250 (defcustom break-hardlink-on-save nil
251 "Non-nil means when saving a file that exists under several names
252 \(i.e., has multiple hardlinks), break the hardlink associated with
253 `buffer-file-name' and write to a new file, so that the other
254 instances of the file are not affected by the save.
256 If `buffer-file-name' refers to a symlink, do not break the symlink.
258 Unlike `file-precious-flag', `break-hardlink-on-save' is not advisory.
259 For example, if the directory in which a file is being saved is not
260 itself writable, then error instead of saving in some
261 hardlink-nonbreaking way.
263 See also `backup-by-copying' and `backup-by-copying-when-linked'."
268 (defcustom version-control nil
269 "Control use of version numbers for backup files.
270 When t, make numeric backup versions unconditionally.
271 When nil, make them for files that have some already.
272 The value `never' means do not make them."
273 :type
'(choice (const :tag
"Never" never
)
274 (const :tag
"If existing" nil
)
275 (other :tag
"Always" t
))
278 (put 'version-control
'safe-local-variable
279 (lambda (x) (or (booleanp x
) (equal x
'never
))))
281 (defcustom dired-kept-versions
2
282 "When cleaning directory, number of versions to keep."
287 (defcustom delete-old-versions nil
288 "If t, delete excess backup versions silently.
289 If nil, ask confirmation. Any other value prevents any trimming."
290 :type
'(choice (const :tag
"Delete" t
)
291 (const :tag
"Ask" nil
)
292 (other :tag
"Leave" other
))
295 (defcustom kept-old-versions
2
296 "Number of oldest versions to keep when a new numbered backup is made."
299 (put 'kept-old-versions
'safe-local-variable
'integerp
)
301 (defcustom kept-new-versions
2
302 "Number of newest versions to keep when a new numbered backup is made.
303 Includes the new backup. Must be > 0"
306 (put 'kept-new-versions
'safe-local-variable
'integerp
)
308 (defcustom require-final-newline nil
309 "Whether to add a newline automatically at the end of the file.
311 A value of t means do this only when the file is about to be saved.
312 A value of `visit' means do this right after the file is visited.
313 A value of `visit-save' means do it at both of those times.
314 Any other non-nil value means ask user whether to add a newline, when saving.
315 A value of nil means don't add newlines.
317 Certain major modes set this locally to the value obtained
318 from `mode-require-final-newline'."
319 :type
'(choice (const :tag
"When visiting" visit
)
320 (const :tag
"When saving" t
)
321 (const :tag
"When visiting or saving" visit-save
)
322 (const :tag
"Don't add newlines" nil
)
323 (other :tag
"Ask each time" ask
))
324 :group
'editing-basics
)
326 (defcustom mode-require-final-newline t
327 "Whether to add a newline at end of file, in certain major modes.
328 Those modes set `require-final-newline' to this value when you enable them.
329 They do so because they are often used for files that are supposed
330 to end in newlines, and the question is how to arrange that.
332 A value of t means do this only when the file is about to be saved.
333 A value of `visit' means do this right after the file is visited.
334 A value of `visit-save' means do it at both of those times.
335 Any other non-nil value means ask user whether to add a newline, when saving.
337 A value of nil means do not add newlines. That is a risky choice in this
338 variable since this value is used for modes for files that ought to have
339 final newlines. So if you set this to nil, you must explicitly check and
340 add a final newline, whenever you save a file that really needs one."
341 :type
'(choice (const :tag
"When visiting" visit
)
342 (const :tag
"When saving" t
)
343 (const :tag
"When visiting or saving" visit-save
)
344 (const :tag
"Don't add newlines" nil
)
345 (other :tag
"Ask each time" ask
))
346 :group
'editing-basics
349 (defcustom auto-save-default t
350 "Non-nil says by default do auto-saving of every file-visiting buffer."
354 (defcustom auto-save-file-name-transforms
355 `(("\\`/[^/]*:\\([^/]*/\\)*\\([^/]*\\)\\'"
356 ;; Don't put "\\2" inside expand-file-name, since it will be
357 ;; transformed to "/2" on DOS/Windows.
358 ,(concat temporary-file-directory
"\\2") t
))
359 "Transforms to apply to buffer file name before making auto-save file name.
360 Each transform is a list (REGEXP REPLACEMENT UNIQUIFY):
361 REGEXP is a regular expression to match against the file name.
362 If it matches, `replace-match' is used to replace the
363 matching part with REPLACEMENT.
364 If the optional element UNIQUIFY is non-nil, the auto-save file name is
365 constructed by taking the directory part of the replaced file-name,
366 concatenated with the buffer file name with all directory separators
367 changed to `!' to prevent clashes. This will not work
368 correctly if your filesystem truncates the resulting name.
370 All the transforms in the list are tried, in the order they are listed.
371 When one transform applies, its result is final;
372 no further transforms are tried.
374 The default value is set up to put the auto-save file into the
375 temporary directory (see the variable `temporary-file-directory') for
376 editing a remote file.
378 On MS-DOS filesystems without long names this variable is always
381 :type
'(repeat (list (string :tag
"Regexp") (string :tag
"Replacement")
382 (boolean :tag
"Uniquify")))
383 :initialize
'custom-initialize-delay
386 (defcustom save-abbrevs t
387 "Non-nil means save word abbrevs too when files are saved.
388 If `silently', don't ask the user before saving."
389 :type
'(choice (const t
) (const nil
) (const silently
))
392 (defcustom find-file-run-dired t
393 "Non-nil means allow `find-file' to visit directories.
394 To visit the directory, `find-file' runs `find-directory-functions'."
398 (defcustom find-directory-functions
'(cvs-dired-noselect dired-noselect
)
399 "List of functions to try in sequence to visit a directory.
400 Each function is called with the directory name as the sole argument
401 and should return either a buffer or nil."
402 :type
'(hook :options
(cvs-dired-noselect dired-noselect
))
405 ;; FIXME: also add a hook for `(thing-at-point 'filename)'
406 (defcustom file-name-at-point-functions
'(ffap-guess-file-name-at-point)
407 "List of functions to try in sequence to get a file name at point.
408 Each function should return either nil or a file name found at the
409 location of point in the current buffer."
410 :type
'(hook :options
(ffap-guess-file-name-at-point))
413 ;;;It is not useful to make this a local variable.
414 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
415 (define-obsolete-variable-alias 'find-file-not-found-hooks
416 'find-file-not-found-functions
"22.1")
417 (defvar find-file-not-found-functions nil
418 "List of functions to be called for `find-file' on nonexistent file.
419 These functions are called as soon as the error is detected.
420 Variable `buffer-file-name' is already set up.
421 The functions are called in the order given until one of them returns non-nil.")
423 ;;;It is not useful to make this a local variable.
424 ;;;(put 'find-file-hooks 'permanent-local t)
425 (define-obsolete-variable-alias 'find-file-hooks
'find-file-hook
"22.1")
426 (defcustom find-file-hook nil
427 "List of functions to be called after a buffer is loaded from a file.
428 The buffer's local variables (if any) will have been processed before the
429 functions are called."
432 :options
'(auto-insert)
435 (define-obsolete-variable-alias 'write-file-hooks
'write-file-functions
"22.1")
436 (defvar write-file-functions nil
437 "List of functions to be called before writing out a buffer to a file.
438 If one of them returns non-nil, the file is considered already written
439 and the rest are not called.
440 These hooks are considered to pertain to the visited file.
441 So any buffer-local binding of this variable is discarded if you change
442 the visited file name with \\[set-visited-file-name], but not when you
443 change the major mode.
445 This hook is not run if any of the functions in
446 `write-contents-functions' returns non-nil. Both hooks pertain
447 to how to save a buffer to file, for instance, choosing a suitable
448 coding system and setting mode bits. (See Info
449 node `(elisp)Saving Buffers'.) To perform various checks or
450 updates before the buffer is saved, use `before-save-hook'.")
451 (put 'write-file-functions
'permanent-local t
)
453 (defvar local-write-file-hooks nil
)
454 (make-variable-buffer-local 'local-write-file-hooks
)
455 (put 'local-write-file-hooks
'permanent-local t
)
456 (make-obsolete-variable 'local-write-file-hooks
'write-file-functions
"22.1")
458 (define-obsolete-variable-alias 'write-contents-hooks
459 'write-contents-functions
"22.1")
460 (defvar write-contents-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 and neither are the functions in
464 `write-file-functions'.
466 This variable is meant to be used for hooks that pertain to the
467 buffer's contents, not to the particular visited file; thus,
468 `set-visited-file-name' does not clear this variable; but changing the
469 major mode does clear it.
471 For hooks that _do_ pertain to the particular visited file, use
472 `write-file-functions'. Both this variable and
473 `write-file-functions' relate to how a buffer is saved to file.
474 To perform various checks or updates before the buffer is saved,
475 use `before-save-hook'.")
476 (make-variable-buffer-local 'write-contents-functions
)
478 (defcustom enable-local-variables t
479 "Control use of local variables in files you visit.
480 The value can be t, nil, :safe, :all, or something else.
482 A value of t means file local variables specifications are obeyed
483 if all the specified variable values are safe; if any values are
484 not safe, Emacs queries you, once, whether to set them all.
485 \(When you say yes to certain values, they are remembered as safe.)
487 :safe means set the safe variables, and ignore the rest.
488 :all means set all variables, whether safe or not.
489 (Don't set it permanently to :all.)
490 A value of nil means always ignore the file local variables.
492 Any other value means always query you once whether to set them all.
493 \(When you say yes to certain values, they are remembered as safe, but
494 this has no effect when `enable-local-variables' is \"something else\".)
496 This variable also controls use of major modes specified in
499 The command \\[normal-mode], when used interactively,
500 always obeys file local variable specifications and the -*- line,
501 and ignores this variable."
503 :type
'(choice (const :tag
"Query Unsafe" t
)
504 (const :tag
"Safe Only" :safe
)
505 (const :tag
"Do all" :all
)
506 (const :tag
"Ignore" nil
)
507 (other :tag
"Query" other
))
510 ;; This is an odd variable IMO.
511 ;; You might wonder why it is needed, when we could just do:
512 ;; (set (make-local-variable 'enable-local-variables) nil)
513 ;; These two are not precisely the same.
514 ;; Setting this variable does not cause -*- mode settings to be
515 ;; ignored, whereas setting enable-local-variables does.
516 ;; Only three places in Emacs use this variable: tar and arc modes,
517 ;; and rmail. The first two don't need it. They already use
518 ;; inhibit-local-variables-regexps, which is probably enough, and
519 ;; could also just set enable-local-variables locally to nil.
520 ;; Them setting it has the side-effect that dir-locals cannot apply to
521 ;; eg tar files (?). FIXME Is this appropriate?
522 ;; AFAICS, rmail is the only thing that needs this, and the only
523 ;; reason it uses it is for BABYL files (which are obsolete).
524 ;; These contain "-*- rmail -*-" in the first line, which rmail wants
525 ;; to respect, so that find-file on a BABYL file will switch to
526 ;; rmail-mode automatically (this is nice, but hardly essential,
527 ;; since most people are used to explicitly running a command to
528 ;; access their mail; M-x gnus etc). Rmail files may happen to
529 ;; contain Local Variables sections in messages, which Rmail wants to
530 ;; ignore. So AFAICS the only reason this variable exists is for a
531 ;; minor convenience feature for handling of an obsolete Rmail file format.
532 (defvar local-enable-local-variables t
533 "Like `enable-local-variables' but meant for buffer-local bindings.
534 The meaningful values are nil and non-nil. The default is non-nil.
535 If a major mode sets this to nil, buffer-locally, then any local
536 variables list in a file visited in that mode will be ignored.
538 This variable does not affect the use of major modes specified
541 (defcustom enable-local-eval
'maybe
542 "Control processing of the \"variable\" `eval' in a file's local variables.
543 The value can be t, nil or something else.
544 A value of t means obey `eval' variables.
545 A value of nil means ignore them; anything else means query."
547 :type
'(choice (const :tag
"Obey" t
)
548 (const :tag
"Ignore" nil
)
549 (other :tag
"Query" other
))
552 ;; Avoid losing in versions where CLASH_DETECTION is disabled.
553 (or (fboundp 'lock-buffer
)
554 (defalias 'lock-buffer
'ignore
))
555 (or (fboundp 'unlock-buffer
)
556 (defalias 'unlock-buffer
'ignore
))
557 (or (fboundp 'file-locked-p
)
558 (defalias 'file-locked-p
'ignore
))
560 (defcustom view-read-only nil
561 "Non-nil means buffers visiting files read-only do so in view mode.
562 In fact, this means that all read-only buffers normally have
563 View mode enabled, including buffers that are read-only because
564 you visit a file you cannot alter, and buffers you make read-only
565 using \\[toggle-read-only]."
569 (defvar file-name-history nil
570 "History list of file names entered in the minibuffer.
572 Maximum length of the history list is determined by the value
573 of `history-length', which see.")
575 (put 'ange-ftp-completion-hook-function
'safe-magic t
)
576 (defun ange-ftp-completion-hook-function (op &rest args
)
577 "Provides support for ange-ftp host name completion.
578 Runs the usual ange-ftp hook, but only for completion operations."
579 ;; Having this here avoids the need to load ange-ftp when it's not
581 (if (memq op
'(file-name-completion file-name-all-completions
))
582 (apply 'ange-ftp-hook-function op args
)
583 (let ((inhibit-file-name-handlers
584 (cons 'ange-ftp-completion-hook-function
585 (and (eq inhibit-file-name-operation op
)
586 inhibit-file-name-handlers
)))
587 (inhibit-file-name-operation op
))
590 (declare-function dos-convert-standard-filename
"dos-fns.el" (filename))
591 (declare-function w32-convert-standard-filename
"w32-fns.el" (filename))
593 (defun convert-standard-filename (filename)
594 "Convert a standard file's name to something suitable for the OS.
595 This means to guarantee valid names and perhaps to canonicalize
598 FILENAME should be an absolute file name since the conversion rules
599 sometimes vary depending on the position in the file name. E.g. c:/foo
600 is a valid DOS file name, but c:/bar/c:/foo is not.
602 This function's standard definition is trivial; it just returns
603 the argument. However, on Windows and DOS, replace invalid
604 characters. On DOS, make sure to obey the 8.3 limitations.
605 In the native Windows build, turn Cygwin names into native names,
606 and also turn slashes into backslashes if the shell requires it (see
607 `w32-shell-dos-semantics').
609 See Info node `(elisp)Standard File Names' for more details."
611 ((eq system-type
'cygwin
)
612 (let ((name (copy-sequence filename
))
614 ;; Replace invalid filename characters with !
615 (while (string-match "[?*:<>|\"\000-\037]" name start
)
616 (aset name
(match-beginning 0) ?
!)
617 (setq start
(match-end 0)))
619 ((eq system-type
'windows-nt
)
620 (w32-convert-standard-filename filename
))
621 ((eq system-type
'ms-dos
)
622 (dos-convert-standard-filename filename
))
625 (defun read-directory-name (prompt &optional dir default-dirname mustmatch initial
)
626 "Read directory name, prompting with PROMPT and completing in directory DIR.
627 Value is not expanded---you must call `expand-file-name' yourself.
628 Default name to DEFAULT-DIRNAME if user exits with the same
629 non-empty string that was inserted by this function.
630 (If DEFAULT-DIRNAME is omitted, DIR combined with INITIAL is used,
631 or just DIR if INITIAL is nil.)
632 If the user exits with an empty minibuffer, this function returns
633 an empty string. (This can only happen if the user erased the
634 pre-inserted contents or if `insert-default-directory' is nil.)
635 Fourth arg MUSTMATCH non-nil means require existing directory's name.
636 Non-nil and non-t means also require confirmation after completion.
637 Fifth arg INITIAL specifies text to start with.
638 DIR should be an absolute directory name. It defaults to
639 the value of `default-directory'."
641 (setq dir default-directory
))
642 (read-file-name prompt dir
(or default-dirname
643 (if initial
(expand-file-name initial dir
)
650 "Show the current default directory."
652 (message "Directory %s" default-directory
))
655 "Value of the CDPATH environment variable, as a list.
656 Not actually set up until the first time you use it.")
658 (defun parse-colon-path (search-path)
659 "Explode a search path into a list of directory names.
660 Directories are separated by `path-separator' (which is colon in
661 GNU and Unix systems). Substitute environment variables into the
662 resulting list of directory names. For an empty path element (i.e.,
663 a leading or trailing separator, or two adjacent separators), return
664 nil (meaning `default-directory') as the associated list element."
665 (when (stringp search-path
)
668 (substitute-in-file-name (file-name-as-directory f
))))
669 (split-string search-path path-separator
))))
671 (defun cd-absolute (dir)
672 "Change current directory to given absolute file name DIR."
673 ;; Put the name into directory syntax now,
674 ;; because otherwise expand-file-name may give some bad results.
675 (setq dir
(file-name-as-directory dir
))
676 ;; We used to additionally call abbreviate-file-name here, for an
677 ;; unknown reason. Problem is that most buffers are setup
678 ;; without going through cd-absolute and don't call
679 ;; abbreviate-file-name on their default-directory, so the few that
680 ;; do end up using a superficially different directory.
681 (setq dir
(expand-file-name dir
))
682 (if (not (file-directory-p dir
))
683 (if (file-exists-p dir
)
684 (error "%s is not a directory" dir
)
685 (error "%s: no such directory" dir
))
686 (unless (file-executable-p dir
)
687 (error "Cannot cd to %s: Permission denied" dir
))
688 (setq default-directory dir
)
689 (setq list-buffers-directory dir
)))
692 "Make DIR become the current buffer's default directory.
693 If your environment includes a `CDPATH' variable, try each one of
694 that list of directories (separated by occurrences of
695 `path-separator') when resolving a relative directory name.
696 The path separator is colon in GNU and GNU-like systems."
699 ;; FIXME: There's a subtle bug in the completion below. Seems linked
700 ;; to a fundamental difficulty of implementing `predicate' correctly.
701 ;; The manifestation is that TAB may list non-directories in the case where
702 ;; those files also correspond to valid directories (if your cd-path is (A/
703 ;; B/) and you have A/a a file and B/a a directory, then both `a' and `a/'
704 ;; will be listed as valid completions).
705 ;; This is because `a' (listed because of A/a) is indeed a valid choice
706 ;; (which will lead to the use of B/a).
707 (minibuffer-with-setup-hook
709 (setq minibuffer-completion-table
710 (apply-partially #'locate-file-completion-table
712 (setq minibuffer-completion-predicate
714 (locate-file dir cd-path nil
715 (lambda (f) (and (file-directory-p f
) 'dir-ok
))))))
717 (setq cd-path
(or (parse-colon-path (getenv "CDPATH"))
719 (read-directory-name "Change default directory: "
720 default-directory default-directory
723 (setq cd-path
(or (parse-colon-path (getenv "CDPATH"))
726 (or (locate-file dir cd-path nil
727 (lambda (f) (and (file-directory-p f
) 'dir-ok
)))
728 (error "No such directory found via CDPATH environment variable"))))
730 (defun load-file (file)
731 "Load the Lisp file named FILE."
732 ;; This is a case where .elc makes a lot of sense.
733 (interactive (list (let ((completion-ignored-extensions
734 (remove ".elc" completion-ignored-extensions
)))
735 (read-file-name "Load file: " nil nil
'lambda
))))
736 (load (expand-file-name file
) nil nil t
))
738 (defun locate-file (filename path
&optional suffixes predicate
)
739 "Search for FILENAME through PATH.
740 If found, return the absolute file name of FILENAME, with its suffixes;
741 otherwise return nil.
742 PATH should be a list of directories to look in, like the lists in
743 `exec-path' or `load-path'.
744 If SUFFIXES is non-nil, it should be a list of suffixes to append to
745 file name when searching. If SUFFIXES is nil, it is equivalent to '(\"\").
746 Use '(\"/\") to disable PATH search, but still try the suffixes in SUFFIXES.
747 If non-nil, PREDICATE is used instead of `file-readable-p'.
749 This function will normally skip directories, so if you want it to find
750 directories, make sure the PREDICATE function returns `dir-ok' for them.
752 PREDICATE can also be an integer to pass to the `access' system call,
753 in which case file-name handlers are ignored. This usage is deprecated.
754 For compatibility, PREDICATE can also be one of the symbols
755 `executable', `readable', `writable', or `exists', or a list of
756 one or more of those symbols."
757 (if (and predicate
(symbolp predicate
) (not (functionp predicate
)))
758 (setq predicate
(list predicate
)))
759 (when (and (consp predicate
) (not (functionp predicate
)))
761 (logior (if (memq 'executable predicate
) 1 0)
762 (if (memq 'writable predicate
) 2 0)
763 (if (memq 'readable predicate
) 4 0))))
764 (locate-file-internal filename path suffixes predicate
))
766 (defun locate-file-completion-table (dirs suffixes string pred action
)
767 "Do completion for file names passed to `locate-file'."
769 ((file-name-absolute-p string
)
770 ;; FIXME: maybe we should use completion-file-name-table instead,
771 ;; tho at least for `load', the arg is passed through
772 ;; substitute-in-file-name for historical reasons.
773 (read-file-name-internal string pred action
))
774 ((eq (car-safe action
) 'boundaries
)
775 (let ((suffix (cdr action
)))
777 ,(length (file-name-directory string
))
778 ,@(let ((x (file-name-directory suffix
)))
779 (if x
(1- (length x
)) (length suffix
))))))
782 ;; If we have files like "foo.el" and "foo.elc", we could load one of
783 ;; them with "foo.el", "foo.elc", or "foo", where just "foo" is the
784 ;; preferred way. So if we list all 3, that gives a lot of redundant
785 ;; entries for the poor soul looking just for "foo". OTOH, sometimes
786 ;; the user does want to pay attention to the extension. We try to
787 ;; diffuse this tension by stripping the suffix, except when the
788 ;; result is a single element (i.e. usually we only list "foo" unless
789 ;; it's the only remaining element in the list, in which case we do
790 ;; list "foo", "foo.elc" and "foo.el").
792 (suffix (concat (regexp-opt suffixes t
) "\\'"))
793 (string-dir (file-name-directory string
))
794 (string-file (file-name-nondirectory string
)))
797 (setq dir default-directory
))
798 (if string-dir
(setq dir
(expand-file-name string-dir dir
)))
799 (when (file-directory-p dir
)
800 (dolist (file (file-name-all-completions
802 (if (not (string-match suffix file
))
804 (push file fullnames
)
805 (push (substring file
0 (match-beginning 0)) names
)))))
806 ;; Switching from names to names+fullnames creates a non-monotonicity
807 ;; which can cause problems with things like partial-completion.
808 ;; To minimize the problem, filter out completion-regexp-list, so that
809 ;; M-x load-library RET t/x.e TAB finds some files. Also remove elements
810 ;; from `names' which only matched `string' when they still had
812 (setq names
(all-completions string names
))
813 ;; Remove duplicates of the first element, so that we can easily check
814 ;; if `names' really only contains a single element.
815 (when (cdr names
) (setcdr names
(delete (car names
) (cdr names
))))
817 ;; There's no more than one matching non-suffixed element, so expand
818 ;; the list by adding the suffixed elements as well.
819 (setq names
(nconc names fullnames
)))
820 (completion-table-with-context
821 string-dir names string-file pred action
)))))
823 (defun locate-file-completion (string path-and-suffixes action
)
824 "Do completion for file names passed to `locate-file'.
825 PATH-AND-SUFFIXES is a pair of lists, (DIRECTORIES . SUFFIXES)."
826 (declare (obsolete locate-file-completion-table
"23.1"))
827 (locate-file-completion-table (car path-and-suffixes
)
828 (cdr path-and-suffixes
)
831 (defvar locate-dominating-stop-dir-regexp
832 (purecopy "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'")
833 "Regexp of directory names which stop the search in `locate-dominating-file'.
834 Any directory whose name matches this regexp will be treated like
835 a kind of root directory by `locate-dominating-file' which will stop its search
836 when it bumps into it.
837 The default regexp prevents fruitless and time-consuming attempts to find
838 special files in directories in which filenames are interpreted as hostnames,
839 or mount points potentially requiring authentication as a different user.")
841 ;; (defun locate-dominating-files (file regexp)
842 ;; "Look up the directory hierarchy from FILE for a file matching REGEXP.
843 ;; Stop at the first parent where a matching file is found and return the list
844 ;; of files that that match in this directory."
846 ;; ;; `user' is not initialized yet because `file' may not exist, so we may
847 ;; ;; have to walk up part of the hierarchy before we find the "initial UID".
849 ;; ;; Abbreviate, so as to stop when we cross ~/.
850 ;; (dir (abbreviate-file-name (file-name-as-directory file)))
853 ;; ;; As a heuristic, we stop looking up the hierarchy of
854 ;; ;; directories as soon as we find a directory belonging to
855 ;; ;; another user. This should save us from looking in
856 ;; ;; things like /net and /afs. This assumes that all the
857 ;; ;; files inside a project belong to the same user.
858 ;; (let ((prev-user user))
859 ;; (setq user (nth 2 (file-attributes dir)))
860 ;; (or (null prev-user) (equal user prev-user))))
861 ;; (if (setq files (condition-case nil
862 ;; (directory-files dir 'full regexp 'nosort)
864 ;; (throw 'found files)
866 ;; (setq dir (file-name-directory
867 ;; (directory-file-name dir))))
871 (defun locate-dominating-file (file name
)
872 "Look up the directory hierarchy from FILE for a directory containing NAME.
873 Stop at the first parent directory containing a file NAME,
874 and return the directory. Return nil if not found.
875 Instead of a string, NAME can also be a predicate taking one argument
876 \(a directory) and returning a non-nil value if that directory is the one for
877 which we're looking."
878 ;; We used to use the above locate-dominating-files code, but the
879 ;; directory-files call is very costly, so we're much better off doing
880 ;; multiple calls using the code in here.
882 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
883 ;; `name' in /home or in /.
884 (setq file
(abbreviate-file-name file
))
886 ;; `user' is not initialized outside the loop because
887 ;; `file' may not exist, so we may have to walk up part of the
888 ;; hierarchy before we find the "initial UID". Note: currently unused
893 ;; FIXME: Disabled this heuristic because it is sometimes
895 ;; As a heuristic, we stop looking up the hierarchy of
896 ;; directories as soon as we find a directory belonging
897 ;; to another user. This should save us from looking in
898 ;; things like /net and /afs. This assumes that all the
899 ;; files inside a project belong to the same user.
900 ;; (let ((prev-user user))
901 ;; (setq user (nth 2 (file-attributes file)))
902 ;; (and prev-user (not (equal user prev-user))))
903 (string-match locate-dominating-stop-dir-regexp file
)))
904 (setq try
(if (stringp name
)
905 (file-exists-p (expand-file-name name file
))
906 (funcall name file
)))
907 (cond (try (setq root file
))
908 ((equal file
(setq file
(file-name-directory
909 (directory-file-name file
))))
911 (if root
(file-name-as-directory root
))))
914 (defun executable-find (command)
915 "Search for COMMAND in `exec-path' and return the absolute file name.
916 Return nil if COMMAND is not found anywhere in `exec-path'."
917 ;; Use 1 rather than file-executable-p to better match the behavior of
919 (locate-file command exec-path exec-suffixes
1))
921 (defun load-library (library)
922 "Load the Emacs Lisp library named LIBRARY.
923 This is an interface to the function `load'. LIBRARY is searched
924 for in `load-path', both with and without `load-suffixes' (as
925 well as `load-file-rep-suffixes').
927 See Info node `(emacs)Lisp Libraries' for more details.
928 See `load-file' for a different interface to `load'."
930 (list (completing-read "Load library: "
931 (apply-partially 'locate-file-completion-table
933 (get-load-suffixes)))))
936 (defun file-remote-p (file &optional identification connected
)
937 "Test whether FILE specifies a location on a remote system.
938 A file is considered remote if accessing it is likely to
939 be slower or less reliable than accessing local files.
941 `file-remote-p' never opens a new remote connection. It can
942 only reuse a connection that is already open.
944 Return nil or a string identifying the remote connection
945 \(ideally a prefix of FILE). Return nil if FILE is a relative
948 When IDENTIFICATION is nil, the returned string is a complete
949 remote identifier: with components method, user, and host. The
950 components are those present in FILE, with defaults filled in for
951 any that are missing.
953 IDENTIFICATION can specify which part of the identification to
954 return. IDENTIFICATION can be the symbol `method', `user',
955 `host', or `localname'. Any other value is handled like nil and
956 means to return the complete identification. The string returned
957 for IDENTIFICATION `localname' can differ depending on whether
958 there is an existing connection.
960 If CONNECTED is non-nil, return an identification only if FILE is
961 located on a remote system and a connection is established to
964 Tip: You can use this expansion of remote identifier components
965 to derive a new remote file name from an existing one. For
966 example, if FILE is \"/sudo::/path/to/file\" then
968 \(concat \(file-remote-p FILE) \"/bin/sh\")
970 returns a remote file name for file \"/bin/sh\" that has the
971 same remote identifier as FILE but expanded; a name such as
972 \"/sudo:root@myhost:/bin/sh\"."
973 (let ((handler (find-file-name-handler file
'file-remote-p
)))
975 (funcall handler
'file-remote-p file identification connected
)
978 ;; Probably this entire variable should be obsolete now, in favor of
979 ;; something Tramp-related (?). It is not used in many places.
980 ;; It's not clear what the best file for this to be in is, but given
981 ;; it uses custom-initialize-delay, it is easier if it is preloaded
982 ;; rather than autoloaded.
983 (defcustom remote-shell-program
984 ;; This used to try various hard-coded places for remsh, rsh, and
985 ;; rcmd, trying to guess based on location whether "rsh" was
986 ;; "restricted shell" or "remote shell", but I don't see the point
987 ;; in this day and age. Almost everyone will use ssh, and have
988 ;; whatever command they want to use in PATH.
990 (let ((list '("ssh" "remsh" "rcmd" "rsh")))
992 (not (executable-find (car list
)))
993 (setq list
(cdr list
))))
994 (or (car list
) "ssh")))
995 "Program to use to execute commands on a remote host (e.g. ssh or rsh)."
996 :version
"24.3" ; ssh rather than rsh, etc
997 :initialize
'custom-initialize-delay
1001 (defcustom remote-file-name-inhibit-cache
10
1002 "Whether to use the remote file-name cache for read access.
1003 When `nil', never expire cached values (caution)
1004 When `t', never use the cache (safe, but may be slow)
1005 A number means use cached values for that amount of seconds since caching.
1007 The attributes of remote files are cached for better performance.
1008 If they are changed outside of Emacs's control, the cached values
1009 become invalid, and must be reread. If you are sure that nothing
1010 other than Emacs changes the files, you can set this variable to `nil'.
1012 If a remote file is checked regularly, it might be a good idea to
1013 let-bind this variable to a value less than the interval between
1014 consecutive checks. For example:
1016 (defun display-time-file-nonempty-p (file)
1017 (let ((remote-file-name-inhibit-cache (- display-time-interval 5)))
1018 (and (file-exists-p file)
1019 (< 0 (nth 7 (file-attributes (file-chase-links file)))))))"
1023 (const :tag
"Do not inhibit file name cache" nil
)
1024 (const :tag
"Do not use file name cache" t
)
1025 (integer :tag
"Do not use file name cache"
1026 :format
"Do not use file name cache older then %v seconds"
1029 (defun file-local-copy (file)
1030 "Copy the file FILE into a temporary file on this machine.
1031 Returns the name of the local copy, or nil, if FILE is directly
1033 ;; This formerly had an optional BUFFER argument that wasn't used by
1035 (let ((handler (find-file-name-handler file
'file-local-copy
)))
1037 (funcall handler
'file-local-copy file
)
1040 (defun file-truename (filename &optional counter prev-dirs
)
1041 "Return the truename of FILENAME.
1042 If FILENAME is not absolute, first expands it against `default-directory'.
1043 The truename of a file name is found by chasing symbolic links
1044 both at the level of the file and at the level of the directories
1045 containing it, until no links are left at any level.
1047 \(fn FILENAME)" ;; Don't document the optional arguments.
1048 ;; COUNTER and PREV-DIRS are only used in recursive calls.
1049 ;; COUNTER can be a cons cell whose car is the count of how many
1050 ;; more links to chase before getting an error.
1051 ;; PREV-DIRS can be a cons cell whose car is an alist
1052 ;; of truenames we've just recently computed.
1053 (cond ((or (string= filename
"") (string= filename
"~"))
1054 (setq filename
(expand-file-name filename
))
1055 (if (string= filename
"")
1056 (setq filename
"/")))
1057 ((and (string= (substring filename
0 1) "~")
1058 (string-match "~[^/]*/?" filename
))
1060 (substring filename
0 (match-end 0)))
1061 (rest (substring filename
(match-end 0))))
1062 (setq filename
(concat (expand-file-name first-part
) rest
)))))
1064 (or counter
(setq counter
(list 100)))
1066 ;; For speed, remove the ange-ftp completion handler from the list.
1067 ;; We know it's not needed here.
1068 ;; For even more speed, do this only on the outermost call.
1069 (file-name-handler-alist
1070 (if prev-dirs file-name-handler-alist
1071 (let ((tem (copy-sequence file-name-handler-alist
)))
1072 (delq (rassq 'ange-ftp-completion-hook-function tem
) tem
)))))
1073 (or prev-dirs
(setq prev-dirs
(list nil
)))
1075 ;; andrewi@harlequin.co.uk - on Windows, there is an issue with
1076 ;; case differences being ignored by the OS, and short "8.3 DOS"
1077 ;; name aliases existing for all files. (The short names are not
1078 ;; reported by directory-files, but can be used to refer to files.)
1079 ;; It seems appropriate for file-truename to resolve these issues in
1080 ;; the most natural way, which on Windows is to call the function
1081 ;; `w32-long-file-name' - this returns the exact name of a file as
1082 ;; it is stored on disk (expanding short name aliases with the full
1083 ;; name in the process).
1084 (if (eq system-type
'windows-nt
)
1085 (unless (string-match "[[*?]" filename
)
1086 ;; If filename exists, use its long name. If it doesn't
1087 ;; exist, the recursion below on the directory of filename
1088 ;; will drill down until we find a directory that exists,
1089 ;; and use the long name of that, with the extra
1090 ;; non-existent path components concatenated.
1091 (let ((longname (w32-long-file-name filename
)))
1093 (setq filename longname
)))))
1095 ;; If this file directly leads to a link, process that iteratively
1096 ;; so that we don't use lots of stack.
1098 (setcar counter
(1- (car counter
)))
1099 (if (< (car counter
) 0)
1100 (error "Apparent cycle of symbolic links for %s" filename
))
1101 (let ((handler (find-file-name-handler filename
'file-truename
)))
1102 ;; For file name that has a special handler, call handler.
1103 ;; This is so that ange-ftp can save time by doing a no-op.
1105 (setq filename
(funcall handler
'file-truename filename
)
1107 (let ((dir (or (file-name-directory filename
) default-directory
))
1109 ;; Get the truename of the directory.
1110 (setq dirfile
(directory-file-name dir
))
1111 ;; If these are equal, we have the (or a) root directory.
1112 (or (string= dir dirfile
)
1113 (and (memq system-type
'(windows-nt ms-dos cygwin
))
1114 (eq (compare-strings dir
0 nil dirfile
0 nil t
) t
))
1115 ;; If this is the same dir we last got the truename for,
1116 ;; save time--don't recalculate.
1117 (if (assoc dir
(car prev-dirs
))
1118 (setq dir
(cdr (assoc dir
(car prev-dirs
))))
1120 (new (file-name-as-directory (file-truename dirfile counter prev-dirs
))))
1121 (setcar prev-dirs
(cons (cons old new
) (car prev-dirs
)))
1123 (if (equal ".." (file-name-nondirectory filename
))
1125 (directory-file-name (file-name-directory (directory-file-name dir
)))
1127 (if (equal "." (file-name-nondirectory filename
))
1128 (setq filename
(directory-file-name dir
)
1130 ;; Put it back on the file name.
1131 (setq filename
(concat dir
(file-name-nondirectory filename
)))
1132 ;; Is the file name the name of a link?
1133 (setq target
(file-symlink-p filename
))
1135 ;; Yes => chase that link, then start all over
1136 ;; since the link may point to a directory name that uses links.
1137 ;; We can't safely use expand-file-name here
1138 ;; since target might look like foo/../bar where foo
1139 ;; is itself a link. Instead, we handle . and .. above.
1141 (if (file-name-absolute-p target
)
1143 (concat dir target
))
1146 (setq done t
))))))))
1149 (defun file-chase-links (filename &optional limit
)
1150 "Chase links in FILENAME until a name that is not a link.
1151 Unlike `file-truename', this does not check whether a parent
1152 directory name is a symbolic link.
1153 If the optional argument LIMIT is a number,
1154 it means chase no more than that many links and then stop."
1155 (let (tem (newname filename
)
1157 (while (and (or (null limit
) (< count limit
))
1158 (setq tem
(file-symlink-p newname
)))
1160 (if (and (null limit
) (= count
100))
1161 (error "Apparent cycle of symbolic links for %s" filename
))
1162 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
1163 (while (string-match "//+" tem
)
1164 (setq tem
(replace-match "/" nil nil tem
)))
1165 ;; Handle `..' by hand, since it needs to work in the
1166 ;; target of any directory symlink.
1167 ;; This code is not quite complete; it does not handle
1168 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
1169 (while (string-match "\\`\\.\\./" tem
)
1170 (setq tem
(substring tem
3))
1171 (setq newname
(expand-file-name newname
))
1172 ;; Chase links in the default dir of the symlink.
1175 (directory-file-name (file-name-directory newname
))))
1176 ;; Now find the parent of that dir.
1177 (setq newname
(file-name-directory newname
)))
1178 (setq newname
(expand-file-name tem
(file-name-directory newname
)))
1179 (setq count
(1+ count
))))
1182 ;; A handy function to display file sizes in human-readable form.
1183 ;; See http://en.wikipedia.org/wiki/Kibibyte for the reference.
1184 (defun file-size-human-readable (file-size &optional flavor
)
1185 "Produce a string showing FILE-SIZE in human-readable form.
1187 Optional second argument FLAVOR controls the units and the display format:
1189 If FLAVOR is nil or omitted, each kilobyte is 1024 bytes and the produced
1190 suffixes are \"k\", \"M\", \"G\", \"T\", etc.
1191 If FLAVOR is `si', each kilobyte is 1000 bytes and the produced suffixes
1192 are \"k\", \"M\", \"G\", \"T\", etc.
1193 If FLAVOR is `iec', each kilobyte is 1024 bytes and the produced suffixes
1194 are \"KiB\", \"MiB\", \"GiB\", \"TiB\", etc."
1195 (let ((power (if (or (null flavor
) (eq flavor
'iec
))
1199 ;; none, kilo, mega, giga, tera, peta, exa, zetta, yotta
1200 (list "" "k" "M" "G" "T" "P" "E" "Z" "Y")))
1201 (while (and (>= file-size power
) (cdr post-fixes
))
1202 (setq file-size
(/ file-size power
)
1203 post-fixes
(cdr post-fixes
)))
1204 (format (if (> (mod file-size
1.0) 0.05)
1208 (if (and (eq flavor
'iec
) (string= (car post-fixes
) "k"))
1211 (if (eq flavor
'iec
) "iB" ""))))
1213 (defun make-temp-file (prefix &optional dir-flag suffix
)
1214 "Create a temporary file.
1215 The returned file name (created by appending some random characters at the end
1216 of PREFIX, and expanding against `temporary-file-directory' if necessary),
1217 is guaranteed to point to a newly created empty file.
1218 You can then use `write-region' to write new data into the file.
1220 If DIR-FLAG is non-nil, create a new empty directory instead of a file.
1222 If SUFFIX is non-nil, add that at the end of the file name."
1223 (let ((umask (default-file-modes))
1227 ;; Create temp files with strict access rights. It's easy to
1228 ;; loosen them later, whereas it's impossible to close the
1229 ;; time-window of loose permissions otherwise.
1230 (set-default-file-modes ?
\700)
1231 (while (condition-case ()
1235 (if (zerop (length prefix
))
1236 (file-name-as-directory
1237 temporary-file-directory
)
1238 (expand-file-name prefix
1239 temporary-file-directory
))))
1241 (setq file
(concat file suffix
)))
1243 (make-directory file
)
1244 (write-region "" nil file nil
'silent nil
'excl
))
1246 (file-already-exists t
))
1247 ;; the file was somehow created by someone else between
1248 ;; `make-temp-name' and `write-region', let's try again.
1252 (set-default-file-modes umask
))))
1254 (defun recode-file-name (file coding new-coding
&optional ok-if-already-exists
)
1255 "Change the encoding of FILE's name from CODING to NEW-CODING.
1256 The value is a new name of FILE.
1257 Signals a `file-already-exists' error if a file of the new name
1258 already exists unless optional fourth argument OK-IF-ALREADY-EXISTS
1259 is non-nil. A number as fourth arg means request confirmation if
1260 the new name already exists. This is what happens in interactive
1263 (let ((default-coding (or file-name-coding-system
1264 default-file-name-coding-system
))
1265 (filename (read-file-name "Recode filename: " nil nil t
))
1266 from-coding to-coding
)
1267 (if (and default-coding
1268 ;; We provide the default coding only when it seems that
1269 ;; the filename is correctly decoded by the default
1271 (let ((charsets (find-charset-string filename
)))
1272 (and (not (memq 'eight-bit-control charsets
))
1273 (not (memq 'eight-bit-graphic charsets
)))))
1274 (setq from-coding
(read-coding-system
1275 (format "Recode filename %s from (default %s): "
1276 filename default-coding
)
1278 (setq from-coding
(read-coding-system
1279 (format "Recode filename %s from: " filename
))))
1281 ;; We provide the default coding only when a user is going to
1282 ;; change the encoding not from the default coding.
1283 (if (eq from-coding default-coding
)
1284 (setq to-coding
(read-coding-system
1285 (format "Recode filename %s from %s to: "
1286 filename from-coding
)))
1287 (setq to-coding
(read-coding-system
1288 (format "Recode filename %s from %s to (default %s): "
1289 filename from-coding default-coding
)
1291 (list filename from-coding to-coding
)))
1293 (let* ((default-coding (or file-name-coding-system
1294 default-file-name-coding-system
))
1295 ;; FILE should have been decoded by DEFAULT-CODING.
1296 (encoded (encode-coding-string file default-coding
))
1297 (newname (decode-coding-string encoded coding
))
1298 (new-encoded (encode-coding-string newname new-coding
))
1299 ;; Suppress further encoding.
1300 (file-name-coding-system nil
)
1301 (default-file-name-coding-system nil
)
1302 (locale-coding-system nil
))
1303 (rename-file encoded new-encoded ok-if-already-exists
)
1306 (defcustom confirm-nonexistent-file-or-buffer
'after-completion
1307 "Whether confirmation is requested before visiting a new file or buffer.
1308 If nil, confirmation is not requested.
1309 If the value is `after-completion', confirmation is only
1310 requested if the user called `minibuffer-complete' right before
1311 `minibuffer-complete-and-exit'.
1312 Any other non-nil value means to request confirmation.
1314 This affects commands like `switch-to-buffer' and `find-file'."
1317 :type
'(choice (const :tag
"After completion" after-completion
)
1318 (const :tag
"Never" nil
)
1319 (other :tag
"Always" t
)))
1321 (defun confirm-nonexistent-file-or-buffer ()
1322 "Whether to request confirmation before visiting a new file or buffer.
1323 The variable `confirm-nonexistent-file-or-buffer' determines the
1324 return value, which may be passed as the REQUIRE-MATCH arg to
1325 `read-buffer' or `find-file-read-args'."
1326 (cond ((eq confirm-nonexistent-file-or-buffer
'after-completion
)
1327 'confirm-after-completion
)
1328 (confirm-nonexistent-file-or-buffer
1332 (defmacro minibuffer-with-setup-hook
(fun &rest body
)
1333 "Temporarily add FUN to `minibuffer-setup-hook' while executing BODY.
1334 BODY should use the minibuffer at most once.
1335 Recursive uses of the minibuffer are unaffected (FUN is not
1336 called additional times).
1338 This macro actually adds an auxiliary function that calls FUN,
1339 rather than FUN itself, to `minibuffer-setup-hook'."
1340 (declare (indent 1) (debug t
))
1341 (let ((hook (make-symbol "setup-hook")))
1345 ;; Clear out this hook so it does not interfere
1346 ;; with any recursive minibuffer usage.
1347 (remove-hook 'minibuffer-setup-hook
,hook
)
1351 (add-hook 'minibuffer-setup-hook
,hook
)
1353 (remove-hook 'minibuffer-setup-hook
,hook
)))))
1355 (defun find-file-read-args (prompt mustmatch
)
1356 (list (read-file-name prompt nil default-directory mustmatch
)
1359 (defun find-file (filename &optional wildcards
)
1360 "Edit file FILENAME.
1361 Switch to a buffer visiting file FILENAME,
1362 creating one if none already exists.
1363 Interactively, the default if you just type RET is the current directory,
1364 but the visited file name is available through the minibuffer history:
1365 type M-n to pull it into the minibuffer.
1367 You can visit files on remote machines by specifying something
1368 like /ssh:SOME_REMOTE_MACHINE:FILE for the file name. You can
1369 also visit local files as a different user by specifying
1370 /sudo::FILE for the file name.
1371 See the Info node `(tramp)Filename Syntax' in the Tramp Info
1372 manual, for more about this.
1374 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1375 expand wildcards (if any) and visit multiple files. You can
1376 suppress wildcard expansion by setting `find-file-wildcards' to nil.
1378 To visit a file without any kind of conversion and without
1379 automatically choosing a major mode, use \\[find-file-literally]."
1381 (find-file-read-args "Find file: "
1382 (confirm-nonexistent-file-or-buffer)))
1383 (let ((value (find-file-noselect filename nil nil wildcards
)))
1385 (mapcar 'switch-to-buffer
(nreverse value
))
1386 (switch-to-buffer value
))))
1388 (defun find-file-other-window (filename &optional wildcards
)
1389 "Edit file FILENAME, in another window.
1391 Like \\[find-file] (which see), but creates a new window or reuses
1392 an existing one. See the function `display-buffer'.
1394 Interactively, the default if you just type RET is the current directory,
1395 but the visited file name is available through the minibuffer history:
1396 type M-n to pull it into the minibuffer.
1398 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1399 expand wildcards (if any) and visit multiple files."
1401 (find-file-read-args "Find file in other window: "
1402 (confirm-nonexistent-file-or-buffer)))
1403 (let ((value (find-file-noselect filename nil nil wildcards
)))
1406 (setq value
(nreverse value
))
1407 (cons (switch-to-buffer-other-window (car value
))
1408 (mapcar 'switch-to-buffer
(cdr value
))))
1409 (switch-to-buffer-other-window value
))))
1411 (defun find-file-other-frame (filename &optional wildcards
)
1412 "Edit file FILENAME, in another frame.
1414 Like \\[find-file] (which see), but creates a new frame or reuses
1415 an existing one. See the function `display-buffer'.
1417 Interactively, the default if you just type RET is the current directory,
1418 but the visited file name is available through the minibuffer history:
1419 type M-n to pull it into the minibuffer.
1421 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1422 expand wildcards (if any) and visit multiple files."
1424 (find-file-read-args "Find file in other frame: "
1425 (confirm-nonexistent-file-or-buffer)))
1426 (let ((value (find-file-noselect filename nil nil wildcards
)))
1429 (setq value
(nreverse value
))
1430 (cons (switch-to-buffer-other-frame (car value
))
1431 (mapcar 'switch-to-buffer
(cdr value
))))
1432 (switch-to-buffer-other-frame value
))))
1434 (defun find-file-existing (filename)
1435 "Edit the existing file FILENAME.
1436 Like \\[find-file], but only allow a file that exists, and do not allow
1437 file names with wildcards."
1438 (interactive (nbutlast (find-file-read-args "Find existing file: " t
)))
1439 (if (and (not (called-interactively-p 'interactive
))
1440 (not (file-exists-p filename
)))
1441 (error "%s does not exist" filename
)
1442 (find-file filename
)
1445 (defun find-file--read-only (fun filename wildcards
)
1446 (unless (or (and wildcards find-file-wildcards
1447 (not (string-match "\\`/:" filename
))
1448 (string-match "[[*?]" filename
))
1449 (file-exists-p filename
))
1450 (error "%s does not exist" filename
))
1451 (let ((value (funcall fun filename wildcards
)))
1452 (mapc (lambda (b) (with-current-buffer b
(read-only-mode 1)))
1453 (if (listp value
) value
(list value
)))
1456 (defun find-file-read-only (filename &optional wildcards
)
1457 "Edit file FILENAME but don't allow changes.
1458 Like \\[find-file], but marks buffer as read-only.
1459 Use \\[toggle-read-only] to permit editing."
1461 (find-file-read-args "Find file read-only: "
1462 (confirm-nonexistent-file-or-buffer)))
1463 (find-file--read-only #'find-file filename wildcards
))
1465 (defun find-file-read-only-other-window (filename &optional wildcards
)
1466 "Edit file FILENAME in another window but don't allow changes.
1467 Like \\[find-file-other-window], but marks buffer as read-only.
1468 Use \\[toggle-read-only] to permit editing."
1470 (find-file-read-args "Find file read-only other window: "
1471 (confirm-nonexistent-file-or-buffer)))
1472 (find-file--read-only #'find-file-other-window filename wildcards
))
1474 (defun find-file-read-only-other-frame (filename &optional wildcards
)
1475 "Edit file FILENAME in another frame but don't allow changes.
1476 Like \\[find-file-other-frame], but marks buffer as read-only.
1477 Use \\[toggle-read-only] to permit editing."
1479 (find-file-read-args "Find file read-only other frame: "
1480 (confirm-nonexistent-file-or-buffer)))
1481 (find-file--read-only #'find-file-other-frame filename wildcards
))
1483 (defun find-alternate-file-other-window (filename &optional wildcards
)
1484 "Find file FILENAME as a replacement for the file in the next window.
1485 This command does not select that window.
1487 See \\[find-file] for the possible forms of the FILENAME argument.
1489 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1490 expand wildcards (if any) and replace the file with multiple files."
1492 (save-selected-window
1494 (let ((file buffer-file-name
)
1498 (setq file-name
(file-name-nondirectory file
)
1499 file-dir
(file-name-directory file
)))
1500 (list (read-file-name
1501 "Find alternate file: " file-dir nil
1502 (confirm-nonexistent-file-or-buffer) file-name
)
1505 (find-file-other-window filename wildcards
)
1506 (save-selected-window
1508 (find-alternate-file filename wildcards
))))
1510 ;; Defined and used in buffer.c, but not as a DEFVAR_LISP.
1511 (defvar kill-buffer-hook nil
1512 "Hook run when a buffer is killed.
1513 The buffer being killed is current while the hook is running.
1514 See `kill-buffer'.")
1516 (defun find-alternate-file (filename &optional wildcards
)
1517 "Find file FILENAME, select its buffer, kill previous buffer.
1518 If the current buffer now contains an empty file that you just visited
1519 \(presumably by mistake), use this command to visit the file you really want.
1521 See \\[find-file] for the possible forms of the FILENAME argument.
1523 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1524 expand wildcards (if any) and replace the file with multiple files.
1526 If the current buffer is an indirect buffer, or the base buffer
1527 for one or more indirect buffers, the other buffer(s) are not
1530 (let ((file buffer-file-name
)
1534 (setq file-name
(file-name-nondirectory file
)
1535 file-dir
(file-name-directory file
)))
1536 (list (read-file-name
1537 "Find alternate file: " file-dir nil
1538 (confirm-nonexistent-file-or-buffer) file-name
)
1540 (unless (run-hook-with-args-until-failure 'kill-buffer-query-functions
)
1542 (and (buffer-modified-p) buffer-file-name
1543 (not (yes-or-no-p "Kill and replace the buffer without saving it? "))
1545 (let ((obuf (current-buffer))
1546 (ofile buffer-file-name
)
1547 (onum buffer-file-number
)
1548 (odir dired-directory
)
1549 (otrue buffer-file-truename
)
1550 (oname (buffer-name)))
1551 ;; Run `kill-buffer-hook' here. It needs to happen before
1552 ;; variables like `buffer-file-name' etc are set to nil below,
1553 ;; because some of the hooks that could be invoked
1554 ;; (e.g., `save-place-to-alist') depend on those variables.
1556 ;; Note that `kill-buffer-hook' is not what queries whether to
1557 ;; save a modified buffer visiting a file. Rather, `kill-buffer'
1558 ;; asks that itself. Thus, there's no need to temporarily do
1559 ;; `(set-buffer-modified-p nil)' before running this hook.
1560 (run-hooks 'kill-buffer-hook
)
1561 ;; Okay, now we can end-of-life the old buffer.
1562 (if (get-buffer " **lose**")
1563 (kill-buffer " **lose**"))
1564 (rename-buffer " **lose**")
1568 ;; This prevents us from finding the same buffer
1569 ;; if we specified the same file again.
1570 (setq buffer-file-name nil
)
1571 (setq buffer-file-number nil
)
1572 (setq buffer-file-truename nil
)
1573 ;; Likewise for dired buffers.
1574 (setq dired-directory nil
)
1575 (find-file filename wildcards
))
1576 (when (eq obuf
(current-buffer))
1577 ;; This executes if find-file gets an error
1578 ;; and does not really find anything.
1579 ;; We put things back as they were.
1580 ;; If find-file actually finds something, we kill obuf below.
1581 (setq buffer-file-name ofile
)
1582 (setq buffer-file-number onum
)
1583 (setq buffer-file-truename otrue
)
1584 (setq dired-directory odir
)
1586 (rename-buffer oname
)))
1587 (unless (eq (current-buffer) obuf
)
1588 (with-current-buffer obuf
1589 ;; We already ran these; don't run them again.
1590 (let (kill-buffer-query-functions kill-buffer-hook
)
1591 (kill-buffer obuf
))))))
1593 (defun create-file-buffer (filename)
1594 "Create a suitably named buffer for visiting FILENAME, and return it.
1595 FILENAME (sans directory) is used unchanged if that name is free;
1596 otherwise a string <2> or <3> or ... is appended to get an unused name.
1597 Spaces at the start of FILENAME (sans directory) are removed."
1598 (let ((lastname (file-name-nondirectory filename
)))
1599 (if (string= lastname
"")
1600 (setq lastname filename
))
1602 (string-match "^ *\\(.*\\)" lastname
)
1603 (generate-new-buffer (match-string 1 lastname
)))))
1605 (defun generate-new-buffer (name)
1606 "Create and return a buffer with a name based on NAME.
1607 Choose the buffer's name using `generate-new-buffer-name'."
1608 (get-buffer-create (generate-new-buffer-name name
)))
1610 (defcustom automount-dir-prefix
(purecopy "^/tmp_mnt/")
1611 "Regexp to match the automounter prefix in a directory name."
1614 (make-obsolete-variable 'automount-dir-prefix
'directory-abbrev-alist
"24.3")
1616 (defvar abbreviated-home-dir nil
1617 "The user's homedir abbreviated according to `directory-abbrev-alist'.")
1619 (defun abbreviate-file-name (filename)
1620 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
1621 This also substitutes \"~\" for the user's home directory (unless the
1622 home directory is a root directory) and removes automounter prefixes
1623 \(see the variable `automount-dir-prefix')."
1624 ;; Get rid of the prefixes added by the automounter.
1626 (if (and automount-dir-prefix
1627 (string-match automount-dir-prefix filename
)
1628 (file-exists-p (file-name-directory
1629 (substring filename
(1- (match-end 0))))))
1630 (setq filename
(substring filename
(1- (match-end 0)))))
1631 ;; Avoid treating /home/foo as /home/Foo during `~' substitution.
1632 ;; To fix this right, we need a `file-name-case-sensitive-p'
1633 ;; function, but we don't have that yet, so just guess.
1634 (let ((case-fold-search
1635 (memq system-type
'(ms-dos windows-nt darwin cygwin
))))
1636 ;; If any elt of directory-abbrev-alist matches this name,
1637 ;; abbreviate accordingly.
1638 (dolist (dir-abbrev directory-abbrev-alist
)
1639 (if (string-match (car dir-abbrev
) filename
)
1641 (concat (cdr dir-abbrev
)
1642 (substring filename
(match-end 0))))))
1643 ;; Compute and save the abbreviated homedir name.
1644 ;; We defer computing this until the first time it's needed, to
1645 ;; give time for directory-abbrev-alist to be set properly.
1646 ;; We include a slash at the end, to avoid spurious matches
1647 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
1648 (or abbreviated-home-dir
1649 (setq abbreviated-home-dir
1650 (let ((abbreviated-home-dir "$foo"))
1651 (concat "\\`" (abbreviate-file-name (expand-file-name "~"))
1654 ;; If FILENAME starts with the abbreviated homedir,
1655 ;; make it start with `~' instead.
1656 (if (and (string-match abbreviated-home-dir filename
)
1657 ;; If the home dir is just /, don't change it.
1658 (not (and (= (match-end 0) 1)
1659 (= (aref filename
0) ?
/)))
1660 ;; MS-DOS root directories can come with a drive letter;
1661 ;; Novell Netware allows drive letters beyond `Z:'.
1662 (not (and (memq system-type
'(ms-dos windows-nt cygwin
))
1664 (string-match "^[a-zA-`]:/$" filename
)))))
1667 (match-string 1 filename
)
1668 (substring filename
(match-end 0)))))
1671 (defun find-buffer-visiting (filename &optional predicate
)
1672 "Return the buffer visiting file FILENAME (a string).
1673 This is like `get-file-buffer', except that it checks for any buffer
1674 visiting the same file, possibly under a different name.
1675 If PREDICATE is non-nil, only buffers satisfying it are eligible,
1676 and others are ignored.
1677 If there is no such live buffer, return nil."
1678 (let ((predicate (or predicate
#'identity
))
1679 (truename (abbreviate-file-name (file-truename filename
))))
1680 (or (let ((buf (get-file-buffer filename
)))
1681 (when (and buf
(funcall predicate buf
)) buf
))
1682 (let ((list (buffer-list)) found
)
1683 (while (and (not found
) list
)
1684 (with-current-buffer (car list
)
1685 (if (and buffer-file-name
1686 (string= buffer-file-truename truename
)
1687 (funcall predicate
(current-buffer)))
1688 (setq found
(car list
))))
1689 (setq list
(cdr list
)))
1691 (let* ((attributes (file-attributes truename
))
1692 (number (nthcdr 10 attributes
))
1693 (list (buffer-list)) found
)
1694 (and buffer-file-numbers-unique
1695 (car-safe number
) ;Make sure the inode is not just nil.
1696 (while (and (not found
) list
)
1697 (with-current-buffer (car list
)
1698 (if (and buffer-file-name
1699 (equal buffer-file-number number
)
1700 ;; Verify this buffer's file number
1701 ;; still belongs to its file.
1702 (file-exists-p buffer-file-name
)
1703 (equal (file-attributes buffer-file-truename
)
1705 (funcall predicate
(current-buffer)))
1706 (setq found
(car list
))))
1707 (setq list
(cdr list
))))
1710 (defcustom find-file-wildcards t
1711 "Non-nil means file-visiting commands should handle wildcards.
1712 For example, if you specify `*.c', that would visit all the files
1713 whose names match the pattern."
1718 (defcustom find-file-suppress-same-file-warnings nil
1719 "Non-nil means suppress warning messages for symlinked files.
1720 When nil, Emacs prints a warning when visiting a file that is already
1721 visited, but with a different name. Setting this option to t
1722 suppresses this warning."
1727 (defcustom large-file-warning-threshold
10000000
1728 "Maximum size of file above which a confirmation is requested.
1729 When nil, never request confirmation."
1733 :type
'(choice integer
(const :tag
"Never request confirmation" nil
)))
1735 (defun abort-if-file-too-large (size op-type filename
)
1736 "If file SIZE larger than `large-file-warning-threshold', allow user to abort.
1737 OP-TYPE specifies the file operation being performed (for message to user)."
1738 (when (and large-file-warning-threshold size
1739 (> size large-file-warning-threshold
)
1740 (not (y-or-n-p (format "File %s is large (%s), really %s? "
1741 (file-name-nondirectory filename
)
1742 (file-size-human-readable size
) op-type
))))
1745 (defun find-file-noselect (filename &optional nowarn rawfile wildcards
)
1746 "Read file FILENAME into a buffer and return the buffer.
1747 If a buffer exists visiting FILENAME, return that one, but
1748 verify that the file has not changed since visited or saved.
1749 The buffer is not selected, just returned to the caller.
1750 Optional second arg NOWARN non-nil means suppress any warning messages.
1751 Optional third arg RAWFILE non-nil means the file is read literally.
1752 Optional fourth arg WILDCARDS non-nil means do wildcard processing
1753 and visit all the matching files. When wildcards are actually
1754 used and expanded, return a list of buffers that are visiting
1757 (abbreviate-file-name
1758 (expand-file-name filename
)))
1759 (if (file-directory-p filename
)
1760 (or (and find-file-run-dired
1761 (run-hook-with-args-until-success
1762 'find-directory-functions
1763 (if find-file-visit-truename
1764 (abbreviate-file-name (file-truename filename
))
1766 (error "%s is a directory" filename
))
1769 (not (string-match "\\`/:" filename
))
1770 (string-match "[[*?]" filename
))
1771 (let ((files (condition-case nil
1772 (file-expand-wildcards filename t
)
1773 (error (list filename
))))
1774 (find-file-wildcards nil
))
1776 (find-file-noselect filename
)
1777 (mapcar #'find-file-noselect files
)))
1778 (let* ((buf (get-file-buffer filename
))
1779 (truename (abbreviate-file-name (file-truename filename
)))
1780 (attributes (file-attributes truename
))
1781 (number (nthcdr 10 attributes
))
1782 ;; Find any buffer for a file which has same truename.
1783 (other (and (not buf
) (find-buffer-visiting filename
))))
1784 ;; Let user know if there is a buffer with the same truename.
1788 find-file-suppress-same-file-warnings
1789 (string-equal filename
(buffer-file-name other
))
1790 (message "%s and %s are the same file"
1791 filename
(buffer-file-name other
)))
1792 ;; Optionally also find that buffer.
1793 (if (or find-file-existing-other-name find-file-visit-truename
)
1795 ;; Check to see if the file looks uncommonly large.
1796 (when (not (or buf nowarn
))
1797 (abort-if-file-too-large (nth 7 attributes
) "open" filename
))
1799 ;; We are using an existing buffer.
1802 (verify-visited-file-modtime buf
)
1803 (cond ((not (file-exists-p filename
))
1804 (setq nonexistent t
)
1805 (message "File %s no longer exists!" filename
))
1806 ;; Certain files should be reverted automatically
1807 ;; if they have changed on disk and not in the buffer.
1808 ((and (not (buffer-modified-p buf
))
1809 (let ((tail revert-without-query
)
1812 (if (string-match (car tail
) filename
)
1814 (setq tail
(cdr tail
)))
1816 (with-current-buffer buf
1817 (message "Reverting file %s..." filename
)
1819 (message "Reverting file %s...done" filename
)))
1821 (if (string= (file-name-nondirectory filename
)
1824 (if (buffer-modified-p buf
)
1825 "File %s changed on disk. Discard your edits? "
1826 "File %s changed on disk. Reread from disk? ")
1827 (file-name-nondirectory filename
))
1829 (if (buffer-modified-p buf
)
1830 "File %s changed on disk. Discard your edits in %s? "
1831 "File %s changed on disk. Reread from disk into %s? ")
1832 (file-name-nondirectory filename
)
1833 (buffer-name buf
))))
1834 (with-current-buffer buf
1835 (revert-buffer t t
)))))
1836 (with-current-buffer buf
1838 ;; Check if a formerly read-only file has become
1839 ;; writable and vice versa, but if the buffer agrees
1840 ;; with the new state of the file, that is ok too.
1841 (let ((read-only (not (file-writable-p buffer-file-name
))))
1842 (unless (or nonexistent
1843 (eq read-only buffer-file-read-only
)
1844 (eq read-only buffer-read-only
))
1847 (format "File %s is %s on disk. Change buffer mode? "
1849 (if read-only
"read-only" "writable"))))
1850 (y-or-n-p question
)))
1851 (setq buffer-read-only read-only
)))
1852 (setq buffer-file-read-only read-only
))
1854 (when (and (not (eq (not (null rawfile
))
1855 (not (null find-file-literally
))))
1857 ;; It is confusing to ask whether to visit
1858 ;; non-literally if they have the file in
1859 ;; hexl-mode or image-mode.
1860 (not (memq major-mode
'(hexl-mode image-mode
))))
1861 (if (buffer-modified-p)
1865 "The file %s is already visited normally,
1866 and you have edited the buffer. Now you have asked to visit it literally,
1867 meaning no coding system handling, format conversion, or local variables.
1868 Emacs can only visit a file in one way at a time.
1870 Do you want to save the file, and visit it literally instead? "
1871 "The file %s is already visited literally,
1872 meaning no coding system handling, format conversion, or local variables.
1873 You have edited the buffer. Now you have asked to visit the file normally,
1874 but Emacs can only visit a file in one way at a time.
1876 Do you want to save the file, and visit it normally instead? ")
1877 (file-name-nondirectory filename
)))
1880 (find-file-noselect-1 buf filename nowarn
1881 rawfile truename number
))
1886 Do you want to discard your changes, and visit the file literally now? "
1888 Do you want to discard your changes, and visit the file normally now? ")))
1889 (find-file-noselect-1 buf filename nowarn
1890 rawfile truename number
)
1891 (error (if rawfile
"File already visited non-literally"
1892 "File already visited literally"))))
1896 "The file %s is already visited normally.
1897 You have asked to visit it literally,
1898 meaning no coding system decoding, format conversion, or local variables.
1899 But Emacs can only visit a file in one way at a time.
1901 Do you want to revisit the file literally now? "
1902 "The file %s is already visited literally,
1903 meaning no coding system decoding, format conversion, or local variables.
1904 You have asked to visit it normally,
1905 but Emacs can only visit a file in one way at a time.
1907 Do you want to revisit the file normally now? ")
1908 (file-name-nondirectory filename
)))
1909 (find-file-noselect-1 buf filename nowarn
1910 rawfile truename number
)
1911 (error (if rawfile
"File already visited non-literally"
1912 "File already visited literally"))))))
1913 ;; Return the buffer we are using.
1915 ;; Create a new buffer.
1916 (setq buf
(create-file-buffer filename
))
1917 ;; find-file-noselect-1 may use a different buffer.
1918 (find-file-noselect-1 buf filename nowarn
1919 rawfile truename number
))))))
1921 (defun find-file-noselect-1 (buf filename nowarn rawfile truename number
)
1923 (with-current-buffer buf
1924 (kill-local-variable 'find-file-literally
)
1925 ;; Needed in case we are re-visiting the file with a different
1926 ;; text representation.
1927 (kill-local-variable 'buffer-file-coding-system
)
1928 (kill-local-variable 'cursor-type
)
1929 (let ((inhibit-read-only t
))
1931 (and (default-value 'enable-multibyte-characters
)
1933 (set-buffer-multibyte t
))
1936 (let ((inhibit-read-only t
))
1937 (insert-file-contents-literally filename t
))
1939 (when (and (file-exists-p filename
)
1940 (not (file-readable-p filename
)))
1942 (signal 'file-error
(list "File is not readable"
1944 ;; Unconditionally set error
1947 (let ((inhibit-read-only t
))
1948 (insert-file-contents filename t
))
1950 (when (and (file-exists-p filename
)
1951 (not (file-readable-p filename
)))
1953 (signal 'file-error
(list "File is not readable"
1955 ;; Run find-file-not-found-functions until one returns non-nil.
1956 (or (run-hook-with-args-until-success 'find-file-not-found-functions
)
1957 ;; If they fail too, set error.
1959 ;; Record the file's truename, and maybe use that as visited name.
1960 (if (equal filename buffer-file-name
)
1961 (setq buffer-file-truename truename
)
1962 (setq buffer-file-truename
1963 (abbreviate-file-name (file-truename buffer-file-name
))))
1964 (setq buffer-file-number number
)
1965 (if find-file-visit-truename
1966 (setq buffer-file-name
(expand-file-name buffer-file-truename
)))
1967 ;; Set buffer's default directory to that of the file.
1968 (setq default-directory
(file-name-directory buffer-file-name
))
1969 ;; Turn off backup files for certain file names. Since
1970 ;; this is a permanent local, the major mode won't eliminate it.
1971 (and backup-enable-predicate
1972 (not (funcall backup-enable-predicate buffer-file-name
))
1974 (make-local-variable 'backup-inhibited
)
1975 (setq backup-inhibited t
)))
1978 (set-buffer-multibyte nil
)
1979 (setq buffer-file-coding-system
'no-conversion
)
1980 (set-buffer-major-mode buf
)
1981 (make-local-variable 'find-file-literally
)
1982 (setq find-file-literally t
))
1983 (after-find-file error
(not nowarn
)))
1986 (defun insert-file-contents-literally (filename &optional visit beg end replace
)
1987 "Like `insert-file-contents', but only reads in the file literally.
1988 A buffer may be modified in several ways after reading into the buffer,
1989 to Emacs features such as format decoding, character code
1990 conversion, `find-file-hook', automatic uncompression, etc.
1992 This function ensures that none of these modifications will take place."
1993 (let ((format-alist nil
)
1994 (after-insert-file-functions nil
)
1995 (coding-system-for-read 'no-conversion
)
1996 (coding-system-for-write 'no-conversion
)
1997 (inhibit-file-name-handlers
1998 ;; FIXME: Yuck!! We should turn insert-file-contents-literally
1999 ;; into a file operation instead!
2000 (append '(jka-compr-handler image-file-handler epa-file-handler
)
2001 inhibit-file-name-handlers
))
2002 (inhibit-file-name-operation 'insert-file-contents
))
2003 (insert-file-contents filename visit beg end replace
)))
2005 (defun insert-file-1 (filename insert-func
)
2006 (if (file-directory-p filename
)
2007 (signal 'file-error
(list "Opening input file" "file is a directory"
2009 ;; Check whether the file is uncommonly large
2010 (abort-if-file-too-large (nth 7 (file-attributes filename
)) "insert" filename
)
2011 (let* ((buffer (find-buffer-visiting (abbreviate-file-name (file-truename filename
))
2012 #'buffer-modified-p
))
2013 (tem (funcall insert-func filename
)))
2014 (push-mark (+ (point) (car (cdr tem
))))
2016 (message "File %s already visited and modified in buffer %s"
2017 filename
(buffer-name buffer
)))))
2019 (defun insert-file-literally (filename)
2020 "Insert contents of file FILENAME into buffer after point with no conversion.
2022 This function is meant for the user to run interactively.
2023 Don't call it from programs! Use `insert-file-contents-literally' instead.
2024 \(Its calling sequence is different; see its documentation)."
2025 (interactive "*fInsert file literally: ")
2026 (insert-file-1 filename
#'insert-file-contents-literally
))
2028 (defvar find-file-literally nil
2029 "Non-nil if this buffer was made by `find-file-literally' or equivalent.
2030 This has the `permanent-local' property, which takes effect if you
2031 make the variable buffer-local.")
2032 (put 'find-file-literally
'permanent-local t
)
2034 (defun find-file-literally (filename)
2035 "Visit file FILENAME with no conversion of any kind.
2036 Format conversion and character code conversion are both disabled,
2037 and multibyte characters are disabled in the resulting buffer.
2038 The major mode used is Fundamental mode regardless of the file name,
2039 and local variable specifications in the file are ignored.
2040 Automatic uncompression and adding a newline at the end of the
2041 file due to `require-final-newline' is also disabled.
2043 You cannot absolutely rely on this function to result in
2044 visiting the file literally. If Emacs already has a buffer
2045 which is visiting the file, you get the existing buffer,
2046 regardless of whether it was created literally or not.
2048 In a Lisp program, if you want to be sure of accessing a file's
2049 contents literally, you should create a temporary buffer and then read
2050 the file contents into it using `insert-file-contents-literally'."
2052 (list (read-file-name
2053 "Find file literally: " nil default-directory
2054 (confirm-nonexistent-file-or-buffer))))
2055 (switch-to-buffer (find-file-noselect filename nil t
)))
2057 (defun after-find-file (&optional error warn noauto
2058 _after-find-file-from-revert-buffer
2060 "Called after finding a file and by the default revert function.
2061 Sets buffer mode, parses local variables.
2062 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
2063 error in reading the file. WARN non-nil means warn if there
2064 exists an auto-save file more recent than the visited file.
2065 NOAUTO means don't mess with auto-save mode.
2066 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER is ignored
2067 \(see `revert-buffer-in-progress-p' for similar functionality).
2068 Fifth arg NOMODES non-nil means don't alter the file's modes.
2069 Finishes by calling the functions in `find-file-hook'
2070 unless NOMODES is non-nil."
2071 (setq buffer-read-only
(not (file-writable-p buffer-file-name
)))
2078 ((and error
(file-attributes buffer-file-name
))
2079 (setq buffer-read-only t
)
2080 (if (and (file-symlink-p buffer-file-name
)
2082 (file-chase-links buffer-file-name
))))
2083 "Symbolic link that points to nonexistent file"
2084 "File exists, but cannot be read"))
2085 ((not buffer-read-only
)
2087 ;; No need to warn if buffer is auto-saved
2088 ;; under the name of the visited file.
2089 (not (and buffer-file-name
2090 auto-save-visited-file-name
))
2091 (file-newer-than-file-p (or buffer-auto-save-file-name
2092 (make-auto-save-file-name))
2094 (format "%s has auto save data; consider M-x recover-this-file"
2095 (file-name-nondirectory buffer-file-name
))
2096 (setq not-serious t
)
2097 (if error
"(New file)" nil
)))
2099 (setq not-serious t
)
2100 "Note: file is write protected")
2101 ((file-attributes (directory-file-name default-directory
))
2102 "File not found and directory write-protected")
2103 ((file-exists-p (file-name-directory buffer-file-name
))
2104 (setq buffer-read-only nil
))
2106 (setq buffer-read-only nil
)
2107 "Use M-x make-directory RET RET to create the directory and its parents"))))
2110 (or not-serious
(sit-for 1 t
))))
2111 (when (and auto-save-default
(not noauto
))
2112 (auto-save-mode 1)))
2113 ;; Make people do a little extra work (C-x C-q)
2114 ;; before altering a backup file.
2115 (when (backup-file-name-p buffer-file-name
)
2116 (setq buffer-read-only t
))
2117 ;; When a file is marked read-only,
2118 ;; make the buffer read-only even if root is looking at it.
2119 (when (and (file-modes (buffer-file-name))
2120 (zerop (logand (file-modes (buffer-file-name)) #o222
)))
2121 (setq buffer-read-only t
))
2123 (when (and view-read-only view-mode
)
2126 ;; If requested, add a newline at the end of the file.
2127 (and (memq require-final-newline
'(visit visit-save
))
2128 (> (point-max) (point-min))
2129 (/= (char-after (1- (point-max))) ?
\n)
2130 (not (and (eq selective-display t
)
2131 (= (char-after (1- (point-max))) ?
\r)))
2132 (not buffer-read-only
)
2134 (goto-char (point-max))
2135 (ignore-errors (insert "\n"))))
2136 (when (and buffer-read-only
2138 (not (eq (get major-mode
'mode-class
) 'special
)))
2140 (run-hooks 'find-file-hook
)))
2142 (defmacro report-errors
(format &rest body
)
2143 "Eval BODY and turn any error into a FORMAT message.
2144 FORMAT can have a %s escape which will be replaced with the actual error.
2145 If `debug-on-error' is set, errors are not caught, so that you can
2147 Avoid using a large BODY since it is duplicated."
2148 (declare (debug t
) (indent 1))
2153 (error (message ,format
(prin1-to-string err
))))))
2155 (defun normal-mode (&optional find-file
)
2156 "Choose the major mode for this buffer automatically.
2157 Also sets up any specified local variables of the file.
2158 Uses the visited file name, the -*- line, and the local variables spec.
2160 This function is called automatically from `find-file'. In that case,
2161 we may set up the file-specified mode and local variables,
2162 depending on the value of `enable-local-variables'.
2163 In addition, if `local-enable-local-variables' is nil, we do
2164 not set local variables (though we do notice a mode specified with -*-.)
2166 `enable-local-variables' is ignored if you run `normal-mode' interactively,
2167 or from Lisp without specifying the optional argument FIND-FILE;
2168 in that case, this function acts as if `enable-local-variables' were t."
2170 (funcall (or (default-value 'major-mode
) 'fundamental-mode
))
2171 (let ((enable-local-variables (or (not find-file
) enable-local-variables
)))
2172 ;; FIXME this is less efficient than it could be, since both
2173 ;; s-a-m and h-l-v may parse the same regions, looking for "mode:".
2174 (report-errors "File mode specification error: %s"
2176 (report-errors "File local-variables error: %s"
2177 (hack-local-variables)))
2178 ;; Turn font lock off and on, to make sure it takes account of
2179 ;; whatever file local variables are relevant to it.
2180 (when (and font-lock-mode
2181 ;; Font-lock-mode (now in font-core.el) can be ON when
2182 ;; font-lock.el still hasn't been loaded.
2183 (boundp 'font-lock-keywords
)
2184 (eq (car font-lock-keywords
) t
))
2185 (setq font-lock-keywords
(cadr font-lock-keywords
))
2186 (font-lock-mode 1)))
2188 (defcustom auto-mode-case-fold t
2189 "Non-nil means to try second pass through `auto-mode-alist'.
2190 This means that if the first case-sensitive search through the alist fails
2191 to find a matching major mode, a second case-insensitive search is made.
2192 On systems with case-insensitive file names, this variable is ignored,
2193 since only a single case-insensitive search through the alist is made."
2198 (defvar auto-mode-alist
2199 ;; Note: The entries for the modes defined in cc-mode.el (c-mode,
2200 ;; c++-mode, java-mode and more) are added through autoload
2201 ;; directives in that file. That way is discouraged since it
2202 ;; spreads out the definition of the initial value.
2205 (cons (purecopy (car elt
)) (cdr elt
)))
2206 `(;; do this first, so that .html.pl is Polish html, not Perl
2207 ("\\.[sx]?html?\\(\\.[a-zA-Z_]+\\)?\\'" . html-mode
)
2208 ("\\.svgz?\\'" . image-mode
)
2209 ("\\.svgz?\\'" . xml-mode
)
2210 ("\\.x[bp]m\\'" . image-mode
)
2211 ("\\.x[bp]m\\'" . c-mode
)
2212 ("\\.p[bpgn]m\\'" . image-mode
)
2213 ("\\.tiff?\\'" . image-mode
)
2214 ("\\.gif\\'" . image-mode
)
2215 ("\\.png\\'" . image-mode
)
2216 ("\\.jpe?g\\'" . image-mode
)
2217 ("\\.te?xt\\'" . text-mode
)
2218 ("\\.[tT]e[xX]\\'" . tex-mode
)
2219 ("\\.ins\\'" . tex-mode
) ;Installation files for TeX packages.
2220 ("\\.ltx\\'" . latex-mode
)
2221 ("\\.dtx\\'" . doctex-mode
)
2222 ("\\.org\\'" . org-mode
)
2223 ("\\.el\\'" . emacs-lisp-mode
)
2224 ("Project\\.ede\\'" . emacs-lisp-mode
)
2225 ("\\.\\(scm\\|stk\\|ss\\|sch\\)\\'" . scheme-mode
)
2226 ("\\.l\\'" . lisp-mode
)
2227 ("\\.li?sp\\'" . lisp-mode
)
2228 ("\\.[fF]\\'" . fortran-mode
)
2229 ("\\.for\\'" . fortran-mode
)
2230 ("\\.p\\'" . pascal-mode
)
2231 ("\\.pas\\'" . pascal-mode
)
2232 ("\\.\\(dpr\\|DPR\\)\\'" . delphi-mode
)
2233 ("\\.ad[abs]\\'" . ada-mode
)
2234 ("\\.ad[bs].dg\\'" . ada-mode
)
2235 ("\\.\\([pP]\\([Llm]\\|erl\\|od\\)\\|al\\)\\'" . perl-mode
)
2236 ("Imakefile\\'" . makefile-imake-mode
)
2237 ("Makeppfile\\(?:\\.mk\\)?\\'" . makefile-makepp-mode
) ; Put this before .mk
2238 ("\\.makepp\\'" . makefile-makepp-mode
)
2239 ,@(if (memq system-type
'(berkeley-unix darwin
))
2240 '(("\\.mk\\'" . makefile-bsdmake-mode
)
2241 ("\\.make\\'" . makefile-bsdmake-mode
)
2242 ("GNUmakefile\\'" . makefile-gmake-mode
)
2243 ("[Mm]akefile\\'" . makefile-bsdmake-mode
))
2244 '(("\\.mk\\'" . makefile-gmake-mode
) ; Might be any make, give Gnu the host advantage
2245 ("\\.make\\'" . makefile-gmake-mode
)
2246 ("[Mm]akefile\\'" . makefile-gmake-mode
)))
2247 ("\\.am\\'" . makefile-automake-mode
)
2248 ;; Less common extensions come here
2249 ;; so more common ones above are found faster.
2250 ("\\.texinfo\\'" . texinfo-mode
)
2251 ("\\.te?xi\\'" . texinfo-mode
)
2252 ("\\.[sS]\\'" . asm-mode
)
2253 ("\\.asm\\'" . asm-mode
)
2254 ("\\.css\\'" . css-mode
)
2255 ("\\.mixal\\'" . mixal-mode
)
2256 ("\\.gcov\\'" . compilation-mode
)
2257 ;; Besides .gdbinit, gdb documents other names to be usable for init
2258 ;; files, cross-debuggers can use something like
2259 ;; .PROCESSORNAME-gdbinit so that the host and target gdbinit files
2260 ;; don't interfere with each other.
2261 ("/\\.[a-z0-9-]*gdbinit" . gdb-script-mode
)
2262 ("[cC]hange\\.?[lL]og?\\'" . change-log-mode
)
2263 ("[cC]hange[lL]og[-.][0-9]+\\'" . change-log-mode
)
2264 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode
)
2265 ("\\.scm\\.[0-9]*\\'" . scheme-mode
)
2266 ("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode
)
2267 ("\\.bash\\'" . sh-mode
)
2268 ("\\(/\\|\\`\\)\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode
)
2269 ("\\(/\\|\\`\\)\\.\\(bash_logout\\|shrc\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode
)
2270 ("\\(/\\|\\`\\)\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode
)
2271 ("\\.m?spec\\'" . sh-mode
)
2272 ("\\.m[mes]\\'" . nroff-mode
)
2273 ("\\.man\\'" . nroff-mode
)
2274 ("\\.sty\\'" . latex-mode
)
2275 ("\\.cl[so]\\'" . latex-mode
) ;LaTeX 2e class option
2276 ("\\.bbl\\'" . latex-mode
)
2277 ("\\.bib\\'" . bibtex-mode
)
2278 ("\\.bst\\'" . bibtex-style-mode
)
2279 ("\\.sql\\'" . sql-mode
)
2280 ("\\.m[4c]\\'" . m4-mode
)
2281 ("\\.mf\\'" . metafont-mode
)
2282 ("\\.mp\\'" . metapost-mode
)
2283 ("\\.vhdl?\\'" . vhdl-mode
)
2284 ("\\.article\\'" . text-mode
)
2285 ("\\.letter\\'" . text-mode
)
2286 ("\\.i?tcl\\'" . tcl-mode
)
2287 ("\\.exp\\'" . tcl-mode
)
2288 ("\\.itk\\'" . tcl-mode
)
2289 ("\\.icn\\'" . icon-mode
)
2290 ("\\.sim\\'" . simula-mode
)
2291 ("\\.mss\\'" . scribe-mode
)
2292 ;; The Fortran standard does not say anything about file extensions.
2293 ;; .f90 was widely used for F90, now we seem to be trapped into
2294 ;; using a different extension for each language revision.
2295 ;; Anyway, the following extensions are supported by gfortran.
2296 ("\\.f9[05]\\'" . f90-mode
)
2297 ("\\.f0[38]\\'" . f90-mode
)
2298 ("\\.indent\\.pro\\'" . fundamental-mode
) ; to avoid idlwave-mode
2299 ("\\.\\(pro\\|PRO\\)\\'" . idlwave-mode
)
2300 ("\\.srt\\'" . srecode-template-mode
)
2301 ("\\.prolog\\'" . prolog-mode
)
2302 ("\\.tar\\'" . tar-mode
)
2303 ;; The list of archive file extensions should be in sync with
2304 ;; `auto-coding-alist' with `no-conversion' coding system.
2306 arc\\|zip\\|lzh\\|lha\\|zoo\\|[jew]ar\\|xpi\\|rar\\|7z\\|\
2307 ARC\\|ZIP\\|LZH\\|LHA\\|ZOO\\|[JEW]AR\\|XPI\\|RAR\\|7Z\\)\\'" . archive-mode
)
2308 ("\\.\\(sx[dmicw]\\|od[fgpst]\\|oxt\\)\\'" . archive-mode
) ;OpenOffice.org
2309 ("\\.\\(deb\\|[oi]pk\\)\\'" . archive-mode
) ; Debian/Opkg packages.
2310 ;; Mailer puts message to be edited in
2311 ;; /tmp/Re.... or Message
2312 ("\\`/tmp/Re" . text-mode
)
2313 ("/Message[0-9]*\\'" . text-mode
)
2314 ;; some news reader is reported to use this
2315 ("\\`/tmp/fol/" . text-mode
)
2316 ("\\.oak\\'" . scheme-mode
)
2317 ("\\.sgml?\\'" . sgml-mode
)
2318 ("\\.x[ms]l\\'" . xml-mode
)
2319 ("\\.dbk\\'" . xml-mode
)
2320 ("\\.dtd\\'" . sgml-mode
)
2321 ("\\.ds\\(ss\\)?l\\'" . dsssl-mode
)
2322 ("\\.js\\'" . javascript-mode
)
2323 ("\\.json\\'" . javascript-mode
)
2324 ("\\.[ds]?vh?\\'" . verilog-mode
)
2325 ("\\.by\\'" . bovine-grammar-mode
)
2326 ("\\.wy\\'" . wisent-grammar-mode
)
2327 ;; .emacs or .gnus or .viper following a directory delimiter in
2328 ;; Unix, MSDOG or VMS syntax.
2329 ("[]>:/\\]\\..*\\(emacs\\|gnus\\|viper\\)\\'" . emacs-lisp-mode
)
2330 ("\\`\\..*emacs\\'" . emacs-lisp-mode
)
2331 ;; _emacs following a directory delimiter
2333 ("[:/]_emacs\\'" . emacs-lisp-mode
)
2334 ("/crontab\\.X*[0-9]+\\'" . shell-script-mode
)
2335 ("\\.ml\\'" . lisp-mode
)
2336 ;; Linux-2.6.9 uses some different suffix for linker scripts:
2337 ;; "ld", "lds", "lds.S", "lds.in", "ld.script", and "ld.script.balo".
2338 ;; eCos uses "ld" and "ldi". Netbsd uses "ldscript.*".
2339 ("\\.ld[si]?\\'" . ld-script-mode
)
2340 ("ld\\.?script\\'" . ld-script-mode
)
2341 ;; .xs is also used for ld scripts, but seems to be more commonly
2342 ;; associated with Perl .xs files (C with Perl bindings). (Bug#7071)
2343 ("\\.xs\\'" . c-mode
)
2344 ;; Explained in binutils ld/genscripts.sh. Eg:
2345 ;; A .x script file is the default script.
2346 ;; A .xr script is for linking without relocation (-r flag). Etc.
2347 ("\\.x[abdsru]?[cnw]?\\'" . ld-script-mode
)
2348 ("\\.zone\\'" . dns-mode
)
2349 ("\\.soa\\'" . dns-mode
)
2350 ;; Common Lisp ASDF package system.
2351 ("\\.asd\\'" . lisp-mode
)
2352 ("\\.\\(asn\\|mib\\|smi\\)\\'" . snmp-mode
)
2353 ("\\.\\(as\\|mi\\|sm\\)2\\'" . snmpv2-mode
)
2354 ("\\.\\(diffs?\\|patch\\|rej\\)\\'" . diff-mode
)
2355 ("\\.\\(dif\\|pat\\)\\'" . diff-mode
) ; for MSDOG
2356 ("\\.[eE]?[pP][sS]\\'" . ps-mode
)
2357 ("\\.\\(?:PDF\\|DVI\\|OD[FGPST]\\|DOCX?\\|XLSX?\\|PPTX?\\|pdf\\|djvu\\|dvi\\|od[fgpst]\\|docx?\\|xlsx?\\|pptx?\\)\\'" . doc-view-mode-maybe
)
2358 ("configure\\.\\(ac\\|in\\)\\'" . autoconf-mode
)
2359 ("\\.s\\(v\\|iv\\|ieve\\)\\'" . sieve-mode
)
2360 ("BROWSE\\'" . ebrowse-tree-mode
)
2361 ("\\.ebrowse\\'" . ebrowse-tree-mode
)
2362 ("#\\*mail\\*" . mail-mode
)
2363 ("\\.g\\'" . antlr-mode
)
2364 ("\\.mod\\'" . m2-mode
)
2365 ("\\.ses\\'" . ses-mode
)
2366 ("\\.docbook\\'" . sgml-mode
)
2367 ("\\.com\\'" . dcl-mode
)
2368 ("/config\\.\\(?:bat\\|log\\)\\'" . fundamental-mode
)
2369 ;; Windows candidates may be opened case sensitively on Unix
2370 ("\\.\\(?:[iI][nN][iI]\\|[lL][sS][tT]\\|[rR][eE][gG]\\|[sS][yY][sS]\\)\\'" . conf-mode
)
2371 ("\\.\\(?:desktop\\|la\\)\\'" . conf-unix-mode
)
2372 ("\\.ppd\\'" . conf-ppd-mode
)
2373 ("java.+\\.conf\\'" . conf-javaprop-mode
)
2374 ("\\.properties\\(?:\\.[a-zA-Z0-9._-]+\\)?\\'" . conf-javaprop-mode
)
2375 ("\\`/etc/\\(?:DIR_COLORS\\|ethers\\|.?fstab\\|.*hosts\\|lesskey\\|login\\.?de\\(?:fs\\|vperm\\)\\|magic\\|mtab\\|pam\\.d/.*\\|permissions\\(?:\\.d/.+\\)?\\|protocols\\|rpc\\|services\\)\\'" . conf-space-mode
)
2376 ("\\`/etc/\\(?:acpid?/.+\\|aliases\\(?:\\.d/.+\\)?\\|default/.+\\|group-?\\|hosts\\..+\\|inittab\\|ksysguarddrc\\|opera6rc\\|passwd-?\\|shadow-?\\|sysconfig/.+\\)\\'" . conf-mode
)
2377 ;; ChangeLog.old etc. Other change-log-mode entries are above;
2378 ;; this has lower priority to avoid matching changelog.sgml etc.
2379 ("[cC]hange[lL]og[-.][-0-9a-z]+\\'" . change-log-mode
)
2380 ;; either user's dot-files or under /etc or some such
2381 ("/\\.?\\(?:gnokiirc\\|kde.*rc\\|mime\\.types\\|wgetrc\\)\\'" . conf-mode
)
2382 ;; alas not all ~/.*rc files are like this
2383 ("/\\.\\(?:enigma\\|gltron\\|gtk\\|hxplayer\\|net\\|neverball\\|qt/.+\\|realplayer\\|scummvm\\|sversion\\|sylpheed/.+\\|xmp\\)rc\\'" . conf-mode
)
2384 ("/\\.\\(?:gdbtkinit\\|grip\\|orbital/.+txt\\|rhosts\\|tuxracer/options\\)\\'" . conf-mode
)
2385 ("/\\.?X\\(?:default\\|resource\\|re\\)s\\>" . conf-xdefaults-mode
)
2386 ("/X11.+app-defaults/" . conf-xdefaults-mode
)
2387 ("/X11.+locale/.+/Compose\\'" . conf-colon-mode
)
2388 ;; this contains everything twice, with space and with colon :-(
2389 ("/X11.+locale/compose\\.dir\\'" . conf-javaprop-mode
)
2390 ;; Get rid of any trailing .n.m and try again.
2391 ;; This is for files saved by cvs-merge that look like .#<file>.<rev>
2392 ;; or .#<file>.<rev>-<rev> or VC's <file>.~<rev>~.
2393 ;; Using mode nil rather than `ignore' would let the search continue
2394 ;; through this list (with the shortened name) rather than start over.
2395 ("\\.~?[0-9]+\\.[0-9][-.0-9]*~?\\'" nil t
)
2396 ("\\.\\(?:orig\\|in\\|[bB][aA][kK]\\)\\'" nil t
)
2397 ;; This should come after "in" stripping (e.g. config.h.in).
2398 ;; *.cf, *.cfg, *.conf, *.config[.local|.de_DE.UTF8|...], */config
2399 ("[/.]c\\(?:on\\)?f\\(?:i?g\\)?\\(?:\\.[a-zA-Z0-9._-]+\\)?\\'" . conf-mode-maybe
)
2400 ;; The following should come after the ChangeLog pattern
2401 ;; for the sake of ChangeLog.1, etc.
2402 ;; and after the .scm.[0-9] and CVS' <file>.<rev> patterns too.
2403 ("\\.[1-9]\\'" . nroff-mode
)))
2404 "Alist of filename patterns vs corresponding major mode functions.
2405 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
2406 \(NON-NIL stands for anything that is not nil; the value does not matter.)
2407 Visiting a file whose name matches REGEXP specifies FUNCTION as the
2408 mode function to use. FUNCTION will be called, unless it is nil.
2410 If the element has the form (REGEXP FUNCTION NON-NIL), then after
2411 calling FUNCTION (if it's not nil), we delete the suffix that matched
2412 REGEXP and search the list again for another match.
2414 The extensions whose FUNCTION is `archive-mode' should also
2415 appear in `auto-coding-alist' with `no-conversion' coding system.
2417 See also `interpreter-mode-alist', which detects executable script modes
2418 based on the interpreters they specify to run,
2419 and `magic-mode-alist', which determines modes based on file contents.")
2420 (put 'auto-mode-alist
'risky-local-variable t
)
2422 (defun conf-mode-maybe ()
2423 "Select Conf mode or XML mode according to start of file."
2427 (goto-char (point-min))
2428 (looking-at "<\\?xml \\|<!-- \\|<!DOCTYPE ")))
2432 (defvar interpreter-mode-alist
2433 ;; Note: The entries for the modes defined in cc-mode.el (awk-mode
2434 ;; and pike-mode) are added through autoload directives in that
2435 ;; file. That way is discouraged since it spreads out the
2436 ;; definition of the initial value.
2439 (cons (purecopy (car l
)) (cdr l
)))
2440 '(("perl" . perl-mode
)
2441 ("perl5" . perl-mode
)
2442 ("miniperl" . perl-mode
)
2444 ("wishx" . tcl-mode
)
2446 ("tclsh" . tcl-mode
)
2447 ("scm" . scheme-mode
)
2468 ("tail" . text-mode
)
2469 ("more" . text-mode
)
2470 ("less" . text-mode
)
2472 ("make" . makefile-gmake-mode
) ; Debian uses this
2473 ("guile" . scheme-mode
)
2474 ("clisp" . lisp-mode
)
2475 ("emacs" . emacs-lisp-mode
)))
2476 "Alist mapping interpreter names to major modes.
2477 This is used for files whose first lines match `auto-mode-interpreter-regexp'.
2478 Each element looks like (INTERPRETER . MODE).
2479 If INTERPRETER matches the name of the interpreter specified in the first line
2480 of a script, mode MODE is enabled.
2482 See also `auto-mode-alist'.")
2484 (define-obsolete-variable-alias 'inhibit-first-line-modes-regexps
2485 'inhibit-file-local-variables-regexps
"24.1")
2487 ;; TODO really this should be a list of modes (eg tar-mode), not regexps,
2488 ;; because we are duplicating info from auto-mode-alist.
2489 ;; TODO many elements of this list are also in auto-coding-alist.
2490 (defvar inhibit-local-variables-regexps
2491 (mapcar 'purecopy
'("\\.tar\\'" "\\.t[bg]z\\'"
2492 "\\.arc\\'" "\\.zip\\'" "\\.lzh\\'" "\\.lha\\'"
2493 "\\.zoo\\'" "\\.[jew]ar\\'" "\\.xpi\\'" "\\.rar\\'"
2495 "\\.sx[dmicw]\\'" "\\.odt\\'"
2496 "\\.tiff?\\'" "\\.gif\\'" "\\.png\\'" "\\.jpe?g\\'"))
2497 "List of regexps matching file names in which to ignore local variables.
2498 This includes `-*-' lines as well as trailing \"Local Variables\" sections.
2499 Files matching this list are typically binary file formats.
2500 They may happen to contain sequences that look like local variable
2501 specifications, but are not really, or they may be containers for
2502 member files with their own local variable sections, which are
2503 not appropriate for the containing file.
2504 The function `inhibit-local-variables-p' uses this.")
2506 (define-obsolete-variable-alias 'inhibit-first-line-modes-suffixes
2507 'inhibit-local-variables-suffixes
"24.1")
2509 (defvar inhibit-local-variables-suffixes nil
2510 "List of regexps matching suffixes to remove from file names.
2511 The function `inhibit-local-variables-p' uses this: when checking
2512 a file name, it first discards from the end of the name anything that
2513 matches one of these regexps.")
2515 ;; Can't think of any situation in which you'd want this to be nil...
2516 (defvar inhibit-local-variables-ignore-case t
2517 "Non-nil means `inhibit-local-variables-p' ignores case.")
2519 (defun inhibit-local-variables-p ()
2520 "Return non-nil if file local variables should be ignored.
2521 This checks the file (or buffer) name against `inhibit-local-variables-regexps'
2522 and `inhibit-local-variables-suffixes'. If
2523 `inhibit-local-variables-ignore-case' is non-nil, this ignores case."
2524 (let ((temp inhibit-local-variables-regexps
)
2525 (name (if buffer-file-name
2526 (file-name-sans-versions buffer-file-name
)
2528 (case-fold-search inhibit-local-variables-ignore-case
))
2529 (while (let ((sufs inhibit-local-variables-suffixes
))
2530 (while (and sufs
(not (string-match (car sufs
) name
)))
2531 (setq sufs
(cdr sufs
)))
2533 (setq name
(substring name
0 (match-beginning 0))))
2535 (not (string-match (car temp
) name
)))
2536 (setq temp
(cdr temp
)))
2539 (defvar auto-mode-interpreter-regexp
2540 (purecopy "#![ \t]?\\([^ \t\n]*\
2541 /bin/env[ \t]\\)?\\([^ \t\n]+\\)")
2542 "Regexp matching interpreters, for file mode determination.
2543 This regular expression is matched against the first line of a file
2544 to determine the file's mode in `set-auto-mode'. If it matches, the file
2545 is assumed to be interpreted by the interpreter matched by the second group
2546 of the regular expression. The mode is then determined as the mode
2547 associated with that interpreter in `interpreter-mode-alist'.")
2549 (defvar magic-mode-alist nil
2550 "Alist of buffer beginnings vs. corresponding major mode functions.
2551 Each element looks like (REGEXP . FUNCTION) or (MATCH-FUNCTION . FUNCTION).
2552 After visiting a file, if REGEXP matches the text at the beginning of the
2553 buffer, or calling MATCH-FUNCTION returns non-nil, `normal-mode' will
2554 call FUNCTION rather than allowing `auto-mode-alist' to decide the buffer's
2557 If FUNCTION is nil, then it is not called. (That is a way of saying
2558 \"allow `auto-mode-alist' to decide for these files.\")")
2559 (put 'magic-mode-alist
'risky-local-variable t
)
2561 (defvar magic-fallback-mode-alist
2563 `((image-type-auto-detected-p . image-mode
)
2564 ("\\(PK00\\)?[P]K\003\004" . archive-mode
) ; zip
2565 ;; The < comes before the groups (but the first) to reduce backtracking.
2566 ;; TODO: UTF-16 <?xml may be preceded by a BOM 0xff 0xfe or 0xfe 0xff.
2567 ;; We use [ \t\r\n] instead of `\\s ' to make regex overflow less likely.
2568 (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
2569 (comment-re (concat "\\(?:!--" incomment-re
"*-->[ \t\r\n]*<\\)")))
2570 (concat "\\(?:<\\?xml[ \t\r\n]+[^>]*>\\)?[ \t\r\n]*<"
2572 "\\(?:!DOCTYPE[ \t\r\n]+[^>]*>[ \t\r\n]*<[ \t\r\n]*" comment-re
"*\\)?"
2573 "[Hh][Tt][Mm][Ll]"))
2575 ("<!DOCTYPE[ \t\r\n]+[Hh][Tt][Mm][Ll]" . html-mode
)
2576 ;; These two must come after html, because they are more general:
2577 ("<\\?xml " . xml-mode
)
2578 (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
2579 (comment-re (concat "\\(?:!--" incomment-re
"*-->[ \t\r\n]*<\\)")))
2580 (concat "[ \t\r\n]*<" comment-re
"*!DOCTYPE "))
2583 ("# xmcd " . conf-unix-mode
)))
2584 "Like `magic-mode-alist' but has lower priority than `auto-mode-alist'.
2585 Each element looks like (REGEXP . FUNCTION) or (MATCH-FUNCTION . FUNCTION).
2586 After visiting a file, if REGEXP matches the text at the beginning of the
2587 buffer, or calling MATCH-FUNCTION returns non-nil, `normal-mode' will
2588 call FUNCTION, provided that `magic-mode-alist' and `auto-mode-alist'
2589 have not specified a mode for this file.
2591 If FUNCTION is nil, then it is not called.")
2592 (put 'magic-fallback-mode-alist
'risky-local-variable t
)
2594 (defvar magic-mode-regexp-match-limit
4000
2595 "Upper limit on `magic-mode-alist' regexp matches.
2596 Also applies to `magic-fallback-mode-alist'.")
2598 (defun set-auto-mode (&optional keep-mode-if-same
)
2599 "Select major mode appropriate for current buffer.
2601 To find the right major mode, this function checks for a -*- mode tag
2602 checks for a `mode:' entry in the Local Variables section of the file,
2603 checks if it uses an interpreter listed in `interpreter-mode-alist',
2604 matches the buffer beginning against `magic-mode-alist',
2605 compares the filename against the entries in `auto-mode-alist',
2606 then matches the buffer beginning against `magic-fallback-mode-alist'.
2608 If `enable-local-variables' is nil, or if the file name matches
2609 `inhibit-local-variables-regexps', this function does not check
2610 for any mode: tag anywhere in the file. If `local-enable-local-variables'
2611 is nil, then the only mode: tag that can be relevant is a -*- one.
2613 If the optional argument KEEP-MODE-IF-SAME is non-nil, then we
2614 set the major mode only if that would change it. In other words
2615 we don't actually set it to the same mode the buffer already has."
2616 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
2617 (let ((try-locals (not (inhibit-local-variables-p)))
2618 end done mode modes
)
2619 ;; Once we drop the deprecated feature where mode: is also allowed to
2620 ;; specify minor-modes (ie, there can be more than one "mode:"), we can
2621 ;; remove this section and just let (hack-local-variables t) handle it.
2622 ;; Find a -*- mode tag.
2624 (goto-char (point-min))
2625 (skip-chars-forward " \t\n")
2626 ;; Note by design local-enable-local-variables does not matter here.
2627 (and enable-local-variables
2629 (setq end
(set-auto-mode-1))
2630 (if (save-excursion (search-forward ":" end t
))
2631 ;; Find all specifications for the `mode:' variable
2632 ;; and execute them left to right.
2633 (while (let ((case-fold-search t
))
2634 (or (and (looking-at "mode:")
2635 (goto-char (match-end 0)))
2636 (re-search-forward "[ \t;]mode:" end t
)))
2637 (skip-chars-forward " \t")
2638 (let ((beg (point)))
2639 (if (search-forward ";" end t
)
2642 (skip-chars-backward " \t")
2643 (push (intern (concat (downcase (buffer-substring beg
(point))) "-mode"))
2645 ;; Simple -*-MODE-*- case.
2646 (push (intern (concat (downcase (buffer-substring (point) end
))
2649 ;; If we found modes to use, invoke them now, outside the save-excursion.
2652 (dolist (mode (nreverse modes
))
2653 (if (not (functionp mode
))
2654 (message "Ignoring unknown mode `%s'" mode
)
2656 (or (set-auto-mode-0 mode keep-mode-if-same
)
2657 ;; continuing would call minor modes again, toggling them off
2658 (throw 'nop nil
))))))
2659 ;; hack-local-variables checks local-enable-local-variables etc, but
2660 ;; we might as well be explicit here for the sake of clarity.
2662 enable-local-variables
2663 local-enable-local-variables
2665 (setq mode
(hack-local-variables t
))
2666 (not (memq mode modes
)) ; already tried and failed
2667 (if (not (functionp mode
))
2668 (message "Ignoring unknown mode `%s'" mode
)
2670 (set-auto-mode-0 mode keep-mode-if-same
)))
2671 ;; If we didn't, look for an interpreter specified in the first line.
2672 ;; As a special case, allow for things like "#!/bin/env perl", which
2673 ;; finds the interpreter anywhere in $PATH.
2675 (setq mode
(save-excursion
2676 (goto-char (point-min))
2677 (if (looking-at auto-mode-interpreter-regexp
)
2680 ;; Map interpreter name to a mode, signaling we're done at the
2682 done
(assoc (file-name-nondirectory mode
)
2683 interpreter-mode-alist
))
2684 ;; If we found an interpreter mode to use, invoke it now.
2686 (set-auto-mode-0 (cdr done
) keep-mode-if-same
)))
2687 ;; Next try matching the buffer beginning against magic-mode-alist.
2689 (if (setq done
(save-excursion
2690 (goto-char (point-min))
2692 (narrow-to-region (point-min)
2694 (+ (point-min) magic-mode-regexp-match-limit
)))
2695 (assoc-default nil magic-mode-alist
2699 (looking-at re
)))))))
2700 (set-auto-mode-0 done keep-mode-if-same
)))
2701 ;; Next compare the filename against the entries in auto-mode-alist.
2703 (if buffer-file-name
2704 (let ((name buffer-file-name
)
2705 (remote-id (file-remote-p buffer-file-name
)))
2706 ;; Remove backup-suffixes from file name.
2707 (setq name
(file-name-sans-versions name
))
2708 ;; Remove remote file name identification.
2709 (when (and (stringp remote-id
)
2710 (string-match (regexp-quote remote-id
) name
))
2711 (setq name
(substring name
(match-end 0))))
2713 ;; Find first matching alist entry.
2715 (if (memq system-type
'(windows-nt cygwin
))
2716 ;; System is case-insensitive.
2717 (let ((case-fold-search t
))
2718 (assoc-default name auto-mode-alist
2720 ;; System is case-sensitive.
2722 ;; First match case-sensitively.
2723 (let ((case-fold-search nil
))
2724 (assoc-default name auto-mode-alist
2726 ;; Fallback to case-insensitive match.
2727 (and auto-mode-case-fold
2728 (let ((case-fold-search t
))
2729 (assoc-default name auto-mode-alist
2734 (setq mode
(car mode
)
2735 name
(substring name
0 (match-beginning 0)))
2738 (set-auto-mode-0 mode keep-mode-if-same
)
2740 ;; Next try matching the buffer beginning against magic-fallback-mode-alist.
2742 (if (setq done
(save-excursion
2743 (goto-char (point-min))
2745 (narrow-to-region (point-min)
2747 (+ (point-min) magic-mode-regexp-match-limit
)))
2748 (assoc-default nil magic-fallback-mode-alist
2752 (looking-at re
)))))))
2753 (set-auto-mode-0 done keep-mode-if-same
)))))
2755 ;; When `keep-mode-if-same' is set, we are working on behalf of
2756 ;; set-visited-file-name. In that case, if the major mode specified is the
2757 ;; same one we already have, don't actually reset it. We don't want to lose
2758 ;; minor modes such as Font Lock.
2759 (defun set-auto-mode-0 (mode &optional keep-mode-if-same
)
2760 "Apply MODE and return it.
2761 If optional arg KEEP-MODE-IF-SAME is non-nil, MODE is chased of
2762 any aliases and compared to current major mode. If they are the
2763 same, do nothing and return nil."
2764 (unless (and keep-mode-if-same
2765 (eq (indirect-function mode
)
2766 (indirect-function major-mode
)))
2771 (defvar file-auto-mode-skip
"^\\(#!\\|'\\\\\"\\)"
2772 "Regexp of lines to skip when looking for file-local settings.
2773 If the first line matches this regular expression, then the -*-...-*- file-
2774 local settings will be consulted on the second line instead of the first.")
2776 (defun set-auto-mode-1 ()
2777 "Find the -*- spec in the buffer.
2778 Call with point at the place to start searching from.
2779 If one is found, set point to the beginning and return the position
2780 of the end. Otherwise, return nil; may change point.
2781 The variable `inhibit-local-variables-regexps' can cause a -*- spec to
2782 be ignored; but `enable-local-variables' and `local-enable-local-variables'
2786 ;; Don't look for -*- if this file name matches any
2787 ;; of the regexps in inhibit-local-variables-regexps.
2788 (not (inhibit-local-variables-p))
2789 (search-forward "-*-" (line-end-position
2790 ;; If the file begins with "#!" (exec
2791 ;; interpreter magic), look for mode frobs
2792 ;; in the first two lines. You cannot
2793 ;; necessarily put them in the first line
2794 ;; of such a file without screwing up the
2795 ;; interpreter invocation. The same holds
2796 ;; for '\" in man pages (preprocessor
2797 ;; magic for the `man' program).
2798 (and (looking-at file-auto-mode-skip
) 2)) t
)
2800 (skip-chars-forward " \t")
2802 (search-forward "-*-" (line-end-position) t
))
2805 (skip-chars-backward " \t")
2810 ;;; Handling file local variables
2812 (defvar ignored-local-variables
2813 '(ignored-local-variables safe-local-variable-values
2814 file-local-variables-alist dir-local-variables-alist
)
2815 "Variables to be ignored in a file's local variable spec.")
2816 (put 'ignored-local-variables
'risky-local-variable t
)
2818 (defvar hack-local-variables-hook nil
2819 "Normal hook run after processing a file's local variables specs.
2820 Major modes can use this to examine user-specified local variables
2821 in order to initialize other data structure based on them.")
2823 (defcustom safe-local-variable-values nil
2824 "List variable-value pairs that are considered safe.
2825 Each element is a cons cell (VAR . VAL), where VAR is a variable
2826 symbol and VAL is a value that is considered safe."
2831 (defcustom safe-local-eval-forms
2832 ;; This should be here at least as long as Emacs supports write-file-hooks.
2833 '((add-hook 'write-file-hooks
'time-stamp
)
2834 (add-hook 'write-file-functions
'time-stamp
)
2835 (add-hook 'before-save-hook
'time-stamp nil t
)
2836 (add-hook 'before-save-hook
'delete-trailing-whitespace nil t
))
2837 "Expressions that are considered safe in an `eval:' local variable.
2838 Add expressions to this list if you want Emacs to evaluate them, when
2839 they appear in an `eval' local variable specification, without first
2840 asking you for confirmation."
2843 :version
"24.1" ; added write-file-hooks
2844 :type
'(repeat sexp
))
2846 ;; Risky local variables:
2847 (mapc (lambda (var) (put var
'risky-local-variable t
))
2849 buffer-auto-save-file-name
2851 buffer-file-truename
2854 default-text-properties
2858 file-name-handler-alist
2867 minor-mode-map-alist
2868 minor-mode-overriding-map-alist
2871 overriding-local-map
2872 overriding-terminal-local-map
2876 unread-command-events
))
2878 ;; Safe local variables:
2880 ;; For variables defined by major modes, the safety declarations can go into
2881 ;; the major mode's file, since that will be loaded before file variables are
2884 ;; For variables defined by minor modes, put the safety declarations in the
2885 ;; file defining the minor mode after the defcustom/defvar using an autoload
2888 ;; ;;;###autoload(put 'variable 'safe-local-variable 'stringp)
2890 ;; Otherwise, when Emacs visits a file specifying that local variable, the
2891 ;; minor mode file may not be loaded yet.
2893 ;; For variables defined in the C source code the declaration should go here:
2896 '((buffer-read-only . booleanp
) ;; C source code
2897 (default-directory . stringp
) ;; C source code
2898 (fill-column . integerp
) ;; C source code
2899 (indent-tabs-mode . booleanp
) ;; C source code
2900 (left-margin . integerp
) ;; C source code
2901 (no-update-autoloads . booleanp
)
2902 (lexical-binding . booleanp
) ;; C source code
2903 (tab-width . integerp
) ;; C source code
2904 (truncate-lines . booleanp
) ;; C source code
2905 (word-wrap . booleanp
) ;; C source code
2906 (bidi-display-reordering . booleanp
))) ;; C source code
2907 (put (car pair
) 'safe-local-variable
(cdr pair
)))
2909 (put 'bidi-paragraph-direction
'safe-local-variable
2910 (lambda (v) (memq v
'(nil right-to-left left-to-right
))))
2912 (put 'c-set-style
'safe-local-eval-function t
)
2914 (defvar file-local-variables-alist nil
2915 "Alist of file-local variable settings in the current buffer.
2916 Each element in this list has the form (VAR . VALUE), where VAR
2917 is a file-local variable (a symbol) and VALUE is the value
2918 specified. The actual value in the buffer may differ from VALUE,
2919 if it is changed by the major or minor modes, or by the user.")
2920 (make-variable-buffer-local 'file-local-variables-alist
)
2921 (put 'file-local-variables-alist
'permanent-local t
)
2923 (defvar dir-local-variables-alist nil
2924 "Alist of directory-local variable settings in the current buffer.
2925 Each element in this list has the form (VAR . VALUE), where VAR
2926 is a directory-local variable (a symbol) and VALUE is the value
2927 specified in .dir-locals.el. The actual value in the buffer
2928 may differ from VALUE, if it is changed by the major or minor modes,
2930 (make-variable-buffer-local 'dir-local-variables-alist
)
2932 (defvar before-hack-local-variables-hook nil
2933 "Normal hook run before setting file-local variables.
2934 It is called after checking for unsafe/risky variables and
2935 setting `file-local-variables-alist', and before applying the
2936 variables stored in `file-local-variables-alist'. A hook
2937 function is allowed to change the contents of this alist.
2939 This hook is called only if there is at least one file-local
2942 (defun hack-local-variables-confirm (all-vars unsafe-vars risky-vars dir-name
)
2943 "Get confirmation before setting up local variable values.
2944 ALL-VARS is the list of all variables to be set up.
2945 UNSAFE-VARS is the list of those that aren't marked as safe or risky.
2946 RISKY-VARS is the list of those that are marked as risky.
2947 If these settings come from directory-local variables, then
2948 DIR-NAME is the name of the associated directory. Otherwise it is nil."
2949 (unless noninteractive
2950 (let ((name (cond (dir-name)
2952 (file-name-nondirectory buffer-file-name
))
2953 ((concat "buffer " (buffer-name)))))
2954 (offer-save (and (eq enable-local-variables t
)
2956 (buf (get-buffer-create "*Local Variables*")))
2957 ;; Set up the contents of the *Local Variables* buffer.
2958 (with-current-buffer buf
2962 (insert "The local variables list in " name
2963 "\ncontains values that may not be safe (*)"
2965 ", and variables that are risky (**)."
2968 (insert "The local variables list in " name
2969 "\ncontains variables that are risky (**)."))
2971 (insert "A local variables list is specified in " name
".")))
2972 (insert "\n\nDo you want to apply it? You can type
2973 y -- to apply the local variables list.
2974 n -- to ignore the local variables list.")
2977 ! -- to apply the local variables list, and permanently mark these
2978 values (*) as safe (in the future, they will be set automatically.)\n\n")
2980 (dolist (elt all-vars
)
2981 (cond ((member elt unsafe-vars
)
2983 ((member elt risky-vars
)
2987 (princ (car elt
) buf
)
2989 ;; Make strings with embedded whitespace easier to read.
2990 (let ((print-escape-newlines t
))
2991 (prin1 (cdr elt
) buf
))
2993 (set (make-local-variable 'cursor-type
) nil
)
2994 (set-buffer-modified-p nil
)
2995 (goto-char (point-min)))
2997 ;; Display the buffer and read a choice.
2998 (save-window-excursion
3000 (let* ((exit-chars '(?y ?n ?\s ?\C-g ?\C-v
))
3001 (prompt (format "Please type %s%s: "
3002 (if offer-save
"y, n, or !" "y or n")
3003 (if (< (line-number-at-pos (point-max))
3004 (window-body-height))
3006 (push ?\C-v exit-chars
)
3007 ", or C-v to scroll")))
3009 (if offer-save
(push ?
! exit-chars
))
3011 (setq char
(read-char-choice prompt exit-chars t
))
3012 (when (eq char ?\C-v
)
3015 (error (goto-char (point-min))
3018 (when (and offer-save
(= char ?
!) unsafe-vars
)
3019 (customize-push-and-save 'safe-local-variable-values unsafe-vars
))
3020 (prog1 (memq char
'(?
! ?\s ?y
))
3021 (quit-window t
)))))))
3023 (defun hack-local-variables-prop-line (&optional mode-only
)
3024 "Return local variables specified in the -*- line.
3025 Returns an alist of elements (VAR . VAL), where VAR is a variable
3026 and VAL is the specified value. Ignores any specification for
3027 `mode:' and `coding:' (which should have already been handled
3028 by `set-auto-mode' and `set-auto-coding', respectively).
3029 Return nil if the -*- line is malformed.
3031 If MODE-ONLY is non-nil, just returns the symbol specifying the
3032 mode, if there is one, otherwise nil."
3033 (catch 'malformed-line
3035 (goto-char (point-min))
3036 (let ((end (set-auto-mode-1))
3040 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
3041 ;; Simple form: "-*- MODENAME -*-".
3043 (intern (concat (match-string 1) "-mode"))))
3045 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
3046 ;; (last ";" is optional).
3047 ;; If MODE-ONLY, just check for `mode'.
3048 ;; Otherwise, parse the -*- line into the RESULT alist.
3049 (while (and (or (not mode-only
)
3052 (unless (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
3053 (message "Malformed mode-line")
3054 (throw 'malformed-line nil
))
3055 (goto-char (match-end 0))
3056 ;; There used to be a downcase here,
3057 ;; but the manual didn't say so,
3058 ;; and people want to set var names that aren't all lc.
3059 (let* ((key (intern (match-string 1)))
3060 (val (save-restriction
3061 (narrow-to-region (point) end
)
3062 (let ((read-circle nil
))
3063 (read (current-buffer)))))
3064 ;; It is traditional to ignore
3065 ;; case when checking for `mode' in set-auto-mode,
3066 ;; so we must do that here as well.
3067 ;; That is inconsistent, but we're stuck with it.
3068 ;; The same can be said for `coding' in set-auto-coding.
3069 (keyname (downcase (symbol-name key
))))
3071 (and (equal keyname
"mode")
3073 (intern (concat (downcase (symbol-name val
))
3075 (or (equal keyname
"coding")
3077 (push (cons (cond ((eq key
'eval
) 'eval
)
3078 ;; Downcase "Mode:".
3079 ((equal keyname
"mode") 'mode
)
3080 (t (indirect-variable key
)))
3083 (skip-chars-forward " \t;")))
3086 (defun hack-local-variables-filter (variables dir-name
)
3087 "Filter local variable settings, querying the user if necessary.
3088 VARIABLES is the alist of variable-value settings. This alist is
3089 filtered based on the values of `ignored-local-variables',
3090 `enable-local-eval', `enable-local-variables', and (if necessary)
3091 user interaction. The results are added to
3092 `file-local-variables-alist', without applying them.
3093 If these settings come from directory-local variables, then
3094 DIR-NAME is the name of the associated directory. Otherwise it is nil."
3095 ;; Find those variables that we may want to save to
3096 ;; `safe-local-variable-values'.
3097 (let (all-vars risky-vars unsafe-vars
)
3098 (dolist (elt variables
)
3099 (let ((var (car elt
))
3101 (cond ((memq var ignored-local-variables
)
3102 ;; Ignore any variable in `ignored-local-variables'.
3104 ;; Obey `enable-local-eval'.
3106 (when enable-local-eval
3107 (let ((safe (or (hack-one-local-variable-eval-safep val
)
3108 ;; In case previously marked safe (bug#5636).
3109 (safe-local-variable-p var val
))))
3110 ;; If not safe and e-l-v = :safe, ignore totally.
3111 (when (or safe
(not (eq enable-local-variables
:safe
)))
3113 (or (eq enable-local-eval t
)
3115 (push elt unsafe-vars
))))))
3116 ;; Ignore duplicates (except `mode') in the present list.
3117 ((and (assq var all-vars
) (not (eq var
'mode
))) nil
)
3118 ;; Accept known-safe variables.
3119 ((or (memq var
'(mode unibyte coding
))
3120 (safe-local-variable-p var val
))
3121 (push elt all-vars
))
3122 ;; The variable is either risky or unsafe:
3123 ((not (eq enable-local-variables
:safe
))
3125 (if (risky-local-variable-p var val
)
3126 (push elt risky-vars
)
3127 (push elt unsafe-vars
))))))
3129 ;; Query, unless all vars are safe or user wants no querying.
3130 (or (and (eq enable-local-variables t
)
3133 (memq enable-local-variables
'(:all
:safe
))
3134 (hack-local-variables-confirm all-vars unsafe-vars
3135 risky-vars dir-name
))
3136 (dolist (elt all-vars
)
3137 (unless (memq (car elt
) '(eval mode
))
3139 (setq dir-local-variables-alist
3140 (assq-delete-all (car elt
) dir-local-variables-alist
)))
3141 (setq file-local-variables-alist
3142 (assq-delete-all (car elt
) file-local-variables-alist
)))
3143 (push elt file-local-variables-alist
)))))
3145 (defun hack-local-variables (&optional mode-only
)
3146 "Parse and put into effect this buffer's local variables spec.
3147 Uses `hack-local-variables-apply' to apply the variables.
3149 If MODE-ONLY is non-nil, all we do is check whether a \"mode:\"
3150 is specified, and return the corresponding mode symbol, or nil.
3151 In this case, we try to ignore minor-modes, and only return a
3154 If `enable-local-variables' or `local-enable-local-variables' is nil,
3155 this function does nothing. If `inhibit-local-variables-regexps'
3156 applies to the file in question, the file is not scanned for
3157 local variables, but directory-local variables may still be applied."
3158 ;; We don't let inhibit-local-variables-p influence the value of
3159 ;; enable-local-variables, because then it would affect dir-local
3160 ;; variables. We don't want to search eg tar files for file local
3161 ;; variable sections, but there is no reason dir-locals cannot apply
3162 ;; to them. The real meaning of inhibit-local-variables-p is "do
3163 ;; not scan this file for local variables".
3164 (let ((enable-local-variables
3165 (and local-enable-local-variables enable-local-variables
))
3168 (setq file-local-variables-alist nil
)
3169 (report-errors "Directory-local variables error: %s"
3170 ;; Note this is a no-op if enable-local-variables is nil.
3171 (hack-dir-local-variables)))
3172 ;; This entire function is basically a no-op if enable-local-variables
3173 ;; is nil. All it does is set file-local-variables-alist to nil.
3174 (when enable-local-variables
3175 ;; This part used to ignore enable-local-variables when mode-only
3176 ;; was non-nil. That was inappropriate, eg consider the
3177 ;; (artificial) example of:
3178 ;; (setq local-enable-local-variables nil)
3179 ;; Open a file foo.txt that contains "mode: sh".
3180 ;; It correctly opens in text-mode.
3181 ;; M-x set-visited-file name foo.c, and it incorrectly stays in text-mode.
3182 (unless (or (inhibit-local-variables-p)
3183 ;; If MODE-ONLY is non-nil, and the prop line specifies a
3184 ;; mode, then we're done, and have no need to scan further.
3185 (and (setq result
(hack-local-variables-prop-line mode-only
))
3187 ;; Look for "Local variables:" line in last page.
3189 (goto-char (point-max))
3190 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min))
3192 (when (let ((case-fold-search t
))
3193 (search-forward "Local Variables:" nil t
))
3194 (skip-chars-forward " \t")
3195 ;; suffix is what comes after "local variables:" in its line.
3196 ;; prefix is what comes before "local variables:" in its line.
3199 (regexp-quote (buffer-substring (point)
3200 (line-end-position)))
3203 (concat "^" (regexp-quote
3204 (buffer-substring (line-beginning-position)
3205 (match-beginning 0)))))
3209 (let ((startpos (point))
3211 (thisbuf (current-buffer)))
3213 (unless (let ((case-fold-search t
))
3215 (concat prefix
"[ \t]*End:[ \t]*" suffix
)
3217 ;; This used to be an error, but really all it means is
3218 ;; that this may simply not be a local-variables section,
3219 ;; so just ignore it.
3220 (message "Local variables list is not properly terminated"))
3222 (setq endpos
(point)))
3225 (insert-buffer-substring thisbuf startpos endpos
)
3226 (goto-char (point-min))
3227 (subst-char-in-region (point) (point-max) ?\^m ?
\n)
3229 ;; Discard the prefix.
3230 (if (looking-at prefix
)
3231 (delete-region (point) (match-end 0))
3232 (error "Local variables entry is missing the prefix"))
3234 ;; Discard the suffix.
3235 (if (looking-back suffix
)
3236 (delete-region (match-beginning 0) (point))
3237 (error "Local variables entry is missing the suffix"))
3239 (goto-char (point-min))
3241 (while (and (not (eobp))
3244 ;; Find the variable name; strip whitespace.
3245 (skip-chars-forward " \t")
3247 (skip-chars-forward "^:\n")
3248 (if (eolp) (error "Missing colon in local variables entry"))
3249 (skip-chars-backward " \t")
3250 (let* ((str (buffer-substring beg
(point)))
3251 (var (let ((read-circle nil
))
3254 (and (equal (downcase (symbol-name var
)) "mode")
3256 ;; Read the variable value.
3257 (skip-chars-forward "^:")
3259 (let ((read-circle nil
))
3260 (setq val
(read (current-buffer))))
3263 ;; Specifying minor-modes via mode: is
3264 ;; deprecated, but try to reject them anyway.
3267 (setq val2
(downcase (symbol-name val
)))))
3268 (setq result
(intern (concat val2
"-mode"))))
3269 (unless (eq var
'coding
)
3271 (push (cons (if (eq var
'eval
)
3273 (indirect-variable var
))
3276 (forward-line 1))))))))
3277 ;; Now we've read all the local variables.
3278 ;; If MODE-ONLY is non-nil, return whether the mode was specified.
3279 (if mode-only result
3280 ;; Otherwise, set the variables.
3281 (hack-local-variables-filter result nil
)
3282 (hack-local-variables-apply)))))
3284 (defun hack-local-variables-apply ()
3285 "Apply the elements of `file-local-variables-alist'.
3286 If there are any elements, runs `before-hack-local-variables-hook',
3287 then calls `hack-one-local-variable' to apply the alist elements one by one.
3288 Finishes by running `hack-local-variables-hook', regardless of whether
3289 the alist is empty or not.
3291 Note that this function ignores a `mode' entry if it specifies the same
3292 major mode as the buffer already has."
3293 (when file-local-variables-alist
3294 ;; Any 'evals must run in the Right sequence.
3295 (setq file-local-variables-alist
3296 (nreverse file-local-variables-alist
))
3297 (run-hooks 'before-hack-local-variables-hook
)
3298 (dolist (elt file-local-variables-alist
)
3299 (hack-one-local-variable (car elt
) (cdr elt
))))
3300 (run-hooks 'hack-local-variables-hook
))
3302 (defun safe-local-variable-p (sym val
)
3303 "Non-nil if SYM is safe as a file-local variable with value VAL.
3304 It is safe if any of these conditions are met:
3306 * There is a matching entry (SYM . VAL) in the
3307 `safe-local-variable-values' user option.
3309 * The `safe-local-variable' property of SYM is a function that
3310 evaluates to a non-nil value with VAL as an argument."
3311 (or (member (cons sym val
) safe-local-variable-values
)
3312 (let ((safep (get sym
'safe-local-variable
)))
3313 (and (functionp safep
)
3314 ;; If the function signals an error, that means it
3315 ;; can't assure us that the value is safe.
3316 (with-demoted-errors (funcall safep val
))))))
3318 (defun risky-local-variable-p (sym &optional _ignored
)
3319 "Non-nil if SYM could be dangerous as a file-local variable.
3320 It is dangerous if either of these conditions are met:
3322 * Its `risky-local-variable' property is non-nil.
3324 * Its name ends with \"hook(s)\", \"function(s)\", \"form(s)\", \"map\",
3325 \"program\", \"command(s)\", \"predicate(s)\", \"frame-alist\",
3326 \"mode-alist\", \"font-lock-(syntactic-)keyword*\",
3327 \"map-alist\", or \"bindat-spec\"."
3328 ;; If this is an alias, check the base name.
3330 (setq sym
(indirect-variable sym
))
3332 (or (get sym
'risky-local-variable
)
3333 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|\
3334 -commands?$\\|-predicates?$\\|font-lock-keywords$\\|font-lock-keywords\
3335 -[0-9]+$\\|font-lock-syntactic-keywords$\\|-frame-alist$\\|-mode-alist$\\|\
3336 -map$\\|-map-alist$\\|-bindat-spec$" (symbol-name sym
))))
3338 (defun hack-one-local-variable-quotep (exp)
3339 (and (consp exp
) (eq (car exp
) 'quote
) (consp (cdr exp
))))
3341 (defun hack-one-local-variable-constantp (exp)
3342 (or (and (not (symbolp exp
)) (not (consp exp
)))
3345 (hack-one-local-variable-quotep exp
)))
3347 (defun hack-one-local-variable-eval-safep (exp)
3348 "Return t if it is safe to eval EXP when it is found in a file."
3349 (or (not (consp exp
))
3350 ;; Detect certain `put' expressions.
3351 (and (eq (car exp
) 'put
)
3352 (hack-one-local-variable-quotep (nth 1 exp
))
3353 (hack-one-local-variable-quotep (nth 2 exp
))
3354 (let ((prop (nth 1 (nth 2 exp
)))
3356 (cond ((memq prop
'(lisp-indent-hook
3357 lisp-indent-function
3358 scheme-indent-function
))
3359 ;; Only allow safe values (not functions).
3361 (and (hack-one-local-variable-quotep val
)
3362 (eq (nth 1 val
) 'defun
))))
3363 ((eq prop
'edebug-form-spec
)
3364 ;; Only allow indirect form specs.
3365 ;; During bootstrapping, edebug-basic-spec might not be
3367 (and (fboundp 'edebug-basic-spec
)
3368 (hack-one-local-variable-quotep val
)
3369 (edebug-basic-spec (nth 1 val
)))))))
3370 ;; Allow expressions that the user requested.
3371 (member exp safe-local-eval-forms
)
3372 ;; Certain functions can be allowed with safe arguments
3373 ;; or can specify verification functions to try.
3374 (and (symbolp (car exp
))
3375 ;; Allow (minor)-modes calls with no arguments.
3376 ;; This obsoletes the use of "mode:" for such things. (Bug#8613)
3377 (or (and (member (cdr exp
) '(nil (1) (0) (-1)))
3378 (string-match "-mode\\'" (symbol-name (car exp
))))
3379 (let ((prop (get (car exp
) 'safe-local-eval-function
)))
3382 (dolist (arg (cdr exp
))
3383 (unless (hack-one-local-variable-constantp arg
)
3390 (dolist (function prop
)
3391 (if (funcall function exp
)
3395 (defun hack-one-local-variable--obsolete (var)
3396 (let ((o (get var
'byte-obsolete-variable
)))
3398 (let ((instead (nth 0 o
))
3400 (message "%s is obsolete%s; %s"
3401 var
(if since
(format " (since %s)" since
))
3402 (if (stringp instead
) instead
3403 (format "use `%s' instead" instead
)))))))
3405 (defun hack-one-local-variable (var val
)
3406 "Set local variable VAR with value VAL.
3407 If VAR is `mode', call `VAL-mode' as a function unless it's
3408 already the major mode."
3411 (let ((mode (intern (concat (downcase (symbol-name val
))
3413 (unless (eq (indirect-function mode
)
3414 (indirect-function major-mode
))
3418 (`(add-hook ',hook .
,_
) (hack-one-local-variable--obsolete hook
)))
3419 (save-excursion (eval val
)))
3421 (hack-one-local-variable--obsolete var
)
3422 ;; Make sure the string has no text properties.
3423 ;; Some text properties can get evaluated in various ways,
3424 ;; so it is risky to put them on with a local variable list.
3426 (set-text-properties 0 (length val
) nil val
))
3427 (set (make-local-variable var
) val
))))
3429 ;;; Handling directory-local variables, aka project settings.
3431 (defvar dir-locals-class-alist
'()
3432 "Alist mapping directory-local variable classes (symbols) to variable lists.")
3434 (defvar dir-locals-directory-cache
'()
3435 "List of cached directory roots for directory-local variable classes.
3436 Each element in this list has the form (DIR CLASS MTIME).
3437 DIR is the name of the directory.
3438 CLASS is the name of a variable class (a symbol).
3439 MTIME is the recorded modification time of the directory-local
3440 variables file associated with this entry. This time is a list
3441 of integers (the same format as `file-attributes'), and is
3442 used to test whether the cache entry is still valid.
3443 Alternatively, MTIME can be nil, which means the entry is always
3446 (defsubst dir-locals-get-class-variables
(class)
3447 "Return the variable list for CLASS."
3448 (cdr (assq class dir-locals-class-alist
)))
3450 (defun dir-locals-collect-mode-variables (mode-variables variables
)
3451 "Collect directory-local variables from MODE-VARIABLES.
3452 VARIABLES is the initial list of variables.
3453 Returns the new list."
3454 (dolist (pair mode-variables variables
)
3455 (let* ((variable (car pair
))
3457 (slot (assq variable variables
)))
3458 ;; If variables are specified more than once, only use the last. (Why?)
3459 ;; The pseudo-variables mode and eval are different (bug#3430).
3460 (if (and slot
(not (memq variable
'(mode eval
))))
3462 ;; Need a new cons in case we setcdr later.
3463 (push (cons variable value
) variables
)))))
3465 (defun dir-locals-collect-variables (class-variables root variables
)
3466 "Collect entries from CLASS-VARIABLES into VARIABLES.
3467 ROOT is the root directory of the project.
3468 Return the new variables list."
3469 (let* ((file-name (buffer-file-name))
3470 (sub-file-name (if file-name
3471 ;; FIXME: Why not use file-relative-name?
3472 (substring file-name
(length root
)))))
3474 (dolist (entry class-variables variables
)
3475 (let ((key (car entry
)))
3478 ;; Don't include this in the previous condition, because we
3479 ;; want to filter all strings before the next condition.
3480 (when (and sub-file-name
3481 (>= (length sub-file-name
) (length key
))
3482 (string-prefix-p key sub-file-name
))
3483 (setq variables
(dir-locals-collect-variables
3484 (cdr entry
) root variables
))))
3486 (derived-mode-p key
))
3487 (let* ((alist (cdr entry
))
3488 (subdirs (assq 'subdirs alist
)))
3489 (if (or (not subdirs
)
3491 (setq alist
(delq subdirs alist
))
3493 ;; TODO someone might want to extend this to allow
3494 ;; integer values for subdir, where N means
3495 ;; variables apply to this directory and N levels
3496 ;; below it (0 == nil).
3497 (equal root default-directory
))
3498 (setq variables
(dir-locals-collect-mode-variables
3499 alist variables
))))))))
3501 ;; The file's content might be invalid (e.g. have a merge conflict), but
3502 ;; that shouldn't prevent the user from opening the file.
3503 (message ".dir-locals error: %s" (error-message-string err
))
3506 (defun dir-locals-set-directory-class (directory class
&optional mtime
)
3507 "Declare that the DIRECTORY root is an instance of CLASS.
3508 DIRECTORY is the name of a directory, a string.
3509 CLASS is the name of a project class, a symbol.
3510 MTIME is either the modification time of the directory-local
3511 variables file that defined this class, or nil.
3513 When a file beneath DIRECTORY is visited, the mode-specific
3514 variables from CLASS are applied to the buffer. The variables
3515 for a class are defined using `dir-locals-set-class-variables'."
3516 (setq directory
(file-name-as-directory (expand-file-name directory
)))
3517 (unless (assq class dir-locals-class-alist
)
3518 (error "No such class `%s'" (symbol-name class
)))
3519 (push (list directory class mtime
) dir-locals-directory-cache
))
3521 (defun dir-locals-set-class-variables (class variables
)
3522 "Map the type CLASS to a list of variable settings.
3523 CLASS is the project class, a symbol. VARIABLES is a list
3524 that declares directory-local variables for the class.
3525 An element in VARIABLES is either of the form:
3526 (MAJOR-MODE . ALIST)
3530 In the first form, MAJOR-MODE is a symbol, and ALIST is an alist
3531 whose elements are of the form (VARIABLE . VALUE).
3533 In the second form, DIRECTORY is a directory name (a string), and
3534 LIST is a list of the form accepted by the function.
3536 When a file is visited, the file's class is found. A directory
3537 may be assigned a class using `dir-locals-set-directory-class'.
3538 Then variables are set in the file's buffer according to the
3539 VARIABLES list of the class. The list is processed in order.
3541 * If the element is of the form (MAJOR-MODE . ALIST), and the
3542 buffer's major mode is derived from MAJOR-MODE (as determined
3543 by `derived-mode-p'), then all the variables in ALIST are
3544 applied. A MAJOR-MODE of nil may be used to match any buffer.
3545 `make-local-variable' is called for each variable before it is
3548 * If the element is of the form (DIRECTORY . LIST), and DIRECTORY
3549 is an initial substring of the file's directory, then LIST is
3550 applied by recursively following these rules."
3551 (let ((elt (assq class dir-locals-class-alist
)))
3553 (setcdr elt variables
)
3554 (push (cons class variables
) dir-locals-class-alist
))))
3556 (defconst dir-locals-file
".dir-locals.el"
3557 "File that contains directory-local variables.
3558 It has to be constant to enforce uniform values
3559 across different environments and users.")
3561 (defun dir-locals-find-file (file)
3562 "Find the directory-local variables for FILE.
3563 This searches upward in the directory tree from FILE.
3564 It stops at the first directory that has been registered in
3565 `dir-locals-directory-cache' or contains a `dir-locals-file'.
3566 If it finds an entry in the cache, it checks that it is valid.
3567 A cache entry with no modification time element (normally, one that
3568 has been assigned directly using `dir-locals-set-directory-class', not
3569 set from a file) is always valid.
3570 A cache entry based on a `dir-locals-file' is valid if the modification
3571 time stored in the cache matches the current file modification time.
3572 If not, the cache entry is cleared so that the file will be re-read.
3574 This function returns either nil (no directory local variables found),
3575 or the matching entry from `dir-locals-directory-cache' (a list),
3576 or the full path to the `dir-locals-file' (a string) in the case
3577 of no valid cache entry."
3578 (setq file
(expand-file-name file
))
3579 (let* ((dir-locals-file-name
3580 (if (eq system-type
'ms-dos
)
3581 (dosified-file-name dir-locals-file
)
3583 (locals-file (locate-dominating-file file dir-locals-file-name
))
3585 ;; `locate-dominating-file' may have abbreviated the name.
3587 (setq locals-file
(expand-file-name dir-locals-file-name locals-file
)))
3588 ;; Let dir-locals-read-from-file inform us via demoted-errors
3589 ;; about unreadable files, etc.
3590 ;; Maybe we'd want to keep searching though - that is
3591 ;; a locate-dominating-file issue.
3592 ;;; (or (not (file-readable-p locals-file))
3593 ;;; (not (file-regular-p locals-file)))
3594 ;;; (setq locals-file nil))
3595 ;; Find the best cached value in `dir-locals-directory-cache'.
3596 (dolist (elt dir-locals-directory-cache
)
3597 (when (and (eq t
(compare-strings file nil
(length (car elt
))
3600 '(windows-nt cygwin ms-dos
))))
3601 (> (length (car elt
)) (length (car dir-elt
))))
3602 (setq dir-elt elt
)))
3604 (or (null locals-file
)
3605 (<= (length (file-name-directory locals-file
))
3606 (length (car dir-elt
)))))
3607 ;; Found a potential cache entry. Check validity.
3608 ;; A cache entry with no MTIME is assumed to always be valid
3609 ;; (ie, set directly, not from a dir-locals file).
3610 ;; Note, we don't bother to check that there is a matching class
3611 ;; element in dir-locals-class-alist, since that's done by
3612 ;; dir-locals-set-directory-class.
3613 (if (or (null (nth 2 dir-elt
))
3614 (let ((cached-file (expand-file-name dir-locals-file-name
3616 (and (file-readable-p cached-file
)
3617 (equal (nth 2 dir-elt
)
3618 (nth 5 (file-attributes cached-file
))))))
3619 ;; This cache entry is OK.
3621 ;; This cache entry is invalid; clear it.
3622 (setq dir-locals-directory-cache
3623 (delq dir-elt dir-locals-directory-cache
))
3624 ;; Return the first existing dir-locals file. Might be the same
3625 ;; as dir-elt's, might not (eg latter might have been deleted).
3630 (defun dir-locals-read-from-file (file)
3631 "Load a variables FILE and register a new class and instance.
3632 FILE is the name of the file holding the variables to apply.
3633 The new class name is the same as the directory in which FILE
3634 is found. Returns the new class name."
3636 ;; This is with-demoted-errors, but we want to mention dir-locals
3637 ;; in any error message.
3641 (insert-file-contents file
)
3642 (unless (zerop (buffer-size))
3643 (let* ((dir-name (file-name-directory file
))
3644 (class-name (intern dir-name
))
3645 (variables (let ((read-circle nil
))
3646 (read (current-buffer)))))
3647 (dir-locals-set-class-variables class-name variables
)
3648 (dir-locals-set-directory-class dir-name class-name
3649 (nth 5 (file-attributes file
)))
3651 (error (message "Error reading dir-locals: %S" err
) nil
)))))
3653 (defcustom enable-remote-dir-locals nil
3654 "Non-nil means dir-local variables will be applied to remote files."
3659 (defun hack-dir-local-variables ()
3660 "Read per-directory local variables for the current buffer.
3661 Store the directory-local variables in `dir-local-variables-alist'
3662 and `file-local-variables-alist', without applying them."
3663 (when (and enable-local-variables
3664 (or enable-remote-dir-locals
3665 (not (file-remote-p (or (buffer-file-name)
3666 default-directory
)))))
3667 ;; Find the variables file.
3668 (let ((variables-file (dir-locals-find-file
3669 (or (buffer-file-name) default-directory
)))
3673 ((stringp variables-file
)
3674 (setq dir-name
(file-name-directory variables-file
)
3675 class
(dir-locals-read-from-file variables-file
)))
3676 ((consp variables-file
)
3677 (setq dir-name
(nth 0 variables-file
))
3678 (setq class
(nth 1 variables-file
))))
3681 (dir-locals-collect-variables
3682 (dir-locals-get-class-variables class
) dir-name nil
)))
3684 (dolist (elt variables
)
3685 (if (eq (car elt
) 'coding
)
3686 (display-warning :warning
3687 "Coding cannot be specified by dir-locals")
3688 (unless (memq (car elt
) '(eval mode
))
3689 (setq dir-local-variables-alist
3690 (assq-delete-all (car elt
) dir-local-variables-alist
)))
3691 (push elt dir-local-variables-alist
)))
3692 (hack-local-variables-filter variables dir-name
)))))))
3694 (defun hack-dir-local-variables-non-file-buffer ()
3695 "Apply directory-local variables to a non-file buffer.
3696 For non-file buffers, such as Dired buffers, directory-local
3697 variables are looked for in `default-directory' and its parent
3699 (hack-dir-local-variables)
3700 (hack-local-variables-apply))
3703 (defcustom change-major-mode-with-file-name t
3704 "Non-nil means \\[write-file] should set the major mode from the file name.
3705 However, the mode will not be changed if
3706 \(1) a local variables list or the `-*-' line specifies a major mode, or
3707 \(2) the current major mode is a \"special\" mode,
3708 \ not suitable for ordinary files, or
3709 \(3) the new file name does not particularly specify any mode."
3711 :group
'editing-basics
)
3713 (defun set-visited-file-name (filename &optional no-query along-with-file
)
3714 "Change name of file visited in current buffer to FILENAME.
3715 This also renames the buffer to correspond to the new file.
3716 The next time the buffer is saved it will go in the newly specified file.
3717 FILENAME nil or an empty string means mark buffer as not visiting any file.
3718 Remember to delete the initial contents of the minibuffer
3719 if you wish to pass an empty string as the argument.
3721 The optional second argument NO-QUERY, if non-nil, inhibits asking for
3722 confirmation in the case where another buffer is already visiting FILENAME.
3724 The optional third argument ALONG-WITH-FILE, if non-nil, means that
3725 the old visited file has been renamed to the new name FILENAME."
3726 (interactive "FSet visited file name: ")
3727 (if (buffer-base-buffer)
3728 (error "An indirect buffer cannot visit a file"))
3729 (let (truename old-try-locals
)
3732 (if (string-equal filename
"")
3734 (expand-file-name filename
))))
3737 (setq truename
(file-truename filename
))
3738 (if find-file-visit-truename
3739 (setq filename truename
))))
3741 (let ((new-name (file-name-nondirectory filename
)))
3742 (if (string= new-name
"")
3743 (error "Empty file name"))))
3744 (let ((buffer (and filename
(find-buffer-visiting filename
))))
3745 (and buffer
(not (eq buffer
(current-buffer)))
3747 (not (y-or-n-p (format "A buffer is visiting %s; proceed? "
3750 (or (equal filename buffer-file-name
)
3752 (and filename
(lock-buffer filename
))
3754 (setq old-try-locals
(not (inhibit-local-variables-p))
3755 buffer-file-name filename
)
3756 (if filename
; make buffer name reflect filename.
3757 (let ((new-name (file-name-nondirectory buffer-file-name
)))
3758 (setq default-directory
(file-name-directory buffer-file-name
))
3759 ;; If new-name == old-name, renaming would add a spurious <2>
3760 ;; and it's considered as a feature in rename-buffer.
3761 (or (string= new-name
(buffer-name))
3762 (rename-buffer new-name t
))))
3763 (setq buffer-backed-up nil
)
3765 (clear-visited-file-modtime))
3766 ;; Abbreviate the file names of the buffer.
3769 (setq buffer-file-truename
(abbreviate-file-name truename
))
3770 (if find-file-visit-truename
3771 (setq buffer-file-name truename
))))
3772 (setq buffer-file-number
3774 (nthcdr 10 (file-attributes buffer-file-name
))
3776 ;; write-file-functions is normally used for things like ftp-find-file
3777 ;; that visit things that are not local files as if they were files.
3778 ;; Changing to visit an ordinary local file instead should flush the hook.
3779 (kill-local-variable 'write-file-functions
)
3780 (kill-local-variable 'local-write-file-hooks
)
3781 (kill-local-variable 'revert-buffer-function
)
3782 (kill-local-variable 'backup-inhibited
)
3783 ;; If buffer was read-only because of version control,
3784 ;; that reason is gone now, so make it writable.
3786 (setq buffer-read-only nil
))
3787 (kill-local-variable 'vc-mode
)
3788 ;; Turn off backup files for certain file names.
3789 ;; Since this is a permanent local, the major mode won't eliminate it.
3790 (and buffer-file-name
3791 backup-enable-predicate
3792 (not (funcall backup-enable-predicate buffer-file-name
))
3794 (make-local-variable 'backup-inhibited
)
3795 (setq backup-inhibited t
)))
3796 (let ((oauto buffer-auto-save-file-name
))
3797 ;; If auto-save was not already on, turn it on if appropriate.
3798 (if (not buffer-auto-save-file-name
)
3799 (and buffer-file-name auto-save-default
3801 ;; If auto save is on, start using a new name.
3802 ;; We deliberately don't rename or delete the old auto save
3803 ;; for the old visited file name. This is because perhaps
3804 ;; the user wants to save the new state and then compare with the
3805 ;; previous state from the auto save file.
3806 (setq buffer-auto-save-file-name
3807 (make-auto-save-file-name)))
3808 ;; Rename the old auto save file if any.
3809 (and oauto buffer-auto-save-file-name
3810 (file-exists-p oauto
)
3811 (rename-file oauto buffer-auto-save-file-name t
)))
3812 (and buffer-file-name
3813 (not along-with-file
)
3814 (set-buffer-modified-p t
))
3815 ;; Update the major mode, if the file name determines it.
3817 ;; Don't change the mode if it is special.
3818 (or (not change-major-mode-with-file-name
)
3819 (get major-mode
'mode-class
)
3820 ;; Don't change the mode if the local variable list specifies it.
3821 ;; The file name can influence whether the local variables apply.
3823 ;; h-l-v also checks it, but might as well be explicit.
3824 (not (inhibit-local-variables-p))
3825 (hack-local-variables t
))
3826 ;; TODO consider making normal-mode handle this case.
3827 (let ((old major-mode
))
3829 (or (eq old major-mode
)
3830 (hack-local-variables))))
3833 (defun write-file (filename &optional confirm
)
3834 "Write current buffer into file FILENAME.
3835 This makes the buffer visit that file, and marks it as not modified.
3837 If you specify just a directory name as FILENAME, that means to use
3838 the default file name but in that directory. You can also yank
3839 the default file name into the minibuffer to edit it, using \\<minibuffer-local-map>\\[next-history-element].
3841 If the buffer is not already visiting a file, the default file name
3842 for the output file is the buffer name.
3844 If optional second arg CONFIRM is non-nil, this function
3845 asks for confirmation before overwriting an existing file.
3846 Interactively, confirmation is required unless you supply a prefix argument."
3847 ;; (interactive "FWrite file: ")
3849 (list (if buffer-file-name
3850 (read-file-name "Write file: "
3852 (read-file-name "Write file: " default-directory
3854 (file-name-nondirectory (buffer-name))
3857 (not current-prefix-arg
)))
3858 (or (null filename
) (string-equal filename
"")
3860 ;; If arg is just a directory,
3861 ;; use the default file name, but in that directory.
3862 (if (file-directory-p filename
)
3863 (setq filename
(concat (file-name-as-directory filename
)
3864 (file-name-nondirectory
3865 (or buffer-file-name
(buffer-name))))))
3867 (file-exists-p filename
)
3868 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename
))
3869 (error "Canceled")))
3870 (set-visited-file-name filename
(not confirm
))))
3871 (set-buffer-modified-p t
)
3872 ;; Make buffer writable if file is writable.
3873 (and buffer-file-name
3874 (file-writable-p buffer-file-name
)
3875 (setq buffer-read-only nil
))
3877 ;; It's likely that the VC status at the new location is different from
3878 ;; the one at the old location.
3879 (vc-find-file-hook))
3881 (defun file-extended-attributes (filename)
3882 "Return an alist of extended attributes of file FILENAME.
3884 Extended attributes are platform-specific metadata about the file,
3885 such as SELinux context, list of ACL entries, etc."
3886 `((acl .
,(file-acl filename
))
3887 (selinux-context .
,(file-selinux-context filename
))))
3889 (defun set-file-extended-attributes (filename attributes
)
3890 "Set extended attributes of file FILENAME to ATTRIBUTES.
3892 ATTRIBUTES must be an alist of file attributes as returned by
3893 `file-extended-attributes'."
3894 (dolist (elt attributes
)
3895 (let ((attr (car elt
))
3897 (cond ((eq attr
'acl
)
3898 (set-file-acl filename val
))
3899 ((eq attr
'selinux-context
)
3900 (set-file-selinux-context filename val
))))))
3902 (defun backup-buffer ()
3903 "Make a backup of the disk file visited by the current buffer, if appropriate.
3904 This is normally done before saving the buffer the first time.
3906 A backup may be done by renaming or by copying; see documentation of
3907 variable `make-backup-files'. If it's done by renaming, then the file is
3908 no longer accessible under its old name.
3910 The value is non-nil after a backup was made by renaming.
3911 It has the form (MODES EXTENDED-ATTRIBUTES BACKUPNAME).
3912 MODES is the result of `file-modes' on the original
3913 file; this means that the caller, after saving the buffer, should change
3914 the modes of the new file to agree with the old modes.
3915 EXTENDED-ATTRIBUTES is the result of `file-extended-attributes'
3916 on the original file; this means that the caller, after saving
3917 the buffer, should change the extended attributes of the new file
3918 to agree with the old attributes.
3919 BACKUPNAME is the backup file name, which is the old file renamed."
3920 (if (and make-backup-files
(not backup-inhibited
)
3921 (not buffer-backed-up
)
3922 (file-exists-p buffer-file-name
)
3923 (memq (aref (elt (file-attributes buffer-file-name
) 8) 0)
3925 (let ((real-file-name buffer-file-name
)
3926 backup-info backupname targets setmodes
)
3927 ;; If specified name is a symbolic link, chase it to the target.
3928 ;; Thus we make the backups in the directory where the real file is.
3929 (setq real-file-name
(file-chase-links real-file-name
))
3930 (setq backup-info
(find-backup-file-name real-file-name
)
3931 backupname
(car backup-info
)
3932 targets
(cdr backup-info
))
3933 ;; (if (file-directory-p buffer-file-name)
3934 ;; (error "Cannot save buffer in directory %s" buffer-file-name))
3937 (let ((delete-old-versions
3938 ;; If have old versions to maybe delete,
3939 ;; ask the user to confirm now, before doing anything.
3940 ;; But don't actually delete til later.
3942 (or (eq delete-old-versions t
) (eq delete-old-versions nil
))
3943 (or delete-old-versions
3944 (y-or-n-p (format "Delete excess backup versions of %s? "
3946 (modes (file-modes buffer-file-name
))
3947 (extended-attributes
3948 (file-extended-attributes buffer-file-name
)))
3949 ;; Actually write the back up file.
3951 (if (or file-precious-flag
3952 ; (file-symlink-p buffer-file-name)
3954 ;; Don't rename a suid or sgid file.
3955 (and modes
(< 0 (logand modes
#o6000
)))
3956 (not (file-writable-p (file-name-directory real-file-name
)))
3957 (and backup-by-copying-when-linked
3958 (> (file-nlinks real-file-name
) 1))
3959 (and (or backup-by-copying-when-mismatch
3960 (integerp backup-by-copying-when-privileged-mismatch
))
3961 (let ((attr (file-attributes real-file-name
)))
3962 (and (or backup-by-copying-when-mismatch
3963 (and (integerp (nth 2 attr
))
3964 (integerp backup-by-copying-when-privileged-mismatch
)
3965 (<= (nth 2 attr
) backup-by-copying-when-privileged-mismatch
)))
3966 (not (file-ownership-preserved-p
3967 real-file-name t
))))))
3968 (backup-buffer-copy real-file-name
3970 extended-attributes
)
3971 ;; rename-file should delete old backup.
3972 (rename-file real-file-name backupname t
)
3973 (setq setmodes
(list modes extended-attributes
3976 ;; If trouble writing the backup, write it in
3977 ;; .emacs.d/%backup%.
3978 (setq backupname
(locate-user-emacs-file "%backup%~"))
3979 (message "Cannot write backup file; backing up in %s"
3982 (backup-buffer-copy real-file-name backupname
3983 modes extended-attributes
)))
3984 (setq buffer-backed-up t
)
3985 ;; Now delete the old versions, if desired.
3986 (if delete-old-versions
3989 (delete-file (car targets
))
3991 (setq targets
(cdr targets
))))
3993 (file-error nil
))))))
3995 (defun backup-buffer-copy (from-name to-name modes extended-attributes
)
3996 (let ((umask (default-file-modes)))
3999 ;; Create temp files with strict access rights. It's easy to
4000 ;; loosen them later, whereas it's impossible to close the
4001 ;; time-window of loose permissions otherwise.
4002 (set-default-file-modes ?
\700)
4003 (when (condition-case nil
4004 ;; Try to overwrite old backup first.
4005 (copy-file from-name to-name t t t
)
4007 (while (condition-case nil
4009 (when (file-exists-p to-name
)
4010 (delete-file to-name
))
4011 (copy-file from-name to-name nil t t
)
4013 (file-already-exists t
))
4014 ;; The file was somehow created by someone else between
4015 ;; `delete-file' and `copy-file', so let's try again.
4016 ;; rms says "I think there is also a possible race
4017 ;; condition for making backup files" (emacs-devel 20070821).
4020 (set-default-file-modes umask
)))
4021 ;; If set-file-extended-attributes fails, fall back on set-file-modes.
4022 (unless (and extended-attributes
4023 (with-demoted-errors
4024 (set-file-extended-attributes to-name extended-attributes
)))
4026 (set-file-modes to-name
(logand modes
#o1777
)))))
4028 (defvar file-name-version-regexp
4029 "\\(?:~\\|\\.~[-[:alnum:]:#@^._]+\\(?:~[[:digit:]]+\\)?~\\)"
4030 ;; The last ~[[:digit]]+ matches relative versions in git,
4031 ;; e.g. `foo.js.~HEAD~1~'.
4032 "Regular expression matching the backup/version part of a file name.
4033 Used by `file-name-sans-versions'.")
4035 (defun file-name-sans-versions (name &optional keep-backup-version
)
4036 "Return file NAME sans backup versions or strings.
4037 This is a separate procedure so your site-init or startup file can
4039 If the optional argument KEEP-BACKUP-VERSION is non-nil,
4040 we do not remove backup version numbers, only true file version numbers.
4041 See also `file-name-version-regexp'."
4042 (let ((handler (find-file-name-handler name
'file-name-sans-versions
)))
4044 (funcall handler
'file-name-sans-versions name keep-backup-version
)
4046 (unless keep-backup-version
4047 (string-match (concat file-name-version-regexp
"\\'")
4050 (defun file-ownership-preserved-p (file &optional group
)
4051 "Return t if deleting FILE and rewriting it would preserve the owner.
4052 Return nil if FILE does not exist, or if deleting and recreating it
4053 might not preserve the owner. If GROUP is non-nil, check whether
4054 the group would be preserved too."
4055 (let ((handler (find-file-name-handler file
'file-ownership-preserved-p
)))
4057 (funcall handler
'file-ownership-preserved-p file group
)
4058 (let ((attributes (file-attributes file
'integer
)))
4059 ;; Return t if the file doesn't exist, since it's true that no
4060 ;; information would be lost by an (attempted) delete and create.
4061 (or (null attributes
)
4062 (and (or (= (nth 2 attributes
) (user-uid))
4063 ;; Files created on Windows by Administrator (RID=500)
4064 ;; have the Administrators group (RID=544) recorded as
4065 ;; their owner. Rewriting them will still preserve the
4067 (and (eq system-type
'windows-nt
)
4068 (= (user-uid) 500) (= (nth 2 attributes
) 544)))
4070 ;; On BSD-derived systems files always inherit the parent
4071 ;; directory's group, so skip the group-gid test.
4072 (memq system-type
'(berkeley-unix darwin gnu
/kfreebsd
))
4073 (= (nth 3 attributes
) (group-gid)))
4074 (let* ((parent (or (file-name-directory file
) "."))
4075 (parent-attributes (file-attributes parent
'integer
)))
4076 (and parent-attributes
4077 ;; On some systems, a file created in a setuid directory
4078 ;; inherits that directory's owner.
4080 (= (nth 2 parent-attributes
) (user-uid))
4081 (string-match "^...[^sS]" (nth 8 parent-attributes
)))
4082 ;; On many systems, a file created in a setgid directory
4083 ;; inherits that directory's group. On some systems
4084 ;; this happens even if the setgid bit is not set.
4086 (= (nth 3 parent-attributes
)
4087 (nth 3 attributes
)))))))))))
4089 (defun file-name-sans-extension (filename)
4090 "Return FILENAME sans final \"extension\".
4091 The extension, in a file name, is the part that follows the last `.',
4092 except that a leading `.', if any, doesn't count."
4094 (let ((file (file-name-sans-versions (file-name-nondirectory filename
)))
4096 (if (and (string-match "\\.[^.]*\\'" file
)
4097 (not (eq 0 (match-beginning 0))))
4098 (if (setq directory
(file-name-directory filename
))
4099 ;; Don't use expand-file-name here; if DIRECTORY is relative,
4100 ;; we don't want to expand it.
4101 (concat directory
(substring file
0 (match-beginning 0)))
4102 (substring file
0 (match-beginning 0)))
4105 (defun file-name-extension (filename &optional period
)
4106 "Return FILENAME's final \"extension\".
4107 The extension, in a file name, is the part that follows the last `.',
4108 excluding version numbers and backup suffixes,
4109 except that a leading `.', if any, doesn't count.
4110 Return nil for extensionless file names such as `foo'.
4111 Return the empty string for file names such as `foo.'.
4113 If PERIOD is non-nil, then the returned value includes the period
4114 that delimits the extension, and if FILENAME has no extension,
4117 (let ((file (file-name-sans-versions (file-name-nondirectory filename
))))
4118 (if (and (string-match "\\.[^.]*\\'" file
)
4119 (not (eq 0 (match-beginning 0))))
4120 (substring file
(+ (match-beginning 0) (if period
0 1)))
4124 (defun file-name-base (&optional filename
)
4125 "Return the base name of the FILENAME: no directory, no extension.
4126 FILENAME defaults to `buffer-file-name'."
4127 (file-name-sans-extension
4128 (file-name-nondirectory (or filename
(buffer-file-name)))))
4130 (defcustom make-backup-file-name-function nil
4131 "A function to use instead of the default `make-backup-file-name'.
4132 A value of nil gives the default `make-backup-file-name' behavior.
4134 This could be buffer-local to do something special for specific
4135 files. If you define it, you may need to change `backup-file-name-p'
4136 and `file-name-sans-versions' too.
4138 See also `backup-directory-alist'."
4140 :type
'(choice (const :tag
"Default" nil
)
4141 (function :tag
"Your function")))
4143 (defcustom backup-directory-alist nil
4144 "Alist of filename patterns and backup directory names.
4145 Each element looks like (REGEXP . DIRECTORY). Backups of files with
4146 names matching REGEXP will be made in DIRECTORY. DIRECTORY may be
4147 relative or absolute. If it is absolute, so that all matching files
4148 are backed up into the same directory, the file names in this
4149 directory will be the full name of the file backed up with all
4150 directory separators changed to `!' to prevent clashes. This will not
4151 work correctly if your filesystem truncates the resulting name.
4153 For the common case of all backups going into one directory, the alist
4154 should contain a single element pairing \".\" with the appropriate
4157 If this variable is nil, or it fails to match a filename, the backup
4158 is made in the original file's directory.
4160 On MS-DOS filesystems without long names this variable is always
4163 :type
'(repeat (cons (regexp :tag
"Regexp matching filename")
4164 (directory :tag
"Backup directory name"))))
4166 (defun normal-backup-enable-predicate (name)
4167 "Default `backup-enable-predicate' function.
4168 Checks for files in `temporary-file-directory',
4169 `small-temporary-file-directory', and /tmp."
4170 (not (or (let ((comp (compare-strings temporary-file-directory
0 nil
4172 ;; Directory is under temporary-file-directory.
4173 (and (not (eq comp t
))
4174 (< comp
(- (length temporary-file-directory
)))))
4175 (let ((comp (compare-strings "/tmp" 0 nil
4177 ;; Directory is under /tmp.
4178 (and (not (eq comp t
))
4179 (< comp
(- (length "/tmp")))))
4180 (if small-temporary-file-directory
4181 (let ((comp (compare-strings small-temporary-file-directory
4184 ;; Directory is under small-temporary-file-directory.
4185 (and (not (eq comp t
))
4186 (< comp
(- (length small-temporary-file-directory
)))))))))
4188 (defun make-backup-file-name (file)
4189 "Create the non-numeric backup file name for FILE.
4190 Normally this will just be the file's name with `~' appended.
4191 Customization hooks are provided as follows.
4193 If the variable `make-backup-file-name-function' is non-nil, its value
4194 should be a function which will be called with FILE as its argument;
4195 the resulting name is used.
4197 Otherwise a match for FILE is sought in `backup-directory-alist'; see
4198 the documentation of that variable. If the directory for the backup
4199 doesn't exist, it is created."
4200 (if make-backup-file-name-function
4201 (funcall make-backup-file-name-function file
)
4202 (if (and (eq system-type
'ms-dos
)
4203 (not (msdos-long-file-names)))
4204 (let ((fn (file-name-nondirectory file
)))
4205 (concat (file-name-directory file
)
4206 (or (and (string-match "\\`[^.]+\\'" fn
)
4207 (concat (match-string 0 fn
) ".~"))
4208 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn
)
4209 (concat (match-string 0 fn
) "~")))))
4210 (concat (make-backup-file-name-1 file
) "~"))))
4212 (defun make-backup-file-name-1 (file)
4213 "Subroutine of `make-backup-file-name' and `find-backup-file-name'."
4214 (let ((alist backup-directory-alist
)
4215 elt backup-directory abs-backup-directory
)
4217 (setq elt
(pop alist
))
4218 (if (string-match (car elt
) file
)
4219 (setq backup-directory
(cdr elt
)
4221 ;; If backup-directory is relative, it should be relative to the
4222 ;; file's directory. By expanding explicitly here, we avoid
4223 ;; depending on default-directory.
4224 (if backup-directory
4225 (setq abs-backup-directory
4226 (expand-file-name backup-directory
4227 (file-name-directory file
))))
4228 (if (and abs-backup-directory
(not (file-exists-p abs-backup-directory
)))
4230 (make-directory abs-backup-directory
'parents
)
4231 (file-error (setq backup-directory nil
4232 abs-backup-directory nil
))))
4233 (if (null backup-directory
)
4235 (if (file-name-absolute-p backup-directory
)
4237 (when (memq system-type
'(windows-nt ms-dos cygwin
))
4238 ;; Normalize DOSish file names: downcase the drive
4239 ;; letter, if any, and replace the leading "x:" with
4241 (or (file-name-absolute-p file
)
4242 (setq file
(expand-file-name file
))) ; make defaults explicit
4243 ;; Replace any invalid file-name characters (for the
4244 ;; case of backing up remote files).
4245 (setq file
(expand-file-name (convert-standard-filename file
)))
4246 (if (eq (aref file
1) ?
:)
4247 (setq file
(concat "/"
4249 (char-to-string (downcase (aref file
0)))
4250 (if (eq (aref file
2) ?
/)
4253 (substring file
2)))))
4254 ;; Make the name unique by substituting directory
4255 ;; separators. It may not really be worth bothering about
4256 ;; doubling `!'s in the original name...
4258 (subst-char-in-string
4260 (replace-regexp-in-string "!" "!!" file
))
4262 (expand-file-name (file-name-nondirectory file
)
4263 (file-name-as-directory abs-backup-directory
))))))
4265 (defun backup-file-name-p (file)
4266 "Return non-nil if FILE is a backup file name (numeric or not).
4267 This is a separate function so you can redefine it for customization.
4268 You may need to redefine `file-name-sans-versions' as well."
4269 (string-match "~\\'" file
))
4271 (defvar backup-extract-version-start
)
4273 ;; This is used in various files.
4274 ;; The usage of backup-extract-version-start is not very clean,
4275 ;; but I can't see a good alternative, so as of now I am leaving it alone.
4276 (defun backup-extract-version (fn)
4277 "Given the name of a numeric backup file, FN, return the backup number.
4278 Uses the free variable `backup-extract-version-start', whose value should be
4279 the index in the name where the version number begins."
4280 (if (and (string-match "[0-9]+~/?$" fn backup-extract-version-start
)
4281 (= (match-beginning 0) backup-extract-version-start
))
4282 (string-to-number (substring fn backup-extract-version-start -
1))
4285 (defun find-backup-file-name (fn)
4286 "Find a file name for a backup file FN, and suggestions for deletions.
4287 Value is a list whose car is the name for the backup file
4288 and whose cdr is a list of old versions to consider deleting now.
4289 If the value is nil, don't make a backup.
4290 Uses `backup-directory-alist' in the same way as does
4291 `make-backup-file-name'."
4292 (let ((handler (find-file-name-handler fn
'find-backup-file-name
)))
4293 ;; Run a handler for this function so that ange-ftp can refuse to do it.
4295 (funcall handler
'find-backup-file-name fn
)
4296 (if (or (eq version-control
'never
)
4297 ;; We don't support numbered backups on plain MS-DOS
4298 ;; when long file names are unavailable.
4299 (and (eq system-type
'ms-dos
)
4300 (not (msdos-long-file-names))))
4301 (list (make-backup-file-name fn
))
4302 (let* ((basic-name (make-backup-file-name-1 fn
))
4303 (base-versions (concat (file-name-nondirectory basic-name
)
4305 (backup-extract-version-start (length base-versions
))
4307 (number-to-delete 0)
4308 possibilities deserve-versions-p versions
)
4310 (setq possibilities
(file-name-all-completions
4312 (file-name-directory basic-name
))
4313 versions
(sort (mapcar #'backup-extract-version
4316 high-water-mark
(apply 'max
0 versions
)
4317 deserve-versions-p
(or version-control
4318 (> high-water-mark
0))
4319 number-to-delete
(- (length versions
)
4323 (file-error (setq possibilities nil
)))
4324 (if (not deserve-versions-p
)
4325 (list (make-backup-file-name fn
))
4326 (cons (format "%s.~%d~" basic-name
(1+ high-water-mark
))
4327 (if (and (> number-to-delete
0)
4328 ;; Delete nothing if there is overflow
4329 ;; in the number of versions to keep.
4330 (>= (+ kept-new-versions kept-old-versions -
1) 0))
4332 (format "%s.~%d~" basic-name n
))
4333 (let ((v (nthcdr kept-old-versions versions
)))
4334 (rplacd (nthcdr (1- number-to-delete
) v
) ())
4337 (defun file-nlinks (filename)
4338 "Return number of names file FILENAME has."
4339 (car (cdr (file-attributes filename
))))
4341 ;; (defun file-relative-name (filename &optional directory)
4342 ;; "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
4343 ;; This function returns a relative file name which is equivalent to FILENAME
4344 ;; when used with that default directory as the default.
4345 ;; If this is impossible (which can happen on MSDOS and Windows
4346 ;; when the file name and directory use different drive names)
4347 ;; then it returns FILENAME."
4349 ;; (let ((fname (expand-file-name filename)))
4350 ;; (setq directory (file-name-as-directory
4351 ;; (expand-file-name (or directory default-directory))))
4352 ;; ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
4353 ;; ;; drive names, they can't be relative, so return the absolute name.
4354 ;; (if (and (or (eq system-type 'ms-dos)
4355 ;; (eq system-type 'cygwin)
4356 ;; (eq system-type 'windows-nt))
4357 ;; (not (string-equal (substring fname 0 2)
4358 ;; (substring directory 0 2))))
4360 ;; (let ((ancestor ".")
4361 ;; (fname-dir (file-name-as-directory fname)))
4362 ;; (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
4363 ;; (not (string-match (concat "^" (regexp-quote directory)) fname)))
4364 ;; (setq directory (file-name-directory (substring directory 0 -1))
4365 ;; ancestor (if (equal ancestor ".")
4367 ;; (concat "../" ancestor))))
4368 ;; ;; Now ancestor is empty, or .., or ../.., etc.
4369 ;; (if (string-match (concat "^" (regexp-quote directory)) fname)
4370 ;; ;; We matched within FNAME's directory part.
4371 ;; ;; Add the rest of FNAME onto ANCESTOR.
4372 ;; (let ((rest (substring fname (match-end 0))))
4373 ;; (if (and (equal ancestor ".")
4374 ;; (not (equal rest "")))
4375 ;; ;; But don't bother with ANCESTOR if it would give us `./'.
4377 ;; (concat (file-name-as-directory ancestor) rest)))
4378 ;; ;; We matched FNAME's directory equivalent.
4381 (defun file-relative-name (filename &optional directory
)
4382 "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
4383 This function returns a relative file name which is equivalent to FILENAME
4384 when used with that default directory as the default.
4385 If FILENAME and DIRECTORY lie on different machines or on different drives
4386 on a DOS/Windows machine, it returns FILENAME in expanded form."
4389 (file-name-as-directory (expand-file-name (or directory
4390 default-directory
))))
4391 (setq filename
(expand-file-name filename
))
4392 (let ((fremote (file-remote-p filename
))
4393 (dremote (file-remote-p directory
))
4394 (fold-case (or (memq system-type
'(ms-dos cygwin windows-nt
))
4395 read-file-name-completion-ignore-case
)))
4396 (if ;; Conditions for separate trees
4398 ;; Test for different filesystems on DOS/Windows
4400 ;; Should `cygwin' really be included here? --stef
4401 (memq system-type
'(ms-dos cygwin windows-nt
))
4403 ;; Test for different drive letters
4404 (not (eq t
(compare-strings filename
0 2 directory
0 2 fold-case
)))
4405 ;; Test for UNCs on different servers
4406 (not (eq t
(compare-strings
4408 (if (string-match "\\`//\\([^:/]+\\)/" filename
)
4409 (match-string 1 filename
)
4410 ;; Windows file names cannot have ? in
4411 ;; them, so use that to detect when
4412 ;; neither FILENAME nor DIRECTORY is a
4417 (if (string-match "\\`//\\([^:/]+\\)/" directory
)
4418 (match-string 1 directory
)
4421 ;; Test for different remote file system identification
4422 (not (equal fremote dremote
)))
4424 (let ((ancestor ".")
4425 (filename-dir (file-name-as-directory filename
)))
4428 (eq t
(compare-strings filename-dir nil
(length directory
)
4429 directory nil nil fold-case
))
4430 (eq t
(compare-strings filename nil
(length directory
)
4431 directory nil nil fold-case
))))
4432 (setq directory
(file-name-directory (substring directory
0 -
1))
4433 ancestor
(if (equal ancestor
".")
4435 (concat "../" ancestor
))))
4436 ;; Now ancestor is empty, or .., or ../.., etc.
4437 (if (eq t
(compare-strings filename nil
(length directory
)
4438 directory nil nil fold-case
))
4439 ;; We matched within FILENAME's directory part.
4440 ;; Add the rest of FILENAME onto ANCESTOR.
4441 (let ((rest (substring filename
(length directory
))))
4442 (if (and (equal ancestor
".") (not (equal rest
"")))
4443 ;; But don't bother with ANCESTOR if it would give us `./'.
4445 (concat (file-name-as-directory ancestor
) rest
)))
4446 ;; We matched FILENAME's directory equivalent.
4449 (defun save-buffer (&optional args
)
4450 "Save current buffer in visited file if modified.
4451 Variations are described below.
4453 By default, makes the previous version into a backup file
4454 if previously requested or if this is the first save.
4455 Prefixed with one \\[universal-argument], marks this version
4456 to become a backup when the next save is done.
4457 Prefixed with two \\[universal-argument]'s,
4458 unconditionally makes the previous version into a backup file.
4459 Prefixed with three \\[universal-argument]'s, marks this version
4460 to become a backup when the next save is done,
4461 and unconditionally makes the previous version into a backup file.
4463 With a numeric argument of 0, never make the previous version
4466 If a file's name is FOO, the names of its numbered backup versions are
4467 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
4468 Numeric backups (rather than FOO~) will be made if value of
4469 `version-control' is not the atom `never' and either there are already
4470 numeric versions of the file being backed up, or `version-control' is
4472 We don't want excessive versions piling up, so there are variables
4473 `kept-old-versions', which tells Emacs how many oldest versions to keep,
4474 and `kept-new-versions', which tells how many newest versions to keep.
4475 Defaults are 2 old versions and 2 new.
4476 `dired-kept-versions' controls dired's clean-directory (.) command.
4477 If `delete-old-versions' is nil, system will query user
4478 before trimming versions. Otherwise it does it silently.
4480 If `vc-make-backup-files' is nil, which is the default,
4481 no backup files are made for files managed by version control.
4482 (This is because the version control system itself records previous versions.)
4484 See the subroutine `basic-save-buffer' for more information."
4486 (let ((modp (buffer-modified-p))
4487 (make-backup-files (or (and make-backup-files
(not (eq args
0)))
4488 (memq args
'(16 64)))))
4489 (and modp
(memq args
'(16 64)) (setq buffer-backed-up nil
))
4490 ;; We used to display the message below only for files > 50KB, but
4491 ;; then Rmail-mbox never displays it due to buffer swapping. If
4492 ;; the test is ever re-introduced, be sure to handle saving of
4494 (if (and modp
(buffer-file-name))
4495 (message "Saving file %s..." (buffer-file-name)))
4497 (and modp
(memq args
'(4 64)) (setq buffer-backed-up nil
))))
4499 (defun delete-auto-save-file-if-necessary (&optional force
)
4500 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
4501 Normally delete only if the file was written by this Emacs since
4502 the last real save, but optional arg FORCE non-nil means delete anyway."
4503 (and buffer-auto-save-file-name delete-auto-save-files
4504 (not (string= buffer-file-name buffer-auto-save-file-name
))
4505 (or force
(recent-auto-save-p))
4508 (delete-file buffer-auto-save-file-name
)
4510 (set-buffer-auto-saved))))
4512 (defvar auto-save-hook nil
4513 "Normal hook run just before auto-saving.")
4515 (defcustom before-save-hook nil
4516 "Normal hook that is run before a buffer is saved to its file."
4517 :options
'(copyright-update time-stamp
)
4521 (defcustom after-save-hook nil
4522 "Normal hook that is run after a buffer is saved to its file."
4523 :options
'(executable-make-buffer-file-executable-if-script-p)
4527 (defvar save-buffer-coding-system nil
4528 "If non-nil, use this coding system for saving the buffer.
4529 More precisely, use this coding system in place of the
4530 value of `buffer-file-coding-system', when saving the buffer.
4531 Calling `write-region' for any purpose other than saving the buffer
4532 will still use `buffer-file-coding-system'; this variable has no effect
4535 (make-variable-buffer-local 'save-buffer-coding-system
)
4536 (put 'save-buffer-coding-system
'permanent-local t
)
4538 (defun basic-save-buffer ()
4539 "Save the current buffer in its visited file, if it has been modified.
4540 The hooks `write-contents-functions' and `write-file-functions' get a chance
4541 to do the job of saving; if they do not, then the buffer is saved in
4542 the visited file in the usual way.
4543 Before and after saving the buffer, this function runs
4544 `before-save-hook' and `after-save-hook', respectively."
4546 (save-current-buffer
4547 ;; In an indirect buffer, save its base buffer instead.
4548 (if (buffer-base-buffer)
4549 (set-buffer (buffer-base-buffer)))
4550 (if (or (buffer-modified-p)
4551 ;; handle the case when no modification has been made but
4552 ;; the file disappeared since visited
4553 (and buffer-file-name
4554 (not (file-exists-p buffer-file-name
))))
4555 (let ((recent-save (recent-auto-save-p))
4557 ;; If buffer has no file name, ask user for one.
4558 (or buffer-file-name
4561 (read-file-name "File to save in: "
4562 nil
(expand-file-name (buffer-name))))))
4563 (if (file-exists-p filename
)
4564 (if (file-directory-p filename
)
4565 ;; Signal an error if the user specified the name of an
4566 ;; existing directory.
4567 (error "%s is a directory" filename
)
4568 (unless (y-or-n-p (format "File `%s' exists; overwrite? "
4570 (error "Canceled")))
4571 ;; Signal an error if the specified name refers to a
4572 ;; non-existing directory.
4573 (let ((dir (file-name-directory filename
)))
4574 (unless (file-directory-p dir
)
4575 (if (file-exists-p dir
)
4576 (error "%s is not a directory" dir
)
4577 (error "%s: no such directory" dir
)))))
4578 (set-visited-file-name filename
)))
4579 (or (verify-visited-file-modtime (current-buffer))
4580 (not (file-exists-p buffer-file-name
))
4583 "%s has changed since visited or saved. Save anyway? "
4584 (file-name-nondirectory buffer-file-name
)))
4585 (user-error "Save not confirmed"))
4589 (and (> (point-max) (point-min))
4590 (not find-file-literally
)
4591 (/= (char-after (1- (point-max))) ?
\n)
4592 (not (and (eq selective-display t
)
4593 (= (char-after (1- (point-max))) ?
\r)))
4594 (or (eq require-final-newline t
)
4595 (eq require-final-newline
'visit-save
)
4596 (and require-final-newline
4598 (format "Buffer %s does not end in newline. Add one? "
4601 (goto-char (point-max))
4603 ;; Support VC version backups.
4605 (run-hooks 'before-save-hook
)
4606 (or (run-hook-with-args-until-success 'write-contents-functions
)
4607 (run-hook-with-args-until-success 'local-write-file-hooks
)
4608 (run-hook-with-args-until-success 'write-file-functions
)
4609 ;; If a hook returned t, file is already "written".
4610 ;; Otherwise, write it the usual way now.
4611 (setq setmodes
(basic-save-buffer-1)))
4612 ;; Now we have saved the current buffer. Let's make sure
4613 ;; that buffer-file-coding-system is fixed to what
4614 ;; actually used for saving by binding it locally.
4615 (if save-buffer-coding-system
4616 (setq save-buffer-coding-system last-coding-system-used
)
4617 (setq buffer-file-coding-system last-coding-system-used
))
4618 (setq buffer-file-number
4619 (nthcdr 10 (file-attributes buffer-file-name
)))
4624 (with-demoted-errors
4625 (set-file-modes buffer-file-name
(car setmodes
)))
4626 (set-file-extended-attributes buffer-file-name
4629 ;; If the auto-save file was recent before this command,
4631 (delete-auto-save-file-if-necessary recent-save
)
4632 ;; Support VC `implicit' locking.
4634 (run-hooks 'after-save-hook
))
4635 (message "(No changes need to be saved)"))))
4637 ;; This does the "real job" of writing a buffer into its visited file
4638 ;; and making a backup file. This is what is normally done
4639 ;; but inhibited if one of write-file-functions returns non-nil.
4640 ;; It returns a value (MODES EXTENDED-ATTRIBUTES BACKUPNAME), like
4642 (defun basic-save-buffer-1 ()
4644 (if save-buffer-coding-system
4645 (let ((coding-system-for-write save-buffer-coding-system
))
4646 (basic-save-buffer-2))
4647 (basic-save-buffer-2))
4648 (if buffer-file-coding-system-explicit
4649 (setcar buffer-file-coding-system-explicit last-coding-system-used
))))
4651 ;; This returns a value (MODES EXTENDED-ATTRIBUTES BACKUPNAME), like
4653 (defun basic-save-buffer-2 ()
4654 (let (tempsetmodes setmodes writecoding
)
4655 (if (not (file-writable-p buffer-file-name
))
4656 (let ((dir (file-name-directory buffer-file-name
)))
4657 (if (not (file-directory-p dir
))
4658 (if (file-exists-p dir
)
4659 (error "%s is not a directory" dir
)
4660 (error "%s: no such directory" dir
))
4661 (if (not (file-exists-p buffer-file-name
))
4662 (error "Directory %s write-protected" dir
)
4665 "File %s is write-protected; try to save anyway? "
4666 (file-name-nondirectory
4668 (setq tempsetmodes t
)
4669 (error "Attempt to save to a file which you aren't allowed to write"))))))
4670 ;; This may involve prompting, so do it now before backing up the file.
4671 ;; Otherwise there can be a delay while the user answers the
4672 ;; prompt during which the original file has been renamed. (Bug#13522)
4674 ;; Args here should match write-region call below around
4675 ;; which we use writecoding.
4676 (choose-write-coding-system nil nil buffer-file-name nil t
4677 buffer-file-truename
))
4678 (or buffer-backed-up
4679 (setq setmodes
(backup-buffer)))
4680 (let* ((dir (file-name-directory buffer-file-name
))
4681 (dir-writable (file-writable-p dir
)))
4682 (if (or (and file-precious-flag dir-writable
)
4683 (and break-hardlink-on-save
4684 (file-exists-p buffer-file-name
)
4685 (> (file-nlinks buffer-file-name
) 1)
4687 (error (concat (format
4688 "Directory %s write-protected; " dir
)
4689 "cannot break hardlink when saving")))))
4690 ;; Write temp name, then rename it.
4691 ;; This requires write access to the containing dir,
4692 ;; which is why we don't try it if we don't have that access.
4693 (let ((realname buffer-file-name
)
4695 (umask (default-file-modes))
4696 (old-modtime (visited-file-modtime)))
4697 ;; Create temp files with strict access rights. It's easy to
4698 ;; loosen them later, whereas it's impossible to close the
4699 ;; time-window of loose permissions otherwise.
4702 (clear-visited-file-modtime)
4703 (set-default-file-modes ?
\700)
4704 ;; Try various temporary names.
4705 ;; This code follows the example of make-temp-file,
4706 ;; but it calls write-region in the appropriate way
4707 ;; for saving the buffer.
4708 (while (condition-case ()
4712 (expand-file-name "tmp" dir
)))
4713 ;; Pass in nil&nil rather than point-min&max
4714 ;; cause we're saving the whole buffer.
4715 ;; write-region-annotate-functions may use it.
4716 (write-region nil nil
4717 tempname nil realname
4718 buffer-file-truename
'excl
)
4720 (file-already-exists t
))
4721 ;; The file was somehow created by someone else between
4722 ;; `make-temp-name' and `write-region', let's try again.
4726 (set-default-file-modes umask
)
4727 ;; If we failed, restore the buffer's modtime.
4729 (set-visited-file-modtime old-modtime
)))
4730 ;; Since we have created an entirely new file,
4731 ;; make sure it gets the right permission bits set.
4732 (setq setmodes
(or setmodes
4733 (list (or (file-modes buffer-file-name
)
4734 (logand ?
\666 umask
))
4735 (file-extended-attributes buffer-file-name
)
4737 ;; We succeeded in writing the temp file,
4739 (rename-file tempname buffer-file-name t
))
4740 ;; If file not writable, see if we can make it writable
4741 ;; temporarily while we write it.
4742 ;; But no need to do so if we have just backed it up
4743 ;; (setmodes is set) because that says we're superseding.
4744 (cond ((and tempsetmodes
(not setmodes
))
4745 ;; Change the mode back, after writing.
4746 (setq setmodes
(list (file-modes buffer-file-name
)
4747 (file-extended-attributes buffer-file-name
)
4749 ;; If set-file-extended-attributes fails, fall back on
4752 (with-demoted-errors
4753 (set-file-extended-attributes buffer-file-name
4755 (set-file-modes buffer-file-name
4756 (logior (car setmodes
) 128))))))
4759 ;; Pass in nil&nil rather than point-min&max to indicate
4760 ;; we're saving the buffer rather than just a region.
4761 ;; write-region-annotate-functions may make us of it.
4762 (let ((coding-system-for-write writecoding
)
4763 (coding-system-require-warning nil
))
4764 (write-region nil nil
4765 buffer-file-name nil t buffer-file-truename
)
4767 ;; If we get an error writing the new file, and we made
4768 ;; the backup by renaming, undo the backing-up.
4769 (and setmodes
(not success
)
4771 (rename-file (nth 2 setmodes
) buffer-file-name t
)
4772 (setq buffer-backed-up nil
))))))
4775 (declare-function diff-no-select
"diff"
4776 (old new
&optional switches no-async buf
))
4778 (defvar save-some-buffers-action-alist
4781 (if (not enable-recursive-minibuffers
)
4782 (progn (display-buffer buf
)
4783 (setq other-window-scroll-buffer buf
))
4784 (view-buffer buf
(lambda (_) (exit-recursive-edit)))
4786 ;; Return nil to ask about BUF again.
4788 ,(purecopy "view this buffer"))
4790 (if (null (buffer-file-name buf
))
4791 (message "Not applicable: no file")
4792 (require 'diff
) ;for diff-no-select.
4793 (let ((diffbuf (diff-no-select (buffer-file-name buf
) buf
4795 (if (not enable-recursive-minibuffers
)
4796 (progn (display-buffer diffbuf
)
4797 (setq other-window-scroll-buffer diffbuf
))
4798 (view-buffer diffbuf
(lambda (_) (exit-recursive-edit)))
4800 ;; Return nil to ask about BUF again.
4802 ,(purecopy "view changes in this buffer")))
4803 "ACTION-ALIST argument used in call to `map-y-or-n-p'.")
4804 (put 'save-some-buffers-action-alist
'risky-local-variable t
)
4806 (defvar buffer-save-without-query nil
4807 "Non-nil means `save-some-buffers' should save this buffer without asking.")
4808 (make-variable-buffer-local 'buffer-save-without-query
)
4810 (defun save-some-buffers (&optional arg pred
)
4811 "Save some modified file-visiting buffers. Asks user about each one.
4812 You can answer `y' to save, `n' not to save, `C-r' to look at the
4813 buffer in question with `view-buffer' before deciding or `d' to
4814 view the differences using `diff-buffer-with-file'.
4816 This command first saves any buffers where `buffer-save-without-query' is
4817 non-nil, without asking.
4819 Optional argument (the prefix) non-nil means save all with no questions.
4820 Optional second argument PRED determines which buffers are considered:
4821 If PRED is nil, all the file-visiting buffers are considered.
4822 If PRED is t, then certain non-file buffers will also be considered.
4823 If PRED is a zero-argument function, it indicates for each buffer whether
4824 to consider it or not when called with that buffer current.
4826 See `save-some-buffers-action-alist' if you want to
4827 change the additional actions you can take on files."
4829 (save-window-excursion
4830 (let* (queried autosaved-buffers
4831 files-done abbrevs-done
)
4832 (dolist (buffer (buffer-list))
4833 ;; First save any buffers that we're supposed to save unconditionally.
4834 ;; That way the following code won't ask about them.
4835 (with-current-buffer buffer
4836 (when (and buffer-save-without-query
(buffer-modified-p))
4837 (push (buffer-name) autosaved-buffers
)
4839 ;; Ask about those buffers that merit it,
4840 ;; and record the number thus saved.
4844 ;; Note that killing some buffers may kill others via
4845 ;; hooks (e.g. Rmail and its viewing buffer).
4846 (and (buffer-live-p buffer
)
4847 (buffer-modified-p buffer
)
4848 (not (buffer-base-buffer buffer
))
4850 (buffer-file-name buffer
)
4854 (and buffer-offer-save
(> (buffer-size) 0)))))
4855 (or (not (functionp pred
))
4856 (with-current-buffer buffer
(funcall pred
)))
4860 (if (buffer-file-name buffer
)
4861 (format "Save file %s? "
4862 (buffer-file-name buffer
))
4863 (format "Save buffer %s? "
4864 (buffer-name buffer
))))))
4866 (with-current-buffer buffer
4869 '("buffer" "buffers" "save")
4870 save-some-buffers-action-alist
))
4871 ;; Maybe to save abbrevs, and record whether
4872 ;; we either saved them or asked to.
4873 (and save-abbrevs abbrevs-changed
4876 (eq save-abbrevs
'silently
)
4877 (y-or-n-p (format "Save abbrevs in %s? " abbrev-file-name
)))
4878 (write-abbrev-file nil
))
4879 ;; Don't keep bothering user if he says no.
4880 (setq abbrevs-changed nil
)
4881 (setq abbrevs-done t
)))
4882 (or queried
(> files-done
0) abbrevs-done
4884 ((null autosaved-buffers
)
4885 (message "(No files need saving)"))
4886 ((= (length autosaved-buffers
) 1)
4887 (message "(Saved %s)" (car autosaved-buffers
)))
4889 (message "(Saved %d files: %s)"
4890 (length autosaved-buffers
)
4891 (mapconcat 'identity autosaved-buffers
", "))))))))
4893 (defun not-modified (&optional arg
)
4894 "Mark current buffer as unmodified, not needing to be saved.
4895 With prefix ARG, mark buffer as modified, so \\[save-buffer] will save.
4897 It is not a good idea to use this function in Lisp programs, because it
4898 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
4900 (message (if arg
"Modification-flag set"
4901 "Modification-flag cleared"))
4902 (set-buffer-modified-p arg
))
4904 (defun toggle-read-only (&optional arg interactive
)
4905 (declare (obsolete read-only-mode
"24.3"))
4906 (interactive (list current-prefix-arg t
))
4908 (call-interactively 'read-only-mode
)
4909 (read-only-mode (or arg
'toggle
))))
4911 (defun insert-file (filename)
4912 "Insert contents of file FILENAME into buffer after point.
4913 Set mark after the inserted text.
4915 This function is meant for the user to run interactively.
4916 Don't call it from programs! Use `insert-file-contents' instead.
4917 \(Its calling sequence is different; see its documentation)."
4918 (interactive "*fInsert file: ")
4919 (insert-file-1 filename
#'insert-file-contents
))
4921 (defun append-to-file (start end filename
)
4922 "Append the contents of the region to the end of file FILENAME.
4923 When called from a function, expects three arguments,
4924 START, END and FILENAME. START and END are normally buffer positions
4925 specifying the part of the buffer to write.
4926 If START is nil, that means to use the entire buffer contents.
4927 If START is a string, then output that string to the file
4928 instead of any buffer contents; END is ignored.
4930 This does character code conversion and applies annotations
4931 like `write-region' does."
4932 (interactive "r\nFAppend to file: ")
4933 (write-region start end filename t
))
4935 (defun file-newest-backup (filename)
4936 "Return most recent backup file for FILENAME or nil if no backups exist."
4937 ;; `make-backup-file-name' will get us the right directory for
4938 ;; ordinary or numeric backups. It might create a directory for
4939 ;; backups as a side-effect, according to `backup-directory-alist'.
4940 (let* ((filename (file-name-sans-versions
4941 (make-backup-file-name (expand-file-name filename
))))
4942 (file (file-name-nondirectory filename
))
4943 (dir (file-name-directory filename
))
4944 (comp (file-name-all-completions file dir
))
4948 (setq tem
(pop comp
))
4949 (cond ((and (backup-file-name-p tem
)
4950 (string= (file-name-sans-versions tem
) file
))
4951 (setq tem
(concat dir tem
))
4952 (if (or (null newest
)
4953 (file-newer-than-file-p tem newest
))
4954 (setq newest tem
)))))
4957 (defun rename-uniquely ()
4958 "Rename current buffer to a similar name not already taken.
4959 This function is useful for creating multiple shell process buffers
4960 or multiple mail buffers, etc.
4962 Note that some commands, in particular those based on `compilation-mode'
4963 \(`compile', `grep', etc.) will reuse the current buffer if it has the
4964 appropriate mode even if it has been renamed. So as well as renaming
4965 the buffer, you also need to switch buffers before running another
4966 instance of such commands."
4969 (let ((base-name (buffer-name)))
4970 (and (string-match "<[0-9]+>\\'" base-name
)
4971 (not (and buffer-file-name
4973 (file-name-nondirectory buffer-file-name
))))
4974 ;; If the existing buffer name has a <NNN>,
4975 ;; which isn't part of the file name (if any),
4976 ;; then get rid of that.
4977 (setq base-name
(substring base-name
0 (match-beginning 0))))
4978 (rename-buffer (generate-new-buffer-name base-name
))
4979 (force-mode-line-update))))
4981 (defun make-directory (dir &optional parents
)
4982 "Create the directory DIR and optionally any nonexistent parent dirs.
4983 If DIR already exists as a directory, signal an error, unless
4986 Interactively, the default choice of directory to create is the
4987 current buffer's default directory. That is useful when you have
4988 visited a file in a nonexistent directory.
4990 Noninteractively, the second (optional) argument PARENTS, if
4991 non-nil, says whether to create parent directories that don't
4992 exist. Interactively, this happens by default.
4994 If creating the directory or directories fail, an error will be
4997 (list (read-file-name "Make directory: " default-directory default-directory
5000 ;; If default-directory is a remote directory,
5001 ;; make sure we find its make-directory handler.
5002 (setq dir
(expand-file-name dir
))
5003 (let ((handler (find-file-name-handler dir
'make-directory
)))
5005 (funcall handler
'make-directory dir parents
)
5007 (make-directory-internal dir
)
5008 (let ((dir (directory-file-name (expand-file-name dir
)))
5010 (while (and (not (file-exists-p dir
))
5011 ;; If directory is its own parent, then we can't
5012 ;; keep looping forever
5014 (directory-file-name
5015 (file-name-directory dir
)))))
5016 (setq create-list
(cons dir create-list
)
5017 dir
(directory-file-name (file-name-directory dir
))))
5019 (make-directory-internal (car create-list
))
5020 (setq create-list
(cdr create-list
))))))))
5022 (defconst directory-files-no-dot-files-regexp
5023 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"
5024 "Regexp matching any file name except \".\" and \"..\".")
5026 (defun delete-directory (directory &optional recursive trash
)
5027 "Delete the directory named DIRECTORY. Does not follow symlinks.
5028 If RECURSIVE is non-nil, all files in DIRECTORY are deleted as well.
5029 TRASH non-nil means to trash the directory instead, provided
5030 `delete-by-moving-to-trash' is non-nil.
5032 When called interactively, TRASH is t if no prefix argument is
5033 given. With a prefix argument, TRASH is nil."
5035 (let* ((trashing (and delete-by-moving-to-trash
5036 (null current-prefix-arg
)))
5037 (dir (expand-file-name
5038 (read-directory-name
5040 "Move directory to trash: "
5041 "Delete directory: ")
5042 default-directory default-directory nil nil
))))
5044 (if (directory-files dir nil directory-files-no-dot-files-regexp
)
5046 (format "Directory `%s' is not empty, really %s? "
5047 dir
(if trashing
"trash" "delete")))
5049 (null current-prefix-arg
))))
5050 ;; If default-directory is a remote directory, make sure we find its
5051 ;; delete-directory handler.
5052 (setq directory
(directory-file-name (expand-file-name directory
)))
5053 (let ((handler (find-file-name-handler directory
'delete-directory
)))
5056 (funcall handler
'delete-directory directory recursive
))
5057 ((and delete-by-moving-to-trash trash
)
5058 ;; Only move non-empty dir to trash if recursive deletion was
5059 ;; requested. This mimics the non-`delete-by-moving-to-trash'
5060 ;; case, where the operation fails in delete-directory-internal.
5061 ;; As `move-file-to-trash' trashes directories (empty or
5062 ;; otherwise) as a unit, we do not need to recurse here.
5063 (if (and (not recursive
)
5064 ;; Check if directory is empty apart from "." and "..".
5066 directory
'full directory-files-no-dot-files-regexp
))
5067 (error "Directory is not empty, not moving to trash")
5068 (move-file-to-trash directory
)))
5069 ;; Otherwise, call ourselves recursively if needed.
5071 (if (and recursive
(not (file-symlink-p directory
)))
5072 (mapc (lambda (file)
5073 ;; This test is equivalent to
5074 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
5075 ;; but more efficient
5076 (if (eq t
(car (file-attributes file
)))
5077 (delete-directory file recursive nil
)
5078 (delete-file file nil
)))
5079 ;; We do not want to delete "." and "..".
5081 directory
'full directory-files-no-dot-files-regexp
)))
5082 (delete-directory-internal directory
)))))
5084 (defun file-equal-p (file1 file2
)
5085 "Return non-nil if files FILE1 and FILE2 name the same file.
5086 If FILE1 or FILE2 does not exist, the return value is unspecified."
5087 (let ((handler (or (find-file-name-handler file1
'file-equal-p
)
5088 (find-file-name-handler file2
'file-equal-p
))))
5090 (funcall handler
'file-equal-p file1 file2
)
5091 (let (f1-attr f2-attr
)
5092 (and (setq f1-attr
(file-attributes (file-truename file1
)))
5093 (setq f2-attr
(file-attributes (file-truename file2
)))
5094 (equal f1-attr f2-attr
))))))
5096 (defun file-in-directory-p (file dir
)
5097 "Return non-nil if FILE is in DIR or a subdirectory of DIR.
5098 A directory is considered to be \"in\" itself.
5099 Return nil if DIR is not an existing directory."
5100 (let ((handler (or (find-file-name-handler file
'file-in-directory-p
)
5101 (find-file-name-handler dir
'file-in-directory-p
))))
5103 (funcall handler
'file-in-directory-p file dir
)
5104 (when (file-directory-p dir
) ; DIR must exist.
5105 (setq file
(file-truename file
)
5106 dir
(file-truename dir
))
5107 (let ((ls1 (split-string file
"/" t
))
5108 (ls2 (split-string dir
"/" t
))
5109 (root (if (string-match "\\`/" file
) "/" ""))
5111 (while (and ls1 ls2
(not mismatch
))
5112 (if (string-equal (car ls1
) (car ls2
))
5113 (setq root
(concat root
(car ls1
) "/"))
5118 (file-equal-p root dir
)))))))
5120 (defun copy-directory (directory newname
&optional keep-time parents copy-contents
)
5121 "Copy DIRECTORY to NEWNAME. Both args must be strings.
5122 This function always sets the file modes of the output files to match
5123 the corresponding input file.
5125 The third arg KEEP-TIME non-nil means give the output files the same
5126 last-modified time as the old ones. (This works on only some systems.)
5128 A prefix arg makes KEEP-TIME non-nil.
5130 Noninteractively, the last argument PARENTS says whether to
5131 create parent directories if they don't exist. Interactively,
5132 this happens by default.
5134 If NEWNAME names an existing directory, copy DIRECTORY as a
5135 subdirectory there. However, if called from Lisp with a non-nil
5136 optional argument COPY-CONTENTS, copy the contents of DIRECTORY
5137 directly into NEWNAME instead."
5139 (let ((dir (read-directory-name
5140 "Copy directory: " default-directory default-directory t nil
)))
5142 (read-directory-name
5143 (format "Copy directory %s to: " dir
)
5144 default-directory default-directory nil nil
)
5145 current-prefix-arg t nil
)))
5146 (when (file-in-directory-p newname directory
)
5147 (error "Cannot copy `%s' into its subdirectory `%s'"
5149 ;; If default-directory is a remote directory, make sure we find its
5150 ;; copy-directory handler.
5151 (let ((handler (or (find-file-name-handler directory
'copy-directory
)
5152 (find-file-name-handler newname
'copy-directory
))))
5154 (funcall handler
'copy-directory directory
5155 newname keep-time parents copy-contents
)
5157 ;; Compute target name.
5158 (setq directory
(directory-file-name (expand-file-name directory
))
5159 newname
(directory-file-name (expand-file-name newname
)))
5161 (cond ((not (file-directory-p newname
))
5162 ;; If NEWNAME is not an existing directory, create it;
5163 ;; that is where we will copy the files of DIRECTORY.
5164 (make-directory newname parents
))
5165 ;; If NEWNAME is an existing directory and COPY-CONTENTS
5166 ;; is nil, copy into NEWNAME/[DIRECTORY-BASENAME].
5167 ((not copy-contents
)
5168 (setq newname
(expand-file-name
5169 (file-name-nondirectory
5170 (directory-file-name directory
))
5172 (and (file-exists-p newname
)
5173 (not (file-directory-p newname
))
5174 (error "Cannot overwrite non-directory %s with a directory"
5176 (make-directory newname t
)))
5178 ;; Copy recursively.
5180 ;; We do not want to copy "." and "..".
5181 (directory-files directory
'full
5182 directory-files-no-dot-files-regexp
))
5183 (let ((target (expand-file-name (file-name-nondirectory file
) newname
))
5184 (filetype (car (file-attributes file
))))
5186 ((eq filetype t
) ; Directory but not a symlink.
5187 (copy-directory file newname keep-time parents
))
5188 ((stringp filetype
) ; Symbolic link
5189 (make-symbolic-link filetype target t
))
5190 ((copy-file file target t keep-time
)))))
5192 ;; Set directory attributes.
5193 (let ((modes (file-modes directory
))
5194 (times (and keep-time
(nth 5 (file-attributes directory
)))))
5195 (if modes
(set-file-modes newname modes
))
5196 (if times
(set-file-times newname times
))))))
5199 ;; At time of writing, only info uses this.
5200 (defun prune-directory-list (dirs &optional keep reject
)
5201 "Return a copy of DIRS with all non-existent directories removed.
5202 The optional argument KEEP is a list of directories to retain even if
5203 they don't exist, and REJECT is a list of directories to remove from
5204 DIRS, even if they exist; REJECT takes precedence over KEEP.
5206 Note that membership in REJECT and KEEP is checked using simple string
5209 (mapcar (lambda (dir)
5210 (and (not (member dir reject
))
5211 (or (member dir keep
) (file-directory-p dir
))
5216 (put 'revert-buffer-function
'permanent-local t
)
5217 (defvar revert-buffer-function nil
5218 "Function to use to revert this buffer, or nil to do the default.
5219 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
5220 which are the arguments that `revert-buffer' received.")
5222 (put 'revert-buffer-insert-file-contents-function
'permanent-local t
)
5223 (defvar revert-buffer-insert-file-contents-function nil
5224 "Function to use to insert contents when reverting this buffer.
5225 Gets two args, first the nominal file name to use,
5226 and second, t if reading the auto-save file.
5228 The function you specify is responsible for updating (or preserving) point.")
5230 (defvar buffer-stale-function nil
5231 "Function to check whether a non-file buffer needs reverting.
5232 This should be a function with one optional argument NOCONFIRM.
5233 Auto Revert Mode passes t for NOCONFIRM. The function should return
5234 non-nil if the buffer should be reverted. A return value of
5235 `fast' means that the need for reverting was not checked, but
5236 that reverting the buffer is fast. The buffer is current when
5237 this function is called.
5239 The idea behind the NOCONFIRM argument is that it should be
5240 non-nil if the buffer is going to be reverted without asking the
5241 user. In such situations, one has to be careful with potentially
5242 time consuming operations.
5244 For more information on how this variable is used by Auto Revert mode,
5245 see Info node `(emacs)Supporting additional buffers'.")
5247 (defvar before-revert-hook nil
5248 "Normal hook for `revert-buffer' to run before reverting.
5249 If `revert-buffer-function' is used to override the normal revert
5250 mechanism, this hook is not used.")
5252 (defvar after-revert-hook nil
5253 "Normal hook for `revert-buffer' to run after reverting.
5254 Note that the hook value that it runs is the value that was in effect
5255 before reverting; that makes a difference if you have buffer-local
5258 If `revert-buffer-function' is used to override the normal revert
5259 mechanism, this hook is not used.")
5261 (defvar revert-buffer-in-progress-p nil
5262 "Non-nil if a `revert-buffer' operation is in progress, nil otherwise.
5263 This is true even if a `revert-buffer-function' is being used.")
5265 (defvar revert-buffer-internal-hook
)
5267 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes
)
5268 "Replace current buffer text with the text of the visited file on disk.
5269 This undoes all changes since the file was visited or saved.
5270 With a prefix argument, offer to revert from latest auto-save file, if
5271 that is more recent than the visited file.
5273 This command also implements an interface for special buffers
5274 that contain text which doesn't come from a file, but reflects
5275 some other data instead (e.g. Dired buffers, `buffer-list'
5276 buffers). This is done via the variable `revert-buffer-function'.
5277 In these cases, it should reconstruct the buffer contents from the
5280 When called from Lisp, the first argument is IGNORE-AUTO; only offer
5281 to revert from the auto-save file when this is nil. Note that the
5282 sense of this argument is the reverse of the prefix argument, for the
5283 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
5286 Optional second argument NOCONFIRM means don't ask for confirmation
5287 at all. (The variable `revert-without-query' offers another way to
5288 revert buffers without querying for confirmation.)
5290 Optional third argument PRESERVE-MODES non-nil means don't alter
5291 the files modes. Normally we reinitialize them using `normal-mode'.
5293 This function binds `revert-buffer-in-progress-p' non-nil while it operates.
5295 If the value of `revert-buffer-function' is non-nil, it is called to
5296 do all the work for this command. Otherwise, the hooks
5297 `before-revert-hook' and `after-revert-hook' are run at the beginning
5298 and the end, and if `revert-buffer-insert-file-contents-function' is
5299 non-nil, it is called instead of rereading visited file contents."
5301 ;; I admit it's odd to reverse the sense of the prefix argument, but
5302 ;; there is a lot of code out there which assumes that the first
5303 ;; argument should be t to avoid consulting the auto-save file, and
5304 ;; there's no straightforward way to encourage authors to notice a
5305 ;; reversal of the argument sense. So I'm just changing the user
5306 ;; interface, but leaving the programmatic interface the same.
5307 (interactive (list (not current-prefix-arg
)))
5308 (if revert-buffer-function
5309 (let ((revert-buffer-in-progress-p t
))
5310 (funcall revert-buffer-function ignore-auto noconfirm
))
5311 (with-current-buffer (or (buffer-base-buffer (current-buffer))
5313 (let* ((revert-buffer-in-progress-p t
)
5314 (auto-save-p (and (not ignore-auto
)
5315 (recent-auto-save-p)
5316 buffer-auto-save-file-name
5317 (file-readable-p buffer-auto-save-file-name
)
5319 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
5320 (file-name (if auto-save-p
5321 buffer-auto-save-file-name
5323 (cond ((null file-name
)
5324 (error "Buffer does not seem to be associated with any file"))
5326 (and (not (buffer-modified-p))
5328 (dolist (regexp revert-without-query
)
5329 (when (string-match regexp file-name
)
5330 (throw 'found t
)))))
5331 (yes-or-no-p (format "Revert buffer from file %s? "
5333 (run-hooks 'before-revert-hook
)
5334 ;; If file was backed up but has changed since,
5335 ;; we should make another backup.
5336 (and (not auto-save-p
)
5337 (not (verify-visited-file-modtime (current-buffer)))
5338 (setq buffer-backed-up nil
))
5339 ;; Effectively copy the after-revert-hook status,
5340 ;; since after-find-file will clobber it.
5341 (let ((global-hook (default-value 'after-revert-hook
))
5342 (local-hook (when (local-variable-p 'after-revert-hook
)
5344 (inhibit-read-only t
))
5346 (revert-buffer-insert-file-contents-function
5347 (unless (eq buffer-undo-list t
)
5348 ;; Get rid of all undo records for this buffer.
5349 (setq buffer-undo-list nil
))
5350 ;; Don't make undo records for the reversion.
5351 (let ((buffer-undo-list t
))
5352 (funcall revert-buffer-insert-file-contents-function
5353 file-name auto-save-p
)))
5354 ((not (file-exists-p file-name
))
5355 (error (if buffer-file-number
5356 "File %s no longer exists!"
5357 "Cannot revert nonexistent file %s")
5359 ((not (file-readable-p file-name
))
5360 (error (if buffer-file-number
5361 "File %s no longer readable!"
5362 "Cannot revert unreadable file %s")
5365 ;; Bind buffer-file-name to nil
5366 ;; so that we don't try to lock the file.
5367 (let ((buffer-file-name nil
))
5371 (let ((coding-system-for-read
5372 ;; Auto-saved file should be read by Emacs's
5374 (if auto-save-p
'auto-save-coding
5375 (or coding-system-for-read
5377 buffer-file-coding-system-explicit
5378 (car buffer-file-coding-system-explicit
))))))
5379 (if (and (not enable-multibyte-characters
)
5380 coding-system-for-read
5381 (not (memq (coding-system-base
5382 coding-system-for-read
)
5383 '(no-conversion raw-text
))))
5384 ;; As a coding system suitable for multibyte
5385 ;; buffer is specified, make the current
5386 ;; buffer multibyte.
5387 (set-buffer-multibyte t
))
5389 ;; This force after-insert-file-set-coding
5390 ;; (called from insert-file-contents) to set
5391 ;; buffer-file-coding-system to a proper value.
5392 (kill-local-variable 'buffer-file-coding-system
)
5394 ;; Note that this preserves point in an intelligent way.
5396 (let ((buffer-file-format buffer-file-format
))
5397 (insert-file-contents file-name
(not auto-save-p
)
5399 (insert-file-contents file-name
(not auto-save-p
)
5401 ;; Recompute the truename in case changes in symlinks
5402 ;; have changed the truename.
5403 (setq buffer-file-truename
5404 (abbreviate-file-name (file-truename buffer-file-name
)))
5405 (after-find-file nil nil t nil preserve-modes
)
5406 ;; Run after-revert-hook as it was before we reverted.
5407 (setq-default revert-buffer-internal-hook global-hook
)
5409 (set (make-local-variable 'revert-buffer-internal-hook
)
5411 (kill-local-variable 'revert-buffer-internal-hook
))
5412 (run-hooks 'revert-buffer-internal-hook
))
5415 (defun recover-this-file ()
5416 "Recover the visited file--get contents from its last auto-save file."
5418 (recover-file buffer-file-name
))
5420 (defun recover-file (file)
5421 "Visit file FILE, but get contents from its last auto-save file."
5422 ;; Actually putting the file name in the minibuffer should be used
5424 ;; Not just because users often use the default.
5425 (interactive "FRecover file: ")
5426 (setq file
(expand-file-name file
))
5427 (if (auto-save-file-name-p (file-name-nondirectory file
))
5428 (error "%s is an auto-save file" (abbreviate-file-name file
)))
5429 (let ((file-name (let ((buffer-file-name file
))
5430 (make-auto-save-file-name))))
5431 (cond ((if (file-exists-p file
)
5432 (not (file-newer-than-file-p file-name file
))
5433 (not (file-exists-p file-name
)))
5434 (error "Auto-save file %s not current"
5435 (abbreviate-file-name file-name
)))
5436 ((with-temp-buffer-window
5438 #'(lambda (window _value
)
5439 (with-selected-window window
5441 (yes-or-no-p (format "Recover auto save file %s? " file-name
))
5442 (when (window-live-p window
)
5443 (quit-restore-window window
'kill
)))))
5444 (with-current-buffer standard-output
5445 (let ((switches dired-listing-switches
))
5446 (if (file-symlink-p file
)
5447 (setq switches
(concat switches
" -L")))
5448 ;; Use insert-directory-safely, not insert-directory,
5449 ;; because these files might not exist. In particular,
5450 ;; FILE might not exist if the auto-save file was for
5451 ;; a buffer that didn't visit a file, such as "*mail*".
5452 ;; The code in v20.x called `ls' directly, so we need
5453 ;; to emulate what `ls' did in that case.
5454 (insert-directory-safely file switches
)
5455 (insert-directory-safely file-name switches
))))
5456 (switch-to-buffer (find-file-noselect file t
))
5457 (let ((inhibit-read-only t
)
5458 ;; Keep the current buffer-file-coding-system.
5459 (coding-system buffer-file-coding-system
)
5460 ;; Auto-saved file should be read with special coding.
5461 (coding-system-for-read 'auto-save-coding
))
5463 (insert-file-contents file-name nil
)
5464 (set-buffer-file-coding-system coding-system
))
5465 (after-find-file nil nil t
))
5466 (t (user-error "Recover-file cancelled")))))
5468 (defun recover-session ()
5469 "Recover auto save files from a previous Emacs session.
5470 This command first displays a Dired buffer showing you the
5471 previous sessions that you could recover from.
5472 To choose one, move point to the proper line and then type C-c C-c.
5473 Then you'll be asked about a number of files to recover."
5475 (if (null auto-save-list-file-prefix
)
5476 (error "You set `auto-save-list-file-prefix' to disable making session files"))
5477 (let ((dir (file-name-directory auto-save-list-file-prefix
)))
5478 (unless (file-directory-p dir
)
5479 (make-directory dir t
))
5480 (unless (directory-files dir nil
5481 (concat "\\`" (regexp-quote
5482 (file-name-nondirectory
5483 auto-save-list-file-prefix
)))
5485 (error "No previous sessions to recover")))
5486 (let ((ls-lisp-support-shell-wildcards t
))
5487 (dired (concat auto-save-list-file-prefix
"*")
5488 (concat dired-listing-switches
" -t")))
5489 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
5490 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish
)
5492 (goto-char (point-min))
5493 (or (looking-at " Move to the session you want to recover,")
5494 (let ((inhibit-read-only t
))
5495 ;; Each line starts with a space
5496 ;; so that Font Lock mode won't highlight the first character.
5497 (insert " To recover a session, move to it and type C-c C-c.\n"
5498 (substitute-command-keys
5499 " To delete a session file, type \
5500 \\[dired-flag-file-deletion] on its line to flag
5501 the file for deletion, then \\[dired-do-flagged-delete] to \
5502 delete flagged files.\n\n"))))))
5504 (defun recover-session-finish ()
5505 "Choose one saved session to recover auto-save files from.
5506 This command is used in the special Dired buffer created by
5507 \\[recover-session]."
5509 ;; Get the name of the session file to recover from.
5510 (let ((file (dired-get-filename))
5512 (buffer (get-buffer-create " *recover*")))
5514 (dired-do-flagged-delete t
)
5516 (with-current-buffer buffer
5517 ;; Read in the auto-save-list file.
5519 (insert-file-contents file
)
5520 ;; Loop thru the text of that file
5521 ;; and get out the names of the files to recover.
5523 (let (thisfile autofile
)
5525 ;; This is a pair of lines for a non-file-visiting buffer.
5526 ;; Get the auto-save file name and manufacture
5527 ;; a "visited file name" from that.
5530 ;; If there is no auto-save file name, the
5531 ;; auto-save-list file is probably corrupted.
5534 (buffer-substring-no-properties
5536 (line-end-position)))
5540 (file-name-nondirectory autofile
)
5542 (file-name-directory autofile
))))
5544 ;; This pair of lines is a file-visiting
5545 ;; buffer. Use the visited file name.
5548 (buffer-substring-no-properties
5549 (point) (progn (end-of-line) (point))))
5552 (buffer-substring-no-properties
5553 (point) (progn (end-of-line) (point))))
5555 ;; Ignore a file if its auto-save file does not exist now.
5556 (if (and autofile
(file-exists-p autofile
))
5557 (setq files
(cons thisfile files
)))))
5558 (setq files
(nreverse files
))
5559 ;; The file contains a pair of line for each auto-saved buffer.
5560 ;; The first line of the pair contains the visited file name
5561 ;; or is empty if the buffer was not visiting a file.
5562 ;; The second line is the auto-save file name.
5564 (map-y-or-n-p "Recover %s? "
5567 (save-excursion (recover-file file
))
5569 "Failed to recover `%s'" file
)))
5571 '("file" "files" "recover"))
5572 (message "No files can be recovered from this session now")))
5573 (kill-buffer buffer
))))
5575 (defun kill-buffer-ask (buffer)
5576 "Kill BUFFER if confirmed."
5577 (when (yes-or-no-p (format "Buffer %s %s. Kill? "
5578 (buffer-name buffer
)
5579 (if (buffer-modified-p buffer
)
5580 "HAS BEEN EDITED" "is unmodified")))
5581 (kill-buffer buffer
)))
5583 (defun kill-some-buffers (&optional list
)
5584 "Kill some buffers. Asks the user whether to kill each one of them.
5585 Non-interactively, if optional argument LIST is non-nil, it
5586 specifies the list of buffers to kill, asking for approval for each one."
5589 (setq list
(buffer-list)))
5591 (let* ((buffer (car list
))
5592 (name (buffer-name buffer
)))
5593 (and name
; Can be nil for an indirect buffer
5594 ; if we killed the base buffer.
5595 (not (string-equal name
""))
5596 (/= (aref name
0) ?\s
)
5597 (kill-buffer-ask buffer
)))
5598 (setq list
(cdr list
))))
5600 (defun kill-matching-buffers (regexp &optional internal-too
)
5601 "Kill buffers whose name matches the specified REGEXP.
5602 The optional second argument indicates whether to kill internal buffers too."
5603 (interactive "sKill buffers matching this regular expression: \nP")
5604 (dolist (buffer (buffer-list))
5605 (let ((name (buffer-name buffer
)))
5606 (when (and name
(not (string-equal name
""))
5607 (or internal-too
(/= (aref name
0) ?\s
))
5608 (string-match regexp name
))
5609 (kill-buffer-ask buffer
)))))
5612 (defun rename-auto-save-file ()
5613 "Adjust current buffer's auto save file name for current conditions.
5614 Also rename any existing auto save file, if it was made in this session."
5615 (let ((osave buffer-auto-save-file-name
))
5616 (setq buffer-auto-save-file-name
5617 (make-auto-save-file-name))
5618 (if (and osave buffer-auto-save-file-name
5619 (not (string= buffer-auto-save-file-name buffer-file-name
))
5620 (not (string= buffer-auto-save-file-name osave
))
5621 (file-exists-p osave
)
5622 (recent-auto-save-p))
5623 (rename-file osave buffer-auto-save-file-name t
))))
5625 (defun make-auto-save-file-name ()
5626 "Return file name to use for auto-saves of current buffer.
5627 Does not consider `auto-save-visited-file-name' as that variable is checked
5628 before calling this function. You can redefine this for customization.
5629 See also `auto-save-file-name-p'."
5630 (if buffer-file-name
5631 (let ((handler (find-file-name-handler buffer-file-name
5632 'make-auto-save-file-name
)))
5634 (funcall handler
'make-auto-save-file-name
)
5635 (let ((list auto-save-file-name-transforms
)
5636 (filename buffer-file-name
)
5638 ;; Apply user-specified translations
5639 ;; to the file name.
5640 (while (and list
(not result
))
5641 (if (string-match (car (car list
)) filename
)
5642 (setq result
(replace-match (cadr (car list
)) t nil
5644 uniq
(car (cddr (car list
)))))
5645 (setq list
(cdr list
)))
5648 (setq filename
(concat
5649 (file-name-directory result
)
5650 (subst-char-in-string
5652 (replace-regexp-in-string "!" "!!"
5654 (setq filename result
)))
5656 (if (and (eq system-type
'ms-dos
)
5657 (not (msdos-long-file-names)))
5658 ;; We truncate the file name to DOS 8+3 limits
5659 ;; before doing anything else, because the regexp
5660 ;; passed to string-match below cannot handle
5661 ;; extensions longer than 3 characters, multiple
5662 ;; dots, and other atrocities.
5663 (let ((fn (dos-8+3-filename
5664 (file-name-nondirectory buffer-file-name
))))
5666 "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'"
5668 (concat (file-name-directory buffer-file-name
)
5669 "#" (match-string 1 fn
)
5670 "." (match-string 3 fn
) "#"))
5671 (concat (file-name-directory filename
)
5673 (file-name-nondirectory filename
)
5675 ;; Make sure auto-save file names don't contain characters
5676 ;; invalid for the underlying filesystem.
5677 (if (and (memq system-type
'(ms-dos windows-nt cygwin
))
5678 ;; Don't modify remote (ange-ftp) filenames
5679 (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" result
)))
5680 (convert-standard-filename result
)
5683 ;; Deal with buffers that don't have any associated files. (Mail
5684 ;; mode tends to create a good number of these.)
5686 (let ((buffer-name (buffer-name))
5689 ;; Restrict the characters used in the file name to those which
5690 ;; are known to be safe on all filesystems, url-encoding the
5692 ;; We do this on all platforms, because even if we are not
5693 ;; running on DOS/Windows, the current directory may be on a
5694 ;; mounted VFAT filesystem, such as a USB memory stick.
5695 (while (string-match "[^A-Za-z0-9-_.~#+]" buffer-name limit
)
5696 (let* ((character (aref buffer-name
(match-beginning 0)))
5698 ;; For multibyte characters, this will produce more than
5699 ;; 2 hex digits, so is not true URL encoding.
5700 (format "%%%02X" character
)))
5701 (setq buffer-name
(replace-match replacement t t buffer-name
))
5702 (setq limit
(1+ (match-end 0)))))
5703 ;; Generate the file name.
5708 (format "#%s#" buffer-name
)
5709 ;; Try a few alternative directories, to get one we can
5712 ((file-writable-p default-directory
) default-directory
)
5713 ((file-writable-p "/var/tmp/") "/var/tmp/")
5715 (if (and (memq system-type
'(ms-dos windows-nt cygwin
))
5716 ;; Don't modify remote (ange-ftp) filenames
5717 (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" fname
)))
5718 ;; The call to convert-standard-filename is in case
5719 ;; buffer-name includes characters not allowed by the
5720 ;; DOS/Windows filesystems. make-temp-file writes to the
5721 ;; file it creates, so we must fix the file name _before_
5722 ;; make-temp-file is called.
5723 (convert-standard-filename fname
)
5726 ;; make-temp-file creates the file,
5727 ;; but we don't want it to exist until we do an auto-save.
5729 (delete-file file-name
)
5733 (defun auto-save-file-name-p (filename)
5734 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
5735 FILENAME should lack slashes. You can redefine this for customization."
5736 (string-match "\\`#.*#\\'" filename
))
5738 (defun wildcard-to-regexp (wildcard)
5739 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
5740 The generated regexp will match a filename only if the filename
5741 matches that wildcard according to shell rules. Only wildcards known
5742 by `sh' are supported."
5743 (let* ((i (string-match "[[.*+\\^$?]" wildcard
))
5744 ;; Copy the initial run of non-special characters.
5745 (result (substring wildcard
0 i
))
5746 (len (length wildcard
)))
5747 ;; If no special characters, we're almost done.
5750 (let ((ch (aref wildcard i
))
5758 (eq (aref wildcard
(1+ i
)) ?\
]))
5760 ((eq ch ?\
[) ; [...] maps to regexp char class
5765 ((eq (aref wildcard i
) ?
!) ; [!...] -> [^...]
5768 (if (eq (aref wildcard i
) ?\
])
5773 ((eq (aref wildcard i
) ?^
)
5774 ;; Found "[^". Insert a `\0' character
5775 ;; (which cannot happen in a filename)
5776 ;; into the character class, so that `^'
5777 ;; is not the first character after `[',
5778 ;; and thus non-special in a regexp.
5782 ((eq (aref wildcard i
) ?\
])
5783 ;; I don't think `]' can appear in a
5784 ;; character class in a wildcard, but
5785 ;; let's be general here.
5790 (prog1 ; copy everything upto next `]'.
5793 (setq j
(string-match
5795 (setq i
(if j
(1- j
) (1- len
)))))))
5797 ((eq ch ?
*) "[^\000]*")
5801 ((eq ch ?
\\) "\\\\") ; probably cannot happen...
5802 ((eq ch ??
) "[^\000]")
5803 (t (char-to-string ch
)))))
5805 ;; Shell wildcards should match the entire filename,
5806 ;; not its part. Make the regexp say so.
5807 (concat "\\`" result
"\\'")))
5809 (defcustom list-directory-brief-switches
5811 "Switches for `list-directory' to pass to `ls' for brief listing."
5815 (defcustom list-directory-verbose-switches
5817 "Switches for `list-directory' to pass to `ls' for verbose listing."
5821 (defun file-expand-wildcards (pattern &optional full
)
5822 "Expand wildcard pattern PATTERN.
5823 This returns a list of file names which match the pattern.
5825 If PATTERN is written as an absolute file name,
5826 the values are absolute also.
5828 If PATTERN is written as a relative file name, it is interpreted
5829 relative to the current default directory, `default-directory'.
5830 The file names returned are normally also relative to the current
5831 default directory. However, if FULL is non-nil, they are absolute."
5833 (let* ((nondir (file-name-nondirectory pattern
))
5834 (dirpart (file-name-directory pattern
))
5835 ;; A list of all dirs that DIRPART specifies.
5836 ;; This can be more than one dir
5837 ;; if DIRPART contains wildcards.
5838 (dirs (if (and dirpart
5839 (string-match "[[*?]"
5840 (or (file-remote-p dirpart
'localname
)
5842 (mapcar 'file-name-as-directory
5843 (file-expand-wildcards (directory-file-name dirpart
)))
5847 (when (or (null (car dirs
)) ; Possible if DIRPART is not wild.
5848 (and (file-directory-p (directory-file-name (car dirs
)))
5849 (file-readable-p (car dirs
))))
5850 (let ((this-dir-contents
5851 ;; Filter out "." and ".."
5853 (mapcar #'(lambda (name)
5854 (unless (string-match "\\`\\.\\.?\\'"
5855 (file-name-nondirectory name
))
5857 (directory-files (or (car dirs
) ".") full
5858 (wildcard-to-regexp nondir
))))))
5861 (if (and (car dirs
) (not full
))
5862 (mapcar (function (lambda (name) (concat (car dirs
) name
)))
5866 (setq dirs
(cdr dirs
)))
5869 ;; Let Tramp know that `file-expand-wildcards' does not need an advice.
5870 (provide 'files
'(remote-wildcards))
5872 (defun list-directory (dirname &optional verbose
)
5873 "Display a list of files in or matching DIRNAME, a la `ls'.
5874 DIRNAME is globbed by the shell if necessary.
5875 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
5876 Actions controlled by variables `list-directory-brief-switches'
5877 and `list-directory-verbose-switches'."
5878 (interactive (let ((pfx current-prefix-arg
))
5879 (list (read-directory-name (if pfx
"List directory (verbose): "
5880 "List directory (brief): ")
5881 nil default-directory nil
)
5883 (let ((switches (if verbose list-directory-verbose-switches
5884 list-directory-brief-switches
))
5886 (or dirname
(setq dirname default-directory
))
5887 (setq dirname
(expand-file-name dirname
))
5888 (with-output-to-temp-buffer "*Directory*"
5889 (setq buffer standard-output
)
5890 (buffer-disable-undo standard-output
)
5891 (princ "Directory ")
5894 (with-current-buffer "*Directory*"
5895 (let ((wildcard (not (file-directory-p dirname
))))
5896 (insert-directory dirname switches wildcard
(not wildcard
)))))
5897 ;; Finishing with-output-to-temp-buffer seems to clobber default-directory.
5898 (with-current-buffer buffer
5899 (setq default-directory
5900 (if (file-directory-p dirname
)
5901 (file-name-as-directory dirname
)
5902 (file-name-directory dirname
))))))
5904 (defun shell-quote-wildcard-pattern (pattern)
5905 "Quote characters special to the shell in PATTERN, leave wildcards alone.
5907 PATTERN is assumed to represent a file-name wildcard suitable for the
5908 underlying filesystem. For Unix and GNU/Linux, each character from the
5909 set [ \\t\\n;<>&|()'\"#$] is quoted with a backslash; for DOS/Windows, all
5910 the parts of the pattern which don't include wildcard characters are
5911 quoted with double quotes.
5913 This function leaves alone existing quote characters (\\ on Unix and \"
5914 on Windows), so PATTERN can use them to quote wildcard characters that
5915 need to be passed verbatim to shell commands."
5918 ((memq system-type
'(ms-dos windows-nt cygwin
))
5919 ;; DOS/Windows don't allow `"' in file names. So if the
5920 ;; argument has quotes, we can safely assume it is already
5921 ;; quoted by the caller.
5922 (if (or (string-match "[\"]" pattern
)
5923 ;; We quote [&()#$'] in case their shell is a port of a
5924 ;; Unixy shell. We quote [,=+] because stock DOS and
5925 ;; Windows shells require that in some cases, such as
5926 ;; passing arguments to batch files that use positional
5927 ;; arguments like %1.
5928 (not (string-match "[ \t;&()#$',=+]" pattern
)))
5933 (while (string-match "[*?]+" pattern beg
)
5934 (setq end
(match-beginning 0)
5935 result
(concat result
(substring pattern beg end
)
5937 (substring pattern end
(match-end 0))
5940 (concat result
(substring pattern beg
) "\""))))
5943 (while (string-match "[ \t\n;<>&|()'\"#$]" pattern beg
)
5945 (concat (substring pattern
0 (match-beginning 0))
5947 (substring pattern
(match-beginning 0)))
5948 beg
(1+ (match-end 0)))))
5952 (defvar insert-directory-program
(purecopy "ls")
5953 "Absolute or relative name of the `ls' program used by `insert-directory'.")
5955 (defcustom directory-free-space-program
(purecopy "df")
5956 "Program to get the amount of free space on a file system.
5957 We assume the output has the format of `df'.
5958 The value of this variable must be just a command name or file name;
5959 if you want to specify options, use `directory-free-space-args'.
5961 A value of nil disables this feature.
5963 If the function `file-system-info' is defined, it is always used in
5964 preference to the program given by this variable."
5965 :type
'(choice (string :tag
"Program") (const :tag
"None" nil
))
5968 (defcustom directory-free-space-args
5969 (purecopy (if (eq system-type
'darwin
) "-k" "-Pk"))
5970 "Options to use when running `directory-free-space-program'."
5974 (defun get-free-disk-space (dir)
5975 "Return the amount of free space on directory DIR's file system.
5976 The return value is a string describing the amount of free
5977 space (normally, the number of free 1KB blocks).
5979 This function calls `file-system-info' if it is available, or
5980 invokes the program specified by `directory-free-space-program'
5981 and `directory-free-space-args'. If the system call or program
5982 is unsuccessful, or if DIR is a remote directory, this function
5984 (unless (file-remote-p dir
)
5985 ;; Try to find the number of free blocks. Non-Posix systems don't
5986 ;; always have df, but might have an equivalent system call.
5987 (if (fboundp 'file-system-info
)
5988 (let ((fsinfo (file-system-info dir
)))
5990 (format "%.0f" (/ (nth 2 fsinfo
) 1024))))
5991 (setq dir
(expand-file-name dir
))
5994 (when (and directory-free-space-program
5995 ;; Avoid failure if the default directory does
5996 ;; not exist (Bug#2631, Bug#3911).
5997 (let ((default-directory
5998 (locate-dominating-file dir
'file-directory-p
)))
5999 (eq (process-file directory-free-space-program
6001 directory-free-space-args
6002 (file-relative-name dir
))
6004 ;; Assume that the "available" column is before the
6005 ;; "capacity" column. Find the "%" and scan backward.
6006 (goto-char (point-min))
6008 (when (re-search-forward
6009 "[[:space:]]+[^[:space:]]+%[^%]*$"
6010 (line-end-position) t
)
6011 (goto-char (match-beginning 0))
6012 (let ((endpt (point)))
6013 (skip-chars-backward "^[:space:]")
6014 (buffer-substring-no-properties (point) endpt
)))))))))
6016 ;; The following expression replaces `dired-move-to-filename-regexp'.
6017 (defvar directory-listing-before-filename-regexp
6018 (let* ((l "\\([A-Za-z]\\|[^\0-\177]\\)")
6019 (l-or-quote "\\([A-Za-z']\\|[^\0-\177]\\)")
6020 ;; In some locales, month abbreviations are as short as 2 letters,
6021 ;; and they can be followed by ".".
6022 ;; In Breton, a month name can include a quote character.
6023 (month (concat l-or-quote l-or-quote
"+\\.?"))
6025 (yyyy "[0-9][0-9][0-9][0-9]")
6027 (HH:MM
"[ 0-2][0-9][:.][0-5][0-9]")
6028 (seconds "[0-6][0-9]\\([.,][0-9]+\\)?")
6029 (zone "[-+][0-2][0-9][0-5][0-9]")
6030 (iso-mm-dd "[01][0-9]-[0-3][0-9]")
6031 (iso-time (concat HH
:MM
"\\(:" seconds
"\\( ?" zone
"\\)?\\)?"))
6032 (iso (concat "\\(\\(" yyyy
"-\\)?" iso-mm-dd
"[ T]" iso-time
6033 "\\|" yyyy
"-" iso-mm-dd
"\\)"))
6034 (western (concat "\\(" month s
"+" dd
"\\|" dd
"\\.?" s month
"\\)"
6036 "\\(" HH
:MM
"\\|" yyyy
"\\)"))
6037 (western-comma (concat month s
"+" dd
"," s
"+" yyyy
))
6038 ;; Japanese MS-Windows ls-lisp has one-digit months, and
6039 ;; omits the Kanji characters after month and day-of-month.
6040 ;; On Mac OS X 10.3, the date format in East Asian locales is
6041 ;; day-of-month digits followed by month digits.
6044 (concat "\\(" mm l
"?" s dd l
"?" s
"+"
6045 "\\|" dd s mm s
"+" "\\)"
6046 "\\(" HH
:MM
"\\|" yyyy l
"?" "\\)")))
6047 ;; The "[0-9]" below requires the previous column to end in a digit.
6048 ;; This avoids recognizing `1 may 1997' as a date in the line:
6049 ;; -r--r--r-- 1 may 1997 1168 Oct 19 16:49 README
6051 ;; The "[BkKMGTPEZY]?" below supports "ls -alh" output.
6053 ;; For non-iso date formats, we add the ".*" in order to find
6054 ;; the last possible match. This avoids recognizing
6055 ;; `jservice 10 1024' as a date in the line:
6056 ;; drwxr-xr-x 3 jservice 10 1024 Jul 2 1997 esg-host
6058 ;; vc dired listings provide the state or blanks between file
6059 ;; permissions and date. The state is always surrounded by
6061 ;; -rw-r--r-- (modified) 2005-10-22 21:25 files.el
6062 ;; This is not supported yet.
6063 (purecopy (concat "\\([0-9][BkKMGTPEZY]? " iso
6064 "\\|.*[0-9][BkKMGTPEZY]? "
6065 "\\(" western
"\\|" western-comma
"\\|" east-asian
"\\)"
6067 "Regular expression to match up to the file name in a directory listing.
6068 The default value is designed to recognize dates and times
6069 regardless of the language.")
6071 (defvar insert-directory-ls-version
'unknown
)
6074 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
6075 ;; FULL-DIRECTORY-P is nil.
6076 ;; The single line of output must display FILE's name as it was
6077 ;; given, namely, an absolute path name.
6078 ;; - must insert exactly one line for each file if WILDCARD or
6079 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
6080 ;; before the file lines, plus optional text after the file lines.
6081 ;; Lines are delimited by "\n", so filenames containing "\n" are not
6083 ;; File lines should display the basename.
6084 ;; - must be consistent with
6085 ;; - functions dired-move-to-filename, (these two define what a file line is)
6086 ;; dired-move-to-end-of-filename,
6087 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
6088 ;; dired-insert-headerline
6089 ;; dired-after-subdir-garbage (defines what a "total" line is)
6090 ;; - variable dired-subdir-regexp
6091 ;; - may be passed "--dired" as the first argument in SWITCHES.
6092 ;; Filename handlers might have to remove this switch if their
6093 ;; "ls" command does not support it.
6094 (defun insert-directory (file switches
&optional wildcard full-directory-p
)
6095 "Insert directory listing for FILE, formatted according to SWITCHES.
6096 Leaves point after the inserted text.
6097 SWITCHES may be a string of options, or a list of strings
6098 representing individual options.
6099 Optional third arg WILDCARD means treat FILE as shell wildcard.
6100 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
6101 switches do not contain `d', so that a full listing is expected.
6103 This works by running a directory listing program
6104 whose name is in the variable `insert-directory-program'.
6105 If WILDCARD, it also runs the shell specified by `shell-file-name'.
6107 When SWITCHES contains the long `--dired' option, this function
6108 treats it specially, for the sake of dired. However, the
6109 normally equivalent short `-D' option is just passed on to
6110 `insert-directory-program', as any other option."
6111 ;; We need the directory in order to find the right handler.
6112 (let ((handler (find-file-name-handler (expand-file-name file
)
6113 'insert-directory
)))
6115 (funcall handler
'insert-directory file switches
6116 wildcard full-directory-p
)
6117 (let (result (beg (point)))
6119 ;; Read the actual directory using `insert-directory-program'.
6120 ;; RESULT gets the status code.
6121 (let* (;; We at first read by no-conversion, then after
6122 ;; putting text property `dired-filename, decode one
6123 ;; bunch by one to preserve that property.
6124 (coding-system-for-read 'no-conversion
)
6125 ;; This is to control encoding the arguments in call-process.
6126 (coding-system-for-write
6127 (and enable-multibyte-characters
6128 (or file-name-coding-system
6129 default-file-name-coding-system
))))
6132 ;; Run ls in the directory part of the file pattern
6133 ;; using the last component as argument.
6134 (let ((default-directory
6135 (if (file-name-absolute-p file
)
6136 (file-name-directory file
)
6137 (file-name-directory (expand-file-name file
))))
6138 (pattern (file-name-nondirectory file
)))
6139 ;; NB since switches is passed to the shell, be
6140 ;; careful of malicious values, eg "-l;reboot".
6141 ;; See eg dired-safe-switches-p.
6143 shell-file-name nil t nil
6145 (concat (if (memq system-type
'(ms-dos windows-nt
))
6147 "\\") ; Disregard Unix shell aliases!
6148 insert-directory-program
6150 (if (stringp switches
)
6152 (mapconcat 'identity switches
" "))
6154 ;; Quote some characters that have
6155 ;; special meanings in shells; but
6156 ;; don't quote the wildcards--we want
6157 ;; them to be special. We also
6158 ;; currently don't quote the quoting
6159 ;; characters in case people want to
6160 ;; use them explicitly to quote
6161 ;; wildcard characters.
6162 (shell-quote-wildcard-pattern pattern
))))
6163 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
6164 ;; directory if FILE is a symbolic link.
6165 (unless full-directory-p
6167 (if (stringp switches
)
6168 (concat switches
" -d")
6169 (add-to-list 'switches
"-d" 'append
))))
6170 (apply 'call-process
6171 insert-directory-program nil t nil
6173 (if (listp switches
) switches
6174 (unless (equal switches
"")
6175 ;; Split the switches at any spaces so we can
6176 ;; pass separate options as separate args.
6177 (split-string switches
)))
6178 ;; Avoid lossage if FILE starts with `-'.
6181 (if (string-match "\\`~" file
)
6182 (setq file
(expand-file-name file
)))
6184 (if full-directory-p
6185 (concat (file-name-as-directory file
) ".")
6188 ;; If we got "//DIRED//" in the output, it means we got a real
6189 ;; directory listing, even if `ls' returned nonzero.
6190 ;; So ignore any errors.
6191 (when (if (stringp switches
)
6192 (string-match "--dired\\>" switches
)
6193 (member "--dired" switches
))
6196 (when (looking-at "//SUBDIRED//")
6198 (if (looking-at "//DIRED//")
6201 (when (and (not (eq 0 result
))
6202 (eq insert-directory-ls-version
'unknown
))
6203 ;; The first time ls returns an error,
6204 ;; find the version numbers of ls,
6205 ;; and set insert-directory-ls-version
6206 ;; to > if it is more than 5.2.1, < if it is less, nil if it
6207 ;; is equal or if the info cannot be obtained.
6208 ;; (That can mean it isn't GNU ls.)
6211 (call-process "ls" nil t nil
"--version")
6213 (if (string-match "ls (.*utils) \\([0-9.]*\\)$" version-out
)
6214 (let* ((version (match-string 1 version-out
))
6215 (split (split-string version
"[.]"))
6216 (numbers (mapcar 'string-to-number split
))
6219 (while (and (not comparison
) (or numbers min
))
6221 (setq comparison
'>))
6223 (setq comparison
'<))
6224 ((> (car numbers
) (car min
))
6225 (setq comparison
'>))
6226 ((< (car numbers
) (car min
))
6227 (setq comparison
'<))
6229 (setq numbers
(cdr numbers
)
6231 (setq insert-directory-ls-version
(or comparison
'=)))
6232 (setq insert-directory-ls-version nil
))))
6234 ;; For GNU ls versions 5.2.2 and up, ignore minor errors.
6235 (when (and (eq 1 result
) (eq insert-directory-ls-version
'>))
6238 ;; If `insert-directory-program' failed, signal an error.
6239 (unless (eq 0 result
)
6240 ;; Delete the error message it may have output.
6241 (delete-region beg
(point))
6242 ;; On non-Posix systems, we cannot open a directory, so
6243 ;; don't even try, because that will always result in
6244 ;; the ubiquitous "Access denied". Instead, show the
6245 ;; command line so the user can try to guess what went wrong.
6246 (if (and (file-directory-p file
)
6247 (memq system-type
'(ms-dos windows-nt
)))
6249 "Reading directory: \"%s %s -- %s\" exited with status %s"
6250 insert-directory-program
6251 (if (listp switches
) (concat switches
) switches
)
6253 ;; Unix. Access the file to get a suitable error.
6254 (access-file file
"Reading directory")
6255 (error "Listing directory failed but `access-file' worked")))
6257 (when (if (stringp switches
)
6258 (string-match "--dired\\>" switches
)
6259 (member "--dired" switches
))
6260 ;; The following overshoots by one line for an empty
6261 ;; directory listed with "--dired", but without "-a"
6262 ;; switch, where the ls output contains a
6263 ;; "//DIRED-OPTIONS//" line, but no "//DIRED//" line.
6264 ;; We take care of that case later.
6266 (when (looking-at "//SUBDIRED//")
6267 (delete-region (point) (progn (forward-line 1) (point)))
6269 (if (looking-at "//DIRED//")
6270 (let ((end (line-end-position))
6273 ;; Find all the lines that are error messages,
6274 ;; and record the bounds of each one.
6276 (while (< (point) linebeg
)
6277 (or (eql (following-char) ?\s
)
6278 (push (list (point) (line-end-position)) error-lines
))
6280 (setq error-lines
(nreverse error-lines
))
6281 ;; Now read the numeric positions of file names.
6285 (while (< (point) end
)
6286 (let ((start (insert-directory-adj-pos
6287 (+ beg
(read (current-buffer)))
6289 (end (insert-directory-adj-pos
6290 (+ beg
(read (current-buffer)))
6292 (if (memq (char-after end
) '(?
\n ?\s
))
6293 ;; End is followed by \n or by " -> ".
6294 (put-text-property start end
'dired-filename t
)
6295 ;; It seems that we can't trust ls's output as to
6296 ;; byte positions of filenames.
6297 (put-text-property beg
(point) 'dired-filename nil
)
6301 (delete-region (point) (progn (forward-line 1) (point))))
6302 ;; Take care of the case where the ls output contains a
6303 ;; "//DIRED-OPTIONS//"-line, but no "//DIRED//"-line
6304 ;; and we went one line too far back (see above).
6306 (if (looking-at "//DIRED-OPTIONS//")
6307 (delete-region (point) (progn (forward-line 1) (point)))))
6309 ;; Now decode what read if necessary.
6310 (let ((coding (or coding-system-for-read
6311 file-name-coding-system
6312 default-file-name-coding-system
6316 (when (and enable-multibyte-characters
6317 (not (memq (coding-system-base coding
)
6318 '(raw-text no-conversion
))))
6319 ;; If no coding system is specified or detection is
6320 ;; requested, detect the coding.
6321 (if (eq (coding-system-base coding
) 'undecided
)
6322 (setq coding
(detect-coding-region beg
(point) t
)))
6323 (if (not (eq (coding-system-base coding
) 'undecided
))
6326 (coding-system-change-eol-conversion coding
'unix
))
6327 (narrow-to-region beg
(point))
6328 (goto-char (point-min))
6331 val
(get-text-property (point) 'dired-filename
))
6332 (goto-char (next-single-property-change
6333 (point) 'dired-filename nil
(point-max)))
6334 ;; Force no eol conversion on a file name, so
6335 ;; that CR is preserved.
6336 (decode-coding-region pos
(point)
6337 (if val coding-no-eol coding
))
6339 (put-text-property pos
(point)
6340 'dired-filename t
)))))))
6342 (if full-directory-p
6343 ;; Try to insert the amount of free space.
6346 ;; First find the line to put it on.
6347 (when (re-search-forward "^ *\\(total\\)" nil t
)
6348 (let ((available (get-free-disk-space ".")))
6350 ;; Replace "total" with "used", to avoid confusion.
6351 (replace-match "total used in directory" nil nil nil
1)
6353 (insert " available " available
))))))))))
6355 (defun insert-directory-adj-pos (pos error-lines
)
6356 "Convert `ls --dired' file name position value POS to a buffer position.
6357 File name position values returned in ls --dired output
6358 count only stdout; they don't count the error messages sent to stderr.
6359 So this function converts to them to real buffer positions.
6360 ERROR-LINES is a list of buffer positions of error message lines,
6361 of the form (START END)."
6362 (while (and error-lines
(< (caar error-lines
) pos
))
6363 (setq pos
(+ pos
(- (nth 1 (car error-lines
)) (nth 0 (car error-lines
)))))
6367 (defun insert-directory-safely (file switches
6368 &optional wildcard full-directory-p
)
6369 "Insert directory listing for FILE, formatted according to SWITCHES.
6371 Like `insert-directory', but if FILE does not exist, it inserts a
6372 message to that effect instead of signaling an error."
6373 (if (file-exists-p file
)
6374 (insert-directory file switches wildcard full-directory-p
)
6375 ;; Simulate the message printed by `ls'.
6376 (insert (format "%s: No such file or directory\n" file
))))
6378 (defvar kill-emacs-query-functions nil
6379 "Functions to call with no arguments to query about killing Emacs.
6380 If any of these functions returns nil, killing Emacs is canceled.
6381 `save-buffers-kill-emacs' calls these functions, but `kill-emacs',
6382 the low level primitive, does not. See also `kill-emacs-hook'.")
6384 (defcustom confirm-kill-emacs nil
6385 "How to ask for confirmation when leaving Emacs.
6386 If nil, the default, don't ask at all. If the value is non-nil, it should
6387 be a predicate function such as `yes-or-no-p'."
6388 :type
'(choice (const :tag
"Ask with yes-or-no-p" yes-or-no-p
)
6389 (const :tag
"Ask with y-or-n-p" y-or-n-p
)
6390 (const :tag
"Don't confirm" nil
))
6394 (defun save-buffers-kill-emacs (&optional arg
)
6395 "Offer to save each buffer, then kill this Emacs process.
6396 With prefix ARG, silently save all file-visiting buffers without asking.
6397 If there are active processes where `process-query-on-exit-flag'
6398 returns non-nil, asks whether processes should be killed.
6399 Runs the members of `kill-emacs-query-functions' in turn and stops
6400 if any returns nil. If `confirm-kill-emacs' is non-nil, calls it."
6402 (save-some-buffers arg t
)
6403 (and (or (not (memq t
(mapcar (function
6404 (lambda (buf) (and (buffer-file-name buf
)
6405 (buffer-modified-p buf
))))
6407 (yes-or-no-p "Modified buffers exist; exit anyway? "))
6408 (or (not (fboundp 'process-list
))
6409 ;; process-list is not defined on MSDOS.
6410 (let ((processes (process-list))
6413 (and (memq (process-status (car processes
)) '(run stop open listen
))
6414 (process-query-on-exit-flag (car processes
))
6416 (setq processes
(cdr processes
)))
6418 (with-temp-buffer-window
6419 (get-buffer-create "*Process List*") nil
6420 #'(lambda (window _value
)
6421 (with-selected-window window
6423 (yes-or-no-p "Active processes exist; kill them and exit anyway? ")
6424 (when (window-live-p window
)
6425 (quit-restore-window window
'kill
)))))
6426 (list-processes t
)))))
6427 ;; Query the user for other things, perhaps.
6428 (run-hook-with-args-until-failure 'kill-emacs-query-functions
)
6429 (or (null confirm-kill-emacs
)
6430 (funcall confirm-kill-emacs
"Really exit Emacs? "))
6433 (defun save-buffers-kill-terminal (&optional arg
)
6434 "Offer to save each buffer, then kill the current connection.
6435 If the current frame has no client, kill Emacs itself.
6437 With prefix ARG, silently save all file-visiting buffers, then kill.
6439 If emacsclient was started with a list of filenames to edit, then
6440 only these files will be asked to be saved."
6442 (if (frame-parameter (selected-frame) 'client
)
6443 (server-save-buffers-kill-terminal arg
)
6444 (save-buffers-kill-emacs arg
)))
6446 ;; We use /: as a prefix to "quote" a file name
6447 ;; so that magic file name handlers will not apply to it.
6449 (setq file-name-handler-alist
6450 (cons (cons (purecopy "\\`/:") 'file-name-non-special
)
6451 file-name-handler-alist
))
6453 ;; We depend on being the last handler on the list,
6454 ;; so that anything else which does need handling
6455 ;; has been handled already.
6456 ;; So it is safe for us to inhibit *all* magic file name handlers.
6458 (defun file-name-non-special (operation &rest arguments
)
6459 (let ((file-name-handler-alist nil
)
6461 (if (eq operation
'insert-directory
)
6462 (directory-file-name
6464 (unhandled-file-name-directory default-directory
)))
6466 ;; Get a list of the indices of the args which are file names.
6468 (cdr (or (assq operation
6469 ;; The first six are special because they
6470 ;; return a file name. We want to include the /:
6471 ;; in the return value.
6472 ;; So just avoid stripping it in the first place.
6473 '((expand-file-name . nil
)
6474 (file-name-directory . nil
)
6475 (file-name-as-directory . nil
)
6476 (directory-file-name . nil
)
6477 (file-name-sans-versions . nil
)
6478 (find-backup-file-name . nil
)
6479 ;; `identity' means just return the first arg
6480 ;; not stripped of its quoting.
6481 (substitute-in-file-name identity
)
6482 ;; `add' means add "/:" to the result.
6483 (file-truename add
0)
6484 (insert-file-contents insert-file-contents
0)
6485 ;; `unquote-then-quote' means set buffer-file-name
6486 ;; temporarily to unquoted filename.
6487 (verify-visited-file-modtime unquote-then-quote
)
6488 ;; List the arguments which are filenames.
6489 (file-name-completion 1)
6490 (file-name-all-completions 1)
6494 (make-symbolic-link 0 1)
6495 (add-name-to-file 0 1)))
6496 ;; For all other operations, treat the first argument only
6497 ;; as the file name.
6500 ;; Copy ARGUMENTS so we can replace elements in it.
6501 (arguments (copy-sequence arguments
)))
6502 (if (symbolp (car file-arg-indices
))
6503 (setq method
(pop file-arg-indices
)))
6504 ;; Strip off the /: from the file names that have it.
6506 (while (consp file-arg-indices
)
6507 (let ((pair (nthcdr (car file-arg-indices
) arguments
)))
6509 (string-match "\\`/:" (car pair
))
6511 (if (= (length (car pair
)) 2)
6513 (substring (car pair
) 2)))))
6514 (setq file-arg-indices
(cdr file-arg-indices
))))
6516 (`identity
(car arguments
))
6517 (`add
(concat "/:" (apply operation arguments
)))
6518 (`insert-file-contents
6519 (let ((visit (nth 1 arguments
)))
6521 (apply operation arguments
)
6522 (when (and visit buffer-file-name
)
6523 (setq buffer-file-name
(concat "/:" buffer-file-name
))))))
6524 (`unquote-then-quote
6525 (let ((buffer-file-name (substring buffer-file-name
2)))
6526 (apply operation arguments
)))
6528 (apply operation arguments
)))))
6530 ;; Symbolic modes and read-file-modes.
6532 (defun file-modes-char-to-who (char)
6533 "Convert CHAR to a numeric bit-mask for extracting mode bits.
6534 CHAR is in [ugoa] and represents the category of users (Owner, Group,
6535 Others, or All) for whom to produce the mask.
6536 The bit-mask that is returned extracts from mode bits the access rights
6537 for the specified category of users."
6538 (cond ((= char ?u
) #o4700
)
6539 ((= char ?g
) #o2070
)
6540 ((= char ?o
) #o1007
)
6541 ((= char ?a
) #o7777
)
6542 (t (error "%c: bad `who' character" char
))))
6544 (defun file-modes-char-to-right (char &optional from
)
6545 "Convert CHAR to a numeric value of mode bits.
6546 CHAR is in [rwxXstugo] and represents symbolic access permissions.
6547 If CHAR is in [Xugo], the value is taken from FROM (or 0 if omitted)."
6548 (or from
(setq from
0))
6549 (cond ((= char ?r
) #o0444
)
6550 ((= char ?w
) #o0222
)
6551 ((= char ?x
) #o0111
)
6552 ((= char ?s
) #o1000
)
6553 ((= char ?t
) #o6000
)
6554 ;; Rights relative to the previous file modes.
6555 ((= char ?X
) (if (= (logand from
#o111
) 0) 0 #o0111
))
6556 ((= char ?u
) (let ((uright (logand #o4700 from
)))
6557 (+ uright
(/ uright
#o10
) (/ uright
#o100
))))
6558 ((= char ?g
) (let ((gright (logand #o2070 from
)))
6559 (+ gright
(/ gright
#o10
) (* gright
#o10
))))
6560 ((= char ?o
) (let ((oright (logand #o1007 from
)))
6561 (+ oright
(* oright
#o10
) (* oright
#o100
))))
6562 (t (error "%c: bad right character" char
))))
6564 (defun file-modes-rights-to-number (rights who-mask
&optional from
)
6565 "Convert a symbolic mode string specification to an equivalent number.
6566 RIGHTS is the symbolic mode spec, it should match \"([+=-][rwxXstugo]*)+\".
6567 WHO-MASK is the bit-mask specifying the category of users to which to
6568 apply the access permissions. See `file-modes-char-to-who'.
6569 FROM (or 0 if nil) gives the mode bits on which to base permissions if
6570 RIGHTS request to add, remove, or set permissions based on existing ones,
6572 (let* ((num-rights (or from
0))
6573 (list-rights (string-to-list rights
))
6574 (op (pop list-rights
)))
6575 (while (memq op
'(?
+ ?- ?
=))
6578 (while (memq (setq char-right
(pop list-rights
))
6579 '(?r ?w ?x ?X ?s ?t ?u ?g ?o
))
6582 (file-modes-char-to-right char-right num-rights
))))
6583 (setq num-right
(logand who-mask num-right
)
6585 (cond ((= op ?
+) (logior num-rights num-right
))
6586 ((= op ?-
) (logand num-rights
(lognot num-right
)))
6587 (t (logior (logand num-rights
(lognot who-mask
)) num-right
)))
6591 (defun file-modes-symbolic-to-number (modes &optional from
)
6592 "Convert symbolic file modes to numeric file modes.
6593 MODES is the string to convert, it should match
6594 \"[ugoa]*([+-=][rwxXstugo]*)+,...\".
6595 See Info node `(coreutils)File permissions' for more information on this
6597 FROM (or 0 if nil) gives the mode bits on which to base permissions if
6598 MODES request to add, remove, or set permissions based on existing ones,
6601 (let ((case-fold-search nil
)
6602 (num-modes (or from
0)))
6603 (while (/= (string-to-char modes
) 0)
6604 (if (string-match "^\\([ugoa]*\\)\\([+=-][rwxXstugo]*\\)+\\(,\\|\\)" modes
)
6605 (let ((num-who (apply 'logior
0
6606 (mapcar 'file-modes-char-to-who
6607 (match-string 1 modes
)))))
6609 (setq num-who
(default-file-modes)))
6611 (file-modes-rights-to-number (substring modes
(match-end 1))
6613 modes
(substring modes
(match-end 3))))
6614 (error "Parse error in modes near `%s'" (substring modes
0))))
6617 (defun read-file-modes (&optional prompt orig-file
)
6618 "Read file modes in octal or symbolic notation and return its numeric value.
6619 PROMPT is used as the prompt, default to `File modes (octal or symbolic): '.
6620 ORIG-FILE is the name of a file on whose mode bits to base returned
6621 permissions if what user types requests to add, remove, or set permissions
6622 based on existing mode bits, as in \"og+rX-w\"."
6623 (let* ((modes (or (if orig-file
(file-modes orig-file
) 0)
6624 (error "File not found")))
6625 (modestr (and (stringp orig-file
)
6626 (nth 8 (file-attributes orig-file
))))
6628 (and (stringp modestr
)
6629 (string-match "^.\\(...\\)\\(...\\)\\(...\\)$" modestr
)
6630 (replace-regexp-in-string
6632 (format "u=%s,g=%s,o=%s"
6633 (match-string 1 modestr
)
6634 (match-string 2 modestr
)
6635 (match-string 3 modestr
)))))
6636 (value (read-string (or prompt
"File modes (octal or symbolic): ")
6639 (if (string-match "^[0-7]+" value
)
6640 (string-to-number value
8)
6641 (file-modes-symbolic-to-number value modes
)))))
6644 ;; Trashcan handling.
6645 (defcustom trash-directory nil
6646 "Directory for `move-file-to-trash' to move files and directories to.
6647 This directory is only used when the function `system-move-file-to-trash'
6649 Relative paths are interpreted relative to `default-directory'.
6650 If the value is nil, Emacs uses a freedesktop.org-style trashcan."
6651 :type
'(choice (const nil
) directory
)
6655 (defvar trash--hexify-table
)
6657 (declare-function system-move-file-to-trash
"w32fns.c" (filename))
6659 (defun move-file-to-trash (filename)
6660 "Move the file (or directory) named FILENAME to the trash.
6661 When `delete-by-moving-to-trash' is non-nil, this function is
6662 called by `delete-file' and `delete-directory' instead of
6663 deleting files outright.
6665 If the function `system-move-file-to-trash' is defined, call it
6666 with FILENAME as an argument.
6667 Otherwise, if `trash-directory' is non-nil, move FILENAME to that
6669 Otherwise, trash FILENAME using the freedesktop.org conventions,
6670 like the GNOME, KDE and XFCE desktop environments. Emacs only
6671 moves files to \"home trash\", ignoring per-volume trashcans."
6672 (interactive "fMove file to trash: ")
6673 (cond (trash-directory
6674 ;; If `trash-directory' is non-nil, move the file there.
6675 (let* ((trash-dir (expand-file-name trash-directory
))
6676 (fn (directory-file-name (expand-file-name filename
)))
6677 (new-fn (expand-file-name (file-name-nondirectory fn
)
6679 ;; We can't trash a parent directory of trash-directory.
6680 (if (string-prefix-p fn trash-dir
)
6681 (error "Trash directory `%s' is a subdirectory of `%s'"
6682 trash-dir filename
))
6683 (unless (file-directory-p trash-dir
)
6684 (make-directory trash-dir t
))
6685 ;; Ensure that the trashed file-name is unique.
6686 (if (file-exists-p new-fn
)
6687 (let ((version-control t
)
6688 (backup-directory-alist nil
))
6689 (setq new-fn
(car (find-backup-file-name new-fn
)))))
6690 (let (delete-by-moving-to-trash)
6691 (rename-file fn new-fn
))))
6692 ;; If `system-move-file-to-trash' is defined, use it.
6693 ((fboundp 'system-move-file-to-trash
)
6694 (system-move-file-to-trash filename
))
6695 ;; Otherwise, use the freedesktop.org method, as specified at
6696 ;; http://freedesktop.org/wiki/Specifications/trash-spec
6698 (let* ((xdg-data-dir
6699 (directory-file-name
6700 (expand-file-name "Trash"
6701 (or (getenv "XDG_DATA_HOME")
6702 "~/.local/share"))))
6703 (trash-files-dir (expand-file-name "files" xdg-data-dir
))
6704 (trash-info-dir (expand-file-name "info" xdg-data-dir
))
6705 (fn (directory-file-name (expand-file-name filename
))))
6707 ;; Check if we have permissions to delete.
6708 (unless (file-writable-p (directory-file-name
6709 (file-name-directory fn
)))
6710 (error "Cannot move %s to trash: Permission denied" filename
))
6711 ;; The trashed file cannot be the trash dir or its parent.
6712 (if (string-prefix-p fn trash-files-dir
)
6713 (error "The trash directory %s is a subdirectory of %s"
6714 trash-files-dir filename
))
6715 (if (string-prefix-p fn trash-info-dir
)
6716 (error "The trash directory %s is a subdirectory of %s"
6717 trash-info-dir filename
))
6719 ;; Ensure that the trash directory exists; otherwise, create it.
6720 (let ((saved-default-file-modes (default-file-modes)))
6723 (set-default-file-modes #o700
)
6724 (unless (file-exists-p trash-files-dir
)
6725 (make-directory trash-files-dir t
))
6726 (unless (file-exists-p trash-info-dir
)
6727 (make-directory trash-info-dir t
)))
6728 (set-default-file-modes saved-default-file-modes
)))
6730 ;; Try to move to trash with .trashinfo undo information
6733 (set-buffer-file-coding-system 'utf-8-unix
)
6734 (insert "[Trash Info]\nPath=")
6735 ;; Perform url-encoding on FN. For compatibility with
6736 ;; other programs (e.g. XFCE Thunar), allow literal "/"
6737 ;; for path separators.
6738 (unless (boundp 'trash--hexify-table
)
6739 (setq trash--hexify-table
(make-vector 256 nil
))
6740 (let ((unreserved-chars
6741 (list ?
/ ?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m
6742 ?n ?o ?p ?q ?r ?s ?t ?u ?v ?w ?x ?y ?z ?A
6743 ?B ?C ?D ?E ?F ?G ?H ?I ?J ?K ?L ?M ?N ?O
6744 ?P ?Q ?R ?S ?T ?U ?V ?W ?X ?Y ?Z ?
0 ?
1 ?
2
6745 ?
3 ?
4 ?
5 ?
6 ?
7 ?
8 ?
9 ?- ?_ ?. ?
! ?~ ?
* ?
'
6748 (aset trash--hexify-table byte
6749 (if (memq byte unreserved-chars
)
6750 (char-to-string byte
)
6751 (format "%%%02x" byte
))))))
6752 (mapc (lambda (byte)
6753 (insert (aref trash--hexify-table byte
)))
6754 (if (multibyte-string-p fn
)
6755 (encode-coding-string fn
'utf-8
)
6757 (insert "\nDeletionDate="
6758 (format-time-string "%Y-%m-%dT%T")
6761 ;; Attempt to make .trashinfo file, trying up to 5
6762 ;; times. The .trashinfo file is opened with O_EXCL,
6763 ;; as per trash-spec 0.7, even if that can be a problem
6764 ;; on old NFS versions...
6766 (base-fn (expand-file-name
6767 (file-name-nondirectory fn
)
6772 (setq info-fn
(expand-file-name
6773 (concat (file-name-nondirectory new-fn
)
6776 (unless (condition-case nil
6778 (write-region nil nil info-fn nil
6779 'quiet info-fn
'excl
)
6780 (setq tries
0 success t
))
6781 (file-already-exists nil
))
6782 (setq tries
(1- tries
))
6783 ;; Uniquify new-fn. (Some file managers do not
6784 ;; like Emacs-style backup file names---e.g. bug
6785 ;; 170956 in Konqueror bug tracker.)
6786 (setq new-fn
(make-temp-name (concat base-fn
"_")))))
6788 (error "Cannot move %s to trash: Lock failed" filename
))
6790 ;; Finally, try to move the file to the trashcan.
6791 (let ((delete-by-moving-to-trash nil
))
6792 (rename-file fn new-fn
)))))))))
6795 (define-key ctl-x-map
"\C-f" 'find-file
)
6796 (define-key ctl-x-map
"\C-r" 'find-file-read-only
)
6797 (define-key ctl-x-map
"\C-v" 'find-alternate-file
)
6798 (define-key ctl-x-map
"\C-s" 'save-buffer
)
6799 (define-key ctl-x-map
"s" 'save-some-buffers
)
6800 (define-key ctl-x-map
"\C-w" 'write-file
)
6801 (define-key ctl-x-map
"i" 'insert-file
)
6802 (define-key esc-map
"~" 'not-modified
)
6803 (define-key ctl-x-map
"\C-d" 'list-directory
)
6804 (define-key ctl-x-map
"\C-c" 'save-buffers-kill-terminal
)
6805 (define-key ctl-x-map
"\C-q" 'read-only-mode
)
6807 (define-key ctl-x-4-map
"f" 'find-file-other-window
)
6808 (define-key ctl-x-4-map
"r" 'find-file-read-only-other-window
)
6809 (define-key ctl-x-4-map
"\C-f" 'find-file-other-window
)
6810 (define-key ctl-x-4-map
"b" 'switch-to-buffer-other-window
)
6811 (define-key ctl-x-4-map
"\C-o" 'display-buffer
)
6813 (define-key ctl-x-5-map
"b" 'switch-to-buffer-other-frame
)
6814 (define-key ctl-x-5-map
"f" 'find-file-other-frame
)
6815 (define-key ctl-x-5-map
"\C-f" 'find-file-other-frame
)
6816 (define-key ctl-x-5-map
"r" 'find-file-read-only-other-frame
)
6817 (define-key ctl-x-5-map
"\C-o" 'display-buffer-other-frame
)
6819 ;;; files.el ends here