1 ;;; files.el --- file input and output commands for Emacs -*- lexical-binding:t -*-
3 ;; Copyright (C) 1985-1987, 1992-2016 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
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 a match for FROM with TO when a directory name matches FROM. This
55 replacement is done when setting up the default directory of a
56 newly visited file buffer.
58 FROM is a regexp that is matched against directory names anchored at
59 the first character, so it should start with a \"\\\\\\=`\", or, if
60 directory names cannot have embedded newlines, with a \"^\".
62 FROM and TO should be equivalent names, which refer to the
63 same directory. TO should be an absolute directory name.
64 Do not use `~' in the TO strings.
66 Use this feature when you have directories which you normally refer to
67 via absolute symbolic links. Make TO the name of the link, and FROM
68 a regexp matching the name it is linked to."
69 :type
'(repeat (cons :format
"%v"
76 (defcustom make-backup-files t
77 "Non-nil means make a backup of a file the first time it is saved.
78 This can be done by renaming the file or by copying.
80 Renaming means that Emacs renames the existing file so that it is a
81 backup file, then writes the buffer into a new file. Any other names
82 that the old file had will now refer to the backup file. The new file
83 is owned by you and its group is defaulted.
85 Copying means that Emacs copies the existing file into the backup
86 file, then writes the buffer on top of the existing file. Any other
87 names that the old file had will now refer to the new (edited) file.
88 The file's owner and group are unchanged.
90 The choice of renaming or copying is controlled by the variables
91 `backup-by-copying', `backup-by-copying-when-linked',
92 `backup-by-copying-when-mismatch' and
93 `backup-by-copying-when-privileged-mismatch'. See also `backup-inhibited'."
97 ;; Do this so that local variables based on the file name
98 ;; are not overridden by the major mode.
99 (defvar backup-inhibited nil
100 "If non-nil, backups will be inhibited.
101 This variable is intended for use by making it local to a buffer,
102 but it is not an automatically buffer-local variable.")
103 (put 'backup-inhibited
'permanent-local t
)
105 (defcustom backup-by-copying nil
106 "Non-nil means always use copying to create backup files.
107 See documentation of variable `make-backup-files'."
111 (defcustom backup-by-copying-when-linked nil
112 "Non-nil means use copying to create backups for files with multiple names.
113 This causes the alternate names to refer to the latest version as edited.
114 This variable is relevant only if `backup-by-copying' is nil."
118 (defcustom backup-by-copying-when-mismatch t
119 "Non-nil means create backups by copying if this preserves owner or group.
120 Renaming may still be used (subject to control of other variables)
121 when it would not result in changing the owner or group of the file;
122 that is, for files which are owned by you and whose group matches
123 the default for a new file created there by you.
124 This variable is relevant only if `backup-by-copying' is nil."
128 (put 'backup-by-copying-when-mismatch
'permanent-local t
)
130 (defcustom backup-by-copying-when-privileged-mismatch
200
131 "Non-nil means create backups by copying to preserve a privileged owner.
132 Renaming may still be used (subject to control of other variables)
133 when it would not result in changing the owner of the file or if the owner
134 has a user id greater than the value of this variable. This is useful
135 when low-numbered uid's are used for special system users (such as root)
136 that must maintain ownership of certain files.
137 This variable is relevant only if `backup-by-copying' and
138 `backup-by-copying-when-mismatch' are nil."
139 :type
'(choice (const nil
) integer
)
142 (defvar backup-enable-predicate
'normal-backup-enable-predicate
143 "Predicate that looks at a file name and decides whether to make backups.
144 Called with an absolute file name as argument, it returns t to enable backup.")
146 (defcustom buffer-offer-save nil
147 "Non-nil in a buffer means always offer to save buffer on exit.
148 Do so even if the buffer is not visiting a file.
149 Automatically local in all buffers."
152 (make-variable-buffer-local 'buffer-offer-save
)
153 (put 'buffer-offer-save
'permanent-local t
)
155 (defcustom find-file-existing-other-name t
156 "Non-nil means find a file under alternative names, in existing buffers.
157 This means if any existing buffer is visiting the file you want
158 under another name, you get the existing buffer instead of a new buffer."
162 (defcustom find-file-visit-truename nil
163 "Non-nil means visiting a file uses its truename as the visited-file name.
164 That is, the buffer visiting the file has the truename as the
165 value of `buffer-file-name'. The truename of a file is found by
166 chasing all links both at the file level and at the levels of the
167 containing directories."
170 (put 'find-file-visit-truename
'safe-local-variable
'booleanp
)
172 (defcustom revert-without-query nil
173 "Specify which files should be reverted without query.
174 The value is a list of regular expressions.
175 If the file name matches one of these regular expressions,
176 then `revert-buffer' reverts the file without querying
177 if the file has changed on disk and you have not edited the buffer."
178 :type
'(repeat regexp
)
181 (defvar buffer-file-number nil
182 "The device number and file number of the file visited in the current buffer.
183 The value is a list of the form (FILENUM DEVNUM).
184 This pair of numbers uniquely identifies the file.
185 If the buffer is visiting a new file, the value is nil.")
186 (make-variable-buffer-local 'buffer-file-number
)
187 (put 'buffer-file-number
'permanent-local t
)
189 (defvar buffer-file-numbers-unique
(not (memq system-type
'(windows-nt)))
190 "Non-nil means that `buffer-file-number' uniquely identifies files.")
192 (defvar buffer-file-read-only nil
193 "Non-nil if visited file was read-only when visited.")
194 (make-variable-buffer-local 'buffer-file-read-only
)
196 (defcustom small-temporary-file-directory
197 (if (eq system-type
'ms-dos
) (getenv "TMPDIR"))
198 "The directory for writing small temporary files.
199 If non-nil, this directory is used instead of `temporary-file-directory'
200 by programs that create small temporary files. This is for systems that
201 have fast storage with limited space, such as a RAM disk."
203 :initialize
'custom-initialize-delay
204 :type
'(choice (const nil
) directory
))
206 ;; The system null device. (Should reference NULL_DEVICE from C.)
207 (defvar null-device
(purecopy "/dev/null") "The system null device.")
209 (declare-function msdos-long-file-names
"msdos.c")
210 (declare-function w32-long-file-name
"w32proc.c")
211 (declare-function dired-get-filename
"dired" (&optional localp no-error-if-not-filep
))
212 (declare-function dired-unmark
"dired" (arg &optional interactive
))
213 (declare-function dired-do-flagged-delete
"dired" (&optional nomessage
))
214 (declare-function dos-8
+3-filename
"dos-fns" (filename))
215 (declare-function dosified-file-name
"dos-fns" (file-name))
217 (defvar file-name-invalid-regexp
218 (cond ((and (eq system-type
'ms-dos
) (not (msdos-long-file-names)))
220 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
221 "[+, ;=|<>\"?*]\\|\\[\\|\\]\\|" ; invalid characters
222 "[\000-\037]\\|" ; control characters
223 "\\(/\\.\\.?[^/]\\)\\|" ; leading dots
224 "\\(/[^/.]+\\.[^/.]*\\.\\)"))) ; more than a single dot
225 ((memq system-type
'(ms-dos windows-nt cygwin
))
227 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
228 "[|<>\"?*\000-\037]"))) ; invalid characters
229 (t (purecopy "[\000]")))
230 "Regexp recognizing file names which aren't allowed by the filesystem.")
232 (defcustom file-precious-flag nil
233 "Non-nil means protect against I/O errors while saving files.
234 Some modes set this non-nil in particular buffers.
236 This feature works by writing the new contents into a temporary file
237 and then renaming the temporary file to replace the original.
238 In this way, any I/O error in writing leaves the original untouched,
239 and there is never any instant where the file is nonexistent.
241 Note that this feature forces backups to be made by copying.
242 Yet, at the same time, saving a precious file
243 breaks any hard links between it and other files.
245 This feature is advisory: for example, if the directory in which the
246 file is being saved is not writable, Emacs may ignore a non-nil value
247 of `file-precious-flag' and write directly into the file.
249 See also: `break-hardlink-on-save'."
253 (defcustom break-hardlink-on-save nil
254 "Whether to allow breaking hardlinks when saving files.
255 If non-nil, then when saving a file that exists under several
256 names \(i.e., has multiple hardlinks), break the hardlink
257 associated with `buffer-file-name' and write to a new file, so
258 that the other instances of the file are not affected by the
261 If `buffer-file-name' refers to a symlink, do not break the symlink.
263 Unlike `file-precious-flag', `break-hardlink-on-save' is not advisory.
264 For example, if the directory in which a file is being saved is not
265 itself writable, then error instead of saving in some
266 hardlink-nonbreaking way.
268 See also `backup-by-copying' and `backup-by-copying-when-linked'."
273 (defcustom version-control nil
274 "Control use of version numbers for backup files.
275 When t, make numeric backup versions unconditionally.
276 When nil, make them for files that have some already.
277 The value `never' means do not make them."
278 :type
'(choice (const :tag
"Never" never
)
279 (const :tag
"If existing" nil
)
280 (other :tag
"Always" t
))
283 (put 'version-control
'safe-local-variable
284 (lambda (x) (or (booleanp x
) (equal x
'never
))))
286 (defcustom dired-kept-versions
2
287 "When cleaning directory, number of versions to keep."
292 (defcustom delete-old-versions nil
293 "If t, delete excess backup versions silently.
294 If nil, ask confirmation. Any other value prevents any trimming."
295 :type
'(choice (const :tag
"Delete" t
)
296 (const :tag
"Ask" nil
)
297 (other :tag
"Leave" other
))
300 (defcustom kept-old-versions
2
301 "Number of oldest versions to keep when a new numbered backup is made."
304 (put 'kept-old-versions
'safe-local-variable
'integerp
)
306 (defcustom kept-new-versions
2
307 "Number of newest versions to keep when a new numbered backup is made.
308 Includes the new backup. Must be > 0"
311 (put 'kept-new-versions
'safe-local-variable
'integerp
)
313 (defcustom require-final-newline nil
314 "Whether to add a newline automatically at the end of the file.
316 A value of t means do this only when the file is about to be saved.
317 A value of `visit' means do this right after the file is visited.
318 A value of `visit-save' means do it at both of those times.
319 Any other non-nil value means ask user whether to add a newline, when saving.
320 A value of nil means don't add newlines.
322 Certain major modes set this locally to the value obtained
323 from `mode-require-final-newline'."
325 :type
'(choice (const :tag
"When visiting" visit
)
326 (const :tag
"When saving" t
)
327 (const :tag
"When visiting or saving" visit-save
)
328 (const :tag
"Don't add newlines" nil
)
329 (other :tag
"Ask each time" ask
))
330 :group
'editing-basics
)
332 (defcustom mode-require-final-newline t
333 "Whether to add a newline at end of file, in certain major modes.
334 Those modes set `require-final-newline' to this value when you enable them.
335 They do so because they are often used for files that are supposed
336 to end in newlines, and the question is how to arrange that.
338 A value of t means do this only when the file is about to be saved.
339 A value of `visit' means do this right after the file is visited.
340 A value of `visit-save' means do it at both of those times.
341 Any other non-nil value means ask user whether to add a newline, when saving.
343 A value of nil means do not add newlines. That is a risky choice in this
344 variable since this value is used for modes for files that ought to have
345 final newlines. So if you set this to nil, you must explicitly check and
346 add a final newline, whenever you save a file that really needs one."
347 :type
'(choice (const :tag
"When visiting" visit
)
348 (const :tag
"When saving" t
)
349 (const :tag
"When visiting or saving" visit-save
)
350 (const :tag
"Don't add newlines" nil
)
351 (other :tag
"Ask each time" ask
))
352 :group
'editing-basics
355 (defcustom auto-save-default t
356 "Non-nil says by default do auto-saving of every file-visiting buffer."
360 (defcustom auto-save-file-name-transforms
361 `(("\\`/[^/]*:\\([^/]*/\\)*\\([^/]*\\)\\'"
362 ;; Don't put "\\2" inside expand-file-name, since it will be
363 ;; transformed to "/2" on DOS/Windows.
364 ,(concat temporary-file-directory
"\\2") t
))
365 "Transforms to apply to buffer file name before making auto-save file name.
366 Each transform is a list (REGEXP REPLACEMENT UNIQUIFY):
367 REGEXP is a regular expression to match against the file name.
368 If it matches, `replace-match' is used to replace the
369 matching part with REPLACEMENT.
370 If the optional element UNIQUIFY is non-nil, the auto-save file name is
371 constructed by taking the directory part of the replaced file-name,
372 concatenated with the buffer file name with all directory separators
373 changed to `!' to prevent clashes. This will not work
374 correctly if your filesystem truncates the resulting name.
376 All the transforms in the list are tried, in the order they are listed.
377 When one transform applies, its result is final;
378 no further transforms are tried.
380 The default value is set up to put the auto-save file into the
381 temporary directory (see the variable `temporary-file-directory') for
382 editing a remote file.
384 On MS-DOS filesystems without long names this variable is always
387 :type
'(repeat (list (string :tag
"Regexp") (string :tag
"Replacement")
388 (boolean :tag
"Uniquify")))
389 :initialize
'custom-initialize-delay
392 (defcustom save-abbrevs t
393 "Non-nil means save word abbrevs too when files are saved.
394 If `silently', don't ask the user before saving."
395 :type
'(choice (const t
) (const nil
) (const silently
))
398 (defcustom find-file-run-dired t
399 "Non-nil means allow `find-file' to visit directories.
400 To visit the directory, `find-file' runs `find-directory-functions'."
404 (defcustom find-directory-functions
'(cvs-dired-noselect dired-noselect
)
405 "List of functions to try in sequence to visit a directory.
406 Each function is called with the directory name as the sole argument
407 and should return either a buffer or nil."
408 :type
'(hook :options
(cvs-dired-noselect dired-noselect
))
411 ;; FIXME: also add a hook for `(thing-at-point 'filename)'
412 (defcustom file-name-at-point-functions
'(ffap-guess-file-name-at-point)
413 "List of functions to try in sequence to get a file name at point.
414 Each function should return either nil or a file name found at the
415 location of point in the current buffer."
416 :type
'(hook :options
(ffap-guess-file-name-at-point))
419 ;;;It is not useful to make this a local variable.
420 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
421 (define-obsolete-variable-alias 'find-file-not-found-hooks
422 'find-file-not-found-functions
"22.1")
423 (defvar find-file-not-found-functions nil
424 "List of functions to be called for `find-file' on nonexistent file.
425 These functions are called as soon as the error is detected.
426 Variable `buffer-file-name' is already set up.
427 The functions are called in the order given until one of them returns non-nil.")
429 ;;;It is not useful to make this a local variable.
430 ;;;(put 'find-file-hooks 'permanent-local t)
431 (define-obsolete-variable-alias 'find-file-hooks
'find-file-hook
"22.1")
432 (defcustom find-file-hook nil
433 "List of functions to be called after a buffer is loaded from a file.
434 The buffer's local variables (if any) will have been processed before the
435 functions are called."
438 :options
'(auto-insert)
441 (define-obsolete-variable-alias 'write-file-hooks
'write-file-functions
"22.1")
442 (defvar write-file-functions nil
443 "List of functions to be called before writing out a buffer to a file.
444 If one of them returns non-nil, the file is considered already written
445 and the rest are not called.
446 These hooks are considered to pertain to the visited file.
447 So any buffer-local binding of this variable is discarded if you change
448 the visited file name with \\[set-visited-file-name], but not when you
449 change the major mode.
451 This hook is not run if any of the functions in
452 `write-contents-functions' returns non-nil. Both hooks pertain
453 to how to save a buffer to file, for instance, choosing a suitable
454 coding system and setting mode bits. (See Info
455 node `(elisp)Saving Buffers'.) To perform various checks or
456 updates before the buffer is saved, use `before-save-hook'.")
457 (put 'write-file-functions
'permanent-local t
)
459 (defvar local-write-file-hooks nil
)
460 (make-variable-buffer-local 'local-write-file-hooks
)
461 (put 'local-write-file-hooks
'permanent-local t
)
462 (make-obsolete-variable 'local-write-file-hooks
'write-file-functions
"22.1")
464 (define-obsolete-variable-alias 'write-contents-hooks
465 'write-contents-functions
"22.1")
466 (defvar write-contents-functions nil
467 "List of functions to be called before writing out a buffer to a file.
468 If one of them returns non-nil, the file is considered already written
469 and the rest are not called and neither are the functions in
470 `write-file-functions'.
472 This variable is meant to be used for hooks that pertain to the
473 buffer's contents, not to the particular visited file; thus,
474 `set-visited-file-name' does not clear this variable; but changing the
475 major mode does clear it.
477 For hooks that _do_ pertain to the particular visited file, use
478 `write-file-functions'. Both this variable and
479 `write-file-functions' relate to how a buffer is saved to file.
480 To perform various checks or updates before the buffer is saved,
481 use `before-save-hook'.")
482 (make-variable-buffer-local 'write-contents-functions
)
484 (defcustom enable-local-variables t
485 "Control use of local variables in files you visit.
486 The value can be t, nil, :safe, :all, or something else.
488 A value of t means file local variables specifications are obeyed
489 if all the specified variable values are safe; if any values are
490 not safe, Emacs queries you, once, whether to set them all.
491 \(When you say yes to certain values, they are remembered as safe.)
493 :safe means set the safe variables, and ignore the rest.
494 :all means set all variables, whether safe or not.
495 (Don't set it permanently to :all.)
496 A value of nil means always ignore the file local variables.
498 Any other value means always query you once whether to set them all.
499 \(When you say yes to certain values, they are remembered as safe, but
500 this has no effect when `enable-local-variables' is \"something else\".)
502 This variable also controls use of major modes specified in
505 The command \\[normal-mode], when used interactively,
506 always obeys file local variable specifications and the -*- line,
507 and ignores this variable."
509 :type
'(choice (const :tag
"Query Unsafe" t
)
510 (const :tag
"Safe Only" :safe
)
511 (const :tag
"Do all" :all
)
512 (const :tag
"Ignore" nil
)
513 (other :tag
"Query" other
))
516 (defvar enable-dir-local-variables t
517 "Non-nil means enable use of directory-local variables.
518 Some modes may wish to set this to nil to prevent directory-local
519 settings being applied, but still respect file-local ones.")
521 ;; This is an odd variable IMO.
522 ;; You might wonder why it is needed, when we could just do:
523 ;; (set (make-local-variable 'enable-local-variables) nil)
524 ;; These two are not precisely the same.
525 ;; Setting this variable does not cause -*- mode settings to be
526 ;; ignored, whereas setting enable-local-variables does.
527 ;; Only three places in Emacs use this variable: tar and arc modes,
528 ;; and rmail. The first two don't need it. They already use
529 ;; inhibit-local-variables-regexps, which is probably enough, and
530 ;; could also just set enable-local-variables locally to nil.
531 ;; Them setting it has the side-effect that dir-locals cannot apply to
532 ;; eg tar files (?). FIXME Is this appropriate?
533 ;; AFAICS, rmail is the only thing that needs this, and the only
534 ;; reason it uses it is for BABYL files (which are obsolete).
535 ;; These contain "-*- rmail -*-" in the first line, which rmail wants
536 ;; to respect, so that find-file on a BABYL file will switch to
537 ;; rmail-mode automatically (this is nice, but hardly essential,
538 ;; since most people are used to explicitly running a command to
539 ;; access their mail; M-x gnus etc). Rmail files may happen to
540 ;; contain Local Variables sections in messages, which Rmail wants to
541 ;; ignore. So AFAICS the only reason this variable exists is for a
542 ;; minor convenience feature for handling of an obsolete Rmail file format.
543 (defvar local-enable-local-variables t
544 "Like `enable-local-variables' but meant for buffer-local bindings.
545 The meaningful values are nil and non-nil. The default is non-nil.
546 If a major mode sets this to nil, buffer-locally, then any local
547 variables list in a file visited in that mode will be ignored.
549 This variable does not affect the use of major modes specified
552 (defcustom enable-local-eval
'maybe
553 "Control processing of the \"variable\" `eval' in a file's local variables.
554 The value can be t, nil or something else.
555 A value of t means obey `eval' variables.
556 A value of nil means ignore them; anything else means query."
558 :type
'(choice (const :tag
"Obey" t
)
559 (const :tag
"Ignore" nil
)
560 (other :tag
"Query" other
))
563 (defcustom view-read-only nil
564 "Non-nil means buffers visiting files read-only do so in view mode.
565 In fact, this means that all read-only buffers normally have
566 View mode enabled, including buffers that are read-only because
567 you visit a file you cannot alter, and buffers you make read-only
568 using \\[read-only-mode]."
572 (defvar file-name-history nil
573 "History list of file names entered in the minibuffer.
575 Maximum length of the history list is determined by the value
576 of `history-length', which see.")
578 (defvar save-silently nil
579 "If non-nil, avoid messages when saving files.
580 Error-related messages will still be printed, but all other
584 (put 'ange-ftp-completion-hook-function
'safe-magic t
)
585 (defun ange-ftp-completion-hook-function (op &rest args
)
586 "Provides support for ange-ftp host name completion.
587 Runs the usual ange-ftp hook, but only for completion operations."
588 ;; Having this here avoids the need to load ange-ftp when it's not
590 (if (memq op
'(file-name-completion file-name-all-completions
))
591 (apply 'ange-ftp-hook-function op args
)
592 (let ((inhibit-file-name-handlers
593 (cons 'ange-ftp-completion-hook-function
594 (and (eq inhibit-file-name-operation op
)
595 inhibit-file-name-handlers
)))
596 (inhibit-file-name-operation op
))
599 (declare-function dos-convert-standard-filename
"dos-fns.el" (filename))
600 (declare-function w32-convert-standard-filename
"w32-fns.el" (filename))
602 (defun convert-standard-filename (filename)
603 "Convert a standard file's name to something suitable for the OS.
604 This means to guarantee valid names and perhaps to canonicalize
607 FILENAME should be an absolute file name since the conversion rules
608 sometimes vary depending on the position in the file name. E.g. c:/foo
609 is a valid DOS file name, but c:/bar/c:/foo is not.
611 This function's standard definition is trivial; it just returns
612 the argument. However, on Windows and DOS, replace invalid
613 characters. On DOS, make sure to obey the 8.3 limitations.
614 In the native Windows build, turn Cygwin names into native names,
615 and also turn slashes into backslashes if the shell requires it (see
616 `w32-shell-dos-semantics').
618 See Info node `(elisp)Standard File Names' for more details."
620 ((eq system-type
'cygwin
)
621 (let ((name (copy-sequence filename
))
623 ;; Replace invalid filename characters with !
624 (while (string-match "[?*:<>|\"\000-\037]" name start
)
625 (aset name
(match-beginning 0) ?
!)
626 (setq start
(match-end 0)))
628 ((eq system-type
'windows-nt
)
629 (w32-convert-standard-filename filename
))
630 ((eq system-type
'ms-dos
)
631 (dos-convert-standard-filename filename
))
634 (defun read-directory-name (prompt &optional dir default-dirname mustmatch initial
)
635 "Read directory name, prompting with PROMPT and completing in directory DIR.
636 Value is not expanded---you must call `expand-file-name' yourself.
637 Default name to DEFAULT-DIRNAME if user exits with the same
638 non-empty string that was inserted by this function.
639 (If DEFAULT-DIRNAME is omitted, DIR combined with INITIAL is used,
640 or just DIR if INITIAL is nil.)
641 If the user exits with an empty minibuffer, this function returns
642 an empty string. (This can only happen if the user erased the
643 pre-inserted contents or if `insert-default-directory' is nil.)
644 Fourth arg MUSTMATCH non-nil means require existing directory's name.
645 Non-nil and non-t means also require confirmation after completion.
646 Fifth arg INITIAL specifies text to start with.
647 DIR should be an absolute directory name. It defaults to
648 the value of `default-directory'."
650 (setq dir default-directory
))
651 (read-file-name prompt dir
(or default-dirname
652 (if initial
(expand-file-name initial dir
)
658 (defun pwd (&optional insert
)
659 "Show the current default directory.
660 With prefix argument INSERT, insert the current default directory
664 (insert default-directory
)
665 (message "Directory %s" default-directory
)))
668 "Value of the CDPATH environment variable, as a list.
669 Not actually set up until the first time you use it.")
671 (defun parse-colon-path (search-path)
672 "Explode a search path into a list of directory names.
673 Directories are separated by `path-separator' (which is colon in
674 GNU and Unix systems). Substitute environment variables into the
675 resulting list of directory names. For an empty path element (i.e.,
676 a leading or trailing separator, or two adjacent separators), return
677 nil (meaning `default-directory') as the associated list element."
678 (when (stringp search-path
)
681 (substitute-in-file-name (file-name-as-directory f
))))
682 (split-string search-path path-separator
))))
684 (defun cd-absolute (dir)
685 "Change current directory to given absolute file name DIR."
686 ;; Put the name into directory syntax now,
687 ;; because otherwise expand-file-name may give some bad results.
688 (setq dir
(file-name-as-directory dir
))
689 ;; We used to additionally call abbreviate-file-name here, for an
690 ;; unknown reason. Problem is that most buffers are setup
691 ;; without going through cd-absolute and don't call
692 ;; abbreviate-file-name on their default-directory, so the few that
693 ;; do end up using a superficially different directory.
694 (setq dir
(expand-file-name dir
))
695 (if (not (file-directory-p dir
))
696 (if (file-exists-p dir
)
697 (error "%s is not a directory" dir
)
698 (error "%s: no such directory" dir
))
699 (unless (file-accessible-directory-p dir
)
700 (error "Cannot cd to %s: Permission denied" dir
))
701 (setq default-directory dir
)
702 (setq list-buffers-directory dir
)))
705 "Make DIR become the current buffer's default directory.
706 If your environment includes a `CDPATH' variable, try each one of
707 that list of directories (separated by occurrences of
708 `path-separator') when resolving a relative directory name.
709 The path separator is colon in GNU and GNU-like systems."
712 ;; FIXME: There's a subtle bug in the completion below. Seems linked
713 ;; to a fundamental difficulty of implementing `predicate' correctly.
714 ;; The manifestation is that TAB may list non-directories in the case where
715 ;; those files also correspond to valid directories (if your cd-path is (A/
716 ;; B/) and you have A/a a file and B/a a directory, then both `a' and `a/'
717 ;; will be listed as valid completions).
718 ;; This is because `a' (listed because of A/a) is indeed a valid choice
719 ;; (which will lead to the use of B/a).
720 (minibuffer-with-setup-hook
722 (setq minibuffer-completion-table
723 (apply-partially #'locate-file-completion-table
725 (setq minibuffer-completion-predicate
727 (locate-file dir cd-path nil
728 (lambda (f) (and (file-directory-p f
) 'dir-ok
))))))
730 (setq cd-path
(or (parse-colon-path (getenv "CDPATH"))
732 (read-directory-name "Change default directory: "
733 default-directory default-directory
736 (setq cd-path
(or (parse-colon-path (getenv "CDPATH"))
739 (or (locate-file dir cd-path nil
740 (lambda (f) (and (file-directory-p f
) 'dir-ok
)))
741 (error "No such directory found via CDPATH environment variable"))))
743 (defsubst directory-name-p
(name)
744 "Return non-nil if NAME ends with a directory separator character."
745 (let ((len (length name
))
748 (setq lastc
(aref name
(1- len
))))
750 (and (memq system-type
'(windows-nt ms-dos
))
753 (defun directory-files-recursively (dir regexp
&optional include-directories
)
754 "Return list of all files under DIR that have file names matching REGEXP.
755 This function works recursively. Files are returned in \"depth first\"
756 order, and files from each directory are sorted in alphabetical order.
757 Each file name appears in the returned list in its absolute form.
758 Optional argument INCLUDE-DIRECTORIES non-nil means also include in the
759 output directories whose names match REGEXP."
762 ;; When DIR is "/", remote file names like "/method:" could
763 ;; also be offered. We shall suppress them.
764 (tramp-mode (and tramp-mode
(file-remote-p (expand-file-name dir
)))))
765 (dolist (file (sort (file-name-all-completions "" dir
)
767 (unless (member file
'("./" "../"))
768 (if (directory-name-p file
)
769 (let* ((leaf (substring file
0 (1- (length file
))))
770 (full-file (expand-file-name leaf dir
)))
771 ;; Don't follow symlinks to other directories.
772 (unless (file-symlink-p full-file
)
774 (nconc result
(directory-files-recursively
775 full-file regexp include-directories
))))
776 (when (and include-directories
777 (string-match regexp leaf
))
778 (setq result
(nconc result
(list full-file
)))))
779 (when (string-match regexp file
)
780 (push (expand-file-name file dir
) files
)))))
781 (nconc result
(nreverse files
))))
783 (defvar module-file-suffix
)
785 (defun load-file (file)
786 "Load the Lisp file named FILE."
787 ;; This is a case where .elc and .so/.dll make a lot of sense.
788 (interactive (list (let ((completion-ignored-extensions
789 (remove module-file-suffix
791 completion-ignored-extensions
))))
792 (read-file-name "Load file: " nil nil
'lambda
))))
793 (load (expand-file-name file
) nil nil t
))
795 (defun locate-file (filename path
&optional suffixes predicate
)
796 "Search for FILENAME through PATH.
797 If found, return the absolute file name of FILENAME; otherwise
799 PATH should be a list of directories to look in, like the lists in
800 `exec-path' or `load-path'.
801 If SUFFIXES is non-nil, it should be a list of suffixes to append to
802 file name when searching. If SUFFIXES is nil, it is equivalent to (\"\").
803 Use (\"/\") to disable PATH search, but still try the suffixes in SUFFIXES.
804 If non-nil, PREDICATE is used instead of `file-readable-p'.
806 This function will normally skip directories, so if you want it to find
807 directories, make sure the PREDICATE function returns `dir-ok' for them.
809 PREDICATE can also be an integer to pass to the `access' system call,
810 in which case file-name handlers are ignored. This usage is deprecated.
811 For compatibility, PREDICATE can also be one of the symbols
812 `executable', `readable', `writable', or `exists', or a list of
813 one or more of those symbols."
814 (if (and predicate
(symbolp predicate
) (not (functionp predicate
)))
815 (setq predicate
(list predicate
)))
816 (when (and (consp predicate
) (not (functionp predicate
)))
818 (logior (if (memq 'executable predicate
) 1 0)
819 (if (memq 'writable predicate
) 2 0)
820 (if (memq 'readable predicate
) 4 0))))
821 (locate-file-internal filename path suffixes predicate
))
823 (defun locate-file-completion-table (dirs suffixes string pred action
)
824 "Do completion for file names passed to `locate-file'."
826 ((file-name-absolute-p string
)
827 ;; FIXME: maybe we should use completion-file-name-table instead,
828 ;; tho at least for `load', the arg is passed through
829 ;; substitute-in-file-name for historical reasons.
830 (read-file-name-internal string pred action
))
831 ((eq (car-safe action
) 'boundaries
)
832 (let ((suffix (cdr action
)))
834 ,(length (file-name-directory string
))
835 ,@(let ((x (file-name-directory suffix
)))
836 (if x
(1- (length x
)) (length suffix
))))))
839 ;; If we have files like "foo.el" and "foo.elc", we could load one of
840 ;; them with "foo.el", "foo.elc", or "foo", where just "foo" is the
841 ;; preferred way. So if we list all 3, that gives a lot of redundant
842 ;; entries for the poor soul looking just for "foo". OTOH, sometimes
843 ;; the user does want to pay attention to the extension. We try to
844 ;; diffuse this tension by stripping the suffix, except when the
845 ;; result is a single element (i.e. usually we only list "foo" unless
846 ;; it's the only remaining element in the list, in which case we do
847 ;; list "foo", "foo.elc" and "foo.el").
849 (suffix (concat (regexp-opt suffixes t
) "\\'"))
850 (string-dir (file-name-directory string
))
851 (string-file (file-name-nondirectory string
)))
854 (setq dir default-directory
))
855 (if string-dir
(setq dir
(expand-file-name string-dir dir
)))
856 (when (file-directory-p dir
)
857 (dolist (file (file-name-all-completions
859 (if (not (string-match suffix file
))
861 (push file fullnames
)
862 (push (substring file
0 (match-beginning 0)) names
)))))
863 ;; Switching from names to names+fullnames creates a non-monotonicity
864 ;; which can cause problems with things like partial-completion.
865 ;; To minimize the problem, filter out completion-regexp-list, so that
866 ;; M-x load-library RET t/x.e TAB finds some files. Also remove elements
867 ;; from `names' which only matched `string' when they still had
869 (setq names
(all-completions string names
))
870 ;; Remove duplicates of the first element, so that we can easily check
871 ;; if `names' really only contains a single element.
872 (when (cdr names
) (setcdr names
(delete (car names
) (cdr names
))))
874 ;; There's no more than one matching non-suffixed element, so expand
875 ;; the list by adding the suffixed elements as well.
876 (setq names
(nconc names fullnames
)))
877 (completion-table-with-context
878 string-dir names string-file pred action
)))))
880 (defun locate-file-completion (string path-and-suffixes action
)
881 "Do completion for file names passed to `locate-file'.
882 PATH-AND-SUFFIXES is a pair of lists, (DIRECTORIES . SUFFIXES)."
883 (declare (obsolete locate-file-completion-table
"23.1"))
884 (locate-file-completion-table (car path-and-suffixes
)
885 (cdr path-and-suffixes
)
888 (defvar locate-dominating-stop-dir-regexp
889 (purecopy "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'")
890 "Regexp of directory names which stop the search in `locate-dominating-file'.
891 Any directory whose name matches this regexp will be treated like
892 a kind of root directory by `locate-dominating-file' which will stop its search
893 when it bumps into it.
894 The default regexp prevents fruitless and time-consuming attempts to find
895 special files in directories in which filenames are interpreted as hostnames,
896 or mount points potentially requiring authentication as a different user.")
898 ;; (defun locate-dominating-files (file regexp)
899 ;; "Look up the directory hierarchy from FILE for a file matching REGEXP.
900 ;; Stop at the first parent where a matching file is found and return the list
901 ;; of files that that match in this directory."
903 ;; ;; `user' is not initialized yet because `file' may not exist, so we may
904 ;; ;; have to walk up part of the hierarchy before we find the "initial UID".
906 ;; ;; Abbreviate, so as to stop when we cross ~/.
907 ;; (dir (abbreviate-file-name (file-name-as-directory file)))
910 ;; ;; As a heuristic, we stop looking up the hierarchy of
911 ;; ;; directories as soon as we find a directory belonging to
912 ;; ;; another user. This should save us from looking in
913 ;; ;; things like /net and /afs. This assumes that all the
914 ;; ;; files inside a project belong to the same user.
915 ;; (let ((prev-user user))
916 ;; (setq user (nth 2 (file-attributes dir)))
917 ;; (or (null prev-user) (equal user prev-user))))
918 ;; (if (setq files (condition-case nil
919 ;; (directory-files dir 'full regexp 'nosort)
921 ;; (throw 'found files)
923 ;; (setq dir (file-name-directory
924 ;; (directory-file-name dir))))
928 (defun locate-dominating-file (file name
)
929 "Look up the directory hierarchy from FILE for a directory containing NAME.
930 Stop at the first parent directory containing a file NAME,
931 and return the directory. Return nil if not found.
932 Instead of a string, NAME can also be a predicate taking one argument
933 \(a directory) and returning a non-nil value if that directory is the one for
934 which we're looking."
935 ;; We used to use the above locate-dominating-files code, but the
936 ;; directory-files call is very costly, so we're much better off doing
937 ;; multiple calls using the code in here.
939 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
940 ;; `name' in /home or in /.
941 (setq file
(abbreviate-file-name (expand-file-name file
)))
943 ;; `user' is not initialized outside the loop because
944 ;; `file' may not exist, so we may have to walk up part of the
945 ;; hierarchy before we find the "initial UID". Note: currently unused
950 ;; FIXME: Disabled this heuristic because it is sometimes
952 ;; As a heuristic, we stop looking up the hierarchy of
953 ;; directories as soon as we find a directory belonging
954 ;; to another user. This should save us from looking in
955 ;; things like /net and /afs. This assumes that all the
956 ;; files inside a project belong to the same user.
957 ;; (let ((prev-user user))
958 ;; (setq user (nth 2 (file-attributes file)))
959 ;; (and prev-user (not (equal user prev-user))))
960 (string-match locate-dominating-stop-dir-regexp file
)))
961 (setq try
(if (stringp name
)
962 (file-exists-p (expand-file-name name file
))
963 (funcall name file
)))
964 (cond (try (setq root file
))
965 ((equal file
(setq file
(file-name-directory
966 (directory-file-name file
))))
968 (if root
(file-name-as-directory root
))))
970 (defcustom user-emacs-directory-warning t
971 "Non-nil means warn if cannot access `user-emacs-directory'.
972 Set this to nil at your own risk..."
974 :group
'initialization
977 (defun locate-user-emacs-file (new-name &optional old-name
)
978 "Return an absolute per-user Emacs-specific file name.
979 If NEW-NAME exists in `user-emacs-directory', return it.
980 Else if OLD-NAME is non-nil and ~/OLD-NAME exists, return ~/OLD-NAME.
981 Else return NEW-NAME in `user-emacs-directory', creating the
982 directory if it does not exist."
983 (convert-standard-filename
984 (let* ((home (concat "~" (or init-file-user
"")))
985 (at-home (and old-name
(expand-file-name old-name home
)))
986 (bestname (abbreviate-file-name
987 (expand-file-name new-name user-emacs-directory
))))
988 (if (and at-home
(not (file-readable-p bestname
))
989 (file-readable-p at-home
))
991 ;; Make sure `user-emacs-directory' exists,
992 ;; unless we're in batch mode or dumping Emacs.
996 (if (file-directory-p user-emacs-directory
)
997 (or (file-accessible-directory-p user-emacs-directory
)
998 (setq errtype
"access"))
999 (with-file-modes ?
\700
1001 (make-directory user-emacs-directory
)
1002 (error (setq errtype
"create")))))
1004 user-emacs-directory-warning
1005 (not (get 'user-emacs-directory-warning
'this-session
)))
1006 ;; Only warn once per Emacs session.
1007 (put 'user-emacs-directory-warning
'this-session t
)
1008 (display-warning 'initialization
1010 Unable to %s `user-emacs-directory' (%s).
1011 Any data that would normally be written there may be lost!
1012 If you never want to see this message again,
1013 customize the variable `user-emacs-directory-warning'."
1014 errtype user-emacs-directory
)))))
1018 (defun executable-find (command)
1019 "Search for COMMAND in `exec-path' and return the absolute file name.
1020 Return nil if COMMAND is not found anywhere in `exec-path'."
1021 ;; Use 1 rather than file-executable-p to better match the behavior of
1023 (locate-file command exec-path exec-suffixes
1))
1025 (defun load-library (library)
1026 "Load the Emacs Lisp library named LIBRARY.
1027 LIBRARY should be a string.
1028 This is an interface to the function `load'. LIBRARY is searched
1029 for in `load-path', both with and without `load-suffixes' (as
1030 well as `load-file-rep-suffixes').
1032 See Info node `(emacs)Lisp Libraries' for more details.
1033 See `load-file' for a different interface to `load'."
1035 (let (completion-ignored-extensions)
1036 (list (completing-read "Load library: "
1037 (apply-partially 'locate-file-completion-table
1039 (get-load-suffixes))))))
1042 (defun file-remote-p (file &optional identification connected
)
1043 "Test whether FILE specifies a location on a remote system.
1044 A file is considered remote if accessing it is likely to
1045 be slower or less reliable than accessing local files.
1047 `file-remote-p' never opens a new remote connection. It can
1048 only reuse a connection that is already open.
1050 Return nil or a string identifying the remote connection
1051 \(ideally a prefix of FILE). Return nil if FILE is a relative
1054 When IDENTIFICATION is nil, the returned string is a complete
1055 remote identifier: with components method, user, and host. The
1056 components are those present in FILE, with defaults filled in for
1057 any that are missing.
1059 IDENTIFICATION can specify which part of the identification to
1060 return. IDENTIFICATION can be the symbol `method', `user',
1061 `host', or `localname'. Any other value is handled like nil and
1062 means to return the complete identification. The string returned
1063 for IDENTIFICATION `localname' can differ depending on whether
1064 there is an existing connection.
1066 If CONNECTED is non-nil, return an identification only if FILE is
1067 located on a remote system and a connection is established to
1070 Tip: You can use this expansion of remote identifier components
1071 to derive a new remote file name from an existing one. For
1072 example, if FILE is \"/sudo::/path/to/file\" then
1074 (concat (file-remote-p FILE) \"/bin/sh\")
1076 returns a remote file name for file \"/bin/sh\" that has the
1077 same remote identifier as FILE but expanded; a name such as
1078 \"/sudo:root@myhost:/bin/sh\"."
1079 (let ((handler (find-file-name-handler file
'file-remote-p
)))
1081 (funcall handler
'file-remote-p file identification connected
)
1084 ;; Probably this entire variable should be obsolete now, in favor of
1085 ;; something Tramp-related (?). It is not used in many places.
1086 ;; It's not clear what the best file for this to be in is, but given
1087 ;; it uses custom-initialize-delay, it is easier if it is preloaded
1088 ;; rather than autoloaded.
1089 (defcustom remote-shell-program
1090 ;; This used to try various hard-coded places for remsh, rsh, and
1091 ;; rcmd, trying to guess based on location whether "rsh" was
1092 ;; "restricted shell" or "remote shell", but I don't see the point
1093 ;; in this day and age. Almost everyone will use ssh, and have
1094 ;; whatever command they want to use in PATH.
1096 (let ((list '("ssh" "remsh" "rcmd" "rsh")))
1098 (not (executable-find (car list
)))
1099 (setq list
(cdr list
))))
1100 (or (car list
) "ssh")))
1101 "Program to use to execute commands on a remote host (e.g. ssh or rsh)."
1102 :version
"24.3" ; ssh rather than rsh, etc
1103 :initialize
'custom-initialize-delay
1107 (defcustom remote-file-name-inhibit-cache
10
1108 "Whether to use the remote file-name cache for read access.
1109 When nil, never expire cached values (caution)
1110 When t, never use the cache (safe, but may be slow)
1111 A number means use cached values for that amount of seconds since caching.
1113 The attributes of remote files are cached for better performance.
1114 If they are changed outside of Emacs's control, the cached values
1115 become invalid, and must be reread. If you are sure that nothing
1116 other than Emacs changes the files, you can set this variable to nil.
1118 If a remote file is checked regularly, it might be a good idea to
1119 let-bind this variable to a value less than the interval between
1120 consecutive checks. For example:
1122 (defun display-time-file-nonempty-p (file)
1123 (let ((remote-file-name-inhibit-cache (- display-time-interval 5)))
1124 (and (file-exists-p file)
1125 (< 0 (nth 7 (file-attributes (file-chase-links file)))))))"
1129 (const :tag
"Do not inhibit file name cache" nil
)
1130 (const :tag
"Do not use file name cache" t
)
1131 (integer :tag
"Do not use file name cache"
1132 :format
"Do not use file name cache older then %v seconds"
1135 (defun file-local-copy (file)
1136 "Copy the file FILE into a temporary file on this machine.
1137 Returns the name of the local copy, or nil, if FILE is directly
1139 ;; This formerly had an optional BUFFER argument that wasn't used by
1141 (let ((handler (find-file-name-handler file
'file-local-copy
)))
1143 (funcall handler
'file-local-copy file
)
1146 (defun file-truename (filename &optional counter prev-dirs
)
1147 "Return the truename of FILENAME.
1148 If FILENAME is not absolute, first expands it against `default-directory'.
1149 The truename of a file name is found by chasing symbolic links
1150 both at the level of the file and at the level of the directories
1151 containing it, until no links are left at any level.
1153 \(fn FILENAME)" ;; Don't document the optional arguments.
1154 ;; COUNTER and PREV-DIRS are only used in recursive calls.
1155 ;; COUNTER can be a cons cell whose car is the count of how many
1156 ;; more links to chase before getting an error.
1157 ;; PREV-DIRS can be a cons cell whose car is an alist
1158 ;; of truenames we've just recently computed.
1159 (cond ((or (string= filename
"") (string= filename
"~"))
1160 (setq filename
(expand-file-name filename
))
1161 (if (string= filename
"")
1162 (setq filename
"/")))
1163 ((and (string= (substring filename
0 1) "~")
1164 (string-match "~[^/]*/?" filename
))
1166 (substring filename
0 (match-end 0)))
1167 (rest (substring filename
(match-end 0))))
1168 (setq filename
(concat (expand-file-name first-part
) rest
)))))
1170 (or counter
(setq counter
(list 100)))
1172 ;; For speed, remove the ange-ftp completion handler from the list.
1173 ;; We know it's not needed here.
1174 ;; For even more speed, do this only on the outermost call.
1175 (file-name-handler-alist
1176 (if prev-dirs file-name-handler-alist
1177 (let ((tem (copy-sequence file-name-handler-alist
)))
1178 (delq (rassq 'ange-ftp-completion-hook-function tem
) tem
)))))
1179 (or prev-dirs
(setq prev-dirs
(list nil
)))
1181 ;; andrewi@harlequin.co.uk - on Windows, there is an issue with
1182 ;; case differences being ignored by the OS, and short "8.3 DOS"
1183 ;; name aliases existing for all files. (The short names are not
1184 ;; reported by directory-files, but can be used to refer to files.)
1185 ;; It seems appropriate for file-truename to resolve these issues in
1186 ;; the most natural way, which on Windows is to call the function
1187 ;; `w32-long-file-name' - this returns the exact name of a file as
1188 ;; it is stored on disk (expanding short name aliases with the full
1189 ;; name in the process).
1190 (if (eq system-type
'windows-nt
)
1191 (unless (string-match "[[*?]" filename
)
1192 ;; If filename exists, use its long name. If it doesn't
1193 ;; exist, the recursion below on the directory of filename
1194 ;; will drill down until we find a directory that exists,
1195 ;; and use the long name of that, with the extra
1196 ;; non-existent path components concatenated.
1197 (let ((longname (w32-long-file-name filename
)))
1199 (setq filename longname
)))))
1201 ;; If this file directly leads to a link, process that iteratively
1202 ;; so that we don't use lots of stack.
1204 (setcar counter
(1- (car counter
)))
1205 (if (< (car counter
) 0)
1206 (error "Apparent cycle of symbolic links for %s" filename
))
1207 (let ((handler (find-file-name-handler filename
'file-truename
)))
1208 ;; For file name that has a special handler, call handler.
1209 ;; This is so that ange-ftp can save time by doing a no-op.
1211 (setq filename
(funcall handler
'file-truename filename
)
1213 (let ((dir (or (file-name-directory filename
) default-directory
))
1215 ;; Get the truename of the directory.
1216 (setq dirfile
(directory-file-name dir
))
1217 ;; If these are equal, we have the (or a) root directory.
1218 (or (string= dir dirfile
)
1219 (and (memq system-type
'(windows-nt ms-dos cygwin nacl
))
1220 (eq (compare-strings dir
0 nil dirfile
0 nil t
) t
))
1221 ;; If this is the same dir we last got the truename for,
1222 ;; save time--don't recalculate.
1223 (if (assoc dir
(car prev-dirs
))
1224 (setq dir
(cdr (assoc dir
(car prev-dirs
))))
1226 (new (file-name-as-directory (file-truename dirfile counter prev-dirs
))))
1227 (setcar prev-dirs
(cons (cons old new
) (car prev-dirs
)))
1229 (if (equal ".." (file-name-nondirectory filename
))
1231 (directory-file-name (file-name-directory (directory-file-name dir
)))
1233 (if (equal "." (file-name-nondirectory filename
))
1234 (setq filename
(directory-file-name dir
)
1236 ;; Put it back on the file name.
1237 (setq filename
(concat dir
(file-name-nondirectory filename
)))
1238 ;; Is the file name the name of a link?
1239 (setq target
(file-symlink-p filename
))
1241 ;; Yes => chase that link, then start all over
1242 ;; since the link may point to a directory name that uses links.
1243 ;; We can't safely use expand-file-name here
1244 ;; since target might look like foo/../bar where foo
1245 ;; is itself a link. Instead, we handle . and .. above.
1247 (if (file-name-absolute-p target
)
1249 (concat dir target
))
1252 (setq done t
))))))))
1255 (defun file-chase-links (filename &optional limit
)
1256 "Chase links in FILENAME until a name that is not a link.
1257 Unlike `file-truename', this does not check whether a parent
1258 directory name is a symbolic link.
1259 If the optional argument LIMIT is a number,
1260 it means chase no more than that many links and then stop."
1261 (let (tem (newname filename
)
1263 (while (and (or (null limit
) (< count limit
))
1264 (setq tem
(file-symlink-p newname
)))
1266 (if (and (null limit
) (= count
100))
1267 (error "Apparent cycle of symbolic links for %s" filename
))
1268 ;; In the context of a link, `//' doesn't mean what Emacs thinks.
1269 (while (string-match "//+" tem
)
1270 (setq tem
(replace-match "/" nil nil tem
)))
1271 ;; Handle `..' by hand, since it needs to work in the
1272 ;; target of any directory symlink.
1273 ;; This code is not quite complete; it does not handle
1274 ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
1275 (while (string-match "\\`\\.\\./" tem
)
1276 (setq tem
(substring tem
3))
1277 (setq newname
(expand-file-name newname
))
1278 ;; Chase links in the default dir of the symlink.
1281 (directory-file-name (file-name-directory newname
))))
1282 ;; Now find the parent of that dir.
1283 (setq newname
(file-name-directory newname
)))
1284 (setq newname
(expand-file-name tem
(file-name-directory newname
)))
1285 (setq count
(1+ count
))))
1288 ;; A handy function to display file sizes in human-readable form.
1289 ;; See http://en.wikipedia.org/wiki/Kibibyte for the reference.
1290 (defun file-size-human-readable (file-size &optional flavor
)
1291 "Produce a string showing FILE-SIZE in human-readable form.
1293 Optional second argument FLAVOR controls the units and the display format:
1295 If FLAVOR is nil or omitted, each kilobyte is 1024 bytes and the produced
1296 suffixes are \"k\", \"M\", \"G\", \"T\", etc.
1297 If FLAVOR is `si', each kilobyte is 1000 bytes and the produced suffixes
1298 are \"k\", \"M\", \"G\", \"T\", etc.
1299 If FLAVOR is `iec', each kilobyte is 1024 bytes and the produced suffixes
1300 are \"KiB\", \"MiB\", \"GiB\", \"TiB\", etc."
1301 (let ((power (if (or (null flavor
) (eq flavor
'iec
))
1305 ;; none, kilo, mega, giga, tera, peta, exa, zetta, yotta
1306 (list "" "k" "M" "G" "T" "P" "E" "Z" "Y")))
1307 (while (and (>= file-size power
) (cdr post-fixes
))
1308 (setq file-size
(/ file-size power
)
1309 post-fixes
(cdr post-fixes
)))
1310 (format (if (> (mod file-size
1.0) 0.05)
1314 (if (and (eq flavor
'iec
) (string= (car post-fixes
) "k"))
1317 (if (eq flavor
'iec
) "iB" ""))))
1319 (defun make-temp-file (prefix &optional dir-flag suffix
)
1320 "Create a temporary file.
1321 The returned file name (created by appending some random characters at the end
1322 of PREFIX, and expanding against `temporary-file-directory' if necessary),
1323 is guaranteed to point to a newly created empty file.
1324 You can then use `write-region' to write new data into the file.
1326 If DIR-FLAG is non-nil, create a new empty directory instead of a file.
1328 If SUFFIX is non-nil, add that at the end of the file name."
1329 ;; Create temp files with strict access rights. It's easy to
1330 ;; loosen them later, whereas it's impossible to close the
1331 ;; time-window of loose permissions otherwise.
1332 (with-file-modes ?
\700
1334 (while (condition-case ()
1338 (if (zerop (length prefix
))
1339 (file-name-as-directory
1340 temporary-file-directory
)
1341 (expand-file-name prefix
1342 temporary-file-directory
))))
1344 (setq file
(concat file suffix
)))
1346 (make-directory file
)
1347 (write-region "" nil file nil
'silent nil
'excl
))
1349 (file-already-exists t
))
1350 ;; the file was somehow created by someone else between
1351 ;; `make-temp-name' and `write-region', let's try again.
1355 (defun recode-file-name (file coding new-coding
&optional ok-if-already-exists
)
1356 "Change the encoding of FILE's name from CODING to NEW-CODING.
1357 The value is a new name of FILE.
1358 Signals a `file-already-exists' error if a file of the new name
1359 already exists unless optional fourth argument OK-IF-ALREADY-EXISTS
1360 is non-nil. A number as fourth arg means request confirmation if
1361 the new name already exists. This is what happens in interactive
1364 (let ((default-coding (or file-name-coding-system
1365 default-file-name-coding-system
))
1366 (filename (read-file-name "Recode filename: " nil nil t
))
1367 from-coding to-coding
)
1368 (if (and default-coding
1369 ;; We provide the default coding only when it seems that
1370 ;; the filename is correctly decoded by the default
1372 (let ((charsets (find-charset-string filename
)))
1373 (and (not (memq 'eight-bit-control charsets
))
1374 (not (memq 'eight-bit-graphic charsets
)))))
1375 (setq from-coding
(read-coding-system
1376 (format "Recode filename %s from (default %s): "
1377 filename default-coding
)
1379 (setq from-coding
(read-coding-system
1380 (format "Recode filename %s from: " filename
))))
1382 ;; We provide the default coding only when a user is going to
1383 ;; change the encoding not from the default coding.
1384 (if (eq from-coding default-coding
)
1385 (setq to-coding
(read-coding-system
1386 (format "Recode filename %s from %s to: "
1387 filename from-coding
)))
1388 (setq to-coding
(read-coding-system
1389 (format "Recode filename %s from %s to (default %s): "
1390 filename from-coding default-coding
)
1392 (list filename from-coding to-coding
)))
1394 (let* ((default-coding (or file-name-coding-system
1395 default-file-name-coding-system
))
1396 ;; FILE should have been decoded by DEFAULT-CODING.
1397 (encoded (encode-coding-string file default-coding
))
1398 (newname (decode-coding-string encoded coding
))
1399 (new-encoded (encode-coding-string newname new-coding
))
1400 ;; Suppress further encoding.
1401 (file-name-coding-system nil
)
1402 (default-file-name-coding-system nil
)
1403 (locale-coding-system nil
))
1404 (rename-file encoded new-encoded ok-if-already-exists
)
1407 (defcustom confirm-nonexistent-file-or-buffer
'after-completion
1408 "Whether confirmation is requested before visiting a new file or buffer.
1409 If nil, confirmation is not requested.
1410 If the value is `after-completion', confirmation is only
1411 requested if the user called `minibuffer-complete' right before
1412 `minibuffer-complete-and-exit'.
1413 Any other non-nil value means to request confirmation.
1415 This affects commands like `switch-to-buffer' and `find-file'."
1418 :type
'(choice (const :tag
"After completion" after-completion
)
1419 (const :tag
"Never" nil
)
1420 (other :tag
"Always" t
)))
1422 (defun confirm-nonexistent-file-or-buffer ()
1423 "Whether to request confirmation before visiting a new file or buffer.
1424 The variable `confirm-nonexistent-file-or-buffer' determines the
1425 return value, which may be passed as the REQUIRE-MATCH arg to
1426 `read-buffer' or `find-file-read-args'."
1427 (cond ((eq confirm-nonexistent-file-or-buffer
'after-completion
)
1428 'confirm-after-completion
)
1429 (confirm-nonexistent-file-or-buffer
1433 (defmacro minibuffer-with-setup-hook
(fun &rest body
)
1434 "Temporarily add FUN to `minibuffer-setup-hook' while executing BODY.
1436 By default, FUN is prepended to `minibuffer-setup-hook'. But if FUN is of
1437 the form `(:append FUN1)', FUN1 will be appended to `minibuffer-setup-hook'
1438 instead of prepending it.
1440 BODY should use the minibuffer at most once.
1441 Recursive uses of the minibuffer are unaffected (FUN is not
1442 called additional times).
1444 This macro actually adds an auxiliary function that calls FUN,
1445 rather than FUN itself, to `minibuffer-setup-hook'."
1446 (declare (indent 1) (debug t
))
1447 (let ((hook (make-symbol "setup-hook"))
1448 (funsym (make-symbol "fun"))
1450 (when (eq (car-safe fun
) :append
)
1451 (setq append
'(t) fun
(cadr fun
)))
1452 `(let ((,funsym
,fun
)
1456 ;; Clear out this hook so it does not interfere
1457 ;; with any recursive minibuffer usage.
1458 (remove-hook 'minibuffer-setup-hook
,hook
)
1462 (add-hook 'minibuffer-setup-hook
,hook
,@append
)
1464 (remove-hook 'minibuffer-setup-hook
,hook
)))))
1466 (defun find-file-read-args (prompt mustmatch
)
1467 (list (read-file-name prompt nil default-directory mustmatch
)
1470 (defun find-file (filename &optional wildcards
)
1471 "Edit file FILENAME.
1472 Switch to a buffer visiting file FILENAME,
1473 creating one if none already exists.
1474 Interactively, the default if you just type RET is the current directory,
1475 but the visited file name is available through the minibuffer history:
1476 type M-n to pull it into the minibuffer.
1478 You can visit files on remote machines by specifying something
1479 like /ssh:SOME_REMOTE_MACHINE:FILE for the file name. You can
1480 also visit local files as a different user by specifying
1481 /sudo::FILE for the file name.
1482 See the Info node `(tramp)File name Syntax' in the Tramp Info
1483 manual, for more about this.
1485 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1486 expand wildcards (if any) and visit multiple files. You can
1487 suppress wildcard expansion by setting `find-file-wildcards' to nil.
1489 To visit a file without any kind of conversion and without
1490 automatically choosing a major mode, use \\[find-file-literally]."
1492 (find-file-read-args "Find file: "
1493 (confirm-nonexistent-file-or-buffer)))
1494 (let ((value (find-file-noselect filename nil nil wildcards
)))
1496 (mapcar 'switch-to-buffer
(nreverse value
))
1497 (switch-to-buffer value
))))
1499 (defun find-file-other-window (filename &optional wildcards
)
1500 "Edit file FILENAME, in another window.
1502 Like \\[find-file] (which see), but creates a new window or reuses
1503 an existing one. See the function `display-buffer'.
1505 Interactively, the default if you just type RET is the current directory,
1506 but the visited file name is available through the minibuffer history:
1507 type M-n to pull it into the minibuffer.
1509 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1510 expand wildcards (if any) and visit multiple files."
1512 (find-file-read-args "Find file in other window: "
1513 (confirm-nonexistent-file-or-buffer)))
1514 (let ((value (find-file-noselect filename nil nil wildcards
)))
1517 (setq value
(nreverse value
))
1518 (switch-to-buffer-other-window (car value
))
1519 (mapc 'switch-to-buffer
(cdr value
))
1521 (switch-to-buffer-other-window value
))))
1523 (defun find-file-other-frame (filename &optional wildcards
)
1524 "Edit file FILENAME, in another frame.
1526 Like \\[find-file] (which see), but creates a new frame or reuses
1527 an existing one. See the function `display-buffer'.
1529 Interactively, the default if you just type RET is the current directory,
1530 but the visited file name is available through the minibuffer history:
1531 type M-n to pull it into the minibuffer.
1533 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1534 expand wildcards (if any) and visit multiple files."
1536 (find-file-read-args "Find file in other frame: "
1537 (confirm-nonexistent-file-or-buffer)))
1538 (let ((value (find-file-noselect filename nil nil wildcards
)))
1541 (setq value
(nreverse value
))
1542 (switch-to-buffer-other-frame (car value
))
1543 (mapc 'switch-to-buffer
(cdr value
))
1545 (switch-to-buffer-other-frame value
))))
1547 (defun find-file-existing (filename)
1548 "Edit the existing file FILENAME.
1549 Like \\[find-file], but only allow a file that exists, and do not allow
1550 file names with wildcards."
1551 (interactive (nbutlast (find-file-read-args "Find existing file: " t
)))
1552 (if (and (not (called-interactively-p 'interactive
))
1553 (not (file-exists-p filename
)))
1554 (error "%s does not exist" filename
)
1555 (find-file filename
)
1558 (defun find-file--read-only (fun filename wildcards
)
1559 (unless (or (and wildcards find-file-wildcards
1560 (not (string-match "\\`/:" filename
))
1561 (string-match "[[*?]" filename
))
1562 (file-exists-p filename
))
1563 (error "%s does not exist" filename
))
1564 (let ((value (funcall fun filename wildcards
)))
1565 (mapc (lambda (b) (with-current-buffer b
(read-only-mode 1)))
1566 (if (listp value
) value
(list value
)))
1569 (defun find-file-read-only (filename &optional wildcards
)
1570 "Edit file FILENAME but don't allow changes.
1571 Like \\[find-file], but marks buffer as read-only.
1572 Use \\[read-only-mode] to permit editing."
1574 (find-file-read-args "Find file read-only: "
1575 (confirm-nonexistent-file-or-buffer)))
1576 (find-file--read-only #'find-file filename wildcards
))
1578 (defun find-file-read-only-other-window (filename &optional wildcards
)
1579 "Edit file FILENAME in another window but don't allow changes.
1580 Like \\[find-file-other-window], but marks buffer as read-only.
1581 Use \\[read-only-mode] to permit editing."
1583 (find-file-read-args "Find file read-only other window: "
1584 (confirm-nonexistent-file-or-buffer)))
1585 (find-file--read-only #'find-file-other-window filename wildcards
))
1587 (defun find-file-read-only-other-frame (filename &optional wildcards
)
1588 "Edit file FILENAME in another frame but don't allow changes.
1589 Like \\[find-file-other-frame], but marks buffer as read-only.
1590 Use \\[read-only-mode] to permit editing."
1592 (find-file-read-args "Find file read-only other frame: "
1593 (confirm-nonexistent-file-or-buffer)))
1594 (find-file--read-only #'find-file-other-frame filename wildcards
))
1596 (defun find-alternate-file-other-window (filename &optional wildcards
)
1597 "Find file FILENAME as a replacement for the file in the next window.
1598 This command does not select that window.
1600 See \\[find-file] for the possible forms of the FILENAME argument.
1602 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1603 expand wildcards (if any) and replace the file with multiple files."
1605 (save-selected-window
1607 (let ((file buffer-file-name
)
1611 (setq file-name
(file-name-nondirectory file
)
1612 file-dir
(file-name-directory file
)))
1613 (list (read-file-name
1614 "Find alternate file: " file-dir nil
1615 (confirm-nonexistent-file-or-buffer) file-name
)
1618 (find-file-other-window filename wildcards
)
1619 (save-selected-window
1621 (find-alternate-file filename wildcards
))))
1623 ;; Defined and used in buffer.c, but not as a DEFVAR_LISP.
1624 (defvar kill-buffer-hook nil
1625 "Hook run when a buffer is killed.
1626 The buffer being killed is current while the hook is running.
1629 Note: Be careful with let-binding this hook considering it is
1630 frequently used for cleanup.")
1632 (defun find-alternate-file (filename &optional wildcards
)
1633 "Find file FILENAME, select its buffer, kill previous buffer.
1634 If the current buffer now contains an empty file that you just visited
1635 \(presumably by mistake), use this command to visit the file you really want.
1637 See \\[find-file] for the possible forms of the FILENAME argument.
1639 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1640 expand wildcards (if any) and replace the file with multiple files.
1642 If the current buffer is an indirect buffer, or the base buffer
1643 for one or more indirect buffers, the other buffer(s) are not
1646 (let ((file buffer-file-name
)
1650 (setq file-name
(file-name-nondirectory file
)
1651 file-dir
(file-name-directory file
)))
1652 (list (read-file-name
1653 "Find alternate file: " file-dir nil
1654 (confirm-nonexistent-file-or-buffer) file-name
)
1656 (unless (run-hook-with-args-until-failure 'kill-buffer-query-functions
)
1657 (user-error "Aborted"))
1658 (and (buffer-modified-p) buffer-file-name
1660 (format-message "Kill and replace buffer `%s' without saving it? "
1662 (user-error "Aborted"))
1663 (let ((obuf (current-buffer))
1664 (ofile buffer-file-name
)
1665 (onum buffer-file-number
)
1666 (odir dired-directory
)
1667 (otrue buffer-file-truename
)
1668 (oname (buffer-name)))
1669 ;; Run `kill-buffer-hook' here. It needs to happen before
1670 ;; variables like `buffer-file-name' etc are set to nil below,
1671 ;; because some of the hooks that could be invoked
1672 ;; (e.g., `save-place-to-alist') depend on those variables.
1674 ;; Note that `kill-buffer-hook' is not what queries whether to
1675 ;; save a modified buffer visiting a file. Rather, `kill-buffer'
1676 ;; asks that itself. Thus, there's no need to temporarily do
1677 ;; `(set-buffer-modified-p nil)' before running this hook.
1678 (run-hooks 'kill-buffer-hook
)
1679 ;; Okay, now we can end-of-life the old buffer.
1680 (if (get-buffer " **lose**")
1681 (kill-buffer " **lose**"))
1682 (rename-buffer " **lose**")
1686 ;; This prevents us from finding the same buffer
1687 ;; if we specified the same file again.
1688 (setq buffer-file-name nil
)
1689 (setq buffer-file-number nil
)
1690 (setq buffer-file-truename nil
)
1691 ;; Likewise for dired buffers.
1692 (setq dired-directory nil
)
1693 (find-file filename wildcards
))
1694 (when (eq obuf
(current-buffer))
1695 ;; This executes if find-file gets an error
1696 ;; and does not really find anything.
1697 ;; We put things back as they were.
1698 ;; If find-file actually finds something, we kill obuf below.
1699 (setq buffer-file-name ofile
)
1700 (setq buffer-file-number onum
)
1701 (setq buffer-file-truename otrue
)
1702 (setq dired-directory odir
)
1704 (rename-buffer oname
)))
1705 (unless (eq (current-buffer) obuf
)
1706 (with-current-buffer obuf
1707 ;; We already ran these; don't run them again.
1708 (let (kill-buffer-query-functions kill-buffer-hook
)
1709 (kill-buffer obuf
))))))
1711 ;; FIXME we really need to fold the uniquify stuff in here by default,
1712 ;; not using advice, and add it to the doc string.
1713 (defun create-file-buffer (filename)
1714 "Create a suitably named buffer for visiting FILENAME, and return it.
1715 FILENAME (sans directory) is used unchanged if that name is free;
1716 otherwise a string <2> or <3> or ... is appended to get an unused name.
1718 Emacs treats buffers whose names begin with a space as internal buffers.
1719 To avoid confusion when visiting a file whose name begins with a space,
1720 this function prepends a \"|\" to the final result if necessary."
1721 (let ((lastname (file-name-nondirectory filename
)))
1722 (if (string= lastname
"")
1723 (setq lastname filename
))
1724 (generate-new-buffer (if (string-match-p "\\` " lastname
)
1725 (concat "|" lastname
)
1728 (defun generate-new-buffer (name)
1729 "Create and return a buffer with a name based on NAME.
1730 Choose the buffer's name using `generate-new-buffer-name'."
1731 (get-buffer-create (generate-new-buffer-name name
)))
1733 (defcustom automount-dir-prefix
(purecopy "^/tmp_mnt/")
1734 "Regexp to match the automounter prefix in a directory name."
1737 (make-obsolete-variable 'automount-dir-prefix
'directory-abbrev-alist
"24.3")
1739 (defvar abbreviated-home-dir nil
1740 "Regexp matching the user's homedir at the beginning of file name.
1741 The value includes abbreviation according to `directory-abbrev-alist'.")
1743 (defun abbreviate-file-name (filename)
1744 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
1745 This also substitutes \"~\" for the user's home directory (unless the
1746 home directory is a root directory) and removes automounter prefixes
1747 \(see the variable `automount-dir-prefix')."
1748 ;; Get rid of the prefixes added by the automounter.
1750 (if (and automount-dir-prefix
1751 (string-match automount-dir-prefix filename
)
1752 (file-exists-p (file-name-directory
1753 (substring filename
(1- (match-end 0))))))
1754 (setq filename
(substring filename
(1- (match-end 0)))))
1755 ;; Avoid treating /home/foo as /home/Foo during `~' substitution.
1756 ;; To fix this right, we need a `file-name-case-sensitive-p'
1757 ;; function, but we don't have that yet, so just guess.
1758 (let ((case-fold-search
1759 (memq system-type
'(ms-dos windows-nt darwin cygwin
))))
1760 ;; If any elt of directory-abbrev-alist matches this name,
1761 ;; abbreviate accordingly.
1762 (dolist (dir-abbrev directory-abbrev-alist
)
1763 (if (string-match (car dir-abbrev
) filename
)
1765 (concat (cdr dir-abbrev
)
1766 (substring filename
(match-end 0))))))
1767 ;; Compute and save the abbreviated homedir name.
1768 ;; We defer computing this until the first time it's needed, to
1769 ;; give time for directory-abbrev-alist to be set properly.
1770 ;; We include a slash at the end, to avoid spurious matches
1771 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
1772 (or abbreviated-home-dir
1773 (setq abbreviated-home-dir
1774 (let ((abbreviated-home-dir "$foo"))
1775 (setq abbreviated-home-dir
1777 (abbreviate-file-name (expand-file-name "~"))
1779 ;; Depending on whether default-directory does or
1780 ;; doesn't include non-ASCII characters, the value
1781 ;; of abbreviated-home-dir could be multibyte or
1782 ;; unibyte. In the latter case, we need to decode
1783 ;; it. Note that this function is called for the
1784 ;; first time (from startup.el) when
1785 ;; locale-coding-system is already set up.
1786 (if (multibyte-string-p abbreviated-home-dir
)
1787 abbreviated-home-dir
1788 (decode-coding-string abbreviated-home-dir
1789 (if (eq system-type
'windows-nt
)
1791 locale-coding-system
))))))
1793 ;; If FILENAME starts with the abbreviated homedir,
1794 ;; make it start with `~' instead.
1795 (if (and (string-match abbreviated-home-dir filename
)
1796 ;; If the home dir is just /, don't change it.
1797 (not (and (= (match-end 0) 1)
1798 (= (aref filename
0) ?
/)))
1799 ;; MS-DOS root directories can come with a drive letter;
1800 ;; Novell Netware allows drive letters beyond `Z:'.
1801 (not (and (memq system-type
'(ms-dos windows-nt cygwin
))
1803 (string-match "^[a-zA-`]:/$" filename
)))))
1806 (match-string 1 filename
)
1807 (substring filename
(match-end 0)))))
1810 (defun find-buffer-visiting (filename &optional predicate
)
1811 "Return the buffer visiting file FILENAME (a string).
1812 This is like `get-file-buffer', except that it checks for any buffer
1813 visiting the same file, possibly under a different name.
1814 If PREDICATE is non-nil, only buffers satisfying it are eligible,
1815 and others are ignored.
1816 If there is no such live buffer, return nil."
1817 (let ((predicate (or predicate
#'identity
))
1818 (truename (abbreviate-file-name (file-truename filename
))))
1819 (or (let ((buf (get-file-buffer filename
)))
1820 (when (and buf
(funcall predicate buf
)) buf
))
1821 (let ((list (buffer-list)) found
)
1822 (while (and (not found
) list
)
1823 (with-current-buffer (car list
)
1824 (if (and buffer-file-name
1825 (string= buffer-file-truename truename
)
1826 (funcall predicate
(current-buffer)))
1827 (setq found
(car list
))))
1828 (setq list
(cdr list
)))
1830 (let* ((attributes (file-attributes truename
))
1831 (number (nthcdr 10 attributes
))
1832 (list (buffer-list)) found
)
1833 (and buffer-file-numbers-unique
1834 (car-safe number
) ;Make sure the inode is not just nil.
1835 (while (and (not found
) list
)
1836 (with-current-buffer (car list
)
1837 (if (and buffer-file-name
1838 (equal buffer-file-number number
)
1839 ;; Verify this buffer's file number
1840 ;; still belongs to its file.
1841 (file-exists-p buffer-file-name
)
1842 (equal (file-attributes buffer-file-truename
)
1844 (funcall predicate
(current-buffer)))
1845 (setq found
(car list
))))
1846 (setq list
(cdr list
))))
1849 (defcustom find-file-wildcards t
1850 "Non-nil means file-visiting commands should handle wildcards.
1851 For example, if you specify `*.c', that would visit all the files
1852 whose names match the pattern."
1857 (defcustom find-file-suppress-same-file-warnings nil
1858 "Non-nil means suppress warning messages for symlinked files.
1859 When nil, Emacs prints a warning when visiting a file that is already
1860 visited, but with a different name. Setting this option to t
1861 suppresses this warning."
1866 (defcustom large-file-warning-threshold
10000000
1867 "Maximum size of file above which a confirmation is requested.
1868 When nil, never request confirmation."
1872 :type
'(choice integer
(const :tag
"Never request confirmation" nil
)))
1874 (defcustom out-of-memory-warning-percentage nil
1875 "Warn if file size exceeds this percentage of available free memory.
1876 When nil, never issue warning. Beware: This probably doesn't do what you
1877 think it does, because \"free\" is pretty hard to define in practice."
1881 :type
'(choice integer
(const :tag
"Never issue warning" nil
)))
1883 (defun abort-if-file-too-large (size op-type filename
)
1884 "If file SIZE larger than `large-file-warning-threshold', allow user to abort.
1885 OP-TYPE specifies the file operation being performed (for message to user)."
1886 (when (and large-file-warning-threshold size
1887 (> size large-file-warning-threshold
)
1888 (not (y-or-n-p (format "File %s is large (%s), really %s? "
1889 (file-name-nondirectory filename
)
1890 (file-size-human-readable size
) op-type
))))
1891 (user-error "Aborted")))
1893 (defun warn-maybe-out-of-memory (size)
1894 "Warn if an attempt to open file of SIZE bytes may run out of memory."
1895 (when (and (numberp size
) (not (zerop size
))
1896 (integerp out-of-memory-warning-percentage
))
1897 (let ((meminfo (memory-info)))
1898 (when (consp meminfo
)
1899 (let ((total-free-memory (float (+ (nth 1 meminfo
) (nth 3 meminfo
)))))
1900 (when (> (/ size
1024)
1901 (/ (* total-free-memory out-of-memory-warning-percentage
)
1904 "You are trying to open a file whose size (%s)
1905 exceeds the %S%% of currently available free memory (%s).
1906 If that fails, try to open it with `find-file-literally'
1907 \(but note that some characters might be displayed incorrectly)."
1908 (file-size-human-readable size
)
1909 out-of-memory-warning-percentage
1910 (file-size-human-readable (* total-free-memory
1024)))))))))
1912 (defun files--message (format &rest args
)
1913 "Like `message', except sometimes don't print to minibuffer.
1914 If the variable `save-silently' is non-nil, the message is not
1915 displayed on the minibuffer."
1916 (apply #'message format args
)
1917 (when save-silently
(message nil
)))
1919 (defun find-file-noselect (filename &optional nowarn rawfile wildcards
)
1920 "Read file FILENAME into a buffer and return the buffer.
1921 If a buffer exists visiting FILENAME, return that one, but
1922 verify that the file has not changed since visited or saved.
1923 The buffer is not selected, just returned to the caller.
1924 Optional second arg NOWARN non-nil means suppress any warning messages.
1925 Optional third arg RAWFILE non-nil means the file is read literally.
1926 Optional fourth arg WILDCARDS non-nil means do wildcard processing
1927 and visit all the matching files. When wildcards are actually
1928 used and expanded, return a list of buffers that are visiting
1931 (abbreviate-file-name
1932 (expand-file-name filename
)))
1933 (if (file-directory-p filename
)
1934 (or (and find-file-run-dired
1935 (run-hook-with-args-until-success
1936 'find-directory-functions
1937 (if find-file-visit-truename
1938 (abbreviate-file-name (file-truename filename
))
1940 (error "%s is a directory" filename
))
1943 (not (string-match "\\`/:" filename
))
1944 (string-match "[[*?]" filename
))
1945 (let ((files (condition-case nil
1946 (file-expand-wildcards filename t
)
1947 (error (list filename
))))
1948 (find-file-wildcards nil
))
1950 (find-file-noselect filename
)
1951 (mapcar #'find-file-noselect files
)))
1952 (let* ((buf (get-file-buffer filename
))
1953 (truename (abbreviate-file-name (file-truename filename
)))
1954 (attributes (file-attributes truename
))
1955 (number (nthcdr 10 attributes
))
1956 ;; Find any buffer for a file which has same truename.
1957 (other (and (not buf
) (find-buffer-visiting filename
))))
1958 ;; Let user know if there is a buffer with the same truename.
1962 find-file-suppress-same-file-warnings
1963 (string-equal filename
(buffer-file-name other
))
1964 (files--message "%s and %s are the same file"
1965 filename
(buffer-file-name other
)))
1966 ;; Optionally also find that buffer.
1967 (if (or find-file-existing-other-name find-file-visit-truename
)
1969 ;; Check to see if the file looks uncommonly large.
1970 (when (not (or buf nowarn
))
1971 (abort-if-file-too-large (nth 7 attributes
) "open" filename
)
1972 (warn-maybe-out-of-memory (nth 7 attributes
)))
1974 ;; We are using an existing buffer.
1977 (verify-visited-file-modtime buf
)
1978 (cond ((not (file-exists-p filename
))
1979 (setq nonexistent t
)
1980 (message "File %s no longer exists!" filename
))
1981 ;; Certain files should be reverted automatically
1982 ;; if they have changed on disk and not in the buffer.
1983 ((and (not (buffer-modified-p buf
))
1984 (let ((tail revert-without-query
)
1987 (if (string-match (car tail
) filename
)
1989 (setq tail
(cdr tail
)))
1991 (with-current-buffer buf
1992 (message "Reverting file %s..." filename
)
1994 (message "Reverting file %s...done" filename
)))
1996 (if (string= (file-name-nondirectory filename
)
1999 (if (buffer-modified-p buf
)
2000 "File %s changed on disk. Discard your edits? "
2001 "File %s changed on disk. Reread from disk? ")
2002 (file-name-nondirectory filename
))
2004 (if (buffer-modified-p buf
)
2005 "File %s changed on disk. Discard your edits in %s? "
2006 "File %s changed on disk. Reread from disk into %s? ")
2007 (file-name-nondirectory filename
)
2008 (buffer-name buf
))))
2009 (with-current-buffer buf
2010 (revert-buffer t t
)))))
2011 (with-current-buffer buf
2013 ;; Check if a formerly read-only file has become
2014 ;; writable and vice versa, but if the buffer agrees
2015 ;; with the new state of the file, that is ok too.
2016 (let ((read-only (not (file-writable-p buffer-file-name
))))
2017 (unless (or nonexistent
2018 (eq read-only buffer-file-read-only
)
2019 (eq read-only buffer-read-only
))
2022 (if read-only
"read-only" "writable"))
2024 (format "File %s is %s on disk. Make buffer %s, too? "
2026 new-status new-status
)))
2027 (y-or-n-p question
)))
2028 (setq buffer-read-only read-only
)))
2029 (setq buffer-file-read-only read-only
))
2031 (unless (or (eq (null rawfile
) (null find-file-literally
))
2033 ;; It is confusing to ask whether to visit
2034 ;; non-literally if they have the file in
2035 ;; hexl-mode or image-mode.
2036 (memq major-mode
'(hexl-mode image-mode
)))
2037 (if (buffer-modified-p)
2041 "The file %s is already visited normally,
2042 and you have edited the buffer. Now you have asked to visit it literally,
2043 meaning no coding system handling, format conversion, or local variables.
2044 Emacs can only visit a file in one way at a time.
2046 Do you want to save the file, and visit it literally instead? "
2047 "The file %s is already visited literally,
2048 meaning no coding system handling, format conversion, or local variables.
2049 You have edited the buffer. Now you have asked to visit the file normally,
2050 but Emacs can only visit a file in one way at a time.
2052 Do you want to save the file, and visit it normally instead? ")
2053 (file-name-nondirectory filename
)))
2056 (find-file-noselect-1 buf filename nowarn
2057 rawfile truename number
))
2062 Do you want to discard your changes, and visit the file literally now? "
2064 Do you want to discard your changes, and visit the file normally now? ")))
2065 (find-file-noselect-1 buf filename nowarn
2066 rawfile truename number
)
2067 (error (if rawfile
"File already visited non-literally"
2068 "File already visited literally"))))
2072 "The file %s is already visited normally.
2073 You have asked to visit it literally,
2074 meaning no coding system decoding, format conversion, or local variables.
2075 But Emacs can only visit a file in one way at a time.
2077 Do you want to revisit the file literally now? "
2078 "The file %s is already visited literally,
2079 meaning no coding system decoding, format conversion, or local variables.
2080 You have asked to visit it normally,
2081 but Emacs can only visit a file in one way at a time.
2083 Do you want to revisit the file normally now? ")
2084 (file-name-nondirectory filename
)))
2085 (find-file-noselect-1 buf filename nowarn
2086 rawfile truename number
)
2087 (error (if rawfile
"File already visited non-literally"
2088 "File already visited literally"))))))
2089 ;; Return the buffer we are using.
2091 ;; Create a new buffer.
2092 (setq buf
(create-file-buffer filename
))
2093 ;; find-file-noselect-1 may use a different buffer.
2094 (find-file-noselect-1 buf filename nowarn
2095 rawfile truename number
))))))
2097 (defun find-file-noselect-1 (buf filename nowarn rawfile truename number
)
2099 (with-current-buffer buf
2100 (kill-local-variable 'find-file-literally
)
2101 ;; Needed in case we are re-visiting the file with a different
2102 ;; text representation.
2103 (kill-local-variable 'buffer-file-coding-system
)
2104 (kill-local-variable 'cursor-type
)
2105 (let ((inhibit-read-only t
))
2107 (and (default-value 'enable-multibyte-characters
)
2109 (set-buffer-multibyte t
))
2112 (let ((inhibit-read-only t
))
2113 (insert-file-contents-literally filename t
))
2115 (when (and (file-exists-p filename
)
2116 (not (file-readable-p filename
)))
2118 (signal 'file-error
(list "File is not readable"
2120 ;; Unconditionally set error
2123 (let ((inhibit-read-only t
))
2124 (insert-file-contents filename t
))
2126 (when (and (file-exists-p filename
)
2127 (not (file-readable-p filename
)))
2129 (signal 'file-error
(list "File is not readable"
2131 ;; Run find-file-not-found-functions until one returns non-nil.
2132 (or (run-hook-with-args-until-success 'find-file-not-found-functions
)
2133 ;; If they fail too, set error.
2135 ;; Record the file's truename, and maybe use that as visited name.
2136 (if (equal filename buffer-file-name
)
2137 (setq buffer-file-truename truename
)
2138 (setq buffer-file-truename
2139 (abbreviate-file-name (file-truename buffer-file-name
))))
2140 (setq buffer-file-number number
)
2141 (if find-file-visit-truename
2142 (setq buffer-file-name
(expand-file-name buffer-file-truename
)))
2143 ;; Set buffer's default directory to that of the file.
2144 (setq default-directory
(file-name-directory buffer-file-name
))
2145 ;; Turn off backup files for certain file names. Since
2146 ;; this is a permanent local, the major mode won't eliminate it.
2147 (and backup-enable-predicate
2148 (not (funcall backup-enable-predicate buffer-file-name
))
2150 (make-local-variable 'backup-inhibited
)
2151 (setq backup-inhibited t
)))
2154 (set-buffer-multibyte nil
)
2155 (setq buffer-file-coding-system
'no-conversion
)
2156 (set-buffer-major-mode buf
)
2157 (setq-local find-file-literally t
))
2158 (after-find-file error
(not nowarn
)))
2161 (defun insert-file-contents-literally (filename &optional visit beg end replace
)
2162 "Like `insert-file-contents', but only reads in the file literally.
2163 See `insert-file-contents' for an explanation of the parameters.
2164 A buffer may be modified in several ways after reading into the buffer,
2165 due to Emacs features such as format decoding, character code
2166 conversion, `find-file-hook', automatic uncompression, etc.
2168 This function ensures that none of these modifications will take place."
2169 (let ((format-alist nil
)
2170 (after-insert-file-functions nil
)
2171 (coding-system-for-read 'no-conversion
)
2172 (coding-system-for-write 'no-conversion
)
2173 (inhibit-file-name-handlers
2174 ;; FIXME: Yuck!! We should turn insert-file-contents-literally
2175 ;; into a file operation instead!
2176 (append '(jka-compr-handler image-file-handler epa-file-handler
)
2177 inhibit-file-name-handlers
))
2178 (inhibit-file-name-operation 'insert-file-contents
))
2179 (insert-file-contents filename visit beg end replace
)))
2181 (defun insert-file-1 (filename insert-func
)
2182 (if (file-directory-p filename
)
2183 (signal 'file-error
(list "Opening input file" "Is a directory"
2185 ;; Check whether the file is uncommonly large
2186 (abort-if-file-too-large (nth 7 (file-attributes filename
)) "insert" filename
)
2187 (let* ((buffer (find-buffer-visiting (abbreviate-file-name (file-truename filename
))
2188 #'buffer-modified-p
))
2189 (tem (funcall insert-func filename
)))
2190 (push-mark (+ (point) (car (cdr tem
))))
2192 (message "File %s already visited and modified in buffer %s"
2193 filename
(buffer-name buffer
)))))
2195 (defun insert-file-literally (filename)
2196 "Insert contents of file FILENAME into buffer after point with no conversion.
2198 This function is meant for the user to run interactively.
2199 Don't call it from programs! Use `insert-file-contents-literally' instead.
2200 \(Its calling sequence is different; see its documentation)."
2201 (declare (interactive-only insert-file-contents-literally
))
2202 (interactive "*fInsert file literally: ")
2203 (insert-file-1 filename
#'insert-file-contents-literally
))
2205 (defvar find-file-literally nil
2206 "Non-nil if this buffer was made by `find-file-literally' or equivalent.
2207 This has the `permanent-local' property, which takes effect if you
2208 make the variable buffer-local.")
2209 (put 'find-file-literally
'permanent-local t
)
2211 (defun find-file-literally (filename)
2212 "Visit file FILENAME with no conversion of any kind.
2213 Format conversion and character code conversion are both disabled,
2214 and multibyte characters are disabled in the resulting buffer.
2215 The major mode used is Fundamental mode regardless of the file name,
2216 and local variable specifications in the file are ignored.
2217 Automatic uncompression and adding a newline at the end of the
2218 file due to `require-final-newline' is also disabled.
2220 You cannot absolutely rely on this function to result in
2221 visiting the file literally. If Emacs already has a buffer
2222 which is visiting the file, you get the existing buffer,
2223 regardless of whether it was created literally or not.
2225 In a Lisp program, if you want to be sure of accessing a file's
2226 contents literally, you should create a temporary buffer and then read
2227 the file contents into it using `insert-file-contents-literally'."
2229 (list (read-file-name
2230 "Find file literally: " nil default-directory
2231 (confirm-nonexistent-file-or-buffer))))
2232 (switch-to-buffer (find-file-noselect filename nil t
)))
2234 (defun after-find-file (&optional error warn noauto
2235 _after-find-file-from-revert-buffer
2237 "Called after finding a file and by the default revert function.
2238 Sets buffer mode, parses local variables.
2239 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
2240 error in reading the file. WARN non-nil means warn if there
2241 exists an auto-save file more recent than the visited file.
2242 NOAUTO means don't mess with auto-save mode.
2243 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER is ignored
2244 \(see `revert-buffer-in-progress-p' for similar functionality).
2245 Fifth arg NOMODES non-nil means don't alter the file's modes.
2246 Finishes by calling the functions in `find-file-hook'
2247 unless NOMODES is non-nil."
2248 (setq buffer-read-only
(not (file-writable-p buffer-file-name
)))
2255 ((and error
(file-attributes buffer-file-name
))
2256 (setq buffer-read-only t
)
2257 (if (and (file-symlink-p buffer-file-name
)
2259 (file-chase-links buffer-file-name
))))
2260 "Symbolic link that points to nonexistent file"
2261 "File exists, but cannot be read"))
2262 ((not buffer-read-only
)
2264 ;; No need to warn if buffer is auto-saved
2265 ;; under the name of the visited file.
2266 (not (and buffer-file-name
2267 auto-save-visited-file-name
))
2268 (file-newer-than-file-p (or buffer-auto-save-file-name
2269 (make-auto-save-file-name))
2271 (format "%s has auto save data; consider M-x recover-this-file"
2272 (file-name-nondirectory buffer-file-name
))
2273 (setq not-serious t
)
2274 (if error
"(New file)" nil
)))
2276 (setq not-serious t
)
2277 "Note: file is write protected")
2278 ((file-attributes (directory-file-name default-directory
))
2279 "File not found and directory write-protected")
2280 ((file-exists-p (file-name-directory buffer-file-name
))
2281 (setq buffer-read-only nil
))
2283 (setq buffer-read-only nil
)
2284 "Use M-x make-directory RET RET to create the directory and its parents"))))
2287 (or not-serious
(sit-for 1 t
))))
2288 (when (and auto-save-default
(not noauto
))
2289 (auto-save-mode 1)))
2290 ;; Make people do a little extra work (C-x C-q)
2291 ;; before altering a backup file.
2292 (when (backup-file-name-p buffer-file-name
)
2293 (setq buffer-read-only t
))
2294 ;; When a file is marked read-only,
2295 ;; make the buffer read-only even if root is looking at it.
2296 (when (and (file-modes (buffer-file-name))
2297 (zerop (logand (file-modes (buffer-file-name)) #o222
)))
2298 (setq buffer-read-only t
))
2300 (when (and view-read-only view-mode
)
2303 ;; If requested, add a newline at the end of the file.
2304 (and (memq require-final-newline
'(visit visit-save
))
2305 (> (point-max) (point-min))
2306 (/= (char-after (1- (point-max))) ?
\n)
2307 (not (and (eq selective-display t
)
2308 (= (char-after (1- (point-max))) ?
\r)))
2309 (not buffer-read-only
)
2311 (goto-char (point-max))
2312 (ignore-errors (insert "\n"))))
2313 (when (and buffer-read-only
2315 (not (eq (get major-mode
'mode-class
) 'special
)))
2317 (run-hooks 'find-file-hook
)))
2319 (define-obsolete-function-alias 'report-errors
'with-demoted-errors
"25.1")
2321 (defun normal-mode (&optional find-file
)
2322 "Choose the major mode for this buffer automatically.
2323 Also sets up any specified local variables of the file.
2324 Uses the visited file name, the -*- line, and the local variables spec.
2326 This function is called automatically from `find-file'. In that case,
2327 we may set up the file-specified mode and local variables,
2328 depending on the value of `enable-local-variables'.
2329 In addition, if `local-enable-local-variables' is nil, we do
2330 not set local variables (though we do notice a mode specified with -*-.)
2332 `enable-local-variables' is ignored if you run `normal-mode' interactively,
2333 or from Lisp without specifying the optional argument FIND-FILE;
2334 in that case, this function acts as if `enable-local-variables' were t."
2337 (let ((enable-local-variables (or (not find-file
) enable-local-variables
)))
2338 ;; FIXME this is less efficient than it could be, since both
2339 ;; s-a-m and h-l-v may parse the same regions, looking for "mode:".
2340 (with-demoted-errors "File mode specification error: %s"
2342 (with-demoted-errors "File local-variables error: %s"
2343 (hack-local-variables)))
2344 ;; Turn font lock off and on, to make sure it takes account of
2345 ;; whatever file local variables are relevant to it.
2346 (when (and font-lock-mode
2347 ;; Font-lock-mode (now in font-core.el) can be ON when
2348 ;; font-lock.el still hasn't been loaded.
2349 (boundp 'font-lock-keywords
)
2350 (eq (car font-lock-keywords
) t
))
2351 (setq font-lock-keywords
(cadr font-lock-keywords
))
2352 (font-lock-mode 1)))
2354 (defcustom auto-mode-case-fold t
2355 "Non-nil means to try second pass through `auto-mode-alist'.
2356 This means that if the first case-sensitive search through the alist fails
2357 to find a matching major mode, a second case-insensitive search is made.
2358 On systems with case-insensitive file names, this variable is ignored,
2359 since only a single case-insensitive search through the alist is made."
2364 (defvar auto-mode-alist
2365 ;; Note: The entries for the modes defined in cc-mode.el (c-mode,
2366 ;; c++-mode, java-mode and more) are added through autoload
2367 ;; directives in that file. That way is discouraged since it
2368 ;; spreads out the definition of the initial value.
2371 (cons (purecopy (car elt
)) (cdr elt
)))
2372 `(;; do this first, so that .html.pl is Polish html, not Perl
2373 ("\\.[sx]?html?\\(\\.[a-zA-Z_]+\\)?\\'" . html-mode
)
2374 ("\\.svgz?\\'" . image-mode
)
2375 ("\\.svgz?\\'" . xml-mode
)
2376 ("\\.x[bp]m\\'" . image-mode
)
2377 ("\\.x[bp]m\\'" . c-mode
)
2378 ("\\.p[bpgn]m\\'" . image-mode
)
2379 ("\\.tiff?\\'" . image-mode
)
2380 ("\\.gif\\'" . image-mode
)
2381 ("\\.png\\'" . image-mode
)
2382 ("\\.jpe?g\\'" . image-mode
)
2383 ("\\.te?xt\\'" . text-mode
)
2384 ("\\.[tT]e[xX]\\'" . tex-mode
)
2385 ("\\.ins\\'" . tex-mode
) ;Installation files for TeX packages.
2386 ("\\.ltx\\'" . latex-mode
)
2387 ("\\.dtx\\'" . doctex-mode
)
2388 ("\\.org\\'" . org-mode
)
2389 ("\\.el\\'" . emacs-lisp-mode
)
2390 ("Project\\.ede\\'" . emacs-lisp-mode
)
2391 ("\\.\\(scm\\|stk\\|ss\\|sch\\)\\'" . scheme-mode
)
2392 ("\\.l\\'" . lisp-mode
)
2393 ("\\.li?sp\\'" . lisp-mode
)
2394 ("\\.[fF]\\'" . fortran-mode
)
2395 ("\\.for\\'" . fortran-mode
)
2396 ("\\.p\\'" . pascal-mode
)
2397 ("\\.pas\\'" . pascal-mode
)
2398 ("\\.\\(dpr\\|DPR\\)\\'" . delphi-mode
)
2399 ("\\.ad[abs]\\'" . ada-mode
)
2400 ("\\.ad[bs].dg\\'" . ada-mode
)
2401 ("\\.\\([pP]\\([Llm]\\|erl\\|od\\)\\|al\\)\\'" . perl-mode
)
2402 ("Imakefile\\'" . makefile-imake-mode
)
2403 ("Makeppfile\\(?:\\.mk\\)?\\'" . makefile-makepp-mode
) ; Put this before .mk
2404 ("\\.makepp\\'" . makefile-makepp-mode
)
2405 ,@(if (memq system-type
'(berkeley-unix darwin
))
2406 '(("\\.mk\\'" . makefile-bsdmake-mode
)
2407 ("\\.make\\'" . makefile-bsdmake-mode
)
2408 ("GNUmakefile\\'" . makefile-gmake-mode
)
2409 ("[Mm]akefile\\'" . makefile-bsdmake-mode
))
2410 '(("\\.mk\\'" . makefile-gmake-mode
) ; Might be any make, give Gnu the host advantage
2411 ("\\.make\\'" . makefile-gmake-mode
)
2412 ("[Mm]akefile\\'" . makefile-gmake-mode
)))
2413 ("\\.am\\'" . makefile-automake-mode
)
2414 ;; Less common extensions come here
2415 ;; so more common ones above are found faster.
2416 ("\\.texinfo\\'" . texinfo-mode
)
2417 ("\\.te?xi\\'" . texinfo-mode
)
2418 ("\\.[sS]\\'" . asm-mode
)
2419 ("\\.asm\\'" . asm-mode
)
2420 ("\\.css\\'" . css-mode
)
2421 ("\\.mixal\\'" . mixal-mode
)
2422 ("\\.gcov\\'" . compilation-mode
)
2423 ;; Besides .gdbinit, gdb documents other names to be usable for init
2424 ;; files, cross-debuggers can use something like
2425 ;; .PROCESSORNAME-gdbinit so that the host and target gdbinit files
2426 ;; don't interfere with each other.
2427 ("/\\.[a-z0-9-]*gdbinit" . gdb-script-mode
)
2428 ;; GDB 7.5 introduced OBJFILE-gdb.gdb script files; e.g. a file
2429 ;; named 'emacs-gdb.gdb', if it exists, will be automatically
2430 ;; loaded when GDB reads an objfile called 'emacs'.
2431 ("-gdb\\.gdb" . gdb-script-mode
)
2432 ("[cC]hange\\.?[lL]og?\\'" . change-log-mode
)
2433 ("[cC]hange[lL]og[-.][0-9]+\\'" . change-log-mode
)
2434 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode
)
2435 ("\\.scm\\.[0-9]*\\'" . scheme-mode
)
2436 ("\\.[ckz]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode
)
2437 ("\\.bash\\'" . sh-mode
)
2438 ("\\(/\\|\\`\\)\\.\\(bash_\\(profile\\|history\\|log\\(in\\|out\\)\\)\\|z?log\\(in\\|out\\)\\)\\'" . sh-mode
)
2439 ("\\(/\\|\\`\\)\\.\\(shrc\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode
)
2440 ("\\(/\\|\\`\\)\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode
)
2441 ("\\.m?spec\\'" . sh-mode
)
2442 ("\\.m[mes]\\'" . nroff-mode
)
2443 ("\\.man\\'" . nroff-mode
)
2444 ("\\.sty\\'" . latex-mode
)
2445 ("\\.cl[so]\\'" . latex-mode
) ;LaTeX 2e class option
2446 ("\\.bbl\\'" . latex-mode
)
2447 ("\\.bib\\'" . bibtex-mode
)
2448 ("\\.bst\\'" . bibtex-style-mode
)
2449 ("\\.sql\\'" . sql-mode
)
2450 ("\\.m[4c]\\'" . m4-mode
)
2451 ("\\.mf\\'" . metafont-mode
)
2452 ("\\.mp\\'" . metapost-mode
)
2453 ("\\.vhdl?\\'" . vhdl-mode
)
2454 ("\\.article\\'" . text-mode
)
2455 ("\\.letter\\'" . text-mode
)
2456 ("\\.i?tcl\\'" . tcl-mode
)
2457 ("\\.exp\\'" . tcl-mode
)
2458 ("\\.itk\\'" . tcl-mode
)
2459 ("\\.icn\\'" . icon-mode
)
2460 ("\\.sim\\'" . simula-mode
)
2461 ("\\.mss\\'" . scribe-mode
)
2462 ;; The Fortran standard does not say anything about file extensions.
2463 ;; .f90 was widely used for F90, now we seem to be trapped into
2464 ;; using a different extension for each language revision.
2465 ;; Anyway, the following extensions are supported by gfortran.
2466 ("\\.f9[05]\\'" . f90-mode
)
2467 ("\\.f0[38]\\'" . f90-mode
)
2468 ("\\.indent\\.pro\\'" . fundamental-mode
) ; to avoid idlwave-mode
2469 ("\\.\\(pro\\|PRO\\)\\'" . idlwave-mode
)
2470 ("\\.srt\\'" . srecode-template-mode
)
2471 ("\\.prolog\\'" . prolog-mode
)
2472 ("\\.tar\\'" . tar-mode
)
2473 ;; The list of archive file extensions should be in sync with
2474 ;; `auto-coding-alist' with `no-conversion' coding system.
2476 arc\\|zip\\|lzh\\|lha\\|zoo\\|[jew]ar\\|xpi\\|rar\\|7z\\|\
2477 ARC\\|ZIP\\|LZH\\|LHA\\|ZOO\\|[JEW]AR\\|XPI\\|RAR\\|7Z\\)\\'" . archive-mode
)
2478 ("\\.oxt\\'" . archive-mode
) ;(Open|Libre)Office extensions.
2479 ("\\.\\(deb\\|[oi]pk\\)\\'" . archive-mode
) ; Debian/Opkg packages.
2480 ;; Mailer puts message to be edited in
2481 ;; /tmp/Re.... or Message
2482 ("\\`/tmp/Re" . text-mode
)
2483 ("/Message[0-9]*\\'" . text-mode
)
2484 ;; some news reader is reported to use this
2485 ("\\`/tmp/fol/" . text-mode
)
2486 ("\\.oak\\'" . scheme-mode
)
2487 ("\\.sgml?\\'" . sgml-mode
)
2488 ("\\.x[ms]l\\'" . xml-mode
)
2489 ("\\.dbk\\'" . xml-mode
)
2490 ("\\.dtd\\'" . sgml-mode
)
2491 ("\\.ds\\(ss\\)?l\\'" . dsssl-mode
)
2492 ("\\.jsm?\\'" . javascript-mode
)
2493 ("\\.json\\'" . javascript-mode
)
2494 ("\\.[ds]?vh?\\'" . verilog-mode
)
2495 ("\\.by\\'" . bovine-grammar-mode
)
2496 ("\\.wy\\'" . wisent-grammar-mode
)
2497 ;; .emacs or .gnus or .viper following a directory delimiter in
2498 ;; Unix or MS-DOS syntax.
2499 ("[:/\\]\\..*\\(emacs\\|gnus\\|viper\\)\\'" . emacs-lisp-mode
)
2500 ("\\`\\..*emacs\\'" . emacs-lisp-mode
)
2501 ;; _emacs following a directory delimiter in MS-DOS syntax
2502 ("[:/]_emacs\\'" . emacs-lisp-mode
)
2503 ("/crontab\\.X*[0-9]+\\'" . shell-script-mode
)
2504 ("\\.ml\\'" . lisp-mode
)
2505 ;; Linux-2.6.9 uses some different suffix for linker scripts:
2506 ;; "ld", "lds", "lds.S", "lds.in", "ld.script", and "ld.script.balo".
2507 ;; eCos uses "ld" and "ldi". Netbsd uses "ldscript.*".
2508 ("\\.ld[si]?\\'" . ld-script-mode
)
2509 ("ld\\.?script\\'" . ld-script-mode
)
2510 ;; .xs is also used for ld scripts, but seems to be more commonly
2511 ;; associated with Perl .xs files (C with Perl bindings). (Bug#7071)
2512 ("\\.xs\\'" . c-mode
)
2513 ;; Explained in binutils ld/genscripts.sh. Eg:
2514 ;; A .x script file is the default script.
2515 ;; A .xr script is for linking without relocation (-r flag). Etc.
2516 ("\\.x[abdsru]?[cnw]?\\'" . ld-script-mode
)
2517 ("\\.zone\\'" . dns-mode
)
2518 ("\\.soa\\'" . dns-mode
)
2519 ;; Common Lisp ASDF package system.
2520 ("\\.asd\\'" . lisp-mode
)
2521 ("\\.\\(asn\\|mib\\|smi\\)\\'" . snmp-mode
)
2522 ("\\.\\(as\\|mi\\|sm\\)2\\'" . snmpv2-mode
)
2523 ("\\.\\(diffs?\\|patch\\|rej\\)\\'" . diff-mode
)
2524 ("\\.\\(dif\\|pat\\)\\'" . diff-mode
) ; for MS-DOS
2525 ("\\.[eE]?[pP][sS]\\'" . ps-mode
)
2526 ("\\.\\(?:PDF\\|DVI\\|OD[FGPST]\\|DOCX?\\|XLSX?\\|PPTX?\\|pdf\\|djvu\\|dvi\\|od[fgpst]\\|docx?\\|xlsx?\\|pptx?\\)\\'" . doc-view-mode-maybe
)
2527 ("configure\\.\\(ac\\|in\\)\\'" . autoconf-mode
)
2528 ("\\.s\\(v\\|iv\\|ieve\\)\\'" . sieve-mode
)
2529 ("BROWSE\\'" . ebrowse-tree-mode
)
2530 ("\\.ebrowse\\'" . ebrowse-tree-mode
)
2531 ("#\\*mail\\*" . mail-mode
)
2532 ("\\.g\\'" . antlr-mode
)
2533 ("\\.mod\\'" . m2-mode
)
2534 ("\\.ses\\'" . ses-mode
)
2535 ("\\.docbook\\'" . sgml-mode
)
2536 ("\\.com\\'" . dcl-mode
)
2537 ("/config\\.\\(?:bat\\|log\\)\\'" . fundamental-mode
)
2538 ;; Windows candidates may be opened case sensitively on Unix
2539 ("\\.\\(?:[iI][nN][iI]\\|[lL][sS][tT]\\|[rR][eE][gG]\\|[sS][yY][sS]\\)\\'" . conf-mode
)
2540 ("\\.\\(?:desktop\\|la\\)\\'" . conf-unix-mode
)
2541 ("\\.ppd\\'" . conf-ppd-mode
)
2542 ("java.+\\.conf\\'" . conf-javaprop-mode
)
2543 ("\\.properties\\(?:\\.[a-zA-Z0-9._-]+\\)?\\'" . conf-javaprop-mode
)
2544 ("\\`/etc/\\(?:DIR_COLORS\\|ethers\\|.?fstab\\|.*hosts\\|lesskey\\|login\\.?de\\(?:fs\\|vperm\\)\\|magic\\|mtab\\|pam\\.d/.*\\|permissions\\(?:\\.d/.+\\)?\\|protocols\\|rpc\\|services\\)\\'" . conf-space-mode
)
2545 ("\\`/etc/\\(?:acpid?/.+\\|aliases\\(?:\\.d/.+\\)?\\|default/.+\\|group-?\\|hosts\\..+\\|inittab\\|ksysguarddrc\\|opera6rc\\|passwd-?\\|shadow-?\\|sysconfig/.+\\)\\'" . conf-mode
)
2546 ;; ChangeLog.old etc. Other change-log-mode entries are above;
2547 ;; this has lower priority to avoid matching changelog.sgml etc.
2548 ("[cC]hange[lL]og[-.][-0-9a-z]+\\'" . change-log-mode
)
2549 ;; either user's dot-files or under /etc or some such
2550 ("/\\.?\\(?:gitconfig\\|gnokiirc\\|hgrc\\|kde.*rc\\|mime\\.types\\|wgetrc\\)\\'" . conf-mode
)
2551 ;; alas not all ~/.*rc files are like this
2552 ("/\\.\\(?:enigma\\|gltron\\|gtk\\|hxplayer\\|net\\|neverball\\|qt/.+\\|realplayer\\|scummvm\\|sversion\\|sylpheed/.+\\|xmp\\)rc\\'" . conf-mode
)
2553 ("/\\.\\(?:gdbtkinit\\|grip\\|orbital/.+txt\\|rhosts\\|tuxracer/options\\)\\'" . conf-mode
)
2554 ("/\\.?X\\(?:default\\|resource\\|re\\)s\\>" . conf-xdefaults-mode
)
2555 ("/X11.+app-defaults/\\|\\.ad\\'" . conf-xdefaults-mode
)
2556 ("/X11.+locale/.+/Compose\\'" . conf-colon-mode
)
2557 ;; this contains everything twice, with space and with colon :-(
2558 ("/X11.+locale/compose\\.dir\\'" . conf-javaprop-mode
)
2559 ;; Get rid of any trailing .n.m and try again.
2560 ;; This is for files saved by cvs-merge that look like .#<file>.<rev>
2561 ;; or .#<file>.<rev>-<rev> or VC's <file>.~<rev>~.
2562 ;; Using mode nil rather than `ignore' would let the search continue
2563 ;; through this list (with the shortened name) rather than start over.
2564 ("\\.~?[0-9]+\\.[0-9][-.0-9]*~?\\'" nil t
)
2565 ("\\.\\(?:orig\\|in\\|[bB][aA][kK]\\)\\'" nil t
)
2566 ;; This should come after "in" stripping (e.g. config.h.in).
2567 ;; *.cf, *.cfg, *.conf, *.config[.local|.de_DE.UTF8|...], */config
2568 ("[/.]c\\(?:on\\)?f\\(?:i?g\\)?\\(?:\\.[a-zA-Z0-9._-]+\\)?\\'" . conf-mode-maybe
)
2569 ;; The following should come after the ChangeLog pattern
2570 ;; for the sake of ChangeLog.1, etc.
2571 ;; and after the .scm.[0-9] and CVS' <file>.<rev> patterns too.
2572 ("\\.[1-9]\\'" . nroff-mode
)))
2573 "Alist of filename patterns vs corresponding major mode functions.
2574 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
2575 \(NON-NIL stands for anything that is not nil; the value does not matter.)
2576 Visiting a file whose name matches REGEXP specifies FUNCTION as the
2577 mode function to use. FUNCTION will be called, unless it is nil.
2579 If the element has the form (REGEXP FUNCTION NON-NIL), then after
2580 calling FUNCTION (if it's not nil), we delete the suffix that matched
2581 REGEXP and search the list again for another match.
2583 The extensions whose FUNCTION is `archive-mode' should also
2584 appear in `auto-coding-alist' with `no-conversion' coding system.
2586 See also `interpreter-mode-alist', which detects executable script modes
2587 based on the interpreters they specify to run,
2588 and `magic-mode-alist', which determines modes based on file contents.")
2589 (put 'auto-mode-alist
'risky-local-variable t
)
2591 (defun conf-mode-maybe ()
2592 "Select Conf mode or XML mode according to start of file."
2596 (goto-char (point-min))
2597 (looking-at "<\\?xml \\|<!-- \\|<!DOCTYPE ")))
2601 (defvar interpreter-mode-alist
2602 ;; Note: The entries for the modes defined in cc-mode.el (awk-mode
2603 ;; and pike-mode) are added through autoload directives in that
2604 ;; file. That way is discouraged since it spreads out the
2605 ;; definition of the initial value.
2608 (cons (purecopy (car l
)) (cdr l
)))
2609 '(("\\(mini\\)?perl5?" . perl-mode
)
2610 ("wishx?" . tcl-mode
)
2611 ("tcl\\(sh\\)?" . tcl-mode
)
2612 ("expect" . tcl-mode
)
2613 ("octave" . octave-mode
)
2614 ("scm" . scheme-mode
)
2615 ("[acjkwz]sh" . sh-mode
)
2616 ("r?bash2?" . sh-mode
)
2619 ("\\(dt\\|pd\\|w\\)ksh" . sh-mode
)
2621 ("i?tcsh" . sh-mode
)
2626 ("tail" . text-mode
)
2627 ("more" . text-mode
)
2628 ("less" . text-mode
)
2630 ("make" . makefile-gmake-mode
) ; Debian uses this
2631 ("guile" . scheme-mode
)
2632 ("clisp" . lisp-mode
)
2633 ("emacs" . emacs-lisp-mode
)))
2634 "Alist mapping interpreter names to major modes.
2635 This is used for files whose first lines match `auto-mode-interpreter-regexp'.
2636 Each element looks like (REGEXP . MODE).
2637 If REGEXP matches the entire name (minus any directory part) of
2638 the interpreter specified in the first line of a script, enable
2641 See also `auto-mode-alist'.")
2643 (define-obsolete-variable-alias 'inhibit-first-line-modes-regexps
2644 'inhibit-file-local-variables-regexps
"24.1")
2646 ;; TODO really this should be a list of modes (eg tar-mode), not regexps,
2647 ;; because we are duplicating info from auto-mode-alist.
2648 ;; TODO many elements of this list are also in auto-coding-alist.
2649 (defvar inhibit-local-variables-regexps
2650 (mapcar 'purecopy
'("\\.tar\\'" "\\.t[bg]z\\'"
2651 "\\.arc\\'" "\\.zip\\'" "\\.lzh\\'" "\\.lha\\'"
2652 "\\.zoo\\'" "\\.[jew]ar\\'" "\\.xpi\\'" "\\.rar\\'"
2654 "\\.sx[dmicw]\\'" "\\.odt\\'"
2655 "\\.diff\\'" "\\.patch\\'"
2656 "\\.tiff?\\'" "\\.gif\\'" "\\.png\\'" "\\.jpe?g\\'"))
2657 "List of regexps matching file names in which to ignore local variables.
2658 This includes `-*-' lines as well as trailing \"Local Variables\" sections.
2659 Files matching this list are typically binary file formats.
2660 They may happen to contain sequences that look like local variable
2661 specifications, but are not really, or they may be containers for
2662 member files with their own local variable sections, which are
2663 not appropriate for the containing file.
2664 The function `inhibit-local-variables-p' uses this.")
2666 (define-obsolete-variable-alias 'inhibit-first-line-modes-suffixes
2667 'inhibit-local-variables-suffixes
"24.1")
2669 (defvar inhibit-local-variables-suffixes nil
2670 "List of regexps matching suffixes to remove from file names.
2671 The function `inhibit-local-variables-p' uses this: when checking
2672 a file name, it first discards from the end of the name anything that
2673 matches one of these regexps.")
2675 ;; Can't think of any situation in which you'd want this to be nil...
2676 (defvar inhibit-local-variables-ignore-case t
2677 "Non-nil means `inhibit-local-variables-p' ignores case.")
2679 (defun inhibit-local-variables-p ()
2680 "Return non-nil if file local variables should be ignored.
2681 This checks the file (or buffer) name against `inhibit-local-variables-regexps'
2682 and `inhibit-local-variables-suffixes'. If
2683 `inhibit-local-variables-ignore-case' is non-nil, this ignores case."
2684 (let ((temp inhibit-local-variables-regexps
)
2685 (name (if buffer-file-name
2686 (file-name-sans-versions buffer-file-name
)
2688 (case-fold-search inhibit-local-variables-ignore-case
))
2689 (while (let ((sufs inhibit-local-variables-suffixes
))
2690 (while (and sufs
(not (string-match (car sufs
) name
)))
2691 (setq sufs
(cdr sufs
)))
2693 (setq name
(substring name
0 (match-beginning 0))))
2695 (not (string-match (car temp
) name
)))
2696 (setq temp
(cdr temp
)))
2699 (defvar auto-mode-interpreter-regexp
2700 (purecopy "#![ \t]?\\([^ \t\n]*\
2701 /bin/env[ \t]\\)?\\([^ \t\n]+\\)")
2702 "Regexp matching interpreters, for file mode determination.
2703 This regular expression is matched against the first line of a file
2704 to determine the file's mode in `set-auto-mode'. If it matches, the file
2705 is assumed to be interpreted by the interpreter matched by the second group
2706 of the regular expression. The mode is then determined as the mode
2707 associated with that interpreter in `interpreter-mode-alist'.")
2709 (defvar magic-mode-alist nil
2710 "Alist of buffer beginnings vs. corresponding major mode functions.
2711 Each element looks like (REGEXP . FUNCTION) or (MATCH-FUNCTION . FUNCTION).
2712 After visiting a file, if REGEXP matches the text at the beginning of the
2713 buffer, or calling MATCH-FUNCTION returns non-nil, `normal-mode' will
2714 call FUNCTION rather than allowing `auto-mode-alist' to decide the buffer's
2717 If FUNCTION is nil, then it is not called. (That is a way of saying
2718 \"allow `auto-mode-alist' to decide for these files.\")")
2719 (put 'magic-mode-alist
'risky-local-variable t
)
2721 (defvar magic-fallback-mode-alist
2723 `((image-type-auto-detected-p . image-mode
)
2724 ("\\(PK00\\)?[P]K\003\004" . archive-mode
) ; zip
2725 ;; The < comes before the groups (but the first) to reduce backtracking.
2726 ;; TODO: UTF-16 <?xml may be preceded by a BOM 0xff 0xfe or 0xfe 0xff.
2727 ;; We use [ \t\r\n] instead of `\\s ' to make regex overflow less likely.
2728 (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
2729 (comment-re (concat "\\(?:!--" incomment-re
"*-->[ \t\r\n]*<\\)")))
2730 (concat "\\(?:<\\?xml[ \t\r\n]+[^>]*>\\)?[ \t\r\n]*<"
2732 "\\(?:!DOCTYPE[ \t\r\n]+[^>]*>[ \t\r\n]*<[ \t\r\n]*" comment-re
"*\\)?"
2733 "[Hh][Tt][Mm][Ll]"))
2735 ("<!DOCTYPE[ \t\r\n]+[Hh][Tt][Mm][Ll]" . html-mode
)
2736 ;; These two must come after html, because they are more general:
2737 ("<\\?xml " . xml-mode
)
2738 (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
2739 (comment-re (concat "\\(?:!--" incomment-re
"*-->[ \t\r\n]*<\\)")))
2740 (concat "[ \t\r\n]*<" comment-re
"*!DOCTYPE "))
2743 ("# xmcd " . conf-unix-mode
)))
2744 "Like `magic-mode-alist' but has lower priority than `auto-mode-alist'.
2745 Each element looks like (REGEXP . FUNCTION) or (MATCH-FUNCTION . FUNCTION).
2746 After visiting a file, if REGEXP matches the text at the beginning of the
2747 buffer, or calling MATCH-FUNCTION returns non-nil, `normal-mode' will
2748 call FUNCTION, provided that `magic-mode-alist' and `auto-mode-alist'
2749 have not specified a mode for this file.
2751 If FUNCTION is nil, then it is not called.")
2752 (put 'magic-fallback-mode-alist
'risky-local-variable t
)
2754 (defvar magic-mode-regexp-match-limit
4000
2755 "Upper limit on `magic-mode-alist' regexp matches.
2756 Also applies to `magic-fallback-mode-alist'.")
2758 (defun set-auto-mode (&optional keep-mode-if-same
)
2759 "Select major mode appropriate for current buffer.
2761 To find the right major mode, this function checks for a -*- mode tag
2762 checks for a `mode:' entry in the Local Variables section of the file,
2763 checks if it uses an interpreter listed in `interpreter-mode-alist',
2764 matches the buffer beginning against `magic-mode-alist',
2765 compares the filename against the entries in `auto-mode-alist',
2766 then matches the buffer beginning against `magic-fallback-mode-alist'.
2768 If `enable-local-variables' is nil, or if the file name matches
2769 `inhibit-local-variables-regexps', this function does not check
2770 for any mode: tag anywhere in the file. If `local-enable-local-variables'
2771 is nil, then the only mode: tag that can be relevant is a -*- one.
2773 If the optional argument KEEP-MODE-IF-SAME is non-nil, then we
2774 set the major mode only if that would change it. In other words
2775 we don't actually set it to the same mode the buffer already has."
2776 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
2777 (let ((try-locals (not (inhibit-local-variables-p)))
2778 end done mode modes
)
2779 ;; Once we drop the deprecated feature where mode: is also allowed to
2780 ;; specify minor-modes (ie, there can be more than one "mode:"), we can
2781 ;; remove this section and just let (hack-local-variables t) handle it.
2782 ;; Find a -*- mode tag.
2784 (goto-char (point-min))
2785 (skip-chars-forward " \t\n")
2786 ;; Note by design local-enable-local-variables does not matter here.
2787 (and enable-local-variables
2789 (setq end
(set-auto-mode-1))
2790 (if (save-excursion (search-forward ":" end t
))
2791 ;; Find all specifications for the `mode:' variable
2792 ;; and execute them left to right.
2793 (while (let ((case-fold-search t
))
2794 (or (and (looking-at "mode:")
2795 (goto-char (match-end 0)))
2796 (re-search-forward "[ \t;]mode:" end t
)))
2797 (skip-chars-forward " \t")
2798 (let ((beg (point)))
2799 (if (search-forward ";" end t
)
2802 (skip-chars-backward " \t")
2803 (push (intern (concat (downcase (buffer-substring beg
(point))) "-mode"))
2805 ;; Simple -*-MODE-*- case.
2806 (push (intern (concat (downcase (buffer-substring (point) end
))
2809 ;; If we found modes to use, invoke them now, outside the save-excursion.
2812 (dolist (mode (nreverse modes
))
2813 (if (not (functionp mode
))
2814 (message "Ignoring unknown mode `%s'" mode
)
2816 (or (set-auto-mode-0 mode keep-mode-if-same
)
2817 ;; continuing would call minor modes again, toggling them off
2818 (throw 'nop nil
))))))
2819 ;; hack-local-variables checks local-enable-local-variables etc, but
2820 ;; we might as well be explicit here for the sake of clarity.
2822 enable-local-variables
2823 local-enable-local-variables
2825 (setq mode
(hack-local-variables t
))
2826 (not (memq mode modes
)) ; already tried and failed
2827 (if (not (functionp mode
))
2828 (message "Ignoring unknown mode `%s'" mode
)
2830 (set-auto-mode-0 mode keep-mode-if-same
)))
2831 ;; If we didn't, look for an interpreter specified in the first line.
2832 ;; As a special case, allow for things like "#!/bin/env perl", which
2833 ;; finds the interpreter anywhere in $PATH.
2835 (setq mode
(save-excursion
2836 (goto-char (point-min))
2837 (if (looking-at auto-mode-interpreter-regexp
)
2839 ;; Map interpreter name to a mode, signaling we're done at the
2841 (setq done
(assoc-default
2842 (file-name-nondirectory mode
)
2845 (format "\\`%s\\'" (car e
))
2847 interpreter-mode-alist
)
2849 ;; If we found an interpreter mode to use, invoke it now.
2850 (set-auto-mode-0 done keep-mode-if-same
))
2851 ;; Next try matching the buffer beginning against magic-mode-alist.
2853 (if (setq done
(save-excursion
2854 (goto-char (point-min))
2856 (narrow-to-region (point-min)
2858 (+ (point-min) magic-mode-regexp-match-limit
)))
2859 (assoc-default nil magic-mode-alist
2863 (looking-at re
)))))))
2864 (set-auto-mode-0 done keep-mode-if-same
)))
2865 ;; Next compare the filename against the entries in auto-mode-alist.
2867 (if buffer-file-name
2868 (let ((name buffer-file-name
)
2869 (remote-id (file-remote-p buffer-file-name
)))
2870 ;; Remove backup-suffixes from file name.
2871 (setq name
(file-name-sans-versions name
))
2872 ;; Remove remote file name identification.
2873 (when (and (stringp remote-id
)
2874 (string-match (regexp-quote remote-id
) name
))
2875 (setq name
(substring name
(match-end 0))))
2877 ;; Find first matching alist entry.
2879 (if (memq system-type
'(windows-nt cygwin
))
2880 ;; System is case-insensitive.
2881 (let ((case-fold-search t
))
2882 (assoc-default name auto-mode-alist
2884 ;; System is case-sensitive.
2886 ;; First match case-sensitively.
2887 (let ((case-fold-search nil
))
2888 (assoc-default name auto-mode-alist
2890 ;; Fallback to case-insensitive match.
2891 (and auto-mode-case-fold
2892 (let ((case-fold-search t
))
2893 (assoc-default name auto-mode-alist
2898 (setq mode
(car mode
)
2899 name
(substring name
0 (match-beginning 0)))
2902 (set-auto-mode-0 mode keep-mode-if-same
)
2904 ;; Next try matching the buffer beginning against magic-fallback-mode-alist.
2906 (if (setq done
(save-excursion
2907 (goto-char (point-min))
2909 (narrow-to-region (point-min)
2911 (+ (point-min) magic-mode-regexp-match-limit
)))
2912 (assoc-default nil magic-fallback-mode-alist
2916 (looking-at re
)))))))
2917 (set-auto-mode-0 done keep-mode-if-same
)))
2919 (set-buffer-major-mode (current-buffer)))))
2921 ;; When `keep-mode-if-same' is set, we are working on behalf of
2922 ;; set-visited-file-name. In that case, if the major mode specified is the
2923 ;; same one we already have, don't actually reset it. We don't want to lose
2924 ;; minor modes such as Font Lock.
2925 (defun set-auto-mode-0 (mode &optional keep-mode-if-same
)
2926 "Apply MODE and return it.
2927 If optional arg KEEP-MODE-IF-SAME is non-nil, MODE is chased of
2928 any aliases and compared to current major mode. If they are the
2929 same, do nothing and return nil."
2930 (unless (and keep-mode-if-same
2931 (eq (indirect-function mode
)
2932 (indirect-function major-mode
)))
2937 (defvar file-auto-mode-skip
"^\\(#!\\|'\\\\\"\\)"
2938 "Regexp of lines to skip when looking for file-local settings.
2939 If the first line matches this regular expression, then the -*-...-*- file-
2940 local settings will be consulted on the second line instead of the first.")
2942 (defun set-auto-mode-1 ()
2943 "Find the -*- spec in the buffer.
2944 Call with point at the place to start searching from.
2945 If one is found, set point to the beginning and return the position
2946 of the end. Otherwise, return nil; may change point.
2947 The variable `inhibit-local-variables-regexps' can cause a -*- spec to
2948 be ignored; but `enable-local-variables' and `local-enable-local-variables'
2952 ;; Don't look for -*- if this file name matches any
2953 ;; of the regexps in inhibit-local-variables-regexps.
2954 (not (inhibit-local-variables-p))
2955 (search-forward "-*-" (line-end-position
2956 ;; If the file begins with "#!" (exec
2957 ;; interpreter magic), look for mode frobs
2958 ;; in the first two lines. You cannot
2959 ;; necessarily put them in the first line
2960 ;; of such a file without screwing up the
2961 ;; interpreter invocation. The same holds
2962 ;; for '\" in man pages (preprocessor
2963 ;; magic for the `man' program).
2964 (and (looking-at file-auto-mode-skip
) 2)) t
)
2966 (skip-chars-forward " \t")
2968 (search-forward "-*-" (line-end-position) t
))
2971 (skip-chars-backward " \t")
2976 ;;; Handling file local variables
2978 (defvar ignored-local-variables
2979 '(ignored-local-variables safe-local-variable-values
2980 file-local-variables-alist dir-local-variables-alist
)
2981 "Variables to be ignored in a file's local variable spec.")
2982 (put 'ignored-local-variables
'risky-local-variable t
)
2984 (defvar hack-local-variables-hook nil
2985 "Normal hook run after processing a file's local variables specs.
2986 Major modes can use this to examine user-specified local variables
2987 in order to initialize other data structure based on them.")
2989 (defcustom safe-local-variable-values nil
2990 "List variable-value pairs that are considered safe.
2991 Each element is a cons cell (VAR . VAL), where VAR is a variable
2992 symbol and VAL is a value that is considered safe."
2997 (defcustom safe-local-eval-forms
2998 ;; This should be here at least as long as Emacs supports write-file-hooks.
2999 '((add-hook 'write-file-hooks
'time-stamp
)
3000 (add-hook 'write-file-functions
'time-stamp
)
3001 (add-hook 'before-save-hook
'time-stamp nil t
)
3002 (add-hook 'before-save-hook
'delete-trailing-whitespace nil t
))
3003 "Expressions that are considered safe in an `eval:' local variable.
3004 Add expressions to this list if you want Emacs to evaluate them, when
3005 they appear in an `eval' local variable specification, without first
3006 asking you for confirmation."
3009 :version
"24.1" ; added write-file-hooks
3010 :type
'(repeat sexp
))
3012 ;; Risky local variables:
3013 (mapc (lambda (var) (put var
'risky-local-variable t
))
3015 buffer-auto-save-file-name
3017 buffer-file-truename
3020 default-text-properties
3024 file-name-handler-alist
3033 minor-mode-map-alist
3034 minor-mode-overriding-map-alist
3037 overriding-local-map
3038 overriding-terminal-local-map
3042 unread-command-events
))
3044 ;; Safe local variables:
3046 ;; For variables defined by major modes, the safety declarations can go into
3047 ;; the major mode's file, since that will be loaded before file variables are
3050 ;; For variables defined by minor modes, put the safety declarations in the
3051 ;; file defining the minor mode after the defcustom/defvar using an autoload
3054 ;; ;;;###autoload(put 'variable 'safe-local-variable 'stringp)
3056 ;; Otherwise, when Emacs visits a file specifying that local variable, the
3057 ;; minor mode file may not be loaded yet.
3059 ;; For variables defined in the C source code the declaration should go here:
3062 '((buffer-read-only . booleanp
) ;; C source code
3063 (default-directory . stringp
) ;; C source code
3064 (fill-column . integerp
) ;; C source code
3065 (indent-tabs-mode . booleanp
) ;; C source code
3066 (left-margin . integerp
) ;; C source code
3067 (no-update-autoloads . booleanp
)
3068 (lexical-binding . booleanp
) ;; C source code
3069 (tab-width . integerp
) ;; C source code
3070 (truncate-lines . booleanp
) ;; C source code
3071 (word-wrap . booleanp
) ;; C source code
3072 (bidi-display-reordering . booleanp
))) ;; C source code
3073 (put (car pair
) 'safe-local-variable
(cdr pair
)))
3075 (put 'bidi-paragraph-direction
'safe-local-variable
3076 (lambda (v) (memq v
'(nil right-to-left left-to-right
))))
3078 (put 'c-set-style
'safe-local-eval-function t
)
3080 (defvar file-local-variables-alist nil
3081 "Alist of file-local variable settings in the current buffer.
3082 Each element in this list has the form (VAR . VALUE), where VAR
3083 is a file-local variable (a symbol) and VALUE is the value
3084 specified. The actual value in the buffer may differ from VALUE,
3085 if it is changed by the major or minor modes, or by the user.")
3086 (make-variable-buffer-local 'file-local-variables-alist
)
3087 (put 'file-local-variables-alist
'permanent-local t
)
3089 (defvar dir-local-variables-alist nil
3090 "Alist of directory-local variable settings in the current buffer.
3091 Each element in this list has the form (VAR . VALUE), where VAR
3092 is a directory-local variable (a symbol) and VALUE is the value
3093 specified in .dir-locals.el. The actual value in the buffer
3094 may differ from VALUE, if it is changed by the major or minor modes,
3096 (make-variable-buffer-local 'dir-local-variables-alist
)
3098 (defvar before-hack-local-variables-hook nil
3099 "Normal hook run before setting file-local variables.
3100 It is called after checking for unsafe/risky variables and
3101 setting `file-local-variables-alist', and before applying the
3102 variables stored in `file-local-variables-alist'. A hook
3103 function is allowed to change the contents of this alist.
3105 This hook is called only if there is at least one file-local
3108 (defun hack-local-variables-confirm (all-vars unsafe-vars risky-vars dir-name
)
3109 "Get confirmation before setting up local variable values.
3110 ALL-VARS is the list of all variables to be set up.
3111 UNSAFE-VARS is the list of those that aren't marked as safe or risky.
3112 RISKY-VARS is the list of those that are marked as risky.
3113 If these settings come from directory-local variables, then
3114 DIR-NAME is the name of the associated directory. Otherwise it is nil."
3115 (unless noninteractive
3116 (let ((name (cond (dir-name)
3118 (file-name-nondirectory buffer-file-name
))
3119 ((concat "buffer " (buffer-name)))))
3120 (offer-save (and (eq enable-local-variables t
)
3122 (buf (get-buffer-create "*Local Variables*")))
3123 ;; Set up the contents of the *Local Variables* buffer.
3124 (with-current-buffer buf
3128 (insert "The local variables list in " name
3129 "\ncontains values that may not be safe (*)"
3131 ", and variables that are risky (**)."
3134 (insert "The local variables list in " name
3135 "\ncontains variables that are risky (**)."))
3137 (insert "A local variables list is specified in " name
".")))
3138 (insert "\n\nDo you want to apply it? You can type
3139 y -- to apply the local variables list.
3140 n -- to ignore the local variables list.")
3143 ! -- to apply the local variables list, and permanently mark these
3144 values (*) as safe (in the future, they will be set automatically.)\n\n")
3146 (dolist (elt all-vars
)
3147 (cond ((member elt unsafe-vars
)
3149 ((member elt risky-vars
)
3153 (princ (car elt
) buf
)
3155 ;; Make strings with embedded whitespace easier to read.
3156 (let ((print-escape-newlines t
))
3157 (prin1 (cdr elt
) buf
))
3159 (set (make-local-variable 'cursor-type
) nil
)
3160 (set-buffer-modified-p nil
)
3161 (goto-char (point-min)))
3163 ;; Display the buffer and read a choice.
3164 (save-window-excursion
3166 (let* ((exit-chars '(?y ?n ?\s ?\C-g ?\C-v
))
3167 (prompt (format "Please type %s%s: "
3168 (if offer-save
"y, n, or !" "y or n")
3169 (if (< (line-number-at-pos (point-max))
3170 (window-body-height))
3172 (push ?\C-v exit-chars
)
3173 ", or C-v to scroll")))
3175 (if offer-save
(push ?
! exit-chars
))
3177 (setq char
(read-char-choice prompt exit-chars t
))
3178 (when (eq char ?\C-v
)
3181 (error (goto-char (point-min))
3184 (when (and offer-save
(= char ?
!) unsafe-vars
)
3185 (customize-push-and-save 'safe-local-variable-values unsafe-vars
))
3186 (prog1 (memq char
'(?
! ?\s ?y
))
3187 (quit-window t
)))))))
3189 (defconst hack-local-variable-regexp
3190 "[ \t]*\\([^][;\"'?()\\ \t\n]+\\)[ \t]*:[ \t]*")
3192 (defun hack-local-variables-prop-line (&optional mode-only
)
3193 "Return local variables specified in the -*- line.
3194 Returns an alist of elements (VAR . VAL), where VAR is a variable
3195 and VAL is the specified value. Ignores any specification for
3196 `mode:' and `coding:' (which should have already been handled
3197 by `set-auto-mode' and `set-auto-coding', respectively).
3198 Return nil if the -*- line is malformed.
3200 If MODE-ONLY is non-nil, just returns the symbol specifying the
3201 mode, if there is one, otherwise nil."
3202 (catch 'malformed-line
3204 (goto-char (point-min))
3205 (let ((end (set-auto-mode-1))
3209 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
3210 ;; Simple form: "-*- MODENAME -*-".
3212 (intern (concat (match-string 1) "-mode"))))
3214 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
3215 ;; (last ";" is optional).
3216 ;; If MODE-ONLY, just check for `mode'.
3217 ;; Otherwise, parse the -*- line into the RESULT alist.
3218 (while (not (or (and mode-only result
)
3220 (unless (looking-at hack-local-variable-regexp
)
3221 (message "Malformed mode-line: %S"
3222 (buffer-substring-no-properties (point) end
))
3223 (throw 'malformed-line nil
))
3224 (goto-char (match-end 0))
3225 ;; There used to be a downcase here,
3226 ;; but the manual didn't say so,
3227 ;; and people want to set var names that aren't all lc.
3228 (let* ((key (intern (match-string 1)))
3229 (val (save-restriction
3230 (narrow-to-region (point) end
)
3231 (let ((read-circle nil
))
3232 (read (current-buffer)))))
3233 ;; It is traditional to ignore
3234 ;; case when checking for `mode' in set-auto-mode,
3235 ;; so we must do that here as well.
3236 ;; That is inconsistent, but we're stuck with it.
3237 ;; The same can be said for `coding' in set-auto-coding.
3238 (keyname (downcase (symbol-name key
))))
3240 (and (equal keyname
"mode")
3242 (intern (concat (downcase (symbol-name val
))
3244 (or (equal keyname
"coding")
3246 (push (cons (cond ((eq key
'eval
) 'eval
)
3247 ;; Downcase "Mode:".
3248 ((equal keyname
"mode") 'mode
)
3249 (t (indirect-variable key
)))
3252 (skip-chars-forward " \t;")))
3255 (defun hack-local-variables-filter (variables dir-name
)
3256 "Filter local variable settings, querying the user if necessary.
3257 VARIABLES is the alist of variable-value settings. This alist is
3258 filtered based on the values of `ignored-local-variables',
3259 `enable-local-eval', `enable-local-variables', and (if necessary)
3260 user interaction. The results are added to
3261 `file-local-variables-alist', without applying them.
3262 If these settings come from directory-local variables, then
3263 DIR-NAME is the name of the associated directory. Otherwise it is nil."
3264 ;; Find those variables that we may want to save to
3265 ;; `safe-local-variable-values'.
3266 (let (all-vars risky-vars unsafe-vars
)
3267 (dolist (elt variables
)
3268 (let ((var (car elt
))
3270 (cond ((memq var ignored-local-variables
)
3271 ;; Ignore any variable in `ignored-local-variables'.
3273 ;; Obey `enable-local-eval'.
3275 (when enable-local-eval
3276 (let ((safe (or (hack-one-local-variable-eval-safep val
)
3277 ;; In case previously marked safe (bug#5636).
3278 (safe-local-variable-p var val
))))
3279 ;; If not safe and e-l-v = :safe, ignore totally.
3280 (when (or safe
(not (eq enable-local-variables
:safe
)))
3282 (or (eq enable-local-eval t
)
3284 (push elt unsafe-vars
))))))
3285 ;; Ignore duplicates (except `mode') in the present list.
3286 ((and (assq var all-vars
) (not (eq var
'mode
))) nil
)
3287 ;; Accept known-safe variables.
3288 ((or (memq var
'(mode unibyte coding
))
3289 (safe-local-variable-p var val
))
3290 (push elt all-vars
))
3291 ;; The variable is either risky or unsafe:
3292 ((not (eq enable-local-variables
:safe
))
3294 (if (risky-local-variable-p var val
)
3295 (push elt risky-vars
)
3296 (push elt unsafe-vars
))))))
3298 ;; Query, unless all vars are safe or user wants no querying.
3299 (or (and (eq enable-local-variables t
)
3302 (memq enable-local-variables
'(:all
:safe
))
3303 (hack-local-variables-confirm all-vars unsafe-vars
3304 risky-vars dir-name
))
3305 (dolist (elt all-vars
)
3306 (unless (memq (car elt
) '(eval mode
))
3308 (setq dir-local-variables-alist
3309 (assq-delete-all (car elt
) dir-local-variables-alist
)))
3310 (setq file-local-variables-alist
3311 (assq-delete-all (car elt
) file-local-variables-alist
)))
3312 (push elt file-local-variables-alist
)))))
3314 ;; TODO? Warn once per file rather than once per session?
3315 (defvar hack-local-variables--warned-lexical nil
)
3317 (defun hack-local-variables (&optional mode-only
)
3318 "Parse and put into effect this buffer's local variables spec.
3319 Uses `hack-local-variables-apply' to apply the variables.
3321 If MODE-ONLY is non-nil, all we do is check whether a \"mode:\"
3322 is specified, and return the corresponding mode symbol, or nil.
3323 In this case, we try to ignore minor-modes, and only return a
3326 If `enable-local-variables' or `local-enable-local-variables' is nil,
3327 this function does nothing. If `inhibit-local-variables-regexps'
3328 applies to the file in question, the file is not scanned for
3329 local variables, but directory-local variables may still be applied."
3330 ;; We don't let inhibit-local-variables-p influence the value of
3331 ;; enable-local-variables, because then it would affect dir-local
3332 ;; variables. We don't want to search eg tar files for file local
3333 ;; variable sections, but there is no reason dir-locals cannot apply
3334 ;; to them. The real meaning of inhibit-local-variables-p is "do
3335 ;; not scan this file for local variables".
3336 (let ((enable-local-variables
3337 (and local-enable-local-variables enable-local-variables
))
3340 (setq file-local-variables-alist nil
)
3341 (with-demoted-errors "Directory-local variables error: %s"
3342 ;; Note this is a no-op if enable-local-variables is nil.
3343 (hack-dir-local-variables)))
3344 ;; This entire function is basically a no-op if enable-local-variables
3345 ;; is nil. All it does is set file-local-variables-alist to nil.
3346 (when enable-local-variables
3347 ;; This part used to ignore enable-local-variables when mode-only
3348 ;; was non-nil. That was inappropriate, eg consider the
3349 ;; (artificial) example of:
3350 ;; (setq local-enable-local-variables nil)
3351 ;; Open a file foo.txt that contains "mode: sh".
3352 ;; It correctly opens in text-mode.
3353 ;; M-x set-visited-file name foo.c, and it incorrectly stays in text-mode.
3354 (unless (or (inhibit-local-variables-p)
3355 ;; If MODE-ONLY is non-nil, and the prop line specifies a
3356 ;; mode, then we're done, and have no need to scan further.
3357 (and (setq result
(hack-local-variables-prop-line mode-only
))
3359 ;; Look for "Local variables:" line in last page.
3361 (goto-char (point-max))
3362 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min))
3364 (when (let ((case-fold-search t
))
3365 (search-forward "Local Variables:" nil t
))
3366 (skip-chars-forward " \t")
3367 ;; suffix is what comes after "local variables:" in its line.
3368 ;; prefix is what comes before "local variables:" in its line.
3371 (regexp-quote (buffer-substring (point)
3372 (line-end-position)))
3375 (concat "^" (regexp-quote
3376 (buffer-substring (line-beginning-position)
3377 (match-beginning 0))))))
3380 (let ((startpos (point))
3382 (thisbuf (current-buffer)))
3384 (unless (let ((case-fold-search t
))
3386 (concat prefix
"[ \t]*End:[ \t]*" suffix
)
3388 ;; This used to be an error, but really all it means is
3389 ;; that this may simply not be a local-variables section,
3390 ;; so just ignore it.
3391 (message "Local variables list is not properly terminated"))
3393 (setq endpos
(point)))
3396 (insert-buffer-substring thisbuf startpos endpos
)
3397 (goto-char (point-min))
3398 (subst-char-in-region (point) (point-max) ?\^m ?
\n)
3400 ;; Discard the prefix.
3401 (if (looking-at prefix
)
3402 (delete-region (point) (match-end 0))
3403 (error "Local variables entry is missing the prefix"))
3405 ;; Discard the suffix.
3406 (if (looking-back suffix
(line-beginning-position))
3407 (delete-region (match-beginning 0) (point))
3408 (error "Local variables entry is missing the suffix"))
3410 (goto-char (point-min))
3412 (while (not (or (eobp)
3413 (and mode-only result
)))
3414 ;; Find the variable name;
3415 (unless (looking-at hack-local-variable-regexp
)
3416 (error "Malformed local variable line: %S"
3417 (buffer-substring-no-properties
3418 (point) (line-end-position))))
3419 (goto-char (match-end 1))
3420 (let* ((str (match-string 1))
3423 (and (equal (downcase (symbol-name var
)) "mode")
3425 ;; Read the variable value.
3426 (skip-chars-forward "^:")
3428 (let ((read-circle nil
))
3429 (setq val
(read (current-buffer))))
3432 ;; Specifying minor-modes via mode: is
3433 ;; deprecated, but try to reject them anyway.
3436 (setq val2
(downcase (symbol-name val
)))))
3437 (setq result
(intern (concat val2
"-mode"))))
3438 (cond ((eq var
'coding
))
3439 ((eq var
'lexical-binding
)
3440 (unless hack-local-variables--warned-lexical
3441 (setq hack-local-variables--warned-lexical t
)
3445 "%s: `lexical-binding' at end of file unreliable"
3446 (file-name-nondirectory
3447 ;; We are called from
3448 ;; 'with-temp-buffer', so we need
3449 ;; to use 'thisbuf's name in the
3451 (or (buffer-file-name thisbuf
) ""))))))
3454 (push (cons (if (eq var
'eval
)
3456 (indirect-variable var
))
3458 (forward-line 1))))))))
3459 ;; Now we've read all the local variables.
3460 ;; If MODE-ONLY is non-nil, return whether the mode was specified.
3461 (if mode-only result
3462 ;; Otherwise, set the variables.
3463 (hack-local-variables-filter result nil
)
3464 (hack-local-variables-apply)))))
3466 (defun hack-local-variables-apply ()
3467 "Apply the elements of `file-local-variables-alist'.
3468 If there are any elements, runs `before-hack-local-variables-hook',
3469 then calls `hack-one-local-variable' to apply the alist elements one by one.
3470 Finishes by running `hack-local-variables-hook', regardless of whether
3471 the alist is empty or not.
3473 Note that this function ignores a `mode' entry if it specifies the same
3474 major mode as the buffer already has."
3475 (when file-local-variables-alist
3476 ;; Any 'evals must run in the Right sequence.
3477 (setq file-local-variables-alist
3478 (nreverse file-local-variables-alist
))
3479 (run-hooks 'before-hack-local-variables-hook
)
3480 (dolist (elt file-local-variables-alist
)
3481 (hack-one-local-variable (car elt
) (cdr elt
))))
3482 (run-hooks 'hack-local-variables-hook
))
3484 (defun safe-local-variable-p (sym val
)
3485 "Non-nil if SYM is safe as a file-local variable with value VAL.
3486 It is safe if any of these conditions are met:
3488 * There is a matching entry (SYM . VAL) in the
3489 `safe-local-variable-values' user option.
3491 * The `safe-local-variable' property of SYM is a function that
3492 evaluates to a non-nil value with VAL as an argument."
3493 (or (member (cons sym val
) safe-local-variable-values
)
3494 (let ((safep (get sym
'safe-local-variable
)))
3495 (and (functionp safep
)
3496 ;; If the function signals an error, that means it
3497 ;; can't assure us that the value is safe.
3498 (with-demoted-errors (funcall safep val
))))))
3500 (defun risky-local-variable-p (sym &optional _ignored
)
3501 "Non-nil if SYM could be dangerous as a file-local variable.
3502 It is dangerous if either of these conditions are met:
3504 * Its `risky-local-variable' property is non-nil.
3506 * Its name ends with \"hook(s)\", \"function(s)\", \"form(s)\", \"map\",
3507 \"program\", \"command(s)\", \"predicate(s)\", \"frame-alist\",
3508 \"mode-alist\", \"font-lock-(syntactic-)keyword*\",
3509 \"map-alist\", or \"bindat-spec\"."
3510 ;; If this is an alias, check the base name.
3512 (setq sym
(indirect-variable sym
))
3514 (or (get sym
'risky-local-variable
)
3515 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|\
3516 -commands?$\\|-predicates?$\\|font-lock-keywords$\\|font-lock-keywords\
3517 -[0-9]+$\\|font-lock-syntactic-keywords$\\|-frame-alist$\\|-mode-alist$\\|\
3518 -map$\\|-map-alist$\\|-bindat-spec$" (symbol-name sym
))))
3520 (defun hack-one-local-variable-quotep (exp)
3521 (and (consp exp
) (eq (car exp
) 'quote
) (consp (cdr exp
))))
3523 (defun hack-one-local-variable-constantp (exp)
3524 (or (and (not (symbolp exp
)) (not (consp exp
)))
3527 (hack-one-local-variable-quotep exp
)))
3529 (defun hack-one-local-variable-eval-safep (exp)
3530 "Return t if it is safe to eval EXP when it is found in a file."
3531 (or (not (consp exp
))
3532 ;; Detect certain `put' expressions.
3533 (and (eq (car exp
) 'put
)
3534 (hack-one-local-variable-quotep (nth 1 exp
))
3535 (hack-one-local-variable-quotep (nth 2 exp
))
3536 (let ((prop (nth 1 (nth 2 exp
)))
3538 (cond ((memq prop
'(lisp-indent-hook
3539 lisp-indent-function
3540 scheme-indent-function
))
3541 ;; Only allow safe values (not functions).
3543 (and (hack-one-local-variable-quotep val
)
3544 (eq (nth 1 val
) 'defun
))))
3545 ((eq prop
'edebug-form-spec
)
3546 ;; Only allow indirect form specs.
3547 ;; During bootstrapping, edebug-basic-spec might not be
3549 (and (fboundp 'edebug-basic-spec
)
3550 (hack-one-local-variable-quotep val
)
3551 (edebug-basic-spec (nth 1 val
)))))))
3552 ;; Allow expressions that the user requested.
3553 (member exp safe-local-eval-forms
)
3554 ;; Certain functions can be allowed with safe arguments
3555 ;; or can specify verification functions to try.
3556 (and (symbolp (car exp
))
3557 ;; Allow (minor)-modes calls with no arguments.
3558 ;; This obsoletes the use of "mode:" for such things. (Bug#8613)
3559 (or (and (member (cdr exp
) '(nil (1) (0) (-1)))
3560 (string-match "-mode\\'" (symbol-name (car exp
))))
3561 (let ((prop (get (car exp
) 'safe-local-eval-function
)))
3564 (dolist (arg (cdr exp
))
3565 (unless (hack-one-local-variable-constantp arg
)
3572 (dolist (function prop
)
3573 (if (funcall function exp
)
3577 (defun hack-one-local-variable--obsolete (var)
3578 (let ((o (get var
'byte-obsolete-variable
)))
3580 (let ((instead (nth 0 o
))
3582 (message "%s is obsolete%s; %s"
3583 var
(if since
(format " (since %s)" since
))
3584 (if (stringp instead
)
3585 (substitute-command-keys instead
)
3586 (format-message "use `%s' instead" instead
)))))))
3588 (defun hack-one-local-variable (var val
)
3589 "Set local variable VAR with value VAL.
3590 If VAR is `mode', call `VAL-mode' as a function unless it's
3591 already the major mode."
3594 (let ((mode (intern (concat (downcase (symbol-name val
))
3596 (unless (eq (indirect-function mode
)
3597 (indirect-function major-mode
))
3601 (`(add-hook ',hook .
,_
) (hack-one-local-variable--obsolete hook
)))
3602 (save-excursion (eval val
)))
3604 (hack-one-local-variable--obsolete var
)
3605 ;; Make sure the string has no text properties.
3606 ;; Some text properties can get evaluated in various ways,
3607 ;; so it is risky to put them on with a local variable list.
3609 (set-text-properties 0 (length val
) nil val
))
3610 (set (make-local-variable var
) val
))))
3612 ;;; Handling directory-local variables, aka project settings.
3614 (defvar dir-locals-class-alist
'()
3615 "Alist mapping directory-local variable classes (symbols) to variable lists.")
3617 (defvar dir-locals-directory-cache
'()
3618 "List of cached directory roots for directory-local variable classes.
3619 Each element in this list has the form (DIR CLASS MTIME).
3620 DIR is the name of the directory.
3621 CLASS is the name of a variable class (a symbol).
3622 MTIME is the recorded modification time of the directory-local
3623 variables file associated with this entry. This time is a list
3624 of integers (the same format as `file-attributes'), and is
3625 used to test whether the cache entry is still valid.
3626 Alternatively, MTIME can be nil, which means the entry is always
3629 (defsubst dir-locals-get-class-variables
(class)
3630 "Return the variable list for CLASS."
3631 (cdr (assq class dir-locals-class-alist
)))
3633 (defun dir-locals-collect-mode-variables (mode-variables variables
)
3634 "Collect directory-local variables from MODE-VARIABLES.
3635 VARIABLES is the initial list of variables.
3636 Returns the new list."
3637 (dolist (pair mode-variables variables
)
3638 (let* ((variable (car pair
))
3640 (slot (assq variable variables
)))
3641 ;; If variables are specified more than once, only use the last. (Why?)
3642 ;; The pseudo-variables mode and eval are different (bug#3430).
3643 (if (and slot
(not (memq variable
'(mode eval
))))
3645 ;; Need a new cons in case we setcdr later.
3646 (push (cons variable value
) variables
)))))
3648 (defun dir-locals-collect-variables (class-variables root variables
)
3649 "Collect entries from CLASS-VARIABLES into VARIABLES.
3650 ROOT is the root directory of the project.
3651 Return the new variables list."
3652 (let* ((file-name (or (buffer-file-name)
3653 ;; Handle non-file buffers, too.
3654 (expand-file-name default-directory
)))
3655 (sub-file-name (if file-name
3656 ;; FIXME: Why not use file-relative-name?
3657 (substring file-name
(length root
)))))
3659 (dolist (entry class-variables variables
)
3660 (let ((key (car entry
)))
3663 ;; Don't include this in the previous condition, because we
3664 ;; want to filter all strings before the next condition.
3665 (when (and sub-file-name
3666 (>= (length sub-file-name
) (length key
))
3667 (string-prefix-p key sub-file-name
))
3668 (setq variables
(dir-locals-collect-variables
3669 (cdr entry
) root variables
))))
3671 (derived-mode-p key
))
3672 (let* ((alist (cdr entry
))
3673 (subdirs (assq 'subdirs alist
)))
3674 (if (or (not subdirs
)
3676 (setq alist
(delq subdirs alist
))
3678 ;; TODO someone might want to extend this to allow
3679 ;; integer values for subdir, where N means
3680 ;; variables apply to this directory and N levels
3681 ;; below it (0 == nil).
3682 (equal root default-directory
))
3683 (setq variables
(dir-locals-collect-mode-variables
3684 alist variables
))))))))
3686 ;; The file's content might be invalid (e.g. have a merge conflict), but
3687 ;; that shouldn't prevent the user from opening the file.
3688 (message ".dir-locals error: %s" (error-message-string err
))
3691 (defun dir-locals-set-directory-class (directory class
&optional mtime
)
3692 "Declare that the DIRECTORY root is an instance of CLASS.
3693 DIRECTORY is the name of a directory, a string.
3694 CLASS is the name of a project class, a symbol.
3695 MTIME is either the modification time of the directory-local
3696 variables file that defined this class, or nil.
3698 When a file beneath DIRECTORY is visited, the mode-specific
3699 variables from CLASS are applied to the buffer. The variables
3700 for a class are defined using `dir-locals-set-class-variables'."
3701 (setq directory
(file-name-as-directory (expand-file-name directory
)))
3702 (unless (assq class dir-locals-class-alist
)
3703 (error "No such class `%s'" (symbol-name class
)))
3704 (push (list directory class mtime
) dir-locals-directory-cache
))
3706 (defun dir-locals-set-class-variables (class variables
)
3707 "Map the type CLASS to a list of variable settings.
3708 CLASS is the project class, a symbol. VARIABLES is a list
3709 that declares directory-local variables for the class.
3710 An element in VARIABLES is either of the form:
3711 (MAJOR-MODE . ALIST)
3715 In the first form, MAJOR-MODE is a symbol, and ALIST is an alist
3716 whose elements are of the form (VARIABLE . VALUE).
3718 In the second form, DIRECTORY is a directory name (a string), and
3719 LIST is a list of the form accepted by the function.
3721 When a file is visited, the file's class is found. A directory
3722 may be assigned a class using `dir-locals-set-directory-class'.
3723 Then variables are set in the file's buffer according to the
3724 VARIABLES list of the class. The list is processed in order.
3726 * If the element is of the form (MAJOR-MODE . ALIST), and the
3727 buffer's major mode is derived from MAJOR-MODE (as determined
3728 by `derived-mode-p'), then all the variables in ALIST are
3729 applied. A MAJOR-MODE of nil may be used to match any buffer.
3730 `make-local-variable' is called for each variable before it is
3733 * If the element is of the form (DIRECTORY . LIST), and DIRECTORY
3734 is an initial substring of the file's directory, then LIST is
3735 applied by recursively following these rules."
3736 (setf (alist-get class dir-locals-class-alist
) variables
))
3738 (defconst dir-locals-file
".dir-locals.el"
3739 "File that contains directory-local variables.
3740 It has to be constant to enforce uniform values
3741 across different environments and users.")
3743 (defun dir-locals-find-file (file)
3744 "Find the directory-local variables for FILE.
3745 This searches upward in the directory tree from FILE.
3746 It stops at the first directory that has been registered in
3747 `dir-locals-directory-cache' or contains a `dir-locals-file'.
3748 If it finds an entry in the cache, it checks that it is valid.
3749 A cache entry with no modification time element (normally, one that
3750 has been assigned directly using `dir-locals-set-directory-class', not
3751 set from a file) is always valid.
3752 A cache entry based on a `dir-locals-file' is valid if the modification
3753 time stored in the cache matches the current file modification time.
3754 If not, the cache entry is cleared so that the file will be re-read.
3756 This function returns either nil (no directory local variables found),
3757 or the matching entry from `dir-locals-directory-cache' (a list),
3758 or the full path to the `dir-locals-file' (a string) in the case
3759 of no valid cache entry."
3760 (setq file
(expand-file-name file
))
3761 (let* ((dir-locals-file-name
3762 (if (eq system-type
'ms-dos
)
3763 (dosified-file-name dir-locals-file
)
3765 (locals-file (locate-dominating-file file dir-locals-file-name
))
3767 ;; `locate-dominating-file' may have abbreviated the name.
3769 (setq locals-file
(expand-file-name dir-locals-file-name locals-file
)))
3770 ;; Let dir-locals-read-from-file inform us via demoted-errors
3771 ;; about unreadable files, etc.
3772 ;; Maybe we'd want to keep searching though - that is
3773 ;; a locate-dominating-file issue.
3774 ;;; (or (not (file-readable-p locals-file))
3775 ;;; (not (file-regular-p locals-file)))
3776 ;;; (setq locals-file nil))
3777 ;; Find the best cached value in `dir-locals-directory-cache'.
3778 (dolist (elt dir-locals-directory-cache
)
3779 (when (and (string-prefix-p (car elt
) file
3781 '(windows-nt cygwin ms-dos
)))
3782 (> (length (car elt
)) (length (car dir-elt
))))
3783 (setq dir-elt elt
)))
3785 (or (null locals-file
)
3786 (<= (length (file-name-directory locals-file
))
3787 (length (car dir-elt
)))))
3788 ;; Found a potential cache entry. Check validity.
3789 ;; A cache entry with no MTIME is assumed to always be valid
3790 ;; (ie, set directly, not from a dir-locals file).
3791 ;; Note, we don't bother to check that there is a matching class
3792 ;; element in dir-locals-class-alist, since that's done by
3793 ;; dir-locals-set-directory-class.
3794 (if (or (null (nth 2 dir-elt
))
3795 (let ((cached-file (expand-file-name dir-locals-file-name
3797 (and (file-readable-p cached-file
)
3798 (equal (nth 2 dir-elt
)
3799 (nth 5 (file-attributes cached-file
))))))
3800 ;; This cache entry is OK.
3802 ;; This cache entry is invalid; clear it.
3803 (setq dir-locals-directory-cache
3804 (delq dir-elt dir-locals-directory-cache
))
3805 ;; Return the first existing dir-locals file. Might be the same
3806 ;; as dir-elt's, might not (eg latter might have been deleted).
3811 (defun dir-locals-read-from-file (file)
3812 "Load a variables FILE and register a new class and instance.
3813 FILE is the name of the file holding the variables to apply.
3814 The new class name is the same as the directory in which FILE
3815 is found. Returns the new class name."
3817 (with-demoted-errors "Error reading dir-locals: %S"
3818 (insert-file-contents file
)
3819 (unless (zerop (buffer-size))
3820 (let* ((dir-name (file-name-directory file
))
3821 (class-name (intern dir-name
))
3822 (variables (let ((read-circle nil
))
3823 (read (current-buffer)))))
3824 (dir-locals-set-class-variables class-name variables
)
3825 (dir-locals-set-directory-class dir-name class-name
3826 (nth 5 (file-attributes file
)))
3829 (defcustom enable-remote-dir-locals nil
3830 "Non-nil means dir-local variables will be applied to remote files."
3835 (defvar hack-dir-local-variables--warned-coding nil
)
3837 (defun hack-dir-local-variables ()
3838 "Read per-directory local variables for the current buffer.
3839 Store the directory-local variables in `dir-local-variables-alist'
3840 and `file-local-variables-alist', without applying them.
3842 This does nothing if either `enable-local-variables' or
3843 `enable-dir-local-variables' are nil."
3844 (when (and enable-local-variables
3845 enable-dir-local-variables
3846 (or enable-remote-dir-locals
3847 (not (file-remote-p (or (buffer-file-name)
3848 default-directory
)))))
3849 ;; Find the variables file.
3850 (let ((variables-file (dir-locals-find-file
3851 (or (buffer-file-name) default-directory
)))
3855 ((stringp variables-file
)
3856 (setq dir-name
(file-name-directory variables-file
)
3857 class
(dir-locals-read-from-file variables-file
)))
3858 ((consp variables-file
)
3859 (setq dir-name
(nth 0 variables-file
))
3860 (setq class
(nth 1 variables-file
))))
3863 (dir-locals-collect-variables
3864 (dir-locals-get-class-variables class
) dir-name nil
)))
3866 (dolist (elt variables
)
3867 (if (eq (car elt
) 'coding
)
3868 (unless hack-dir-local-variables--warned-coding
3869 (setq hack-dir-local-variables--warned-coding t
)
3870 (display-warning 'files
3871 "Coding cannot be specified by dir-locals"))
3872 (unless (memq (car elt
) '(eval mode
))
3873 (setq dir-local-variables-alist
3874 (assq-delete-all (car elt
) dir-local-variables-alist
)))
3875 (push elt dir-local-variables-alist
)))
3876 (hack-local-variables-filter variables dir-name
)))))))
3878 (defun hack-dir-local-variables-non-file-buffer ()
3879 "Apply directory-local variables to a non-file buffer.
3880 For non-file buffers, such as Dired buffers, directory-local
3881 variables are looked for in `default-directory' and its parent
3883 (hack-dir-local-variables)
3884 (hack-local-variables-apply))
3887 (defcustom change-major-mode-with-file-name t
3888 "Non-nil means \\[write-file] should set the major mode from the file name.
3889 However, the mode will not be changed if
3890 \(1) a local variables list or the `-*-' line specifies a major mode, or
3891 \(2) the current major mode is a \"special\" mode,
3892 not suitable for ordinary files, or
3893 \(3) the new file name does not particularly specify any mode."
3895 :group
'editing-basics
)
3897 (defun set-visited-file-name (filename &optional no-query along-with-file
)
3898 "Change name of file visited in current buffer to FILENAME.
3899 This also renames the buffer to correspond to the new file.
3900 The next time the buffer is saved it will go in the newly specified file.
3901 FILENAME nil or an empty string means mark buffer as not visiting any file.
3902 Remember to delete the initial contents of the minibuffer
3903 if you wish to pass an empty string as the argument.
3905 The optional second argument NO-QUERY, if non-nil, inhibits asking for
3906 confirmation in the case where another buffer is already visiting FILENAME.
3908 The optional third argument ALONG-WITH-FILE, if non-nil, means that
3909 the old visited file has been renamed to the new name FILENAME."
3910 (interactive "FSet visited file name: ")
3911 (if (buffer-base-buffer)
3912 (error "An indirect buffer cannot visit a file"))
3913 (let (truename old-try-locals
)
3916 (if (string-equal filename
"")
3918 (expand-file-name filename
))))
3921 (setq truename
(file-truename filename
))
3922 (if find-file-visit-truename
3923 (setq filename truename
))))
3925 (let ((new-name (file-name-nondirectory filename
)))
3926 (if (string= new-name
"")
3927 (error "Empty file name"))))
3928 (let ((buffer (and filename
(find-buffer-visiting filename
))))
3929 (and buffer
(not (eq buffer
(current-buffer)))
3931 (not (y-or-n-p (format "A buffer is visiting %s; proceed? "
3933 (user-error "Aborted")))
3934 (or (equal filename buffer-file-name
)
3936 (and filename
(lock-buffer filename
))
3938 (setq old-try-locals
(not (inhibit-local-variables-p))
3939 buffer-file-name filename
)
3940 (if filename
; make buffer name reflect filename.
3941 (let ((new-name (file-name-nondirectory buffer-file-name
)))
3942 (setq default-directory
(file-name-directory buffer-file-name
))
3943 ;; If new-name == old-name, renaming would add a spurious <2>
3944 ;; and it's considered as a feature in rename-buffer.
3945 (or (string= new-name
(buffer-name))
3946 (rename-buffer new-name t
))))
3947 (setq buffer-backed-up nil
)
3949 (clear-visited-file-modtime))
3950 ;; Abbreviate the file names of the buffer.
3953 (setq buffer-file-truename
(abbreviate-file-name truename
))
3954 (if find-file-visit-truename
3955 (setq buffer-file-name truename
))))
3956 (setq buffer-file-number
3958 (nthcdr 10 (file-attributes buffer-file-name
))
3960 ;; write-file-functions is normally used for things like ftp-find-file
3961 ;; that visit things that are not local files as if they were files.
3962 ;; Changing to visit an ordinary local file instead should flush the hook.
3963 (kill-local-variable 'write-file-functions
)
3964 (kill-local-variable 'local-write-file-hooks
)
3965 (kill-local-variable 'revert-buffer-function
)
3966 (kill-local-variable 'backup-inhibited
)
3967 ;; If buffer was read-only because of version control,
3968 ;; that reason is gone now, so make it writable.
3970 (setq buffer-read-only nil
))
3971 (kill-local-variable 'vc-mode
)
3972 ;; Turn off backup files for certain file names.
3973 ;; Since this is a permanent local, the major mode won't eliminate it.
3974 (and buffer-file-name
3975 backup-enable-predicate
3976 (not (funcall backup-enable-predicate buffer-file-name
))
3978 (make-local-variable 'backup-inhibited
)
3979 (setq backup-inhibited t
)))
3980 (let ((oauto buffer-auto-save-file-name
))
3981 (cond ((null filename
)
3982 (setq buffer-auto-save-file-name nil
))
3983 ((not buffer-auto-save-file-name
)
3984 ;; If auto-save was not already on, turn it on if appropriate.
3985 (and buffer-file-name auto-save-default
(auto-save-mode t
)))
3987 ;; If auto save is on, start using a new name. We
3988 ;; deliberately don't rename or delete the old auto save
3989 ;; for the old visited file name. This is because
3990 ;; perhaps the user wants to save the new state and then
3991 ;; compare with the previous state from the auto save
3993 (setq buffer-auto-save-file-name
(make-auto-save-file-name))))
3994 ;; Rename the old auto save file if any.
3995 (and oauto buffer-auto-save-file-name
3996 (file-exists-p oauto
)
3997 (rename-file oauto buffer-auto-save-file-name t
)))
3998 (and buffer-file-name
3999 (not along-with-file
)
4000 (set-buffer-modified-p t
))
4001 ;; Update the major mode, if the file name determines it.
4003 ;; Don't change the mode if it is special.
4004 (or (not change-major-mode-with-file-name
)
4005 (get major-mode
'mode-class
)
4006 ;; Don't change the mode if the local variable list specifies it.
4007 ;; The file name can influence whether the local variables apply.
4009 ;; h-l-v also checks it, but might as well be explicit.
4010 (not (inhibit-local-variables-p))
4011 (hack-local-variables t
))
4012 ;; TODO consider making normal-mode handle this case.
4013 (let ((old major-mode
))
4015 (or (eq old major-mode
)
4016 (hack-local-variables))))
4019 (defun write-file (filename &optional confirm
)
4020 "Write current buffer into file FILENAME.
4021 This makes the buffer visit that file, and marks it as not modified.
4023 If you specify just a directory name as FILENAME, that means to use
4024 the default file name but in that directory. You can also yank
4025 the default file name into the minibuffer to edit it, using \\<minibuffer-local-map>\\[next-history-element].
4027 If the buffer is not already visiting a file, the default file name
4028 for the output file is the buffer name.
4030 If optional second arg CONFIRM is non-nil, this function
4031 asks for confirmation before overwriting an existing file.
4032 Interactively, confirmation is required unless you supply a prefix argument."
4033 ;; (interactive "FWrite file: ")
4035 (list (if buffer-file-name
4036 (read-file-name "Write file: "
4038 (read-file-name "Write file: " default-directory
4040 (file-name-nondirectory (buffer-name))
4043 (not current-prefix-arg
)))
4044 (or (null filename
) (string-equal filename
"")
4046 ;; If arg is just a directory,
4047 ;; use the default file name, but in that directory.
4048 (if (file-directory-p filename
)
4049 (setq filename
(concat (file-name-as-directory filename
)
4050 (file-name-nondirectory
4051 (or buffer-file-name
(buffer-name))))))
4053 (file-exists-p filename
)
4054 ;; NS does its own confirm dialog.
4055 (not (and (eq (framep-on-display) 'ns
)
4056 (listp last-nonmenu-event
)
4058 (or (y-or-n-p (format-message
4059 "File `%s' exists; overwrite? " filename
))
4060 (user-error "Canceled")))
4061 (set-visited-file-name filename
(not confirm
))))
4062 (set-buffer-modified-p t
)
4063 ;; Make buffer writable if file is writable.
4064 (and buffer-file-name
4065 (file-writable-p buffer-file-name
)
4066 (setq buffer-read-only nil
))
4068 ;; It's likely that the VC status at the new location is different from
4069 ;; the one at the old location.
4072 (defun file-extended-attributes (filename)
4073 "Return an alist of extended attributes of file FILENAME.
4075 Extended attributes are platform-specific metadata about the file,
4076 such as SELinux context, list of ACL entries, etc."
4077 `((acl .
,(file-acl filename
))
4078 (selinux-context .
,(file-selinux-context filename
))))
4080 (defun set-file-extended-attributes (filename attributes
)
4081 "Set extended attributes of file FILENAME to ATTRIBUTES.
4083 ATTRIBUTES must be an alist of file attributes as returned by
4084 `file-extended-attributes'.
4085 Value is t if the function succeeds in setting the attributes."
4087 (dolist (elt attributes
)
4088 (let ((attr (car elt
))
4090 (cond ((eq attr
'acl
)
4091 (setq rv
(set-file-acl filename val
)))
4092 ((eq attr
'selinux-context
)
4093 (setq rv
(set-file-selinux-context filename val
))))
4094 (setq result
(or result rv
))))
4098 (defun backup-buffer ()
4099 "Make a backup of the disk file visited by the current buffer, if appropriate.
4100 This is normally done before saving the buffer the first time.
4102 A backup may be done by renaming or by copying; see documentation of
4103 variable `make-backup-files'. If it's done by renaming, then the file is
4104 no longer accessible under its old name.
4106 The value is non-nil after a backup was made by renaming.
4107 It has the form (MODES EXTENDED-ATTRIBUTES BACKUPNAME).
4108 MODES is the result of `file-modes' on the original
4109 file; this means that the caller, after saving the buffer, should change
4110 the modes of the new file to agree with the old modes.
4111 EXTENDED-ATTRIBUTES is the result of `file-extended-attributes'
4112 on the original file; this means that the caller, after saving
4113 the buffer, should change the extended attributes of the new file
4114 to agree with the old attributes.
4115 BACKUPNAME is the backup file name, which is the old file renamed."
4116 (when (and make-backup-files
(not backup-inhibited
) (not buffer-backed-up
))
4117 (let ((attributes (file-attributes buffer-file-name
)))
4118 (when (and attributes
(memq (aref (elt attributes
8) 0) '(?- ?l
)))
4119 ;; If specified name is a symbolic link, chase it to the target.
4120 ;; This makes backups in the directory where the real file is.
4121 (let* ((real-file-name (file-chase-links buffer-file-name
))
4122 (backup-info (find-backup-file-name real-file-name
)))
4124 (let* ((backupname (car backup-info
))
4125 (targets (cdr backup-info
))
4127 ;; If have old versions to maybe delete,
4128 ;; ask the user to confirm now, before doing anything.
4129 ;; But don't actually delete til later.
4131 (booleanp delete-old-versions
)
4132 (or delete-old-versions
4134 (format "Delete excess backup versions of %s? "
4137 (modes (file-modes buffer-file-name
))
4138 (extended-attributes
4139 (file-extended-attributes buffer-file-name
))
4140 (copy-when-priv-mismatch
4141 backup-by-copying-when-privileged-mismatch
)
4143 (or file-precious-flag backup-by-copying
4144 ;; Don't rename a suid or sgid file.
4145 (and modes
(< 0 (logand modes
#o6000
)))
4146 (not (file-writable-p
4147 (file-name-directory real-file-name
)))
4148 (and backup-by-copying-when-linked
4149 (< 1 (file-nlinks real-file-name
)))
4150 (and (or backup-by-copying-when-mismatch
4151 (and (integerp copy-when-priv-mismatch
)
4152 (let ((attr (file-attributes
4156 copy-when-priv-mismatch
))))
4157 (not (file-ownership-preserved-p real-file-name
4162 ;; Actually make the backup file.
4164 (backup-buffer-copy real-file-name backupname
4165 modes extended-attributes
)
4166 ;; rename-file should delete old backup.
4167 (rename-file real-file-name backupname t
)
4168 (setq setmodes
(list modes extended-attributes
4170 (setq buffer-backed-up t
)
4171 ;; Now delete the old versions, if desired.
4172 (dolist (old-version old-versions
)
4173 (delete-file old-version
)))
4175 ;; If trouble writing the backup, write it in .emacs.d/%backup%.
4176 (when (not buffer-backed-up
)
4177 (setq backupname
(locate-user-emacs-file "%backup%~"))
4178 (message "Cannot write backup file; backing up in %s"
4181 (backup-buffer-copy real-file-name backupname
4182 modes extended-attributes
)
4183 (setq buffer-backed-up t
))
4186 (defun backup-buffer-copy (from-name to-name modes extended-attributes
)
4187 ;; Create temp files with strict access rights. It's easy to
4188 ;; loosen them later, whereas it's impossible to close the
4189 ;; time-window of loose permissions otherwise.
4190 (with-file-modes ?
\700
4191 (when (condition-case nil
4192 ;; Try to overwrite old backup first.
4193 (copy-file from-name to-name t t t
)
4195 (while (condition-case nil
4197 (when (file-exists-p to-name
)
4198 (delete-file to-name
))
4199 (copy-file from-name to-name nil t t
)
4201 (file-already-exists t
))
4202 ;; The file was somehow created by someone else between
4203 ;; `delete-file' and `copy-file', so let's try again.
4204 ;; rms says "I think there is also a possible race
4205 ;; condition for making backup files" (emacs-devel 20070821).
4207 ;; If set-file-extended-attributes fails, fall back on set-file-modes.
4208 (unless (and extended-attributes
4209 (with-demoted-errors
4210 (set-file-extended-attributes to-name extended-attributes
)))
4212 (set-file-modes to-name
(logand modes
#o1777
)))))
4214 (defvar file-name-version-regexp
4215 "\\(?:~\\|\\.~[-[:alnum:]:#@^._]+\\(?:~[[:digit:]]+\\)?~\\)"
4216 ;; The last ~[[:digit]]+ matches relative versions in git,
4217 ;; e.g. `foo.js.~HEAD~1~'.
4218 "Regular expression matching the backup/version part of a file name.
4219 Used by `file-name-sans-versions'.")
4221 (defun file-name-sans-versions (name &optional keep-backup-version
)
4222 "Return file NAME sans backup versions or strings.
4223 This is a separate procedure so your site-init or startup file can
4225 If the optional argument KEEP-BACKUP-VERSION is non-nil,
4226 we do not remove backup version numbers, only true file version numbers.
4227 See also `file-name-version-regexp'."
4228 (let ((handler (find-file-name-handler name
'file-name-sans-versions
)))
4230 (funcall handler
'file-name-sans-versions name keep-backup-version
)
4232 (unless keep-backup-version
4233 (string-match (concat file-name-version-regexp
"\\'")
4236 (defun file-ownership-preserved-p (file &optional group
)
4237 "Return t if deleting FILE and rewriting it would preserve the owner.
4238 Return nil if FILE does not exist, or if deleting and recreating it
4239 might not preserve the owner. If GROUP is non-nil, check whether
4240 the group would be preserved too."
4241 (let ((handler (find-file-name-handler file
'file-ownership-preserved-p
)))
4243 (funcall handler
'file-ownership-preserved-p file group
)
4244 (let ((attributes (file-attributes file
'integer
)))
4245 ;; Return t if the file doesn't exist, since it's true that no
4246 ;; information would be lost by an (attempted) delete and create.
4247 (or (null attributes
)
4248 (and (or (= (nth 2 attributes
) (user-uid))
4249 ;; Files created on Windows by Administrator (RID=500)
4250 ;; have the Administrators group (RID=544) recorded as
4251 ;; their owner. Rewriting them will still preserve the
4253 (and (eq system-type
'windows-nt
)
4254 (= (user-uid) 500) (= (nth 2 attributes
) 544)))
4256 ;; On BSD-derived systems files always inherit the parent
4257 ;; directory's group, so skip the group-gid test.
4258 (memq system-type
'(berkeley-unix darwin gnu
/kfreebsd
))
4259 (= (nth 3 attributes
) (group-gid)))
4260 (let* ((parent (or (file-name-directory file
) "."))
4261 (parent-attributes (file-attributes parent
'integer
)))
4262 (and parent-attributes
4263 ;; On some systems, a file created in a setuid directory
4264 ;; inherits that directory's owner.
4266 (= (nth 2 parent-attributes
) (user-uid))
4267 (string-match "^...[^sS]" (nth 8 parent-attributes
)))
4268 ;; On many systems, a file created in a setgid directory
4269 ;; inherits that directory's group. On some systems
4270 ;; this happens even if the setgid bit is not set.
4272 (= (nth 3 parent-attributes
)
4273 (nth 3 attributes
)))))))))))
4275 (defun file-name-sans-extension (filename)
4276 "Return FILENAME sans final \"extension\".
4277 The extension, in a file name, is the part that begins with the last `.',
4278 except that a leading `.' of the file name, if there is one, doesn't count."
4280 (let ((file (file-name-sans-versions (file-name-nondirectory filename
)))
4282 (if (and (string-match "\\.[^.]*\\'" file
)
4283 (not (eq 0 (match-beginning 0))))
4284 (if (setq directory
(file-name-directory filename
))
4285 ;; Don't use expand-file-name here; if DIRECTORY is relative,
4286 ;; we don't want to expand it.
4287 (concat directory
(substring file
0 (match-beginning 0)))
4288 (substring file
0 (match-beginning 0)))
4291 (defun file-name-extension (filename &optional period
)
4292 "Return FILENAME's final \"extension\".
4293 The extension, in a file name, is the part that begins with the last `.',
4294 excluding version numbers and backup suffixes, except that a leading `.'
4295 of the file name, if there is one, doesn't count.
4296 Return nil for extensionless file names such as `foo'.
4297 Return the empty string for file names such as `foo.'.
4299 By default, the returned value excludes the period that starts the
4300 extension, but if the optional argument PERIOD is non-nil, the period
4301 is included in the value, and in that case, if FILENAME has no
4302 extension, the value is \"\"."
4304 (let ((file (file-name-sans-versions (file-name-nondirectory filename
))))
4305 (if (and (string-match "\\.[^.]*\\'" file
)
4306 (not (eq 0 (match-beginning 0))))
4307 (substring file
(+ (match-beginning 0) (if period
0 1)))
4311 (defun file-name-base (&optional filename
)
4312 "Return the base name of the FILENAME: no directory, no extension.
4313 FILENAME defaults to `buffer-file-name'."
4314 (file-name-sans-extension
4315 (file-name-nondirectory (or filename
(buffer-file-name)))))
4317 (defcustom make-backup-file-name-function
4318 #'make-backup-file-name--default-function
4319 "A function that `make-backup-file-name' uses to create backup file names.
4320 The function receives a single argument, the original file name.
4322 If you change this, you may need to change `backup-file-name-p' and
4323 `file-name-sans-versions' too.
4325 You could make this buffer-local to do something special for specific files.
4327 For historical reasons, a value of nil means to use the default function.
4328 This should not be relied upon.
4330 See also `backup-directory-alist'."
4331 :version
"24.4" ; nil -> make-backup-file-name--default-function
4333 :type
'(choice (const :tag
"Deprecated way to get the default function" nil
)
4334 (function :tag
"Function")))
4336 (defcustom backup-directory-alist nil
4337 "Alist of filename patterns and backup directory names.
4338 Each element looks like (REGEXP . DIRECTORY). Backups of files with
4339 names matching REGEXP will be made in DIRECTORY. DIRECTORY may be
4340 relative or absolute. If it is absolute, so that all matching files
4341 are backed up into the same directory, the file names in this
4342 directory will be the full name of the file backed up with all
4343 directory separators changed to `!' to prevent clashes. This will not
4344 work correctly if your filesystem truncates the resulting name.
4346 For the common case of all backups going into one directory, the alist
4347 should contain a single element pairing \".\" with the appropriate
4350 If this variable is nil, or it fails to match a filename, the backup
4351 is made in the original file's directory.
4353 On MS-DOS filesystems without long names this variable is always
4356 :type
'(repeat (cons (regexp :tag
"Regexp matching filename")
4357 (directory :tag
"Backup directory name"))))
4359 (defun normal-backup-enable-predicate (name)
4360 "Default `backup-enable-predicate' function.
4361 Checks for files in `temporary-file-directory',
4362 `small-temporary-file-directory', and /tmp."
4363 (let ((temporary-file-directory temporary-file-directory
)
4365 ;; On MS-Windows, file-truename will convert short 8+3 aliases to
4366 ;; their long file-name equivalents, so compare-strings does TRT.
4367 (if (memq system-type
'(ms-dos windows-nt
))
4368 (setq temporary-file-directory
(file-truename temporary-file-directory
)
4369 name
(file-truename name
)
4371 (not (or (let ((comp (compare-strings temporary-file-directory
0 nil
4372 name
0 nil caseless
)))
4373 ;; Directory is under temporary-file-directory.
4374 (and (not (eq comp t
))
4375 (< comp
(- (length temporary-file-directory
)))))
4376 (let ((comp (compare-strings "/tmp" 0 nil
4378 ;; Directory is under /tmp.
4379 (and (not (eq comp t
))
4380 (< comp
(- (length "/tmp")))))
4381 (if small-temporary-file-directory
4382 (let ((comp (compare-strings small-temporary-file-directory
4384 name
0 nil caseless
)))
4385 ;; Directory is under small-temporary-file-directory.
4386 (and (not (eq comp t
))
4387 (< comp
(- (length small-temporary-file-directory
))))))))))
4389 (defun make-backup-file-name (file)
4390 "Create the non-numeric backup file name for FILE.
4391 This calls the function that `make-backup-file-name-function' specifies,
4392 with a single argument FILE."
4393 (funcall (or make-backup-file-name-function
4394 #'make-backup-file-name--default-function
)
4397 (defun make-backup-file-name--default-function (file)
4398 "Default function for `make-backup-file-name'.
4399 Normally this just returns FILE's name with `~' appended.
4400 It searches for a match for FILE in `backup-directory-alist'.
4401 If the directory for the backup doesn't exist, it is created."
4402 (if (and (eq system-type
'ms-dos
)
4403 (not (msdos-long-file-names)))
4404 (let ((fn (file-name-nondirectory file
)))
4405 (concat (file-name-directory file
)
4406 (or (and (string-match "\\`[^.]+\\'" fn
)
4407 (concat (match-string 0 fn
) ".~"))
4408 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn
)
4409 (concat (match-string 0 fn
) "~")))))
4410 (concat (make-backup-file-name-1 file
) "~")))
4412 (defun make-backup-file-name-1 (file)
4413 "Subroutine of `make-backup-file-name--default-function'.
4414 The function `find-backup-file-name' also uses this."
4415 (let ((alist backup-directory-alist
)
4416 elt backup-directory abs-backup-directory
)
4418 (setq elt
(pop alist
))
4419 (if (string-match (car elt
) file
)
4420 (setq backup-directory
(cdr elt
)
4422 ;; If backup-directory is relative, it should be relative to the
4423 ;; file's directory. By expanding explicitly here, we avoid
4424 ;; depending on default-directory.
4425 (if backup-directory
4426 (setq abs-backup-directory
4427 (expand-file-name backup-directory
4428 (file-name-directory file
))))
4429 (if (and abs-backup-directory
(not (file-exists-p abs-backup-directory
)))
4431 (make-directory abs-backup-directory
'parents
)
4432 (file-error (setq backup-directory nil
4433 abs-backup-directory nil
))))
4434 (if (null backup-directory
)
4436 (if (file-name-absolute-p backup-directory
)
4438 (when (memq system-type
'(windows-nt ms-dos cygwin
))
4439 ;; Normalize DOSish file names: downcase the drive
4440 ;; letter, if any, and replace the leading "x:" with
4442 (or (file-name-absolute-p file
)
4443 (setq file
(expand-file-name file
))) ; make defaults explicit
4444 ;; Replace any invalid file-name characters (for the
4445 ;; case of backing up remote files).
4446 (setq file
(expand-file-name (convert-standard-filename file
)))
4447 (if (eq (aref file
1) ?
:)
4448 (setq file
(concat "/"
4450 (char-to-string (downcase (aref file
0)))
4451 (if (eq (aref file
2) ?
/)
4454 (substring file
2)))))
4455 ;; Make the name unique by substituting directory
4456 ;; separators. It may not really be worth bothering about
4457 ;; doubling `!'s in the original name...
4459 (subst-char-in-string
4461 (replace-regexp-in-string "!" "!!" file
))
4463 (expand-file-name (file-name-nondirectory file
)
4464 (file-name-as-directory abs-backup-directory
))))))
4466 (defun backup-file-name-p (file)
4467 "Return non-nil if FILE is a backup file name (numeric or not).
4468 This is a separate function so you can redefine it for customization.
4469 You may need to redefine `file-name-sans-versions' as well."
4470 (string-match "~\\'" file
))
4472 (defvar backup-extract-version-start
)
4474 ;; This is used in various files.
4475 ;; The usage of backup-extract-version-start is not very clean,
4476 ;; but I can't see a good alternative, so as of now I am leaving it alone.
4477 (defun backup-extract-version (fn)
4478 "Given the name of a numeric backup file, FN, return the backup number.
4479 Uses the free variable `backup-extract-version-start', whose value should be
4480 the index in the name where the version number begins."
4481 (if (and (string-match "[0-9]+~/?$" fn backup-extract-version-start
)
4482 (= (match-beginning 0) backup-extract-version-start
))
4483 (string-to-number (substring fn backup-extract-version-start -
1))
4486 (defun find-backup-file-name (fn)
4487 "Find a file name for a backup file FN, and suggestions for deletions.
4488 Value is a list whose car is the name for the backup file
4489 and whose cdr is a list of old versions to consider deleting now.
4490 If the value is nil, don't make a backup.
4491 Uses `backup-directory-alist' in the same way as
4492 `make-backup-file-name--default-function' does."
4493 (let ((handler (find-file-name-handler fn
'find-backup-file-name
)))
4494 ;; Run a handler for this function so that ange-ftp can refuse to do it.
4496 (funcall handler
'find-backup-file-name fn
)
4497 (if (or (eq version-control
'never
)
4498 ;; We don't support numbered backups on plain MS-DOS
4499 ;; when long file names are unavailable.
4500 (and (eq system-type
'ms-dos
)
4501 (not (msdos-long-file-names))))
4502 (list (make-backup-file-name fn
))
4503 (let* ((basic-name (make-backup-file-name-1 fn
))
4504 (base-versions (concat (file-name-nondirectory basic-name
)
4506 (backup-extract-version-start (length base-versions
))
4508 (number-to-delete 0)
4509 possibilities deserve-versions-p versions
)
4511 (setq possibilities
(file-name-all-completions
4513 (file-name-directory basic-name
))
4514 versions
(sort (mapcar #'backup-extract-version
4517 high-water-mark
(apply 'max
0 versions
)
4518 deserve-versions-p
(or version-control
4519 (> high-water-mark
0))
4520 number-to-delete
(- (length versions
)
4524 (file-error (setq possibilities nil
)))
4525 (if (not deserve-versions-p
)
4526 (list (make-backup-file-name fn
))
4527 (cons (format "%s.~%d~" basic-name
(1+ high-water-mark
))
4528 (if (and (> number-to-delete
0)
4529 ;; Delete nothing if there is overflow
4530 ;; in the number of versions to keep.
4531 (>= (+ kept-new-versions kept-old-versions -
1) 0))
4533 (format "%s.~%d~" basic-name n
))
4534 (let ((v (nthcdr kept-old-versions versions
)))
4535 (rplacd (nthcdr (1- number-to-delete
) v
) ())
4538 (defun file-nlinks (filename)
4539 "Return number of names file FILENAME has."
4540 (car (cdr (file-attributes filename
))))
4542 ;; (defun file-relative-name (filename &optional directory)
4543 ;; "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
4544 ;; This function returns a relative file name which is equivalent to FILENAME
4545 ;; when used with that default directory as the default.
4546 ;; If this is impossible (which can happen on MSDOS and Windows
4547 ;; when the file name and directory use different drive names)
4548 ;; then it returns FILENAME."
4550 ;; (let ((fname (expand-file-name filename)))
4551 ;; (setq directory (file-name-as-directory
4552 ;; (expand-file-name (or directory default-directory))))
4553 ;; ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
4554 ;; ;; drive names, they can't be relative, so return the absolute name.
4555 ;; (if (and (or (eq system-type 'ms-dos)
4556 ;; (eq system-type 'cygwin)
4557 ;; (eq system-type 'windows-nt))
4558 ;; (not (string-equal (substring fname 0 2)
4559 ;; (substring directory 0 2))))
4561 ;; (let ((ancestor ".")
4562 ;; (fname-dir (file-name-as-directory fname)))
4563 ;; (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
4564 ;; (not (string-match (concat "^" (regexp-quote directory)) fname)))
4565 ;; (setq directory (file-name-directory (substring directory 0 -1))
4566 ;; ancestor (if (equal ancestor ".")
4568 ;; (concat "../" ancestor))))
4569 ;; ;; Now ancestor is empty, or .., or ../.., etc.
4570 ;; (if (string-match (concat "^" (regexp-quote directory)) fname)
4571 ;; ;; We matched within FNAME's directory part.
4572 ;; ;; Add the rest of FNAME onto ANCESTOR.
4573 ;; (let ((rest (substring fname (match-end 0))))
4574 ;; (if (and (equal ancestor ".")
4575 ;; (not (equal rest "")))
4576 ;; ;; But don't bother with ANCESTOR if it would give us `./'.
4578 ;; (concat (file-name-as-directory ancestor) rest)))
4579 ;; ;; We matched FNAME's directory equivalent.
4582 (defun file-relative-name (filename &optional directory
)
4583 "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
4584 This function returns a relative file name which is equivalent to FILENAME
4585 when used with that default directory as the default.
4586 If FILENAME is a relative file name, it will be interpreted as existing in
4587 `default-directory'.
4588 If FILENAME and DIRECTORY lie on different machines or on different drives
4589 on a DOS/Windows machine, it returns FILENAME in expanded form."
4592 (file-name-as-directory (expand-file-name (or directory
4593 default-directory
))))
4594 (setq filename
(expand-file-name filename
))
4595 (let ((fremote (file-remote-p filename
))
4596 (dremote (file-remote-p directory
))
4597 (fold-case (or (memq system-type
'(ms-dos cygwin windows-nt
))
4598 read-file-name-completion-ignore-case
)))
4599 (if ;; Conditions for separate trees
4601 ;; Test for different filesystems on DOS/Windows
4603 ;; Should `cygwin' really be included here? --stef
4604 (memq system-type
'(ms-dos cygwin windows-nt
))
4606 ;; Test for different drive letters
4607 (not (eq t
(compare-strings filename
0 2 directory
0 2 fold-case
)))
4608 ;; Test for UNCs on different servers
4609 (not (eq t
(compare-strings
4611 (if (string-match "\\`//\\([^:/]+\\)/" filename
)
4612 (match-string 1 filename
)
4613 ;; Windows file names cannot have ? in
4614 ;; them, so use that to detect when
4615 ;; neither FILENAME nor DIRECTORY is a
4620 (if (string-match "\\`//\\([^:/]+\\)/" directory
)
4621 (match-string 1 directory
)
4624 ;; Test for different remote file system identification
4625 (not (equal fremote dremote
)))
4627 (let ((ancestor ".")
4628 (filename-dir (file-name-as-directory filename
)))
4630 (or (string-prefix-p directory filename-dir fold-case
)
4631 (string-prefix-p directory filename fold-case
)))
4632 (setq directory
(file-name-directory (substring directory
0 -
1))
4633 ancestor
(if (equal ancestor
".")
4635 (concat "../" ancestor
))))
4636 ;; Now ancestor is empty, or .., or ../.., etc.
4637 (if (string-prefix-p directory filename fold-case
)
4638 ;; We matched within FILENAME's directory part.
4639 ;; Add the rest of FILENAME onto ANCESTOR.
4640 (let ((rest (substring filename
(length directory
))))
4641 (if (and (equal ancestor
".") (not (equal rest
"")))
4642 ;; But don't bother with ANCESTOR if it would give us `./'.
4644 (concat (file-name-as-directory ancestor
) rest
)))
4645 ;; We matched FILENAME's directory equivalent.
4648 (defun save-buffer (&optional arg
)
4649 "Save current buffer in visited file if modified.
4650 Variations are described below.
4652 By default, makes the previous version into a backup file
4653 if previously requested or if this is the first save.
4654 Prefixed with one \\[universal-argument], marks this version
4655 to become a backup when the next save is done.
4656 Prefixed with two \\[universal-argument]'s,
4657 makes the previous version into a backup file.
4658 Prefixed with three \\[universal-argument]'s, marks this version
4659 to become a backup when the next save is done,
4660 and makes the previous version into a backup file.
4662 With a numeric prefix argument of 0, never make the previous version
4665 Note that the various variables that control backups, such
4666 as `version-control', `backup-enable-predicate', `vc-make-backup-files',
4667 and `backup-inhibited', to name just the more popular ones, still
4668 control whether a backup will actually be produced, even when you
4669 invoke this command prefixed with two or three \\[universal-argument]'s.
4671 If a file's name is FOO, the names of its numbered backup versions are
4672 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
4673 Numeric backups (rather than FOO~) will be made if value of
4674 `version-control' is not the atom `never' and either there are already
4675 numeric versions of the file being backed up, or `version-control' is
4677 We don't want excessive versions piling up, so there are variables
4678 `kept-old-versions', which tells Emacs how many oldest versions to keep,
4679 and `kept-new-versions', which tells how many newest versions to keep.
4680 Defaults are 2 old versions and 2 new.
4681 `dired-kept-versions' controls dired's clean-directory (.) command.
4682 If `delete-old-versions' is nil, system will query user
4683 before trimming versions. Otherwise it does it silently.
4685 If `vc-make-backup-files' is nil, which is the default,
4686 no backup files are made for files managed by version control.
4687 (This is because the version control system itself records previous versions.)
4689 See the subroutine `basic-save-buffer' for more information."
4691 (let ((modp (buffer-modified-p))
4692 (make-backup-files (or (and make-backup-files
(not (eq arg
0)))
4693 (memq arg
'(16 64)))))
4694 (and modp
(memq arg
'(16 64)) (setq buffer-backed-up nil
))
4695 ;; We used to display the message below only for files > 50KB, but
4696 ;; then Rmail-mbox never displays it due to buffer swapping. If
4697 ;; the test is ever re-introduced, be sure to handle saving of
4701 (not noninteractive
)
4702 (not save-silently
))
4703 (message "Saving file %s..." (buffer-file-name)))
4704 (basic-save-buffer (called-interactively-p 'any
))
4705 (and modp
(memq arg
'(4 64)) (setq buffer-backed-up nil
))))
4707 (defun delete-auto-save-file-if-necessary (&optional force
)
4708 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
4709 Normally delete only if the file was written by this Emacs since
4710 the last real save, but optional arg FORCE non-nil means delete anyway."
4711 (and buffer-auto-save-file-name delete-auto-save-files
4712 (not (string= buffer-file-name buffer-auto-save-file-name
))
4713 (or force
(recent-auto-save-p))
4716 (delete-file buffer-auto-save-file-name
)
4718 (set-buffer-auto-saved))))
4720 (defvar auto-save-hook nil
4721 "Normal hook run just before auto-saving.")
4723 (defcustom before-save-hook nil
4724 "Normal hook that is run before a buffer is saved to its file."
4725 :options
'(copyright-update time-stamp
)
4729 (defcustom after-save-hook nil
4730 "Normal hook that is run after a buffer is saved to its file."
4731 :options
'(executable-make-buffer-file-executable-if-script-p)
4735 (defvar save-buffer-coding-system nil
4736 "If non-nil, use this coding system for saving the buffer.
4737 More precisely, use this coding system in place of the
4738 value of `buffer-file-coding-system', when saving the buffer.
4739 Calling `write-region' for any purpose other than saving the buffer
4740 will still use `buffer-file-coding-system'; this variable has no effect
4743 (make-variable-buffer-local 'save-buffer-coding-system
)
4744 (put 'save-buffer-coding-system
'permanent-local t
)
4746 (defun basic-save-buffer (&optional called-interactively
)
4747 "Save the current buffer in its visited file, if it has been modified.
4748 The hooks `write-contents-functions' and `write-file-functions' get a chance
4749 to do the job of saving; if they do not, then the buffer is saved in
4750 the visited file in the usual way.
4751 Before and after saving the buffer, this function runs
4752 `before-save-hook' and `after-save-hook', respectively."
4753 (interactive '(called-interactively))
4754 (save-current-buffer
4755 ;; In an indirect buffer, save its base buffer instead.
4756 (if (buffer-base-buffer)
4757 (set-buffer (buffer-base-buffer)))
4758 (if (or (buffer-modified-p)
4759 ;; handle the case when no modification has been made but
4760 ;; the file disappeared since visited
4761 (and buffer-file-name
4762 (not (file-exists-p buffer-file-name
))))
4763 (let ((recent-save (recent-auto-save-p))
4765 ;; If buffer has no file name, ask user for one.
4766 (or buffer-file-name
4769 (read-file-name "File to save in: "
4770 nil
(expand-file-name (buffer-name))))))
4771 (if (file-exists-p filename
)
4772 (if (file-directory-p filename
)
4773 ;; Signal an error if the user specified the name of an
4774 ;; existing directory.
4775 (error "%s is a directory" filename
)
4776 (unless (y-or-n-p (format-message
4777 "File `%s' exists; overwrite? "
4779 (error "Canceled"))))
4780 (set-visited-file-name filename
)))
4781 (or (verify-visited-file-modtime (current-buffer))
4782 (not (file-exists-p buffer-file-name
))
4785 "%s has changed since visited or saved. Save anyway? "
4786 (file-name-nondirectory buffer-file-name
)))
4787 (user-error "Save not confirmed"))
4791 (and (> (point-max) (point-min))
4792 (not find-file-literally
)
4793 (/= (char-after (1- (point-max))) ?
\n)
4794 (not (and (eq selective-display t
)
4795 (= (char-after (1- (point-max))) ?
\r)))
4796 (or (eq require-final-newline t
)
4797 (eq require-final-newline
'visit-save
)
4798 (and require-final-newline
4800 (format "Buffer %s does not end in newline. Add one? "
4803 (goto-char (point-max))
4805 ;; Support VC version backups.
4807 ;; Don't let errors prevent saving the buffer.
4808 (with-demoted-errors (run-hooks 'before-save-hook
))
4809 (or (run-hook-with-args-until-success 'write-contents-functions
)
4810 (run-hook-with-args-until-success 'local-write-file-hooks
)
4811 (run-hook-with-args-until-success 'write-file-functions
)
4812 ;; If a hook returned t, file is already "written".
4813 ;; Otherwise, write it the usual way now.
4814 (let ((dir (file-name-directory
4815 (expand-file-name buffer-file-name
))))
4816 (unless (file-exists-p dir
)
4819 "Directory `%s' does not exist; create? " dir
))
4820 (make-directory dir t
)
4821 (error "Canceled")))
4822 (setq setmodes
(basic-save-buffer-1))))
4823 ;; Now we have saved the current buffer. Let's make sure
4824 ;; that buffer-file-coding-system is fixed to what
4825 ;; actually used for saving by binding it locally.
4826 (if save-buffer-coding-system
4827 (setq save-buffer-coding-system last-coding-system-used
)
4828 (setq buffer-file-coding-system last-coding-system-used
))
4829 (setq buffer-file-number
4830 (nthcdr 10 (file-attributes buffer-file-name
)))
4835 (with-demoted-errors
4836 (set-file-modes buffer-file-name
(car setmodes
)))
4837 (set-file-extended-attributes buffer-file-name
4840 ;; If the auto-save file was recent before this command,
4842 (delete-auto-save-file-if-necessary recent-save
)
4843 ;; Support VC `implicit' locking.
4845 (run-hooks 'after-save-hook
))
4847 (not called-interactively
)
4848 (files--message "(No changes need to be saved)")))))
4850 ;; This does the "real job" of writing a buffer into its visited file
4851 ;; and making a backup file. This is what is normally done
4852 ;; but inhibited if one of write-file-functions returns non-nil.
4853 ;; It returns a value (MODES EXTENDED-ATTRIBUTES BACKUPNAME), like
4855 (defun basic-save-buffer-1 ()
4857 (if save-buffer-coding-system
4858 (let ((coding-system-for-write save-buffer-coding-system
))
4859 (basic-save-buffer-2))
4860 (basic-save-buffer-2))
4861 (if buffer-file-coding-system-explicit
4862 (setcar buffer-file-coding-system-explicit last-coding-system-used
))))
4864 ;; This returns a value (MODES EXTENDED-ATTRIBUTES BACKUPNAME), like
4866 (defun basic-save-buffer-2 ()
4867 (let (tempsetmodes setmodes
)
4868 (if (not (file-writable-p buffer-file-name
))
4869 (let ((dir (file-name-directory buffer-file-name
)))
4870 (if (not (file-directory-p dir
))
4871 (if (file-exists-p dir
)
4872 (error "%s is not a directory" dir
)
4873 (error "%s: no such directory" dir
))
4874 (if (not (file-exists-p buffer-file-name
))
4875 (error "Directory %s write-protected" dir
)
4878 "File %s is write-protected; try to save anyway? "
4879 (file-name-nondirectory
4881 (setq tempsetmodes t
)
4882 (error "Attempt to save to a file which you aren't allowed to write"))))))
4883 (or buffer-backed-up
4884 (setq setmodes
(backup-buffer)))
4885 (let* ((dir (file-name-directory buffer-file-name
))
4886 (dir-writable (file-writable-p dir
)))
4887 (if (or (and file-precious-flag dir-writable
)
4888 (and break-hardlink-on-save
4889 (file-exists-p buffer-file-name
)
4890 (> (file-nlinks buffer-file-name
) 1)
4892 (error (concat "Directory %s write-protected; "
4893 "cannot break hardlink when saving")
4895 ;; Write temp name, then rename it.
4896 ;; This requires write access to the containing dir,
4897 ;; which is why we don't try it if we don't have that access.
4898 (let ((realname buffer-file-name
)
4900 (umask (default-file-modes))
4901 (old-modtime (visited-file-modtime)))
4902 ;; Create temp files with strict access rights. It's easy to
4903 ;; loosen them later, whereas it's impossible to close the
4904 ;; time-window of loose permissions otherwise.
4907 (clear-visited-file-modtime)
4908 (set-default-file-modes ?
\700)
4909 ;; Try various temporary names.
4910 ;; This code follows the example of make-temp-file,
4911 ;; but it calls write-region in the appropriate way
4912 ;; for saving the buffer.
4913 (while (condition-case ()
4917 (expand-file-name "tmp" dir
)))
4918 ;; Pass in nil&nil rather than point-min&max
4919 ;; cause we're saving the whole buffer.
4920 ;; write-region-annotate-functions may use it.
4921 (write-region nil nil
4922 tempname nil realname
4923 buffer-file-truename
'excl
)
4924 (when save-silently
(message nil
))
4926 (file-already-exists t
))
4927 ;; The file was somehow created by someone else between
4928 ;; `make-temp-name' and `write-region', let's try again.
4932 (set-default-file-modes umask
)
4933 ;; If we failed, restore the buffer's modtime.
4935 (set-visited-file-modtime old-modtime
)))
4936 ;; Since we have created an entirely new file,
4937 ;; make sure it gets the right permission bits set.
4938 (setq setmodes
(or setmodes
4939 (list (or (file-modes buffer-file-name
)
4940 (logand ?
\666 umask
))
4941 (file-extended-attributes buffer-file-name
)
4943 ;; We succeeded in writing the temp file,
4945 (rename-file tempname buffer-file-name t
))
4946 ;; If file not writable, see if we can make it writable
4947 ;; temporarily while we write it.
4948 ;; But no need to do so if we have just backed it up
4949 ;; (setmodes is set) because that says we're superseding.
4950 (cond ((and tempsetmodes
(not setmodes
))
4951 ;; Change the mode back, after writing.
4952 (setq setmodes
(list (file-modes buffer-file-name
)
4953 (file-extended-attributes buffer-file-name
)
4955 ;; If set-file-extended-attributes fails, fall back on
4958 (with-demoted-errors
4959 (set-file-extended-attributes buffer-file-name
4961 (set-file-modes buffer-file-name
4962 (logior (car setmodes
) 128))))))
4966 ;; Pass in nil&nil rather than point-min&max to indicate
4967 ;; we're saving the buffer rather than just a region.
4968 ;; write-region-annotate-functions may make us of it.
4969 (write-region nil nil
4970 buffer-file-name nil t buffer-file-truename
)
4971 (when save-silently
(message nil
))
4973 ;; If we get an error writing the new file, and we made
4974 ;; the backup by renaming, undo the backing-up.
4975 (and setmodes
(not success
)
4977 (rename-file (nth 2 setmodes
) buffer-file-name t
)
4978 (setq buffer-backed-up nil
))))))
4981 (declare-function diff-no-select
"diff"
4982 (old new
&optional switches no-async buf
))
4984 (defvar save-some-buffers-action-alist
4987 (if (not enable-recursive-minibuffers
)
4988 (progn (display-buffer buf
)
4989 (setq other-window-scroll-buffer buf
))
4990 (view-buffer buf
(lambda (_) (exit-recursive-edit)))
4992 ;; Return nil to ask about BUF again.
4994 ,(purecopy "view this buffer"))
4996 (if (null (buffer-file-name buf
))
4997 (message "Not applicable: no file")
4998 (require 'diff
) ;for diff-no-select.
4999 (let ((diffbuf (diff-no-select (buffer-file-name buf
) buf
5001 (if (not enable-recursive-minibuffers
)
5002 (progn (display-buffer diffbuf
)
5003 (setq other-window-scroll-buffer diffbuf
))
5004 (view-buffer diffbuf
(lambda (_) (exit-recursive-edit)))
5006 ;; Return nil to ask about BUF again.
5008 ,(purecopy "view changes in this buffer")))
5009 "ACTION-ALIST argument used in call to `map-y-or-n-p'.")
5010 (put 'save-some-buffers-action-alist
'risky-local-variable t
)
5012 (defvar buffer-save-without-query nil
5013 "Non-nil means `save-some-buffers' should save this buffer without asking.")
5014 (make-variable-buffer-local 'buffer-save-without-query
)
5016 (defun save-some-buffers (&optional arg pred
)
5017 "Save some modified file-visiting buffers. Asks user about each one.
5018 You can answer `y' to save, `n' not to save, `C-r' to look at the
5019 buffer in question with `view-buffer' before deciding or `d' to
5020 view the differences using `diff-buffer-with-file'.
5022 This command first saves any buffers where `buffer-save-without-query' is
5023 non-nil, without asking.
5025 Optional argument (the prefix) non-nil means save all with no questions.
5026 Optional second argument PRED determines which buffers are considered:
5027 If PRED is nil, all the file-visiting buffers are considered.
5028 If PRED is t, then certain non-file buffers will also be considered.
5029 If PRED is a zero-argument function, it indicates for each buffer whether
5030 to consider it or not when called with that buffer current.
5032 See `save-some-buffers-action-alist' if you want to
5033 change the additional actions you can take on files."
5035 (save-window-excursion
5036 (let* (queried autosaved-buffers
5037 files-done abbrevs-done
)
5038 (dolist (buffer (buffer-list))
5039 ;; First save any buffers that we're supposed to save unconditionally.
5040 ;; That way the following code won't ask about them.
5041 (with-current-buffer buffer
5042 (when (and buffer-save-without-query
(buffer-modified-p))
5043 (push (buffer-name) autosaved-buffers
)
5045 ;; Ask about those buffers that merit it,
5046 ;; and record the number thus saved.
5050 ;; Note that killing some buffers may kill others via
5051 ;; hooks (e.g. Rmail and its viewing buffer).
5052 (and (buffer-live-p buffer
)
5053 (buffer-modified-p buffer
)
5054 (not (buffer-base-buffer buffer
))
5056 (buffer-file-name buffer
)
5060 (and buffer-offer-save
(> (buffer-size) 0)))))
5061 (or (not (functionp pred
))
5062 (with-current-buffer buffer
(funcall pred
)))
5066 (if (buffer-file-name buffer
)
5067 (format "Save file %s? "
5068 (buffer-file-name buffer
))
5069 (format "Save buffer %s? "
5070 (buffer-name buffer
))))))
5072 (with-current-buffer buffer
5075 '("buffer" "buffers" "save")
5076 save-some-buffers-action-alist
))
5077 ;; Maybe to save abbrevs, and record whether
5078 ;; we either saved them or asked to.
5079 (and save-abbrevs abbrevs-changed
5082 (eq save-abbrevs
'silently
)
5083 (y-or-n-p (format "Save abbrevs in %s? " abbrev-file-name
)))
5084 (write-abbrev-file nil
))
5085 ;; Don't keep bothering user if he says no.
5086 (setq abbrevs-changed nil
)
5087 (setq abbrevs-done t
)))
5088 (or queried
(> files-done
0) abbrevs-done
5090 ((null autosaved-buffers
)
5091 (when (called-interactively-p 'any
)
5092 (files--message "(No files need saving)")))
5093 ((= (length autosaved-buffers
) 1)
5094 (files--message "(Saved %s)" (car autosaved-buffers
)))
5096 (files--message "(Saved %d files: %s)"
5097 (length autosaved-buffers
)
5098 (mapconcat 'identity autosaved-buffers
", "))))))))
5100 (defun clear-visited-file-modtime ()
5101 "Clear out records of last mod time of visited file.
5102 Next attempt to save will not complain of a discrepancy."
5103 (set-visited-file-modtime 0))
5105 (defun not-modified (&optional arg
)
5106 "Mark current buffer as unmodified, not needing to be saved.
5107 With prefix ARG, mark buffer as modified, so \\[save-buffer] will save.
5109 It is not a good idea to use this function in Lisp programs, because it
5110 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
5111 (declare (interactive-only set-buffer-modified-p
))
5113 (files--message (if arg
"Modification-flag set"
5114 "Modification-flag cleared"))
5115 (set-buffer-modified-p arg
))
5117 (defun toggle-read-only (&optional arg interactive
)
5118 "Change whether this buffer is read-only."
5119 (declare (obsolete read-only-mode
"24.3"))
5120 (interactive (list current-prefix-arg t
))
5122 (call-interactively 'read-only-mode
)
5123 (read-only-mode (or arg
'toggle
))))
5125 (defun insert-file (filename)
5126 "Insert contents of file FILENAME into buffer after point.
5127 Set mark after the inserted text.
5129 This function is meant for the user to run interactively.
5130 Don't call it from programs! Use `insert-file-contents' instead.
5131 \(Its calling sequence is different; see its documentation)."
5132 (declare (interactive-only insert-file-contents
))
5133 (interactive "*fInsert file: ")
5134 (insert-file-1 filename
#'insert-file-contents
))
5136 (defun append-to-file (start end filename
)
5137 "Append the contents of the region to the end of file FILENAME.
5138 When called from a function, expects three arguments,
5139 START, END and FILENAME. START and END are normally buffer positions
5140 specifying the part of the buffer to write.
5141 If START is nil, that means to use the entire buffer contents.
5142 If START is a string, then output that string to the file
5143 instead of any buffer contents; END is ignored.
5145 This does character code conversion and applies annotations
5146 like `write-region' does."
5147 (interactive "r\nFAppend to file: ")
5148 (prog1 (write-region start end filename t
)
5149 (when save-silently
(message nil
))))
5151 (defun file-newest-backup (filename)
5152 "Return most recent backup file for FILENAME or nil if no backups exist."
5153 ;; `make-backup-file-name' will get us the right directory for
5154 ;; ordinary or numeric backups. It might create a directory for
5155 ;; backups as a side-effect, according to `backup-directory-alist'.
5156 (let* ((filename (file-name-sans-versions
5157 (make-backup-file-name (expand-file-name filename
))))
5158 (file (file-name-nondirectory filename
))
5159 (dir (file-name-directory filename
))
5160 (comp (file-name-all-completions file dir
))
5164 (setq tem
(pop comp
))
5165 (cond ((and (backup-file-name-p tem
)
5166 (string= (file-name-sans-versions tem
) file
))
5167 (setq tem
(concat dir tem
))
5168 (if (or (null newest
)
5169 (file-newer-than-file-p tem newest
))
5170 (setq newest tem
)))))
5173 (defun rename-uniquely ()
5174 "Rename current buffer to a similar name not already taken.
5175 This function is useful for creating multiple shell process buffers
5176 or multiple mail buffers, etc.
5178 Note that some commands, in particular those based on `compilation-mode'
5179 \(`compile', `grep', etc.) will reuse the current buffer if it has the
5180 appropriate mode even if it has been renamed. So as well as renaming
5181 the buffer, you also need to switch buffers before running another
5182 instance of such commands."
5185 (let ((base-name (buffer-name)))
5186 (and (string-match "<[0-9]+>\\'" base-name
)
5187 (not (and buffer-file-name
5189 (file-name-nondirectory buffer-file-name
))))
5190 ;; If the existing buffer name has a <NNN>,
5191 ;; which isn't part of the file name (if any),
5192 ;; then get rid of that.
5193 (setq base-name
(substring base-name
0 (match-beginning 0))))
5194 (rename-buffer (generate-new-buffer-name base-name
))
5195 (force-mode-line-update))))
5197 (defun make-directory (dir &optional parents
)
5198 "Create the directory DIR and optionally any nonexistent parent dirs.
5199 If DIR already exists as a directory, signal an error, unless
5202 Interactively, the default choice of directory to create is the
5203 current buffer's default directory. That is useful when you have
5204 visited a file in a nonexistent directory.
5206 Noninteractively, the second (optional) argument PARENTS, if
5207 non-nil, says whether to create parent directories that don't
5208 exist. Interactively, this happens by default.
5210 If creating the directory or directories fail, an error will be
5213 (list (read-file-name "Make directory: " default-directory default-directory
5216 ;; If default-directory is a remote directory,
5217 ;; make sure we find its make-directory handler.
5218 (setq dir
(expand-file-name dir
))
5219 (let ((handler (find-file-name-handler dir
'make-directory
)))
5221 (funcall handler
'make-directory dir parents
)
5223 (make-directory-internal dir
)
5224 (let ((dir (directory-file-name (expand-file-name dir
)))
5226 (while (and (not (file-exists-p dir
))
5227 ;; If directory is its own parent, then we can't
5228 ;; keep looping forever
5230 (directory-file-name
5231 (file-name-directory dir
)))))
5232 (setq create-list
(cons dir create-list
)
5233 dir
(directory-file-name (file-name-directory dir
))))
5235 (make-directory-internal (car create-list
))
5236 (setq create-list
(cdr create-list
))))))))
5238 (defconst directory-files-no-dot-files-regexp
5239 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"
5240 "Regexp matching any file name except \".\" and \"..\".")
5242 (defun delete-directory (directory &optional recursive trash
)
5243 "Delete the directory named DIRECTORY. Does not follow symlinks.
5244 If RECURSIVE is non-nil, all files in DIRECTORY are deleted as well.
5245 TRASH non-nil means to trash the directory instead, provided
5246 `delete-by-moving-to-trash' is non-nil.
5248 When called interactively, TRASH is t if no prefix argument is
5249 given. With a prefix argument, TRASH is nil."
5251 (let* ((trashing (and delete-by-moving-to-trash
5252 (null current-prefix-arg
)))
5253 (dir (expand-file-name
5254 (read-directory-name
5256 "Move directory to trash: "
5257 "Delete directory: ")
5258 default-directory default-directory nil nil
))))
5260 (if (directory-files dir nil directory-files-no-dot-files-regexp
)
5262 (format-message "Directory `%s' is not empty, really %s? "
5263 dir
(if trashing
"trash" "delete")))
5265 (null current-prefix-arg
))))
5266 ;; If default-directory is a remote directory, make sure we find its
5267 ;; delete-directory handler.
5268 (setq directory
(directory-file-name (expand-file-name directory
)))
5269 (let ((handler (find-file-name-handler directory
'delete-directory
)))
5272 (funcall handler
'delete-directory directory recursive
))
5273 ((and delete-by-moving-to-trash trash
)
5274 ;; Only move non-empty dir to trash if recursive deletion was
5275 ;; requested. This mimics the non-`delete-by-moving-to-trash'
5276 ;; case, where the operation fails in delete-directory-internal.
5277 ;; As `move-file-to-trash' trashes directories (empty or
5278 ;; otherwise) as a unit, we do not need to recurse here.
5279 (if (and (not recursive
)
5280 ;; Check if directory is empty apart from "." and "..".
5282 directory
'full directory-files-no-dot-files-regexp
))
5283 (error "Directory is not empty, not moving to trash")
5284 (move-file-to-trash directory
)))
5285 ;; Otherwise, call ourselves recursively if needed.
5287 (if (and recursive
(not (file-symlink-p directory
)))
5288 (mapc (lambda (file)
5289 ;; This test is equivalent to
5290 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
5291 ;; but more efficient
5292 (if (eq t
(car (file-attributes file
)))
5293 (delete-directory file recursive nil
)
5294 (delete-file file nil
)))
5295 ;; We do not want to delete "." and "..".
5297 directory
'full directory-files-no-dot-files-regexp
)))
5298 (delete-directory-internal directory
)))))
5300 (defun file-equal-p (file1 file2
)
5301 "Return non-nil if files FILE1 and FILE2 name the same file.
5302 If FILE1 or FILE2 does not exist, the return value is unspecified."
5303 (let ((handler (or (find-file-name-handler file1
'file-equal-p
)
5304 (find-file-name-handler file2
'file-equal-p
))))
5306 (funcall handler
'file-equal-p file1 file2
)
5307 (let (f1-attr f2-attr
)
5308 (and (setq f1-attr
(file-attributes (file-truename file1
)))
5309 (setq f2-attr
(file-attributes (file-truename file2
)))
5310 (equal f1-attr f2-attr
))))))
5312 (defun file-in-directory-p (file dir
)
5313 "Return non-nil if FILE is in DIR or a subdirectory of DIR.
5314 A directory is considered to be \"in\" itself.
5315 Return nil if DIR is not an existing directory."
5316 (let ((handler (or (find-file-name-handler file
'file-in-directory-p
)
5317 (find-file-name-handler dir
'file-in-directory-p
))))
5319 (funcall handler
'file-in-directory-p file dir
)
5320 (when (file-directory-p dir
) ; DIR must exist.
5321 (setq file
(file-truename file
)
5322 dir
(file-truename dir
))
5323 (let ((ls1 (split-string file
"/" t
))
5324 (ls2 (split-string dir
"/" t
))
5327 ;; A UNC on Windows systems, or a "super-root" on Apollo.
5328 ((string-match "\\`//" file
) "//")
5329 ((string-match "\\`/" file
) "/")
5332 (while (and ls1 ls2
(not mismatch
))
5333 (if (string-equal (car ls1
) (car ls2
))
5334 (setq root
(concat root
(car ls1
) "/"))
5339 (file-equal-p root dir
)))))))
5341 (defun copy-directory (directory newname
&optional keep-time parents copy-contents
)
5342 "Copy DIRECTORY to NEWNAME. Both args must be strings.
5343 This function always sets the file modes of the output files to match
5344 the corresponding input file.
5346 The third arg KEEP-TIME non-nil means give the output files the same
5347 last-modified time as the old ones. (This works on only some systems.)
5349 A prefix arg makes KEEP-TIME non-nil.
5351 Noninteractively, the last argument PARENTS says whether to
5352 create parent directories if they don't exist. Interactively,
5353 this happens by default.
5355 If NEWNAME names an existing directory, copy DIRECTORY as a
5356 subdirectory there. However, if called from Lisp with a non-nil
5357 optional argument COPY-CONTENTS, copy the contents of DIRECTORY
5358 directly into NEWNAME instead."
5360 (let ((dir (read-directory-name
5361 "Copy directory: " default-directory default-directory t nil
)))
5363 (read-directory-name
5364 (format "Copy directory %s to: " dir
)
5365 default-directory default-directory nil nil
)
5366 current-prefix-arg t nil
)))
5367 (when (file-in-directory-p newname directory
)
5368 (error "Cannot copy `%s' into its subdirectory `%s'"
5370 ;; If default-directory is a remote directory, make sure we find its
5371 ;; copy-directory handler.
5372 (let ((handler (or (find-file-name-handler directory
'copy-directory
)
5373 (find-file-name-handler newname
'copy-directory
))))
5375 (funcall handler
'copy-directory directory
5376 newname keep-time parents copy-contents
)
5378 ;; Compute target name.
5379 (setq directory
(directory-file-name (expand-file-name directory
))
5380 newname
(directory-file-name (expand-file-name newname
)))
5382 (cond ((not (file-directory-p newname
))
5383 ;; If NEWNAME is not an existing directory, create it;
5384 ;; that is where we will copy the files of DIRECTORY.
5385 (make-directory newname parents
))
5386 ;; If NEWNAME is an existing directory and COPY-CONTENTS
5387 ;; is nil, copy into NEWNAME/[DIRECTORY-BASENAME].
5388 ((not copy-contents
)
5389 (setq newname
(expand-file-name
5390 (file-name-nondirectory
5391 (directory-file-name directory
))
5393 (and (file-exists-p newname
)
5394 (not (file-directory-p newname
))
5395 (error "Cannot overwrite non-directory %s with a directory"
5397 (make-directory newname t
)))
5399 ;; Copy recursively.
5401 ;; We do not want to copy "." and "..".
5402 (directory-files directory
'full
5403 directory-files-no-dot-files-regexp
))
5404 (let ((target (expand-file-name (file-name-nondirectory file
) newname
))
5405 (filetype (car (file-attributes file
))))
5407 ((eq filetype t
) ; Directory but not a symlink.
5408 (copy-directory file newname keep-time parents
))
5409 ((stringp filetype
) ; Symbolic link
5410 (make-symbolic-link filetype target t
))
5411 ((copy-file file target t keep-time
)))))
5413 ;; Set directory attributes.
5414 (let ((modes (file-modes directory
))
5415 (times (and keep-time
(nth 5 (file-attributes directory
)))))
5416 (if modes
(set-file-modes newname modes
))
5417 (if times
(set-file-times newname times
))))))
5420 ;; At time of writing, only info uses this.
5421 (defun prune-directory-list (dirs &optional keep reject
)
5422 "Return a copy of DIRS with all non-existent directories removed.
5423 The optional argument KEEP is a list of directories to retain even if
5424 they don't exist, and REJECT is a list of directories to remove from
5425 DIRS, even if they exist; REJECT takes precedence over KEEP.
5427 Note that membership in REJECT and KEEP is checked using simple string
5430 (mapcar (lambda (dir)
5431 (and (not (member dir reject
))
5432 (or (member dir keep
) (file-directory-p dir
))
5437 (put 'revert-buffer-function
'permanent-local t
)
5438 (defvar revert-buffer-function
#'revert-buffer--default
5439 "Function to use to revert this buffer.
5440 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
5441 which are the arguments that `revert-buffer' received.
5442 It also has access to the `preserve-modes' argument of `revert-buffer'
5443 via the `revert-buffer-preserve-modes' dynamic variable.
5445 For historical reasons, a value of nil means to use the default function.
5446 This should not be relied upon.")
5448 (put 'revert-buffer-insert-file-contents-function
'permanent-local t
)
5449 (defvar revert-buffer-insert-file-contents-function
5450 #'revert-buffer-insert-file-contents--default-function
5451 "Function to use to insert contents when reverting this buffer.
5452 The function receives two arguments: the first the nominal file name to use;
5453 the second is t if reading the auto-save file.
5455 The function is responsible for updating (or preserving) point.
5457 For historical reasons, a value of nil means to use the default function.
5458 This should not be relied upon.")
5460 (defun buffer-stale--default-function (&optional _noconfirm
)
5461 "Default function to use for `buffer-stale-function'.
5462 This function ignores its argument.
5463 This returns non-nil if the current buffer is visiting a readable file
5464 whose modification time does not match that of the buffer.
5466 This function only handles buffers that are visiting files.
5467 Non-file buffers need a custom function"
5468 (and buffer-file-name
5469 (file-readable-p buffer-file-name
)
5470 (not (buffer-modified-p (current-buffer)))
5471 (not (verify-visited-file-modtime (current-buffer)))))
5473 (defvar buffer-stale-function
#'buffer-stale--default-function
5474 "Function to check whether a buffer needs reverting.
5475 This should be a function with one optional argument NOCONFIRM.
5476 Auto Revert Mode passes t for NOCONFIRM. The function should return
5477 non-nil if the buffer should be reverted. A return value of
5478 `fast' means that the need for reverting was not checked, but
5479 that reverting the buffer is fast. The buffer is current when
5480 this function is called.
5482 The idea behind the NOCONFIRM argument is that it should be
5483 non-nil if the buffer is going to be reverted without asking the
5484 user. In such situations, one has to be careful with potentially
5485 time consuming operations.
5487 For historical reasons, a value of nil means to use the default function.
5488 This should not be relied upon.
5490 For more information on how this variable is used by Auto Revert mode,
5491 see Info node `(emacs)Supporting additional buffers'.")
5493 (defvar before-revert-hook nil
5494 "Normal hook for `revert-buffer' to run before reverting.
5495 The function `revert-buffer--default' runs this.
5496 A customized `revert-buffer-function' need not run this hook.")
5498 (defvar after-revert-hook nil
5499 "Normal hook for `revert-buffer' to run after reverting.
5500 Note that the hook value that it runs is the value that was in effect
5501 before reverting; that makes a difference if you have buffer-local
5504 The function `revert-buffer--default' runs this.
5505 A customized `revert-buffer-function' need not run this hook.")
5507 (defvar revert-buffer-in-progress-p nil
5508 "Non-nil if a `revert-buffer' operation is in progress, nil otherwise.")
5510 (defvar revert-buffer-internal-hook
)
5512 ;; `revert-buffer-function' was defined long ago to be a function of only
5513 ;; 2 arguments, so we have to use a dynbind variable to pass the
5514 ;; `preserve-modes' argument of `revert-buffer'.
5515 (defvar revert-buffer-preserve-modes
)
5517 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes
)
5518 "Replace current buffer text with the text of the visited file on disk.
5519 This undoes all changes since the file was visited or saved.
5520 With a prefix argument, offer to revert from latest auto-save file, if
5521 that is more recent than the visited file.
5523 This command also implements an interface for special buffers
5524 that contain text which doesn't come from a file, but reflects
5525 some other data instead (e.g. Dired buffers, `buffer-list'
5526 buffers). This is done via the variable `revert-buffer-function'.
5527 In these cases, it should reconstruct the buffer contents from the
5530 When called from Lisp, the first argument is IGNORE-AUTO; only offer
5531 to revert from the auto-save file when this is nil. Note that the
5532 sense of this argument is the reverse of the prefix argument, for the
5533 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
5536 Optional second argument NOCONFIRM means don't ask for confirmation
5537 at all. (The variable `revert-without-query' offers another way to
5538 revert buffers without querying for confirmation.)
5540 Optional third argument PRESERVE-MODES non-nil means don't alter
5541 the files modes. Normally we reinitialize them using `normal-mode'.
5543 This function binds `revert-buffer-in-progress-p' non-nil while it operates.
5545 This function calls the function that `revert-buffer-function' specifies
5546 to do the work, with arguments IGNORE-AUTO and NOCONFIRM.
5547 The default function runs the hooks `before-revert-hook' and
5548 `after-revert-hook'."
5549 ;; I admit it's odd to reverse the sense of the prefix argument, but
5550 ;; there is a lot of code out there which assumes that the first
5551 ;; argument should be t to avoid consulting the auto-save file, and
5552 ;; there's no straightforward way to encourage authors to notice a
5553 ;; reversal of the argument sense. So I'm just changing the user
5554 ;; interface, but leaving the programmatic interface the same.
5555 (interactive (list (not current-prefix-arg
)))
5556 (let ((revert-buffer-in-progress-p t
)
5557 (revert-buffer-preserve-modes preserve-modes
))
5558 (funcall (or revert-buffer-function
#'revert-buffer--default
)
5559 ignore-auto noconfirm
)))
5561 (defun revert-buffer--default (ignore-auto noconfirm
)
5562 "Default function for `revert-buffer'.
5563 The arguments IGNORE-AUTO and NOCONFIRM are as described for `revert-buffer'.
5564 Runs the hooks `before-revert-hook' and `after-revert-hook' at the
5567 Calls `revert-buffer-insert-file-contents-function' to reread the
5568 contents of the visited file, with two arguments: the first is the file
5569 name, the second is non-nil if reading an auto-save file.
5571 This function only handles buffers that are visiting files.
5572 Non-file buffers need a custom function."
5573 (with-current-buffer (or (buffer-base-buffer (current-buffer))
5575 (let* ((auto-save-p (and (not ignore-auto
)
5576 (recent-auto-save-p)
5577 buffer-auto-save-file-name
5578 (file-readable-p buffer-auto-save-file-name
)
5580 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
5581 (file-name (if auto-save-p
5582 buffer-auto-save-file-name
5584 (cond ((null file-name
)
5585 (error "Buffer does not seem to be associated with any file"))
5587 (and (not (buffer-modified-p))
5589 (dolist (regexp revert-without-query
)
5590 (when (string-match regexp file-name
)
5591 (throw 'found t
)))))
5592 (yes-or-no-p (format "Revert buffer from file %s? "
5594 (run-hooks 'before-revert-hook
)
5595 ;; If file was backed up but has changed since,
5596 ;; we should make another backup.
5597 (and (not auto-save-p
)
5598 (not (verify-visited-file-modtime (current-buffer)))
5599 (setq buffer-backed-up nil
))
5600 ;; Effectively copy the after-revert-hook status,
5601 ;; since after-find-file will clobber it.
5602 (let ((global-hook (default-value 'after-revert-hook
))
5603 (local-hook (when (local-variable-p 'after-revert-hook
)
5605 (inhibit-read-only t
))
5606 ;; FIXME: Throw away undo-log when preserve-modes is nil?
5608 (or revert-buffer-insert-file-contents-function
5609 #'revert-buffer-insert-file-contents--default-function
)
5610 file-name auto-save-p
)
5611 ;; Recompute the truename in case changes in symlinks
5612 ;; have changed the truename.
5613 (setq buffer-file-truename
5614 (abbreviate-file-name (file-truename buffer-file-name
)))
5615 (after-find-file nil nil t nil revert-buffer-preserve-modes
)
5616 ;; Run after-revert-hook as it was before we reverted.
5617 (setq-default revert-buffer-internal-hook global-hook
)
5619 (set (make-local-variable 'revert-buffer-internal-hook
)
5621 (kill-local-variable 'revert-buffer-internal-hook
))
5622 (run-hooks 'revert-buffer-internal-hook
))
5625 (defun revert-buffer-insert-file-contents--default-function (file-name auto-save-p
)
5626 "Default function for `revert-buffer-insert-file-contents-function'.
5627 The function `revert-buffer--default' calls this.
5628 FILE-NAME is the name of the file. AUTO-SAVE-P is non-nil if this is
5631 ((not (file-exists-p file-name
))
5632 (error (if buffer-file-number
5633 "File %s no longer exists!"
5634 "Cannot revert nonexistent file %s")
5636 ((not (file-readable-p file-name
))
5637 (error (if buffer-file-number
5638 "File %s no longer readable!"
5639 "Cannot revert unreadable file %s")
5642 ;; Bind buffer-file-name to nil
5643 ;; so that we don't try to lock the file.
5644 (let ((buffer-file-name nil
))
5648 (let ((coding-system-for-read
5649 ;; Auto-saved file should be read by Emacs's
5651 (if auto-save-p
'auto-save-coding
5652 (or coding-system-for-read
5654 buffer-file-coding-system-explicit
5655 (car buffer-file-coding-system-explicit
))))))
5656 (if (and (not enable-multibyte-characters
)
5657 coding-system-for-read
5658 (not (memq (coding-system-base
5659 coding-system-for-read
)
5660 '(no-conversion raw-text
))))
5661 ;; As a coding system suitable for multibyte
5662 ;; buffer is specified, make the current
5663 ;; buffer multibyte.
5664 (set-buffer-multibyte t
))
5666 ;; This force after-insert-file-set-coding
5667 ;; (called from insert-file-contents) to set
5668 ;; buffer-file-coding-system to a proper value.
5669 (kill-local-variable 'buffer-file-coding-system
)
5671 ;; Note that this preserves point in an intelligent way.
5672 (if revert-buffer-preserve-modes
5673 (let ((buffer-file-format buffer-file-format
))
5674 (insert-file-contents file-name
(not auto-save-p
)
5676 (insert-file-contents file-name
(not auto-save-p
)
5679 (defun recover-this-file ()
5680 "Recover the visited file--get contents from its last auto-save file."
5682 (recover-file buffer-file-name
))
5684 (defun recover-file (file)
5685 "Visit file FILE, but get contents from its last auto-save file."
5686 ;; Actually putting the file name in the minibuffer should be used
5688 ;; Not just because users often use the default.
5689 (interactive "FRecover file: ")
5690 (setq file
(expand-file-name file
))
5691 (if (auto-save-file-name-p (file-name-nondirectory file
))
5692 (error "%s is an auto-save file" (abbreviate-file-name file
)))
5693 (let ((file-name (let ((buffer-file-name file
))
5694 (make-auto-save-file-name))))
5695 (cond ((if (file-exists-p file
)
5696 (not (file-newer-than-file-p file-name file
))
5697 (not (file-exists-p file-name
)))
5698 (error "Auto-save file %s not current"
5699 (abbreviate-file-name file-name
)))
5700 ((with-temp-buffer-window
5702 #'(lambda (window _value
)
5703 (with-selected-window window
5705 (yes-or-no-p (format "Recover auto save file %s? " file-name
))
5706 (when (window-live-p window
)
5707 (quit-restore-window window
'kill
)))))
5708 (with-current-buffer standard-output
5709 (let ((switches dired-listing-switches
))
5710 (if (file-symlink-p file
)
5711 (setq switches
(concat switches
" -L")))
5712 ;; Use insert-directory-safely, not insert-directory,
5713 ;; because these files might not exist. In particular,
5714 ;; FILE might not exist if the auto-save file was for
5715 ;; a buffer that didn't visit a file, such as "*mail*".
5716 ;; The code in v20.x called `ls' directly, so we need
5717 ;; to emulate what `ls' did in that case.
5718 (insert-directory-safely file switches
)
5719 (insert-directory-safely file-name switches
))))
5720 (switch-to-buffer (find-file-noselect file t
))
5721 (let ((inhibit-read-only t
)
5722 ;; Keep the current buffer-file-coding-system.
5723 (coding-system buffer-file-coding-system
)
5724 ;; Auto-saved file should be read with special coding.
5725 (coding-system-for-read 'auto-save-coding
))
5727 (insert-file-contents file-name nil
)
5728 (set-buffer-file-coding-system coding-system
))
5729 (after-find-file nil nil t
))
5730 (t (user-error "Recover-file canceled")))))
5732 (defun recover-session ()
5733 "Recover auto save files from a previous Emacs session.
5734 This command first displays a Dired buffer showing you the
5735 previous sessions that you could recover from.
5736 To choose one, move point to the proper line and then type C-c C-c.
5737 Then you'll be asked about a number of files to recover."
5739 (if (null auto-save-list-file-prefix
)
5740 (error "You set `auto-save-list-file-prefix' to disable making session files"))
5741 (let ((dir (file-name-directory auto-save-list-file-prefix
))
5742 (nd (file-name-nondirectory auto-save-list-file-prefix
)))
5743 (unless (file-directory-p dir
)
5744 (make-directory dir t
))
5745 (unless (directory-files dir nil
5747 directory-files-no-dot-files-regexp
5748 (concat "\\`" (regexp-quote nd
)))
5750 (error "No previous sessions to recover")))
5751 (let ((ls-lisp-support-shell-wildcards t
))
5752 (dired (concat auto-save-list-file-prefix
"*")
5753 (concat dired-listing-switches
" -t")))
5754 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
5755 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish
)
5757 (goto-char (point-min))
5758 (or (looking-at " Move to the session you want to recover,")
5759 (let ((inhibit-read-only t
))
5760 ;; Each line starts with a space
5761 ;; so that Font Lock mode won't highlight the first character.
5762 (insert " To recover a session, move to it and type C-c C-c.\n"
5763 (substitute-command-keys
5764 " To delete a session file, type \
5765 \\[dired-flag-file-deletion] on its line to flag
5766 the file for deletion, then \\[dired-do-flagged-delete] to \
5767 delete flagged files.\n\n"))))))
5769 (defun recover-session-finish ()
5770 "Choose one saved session to recover auto-save files from.
5771 This command is used in the special Dired buffer created by
5772 \\[recover-session]."
5774 ;; Get the name of the session file to recover from.
5775 (let ((file (dired-get-filename))
5777 (buffer (get-buffer-create " *recover*")))
5779 (dired-do-flagged-delete t
)
5781 (with-current-buffer buffer
5782 ;; Read in the auto-save-list file.
5784 (insert-file-contents file
)
5785 ;; Loop thru the text of that file
5786 ;; and get out the names of the files to recover.
5788 (let (thisfile autofile
)
5790 ;; This is a pair of lines for a non-file-visiting buffer.
5791 ;; Get the auto-save file name and manufacture
5792 ;; a "visited file name" from that.
5795 ;; If there is no auto-save file name, the
5796 ;; auto-save-list file is probably corrupted.
5799 (buffer-substring-no-properties
5801 (line-end-position)))
5805 (file-name-nondirectory autofile
)
5807 (file-name-directory autofile
))))
5809 ;; This pair of lines is a file-visiting
5810 ;; buffer. Use the visited file name.
5813 (buffer-substring-no-properties
5814 (point) (progn (end-of-line) (point))))
5817 (buffer-substring-no-properties
5818 (point) (progn (end-of-line) (point))))
5820 ;; Ignore a file if its auto-save file does not exist now.
5821 (if (and autofile
(file-exists-p autofile
))
5822 (setq files
(cons thisfile files
)))))
5823 (setq files
(nreverse files
))
5824 ;; The file contains a pair of line for each auto-saved buffer.
5825 ;; The first line of the pair contains the visited file name
5826 ;; or is empty if the buffer was not visiting a file.
5827 ;; The second line is the auto-save file name.
5829 (map-y-or-n-p "Recover %s? "
5832 (save-excursion (recover-file file
))
5834 "Failed to recover `%s'" file
)))
5836 '("file" "files" "recover"))
5837 (message "No files can be recovered from this session now")))
5838 (kill-buffer buffer
))))
5840 (defun kill-buffer-ask (buffer)
5841 "Kill BUFFER if confirmed."
5842 (when (yes-or-no-p (format "Buffer %s %s. Kill? "
5843 (buffer-name buffer
)
5844 (if (buffer-modified-p buffer
)
5845 "HAS BEEN EDITED" "is unmodified")))
5846 (kill-buffer buffer
)))
5848 (defun kill-some-buffers (&optional list
)
5849 "Kill some buffers. Asks the user whether to kill each one of them.
5850 Non-interactively, if optional argument LIST is non-nil, it
5851 specifies the list of buffers to kill, asking for approval for each one."
5854 (setq list
(buffer-list)))
5856 (let* ((buffer (car list
))
5857 (name (buffer-name buffer
)))
5858 (and name
; Can be nil for an indirect buffer
5859 ; if we killed the base buffer.
5860 (not (string-equal name
""))
5861 (/= (aref name
0) ?\s
)
5862 (kill-buffer-ask buffer
)))
5863 (setq list
(cdr list
))))
5865 (defun kill-matching-buffers (regexp &optional internal-too
)
5866 "Kill buffers whose name matches the specified REGEXP.
5867 The optional second argument indicates whether to kill internal buffers too."
5868 (interactive "sKill buffers matching this regular expression: \nP")
5869 (dolist (buffer (buffer-list))
5870 (let ((name (buffer-name buffer
)))
5871 (when (and name
(not (string-equal name
""))
5872 (or internal-too
(/= (aref name
0) ?\s
))
5873 (string-match regexp name
))
5874 (kill-buffer-ask buffer
)))))
5877 (defun rename-auto-save-file ()
5878 "Adjust current buffer's auto save file name for current conditions.
5879 Also rename any existing auto save file, if it was made in this session."
5880 (let ((osave buffer-auto-save-file-name
))
5881 (setq buffer-auto-save-file-name
5882 (make-auto-save-file-name))
5883 (if (and osave buffer-auto-save-file-name
5884 (not (string= buffer-auto-save-file-name buffer-file-name
))
5885 (not (string= buffer-auto-save-file-name osave
))
5886 (file-exists-p osave
)
5887 (recent-auto-save-p))
5888 (rename-file osave buffer-auto-save-file-name t
))))
5890 (defun make-auto-save-file-name ()
5891 "Return file name to use for auto-saves of current buffer.
5892 Does not consider `auto-save-visited-file-name' as that variable is checked
5893 before calling this function. You can redefine this for customization.
5894 See also `auto-save-file-name-p'."
5895 (if buffer-file-name
5896 (let ((handler (find-file-name-handler buffer-file-name
5897 'make-auto-save-file-name
)))
5899 (funcall handler
'make-auto-save-file-name
)
5900 (let ((list auto-save-file-name-transforms
)
5901 (filename buffer-file-name
)
5903 ;; Apply user-specified translations
5904 ;; to the file name.
5905 (while (and list
(not result
))
5906 (if (string-match (car (car list
)) filename
)
5907 (setq result
(replace-match (cadr (car list
)) t nil
5909 uniq
(car (cddr (car list
)))))
5910 (setq list
(cdr list
)))
5913 (setq filename
(concat
5914 (file-name-directory result
)
5915 (subst-char-in-string
5917 (replace-regexp-in-string "!" "!!"
5919 (setq filename result
)))
5921 (if (and (eq system-type
'ms-dos
)
5922 (not (msdos-long-file-names)))
5923 ;; We truncate the file name to DOS 8+3 limits
5924 ;; before doing anything else, because the regexp
5925 ;; passed to string-match below cannot handle
5926 ;; extensions longer than 3 characters, multiple
5927 ;; dots, and other atrocities.
5928 (let ((fn (dos-8+3-filename
5929 (file-name-nondirectory buffer-file-name
))))
5931 "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'"
5933 (concat (file-name-directory buffer-file-name
)
5934 "#" (match-string 1 fn
)
5935 "." (match-string 3 fn
) "#"))
5936 (concat (file-name-directory filename
)
5938 (file-name-nondirectory filename
)
5940 ;; Make sure auto-save file names don't contain characters
5941 ;; invalid for the underlying filesystem.
5942 (if (and (memq system-type
'(ms-dos windows-nt cygwin
))
5943 ;; Don't modify remote (ange-ftp) filenames
5944 (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" result
)))
5945 (convert-standard-filename result
)
5948 ;; Deal with buffers that don't have any associated files. (Mail
5949 ;; mode tends to create a good number of these.)
5951 (let ((buffer-name (buffer-name))
5954 ;; Restrict the characters used in the file name to those which
5955 ;; are known to be safe on all filesystems, url-encoding the
5957 ;; We do this on all platforms, because even if we are not
5958 ;; running on DOS/Windows, the current directory may be on a
5959 ;; mounted VFAT filesystem, such as a USB memory stick.
5960 (while (string-match "[^A-Za-z0-9-_.~#+]" buffer-name limit
)
5961 (let* ((character (aref buffer-name
(match-beginning 0)))
5963 ;; For multibyte characters, this will produce more than
5964 ;; 2 hex digits, so is not true URL encoding.
5965 (format "%%%02X" character
)))
5966 (setq buffer-name
(replace-match replacement t t buffer-name
))
5967 (setq limit
(1+ (match-end 0)))))
5968 ;; Generate the file name.
5973 (format "#%s#" buffer-name
)
5974 ;; Try a few alternative directories, to get one we can
5977 ((file-writable-p default-directory
) default-directory
)
5978 ((file-writable-p "/var/tmp/") "/var/tmp/")
5980 (if (and (memq system-type
'(ms-dos windows-nt cygwin
))
5981 ;; Don't modify remote (ange-ftp) filenames
5982 (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" fname
)))
5983 ;; The call to convert-standard-filename is in case
5984 ;; buffer-name includes characters not allowed by the
5985 ;; DOS/Windows filesystems. make-temp-file writes to the
5986 ;; file it creates, so we must fix the file name _before_
5987 ;; make-temp-file is called.
5988 (convert-standard-filename fname
)
5991 ;; make-temp-file creates the file,
5992 ;; but we don't want it to exist until we do an auto-save.
5994 (delete-file file-name
)
5998 (defun auto-save-file-name-p (filename)
5999 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
6000 FILENAME should lack slashes. You can redefine this for customization."
6001 (string-match "\\`#.*#\\'" filename
))
6003 (defun wildcard-to-regexp (wildcard)
6004 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
6005 The generated regexp will match a filename only if the filename
6006 matches that wildcard according to shell rules. Only wildcards known
6007 by `sh' are supported."
6008 (let* ((i (string-match "[[.*+\\^$?]" wildcard
))
6009 ;; Copy the initial run of non-special characters.
6010 (result (substring wildcard
0 i
))
6011 (len (length wildcard
)))
6012 ;; If no special characters, we're almost done.
6015 (let ((ch (aref wildcard i
))
6023 (eq (aref wildcard
(1+ i
)) ?\
]))
6025 ((eq ch ?\
[) ; [...] maps to regexp char class
6030 ((eq (aref wildcard i
) ?
!) ; [!...] -> [^...]
6033 (if (eq (aref wildcard i
) ?\
])
6038 ((eq (aref wildcard i
) ?^
)
6039 ;; Found "[^". Insert a `\0' character
6040 ;; (which cannot happen in a filename)
6041 ;; into the character class, so that `^'
6042 ;; is not the first character after `[',
6043 ;; and thus non-special in a regexp.
6047 ((eq (aref wildcard i
) ?\
])
6048 ;; I don't think `]' can appear in a
6049 ;; character class in a wildcard, but
6050 ;; let's be general here.
6055 (prog1 ; copy everything upto next `]'.
6058 (setq j
(string-match
6060 (setq i
(if j
(1- j
) (1- len
)))))))
6062 ((eq ch ?
*) "[^\000]*")
6066 ((eq ch ?
\\) "\\\\") ; probably cannot happen...
6067 ((eq ch ??
) "[^\000]")
6068 (t (char-to-string ch
)))))
6070 ;; Shell wildcards should match the entire filename,
6071 ;; not its part. Make the regexp say so.
6072 (concat "\\`" result
"\\'")))
6074 (defcustom list-directory-brief-switches
6076 "Switches for `list-directory' to pass to `ls' for brief listing."
6080 (defcustom list-directory-verbose-switches
6082 "Switches for `list-directory' to pass to `ls' for verbose listing."
6086 (defun file-expand-wildcards (pattern &optional full
)
6087 "Expand wildcard pattern PATTERN.
6088 This returns a list of file names which match the pattern.
6089 Files are sorted in `string<' order.
6091 If PATTERN is written as an absolute file name,
6092 the values are absolute also.
6094 If PATTERN is written as a relative file name, it is interpreted
6095 relative to the current default directory, `default-directory'.
6096 The file names returned are normally also relative to the current
6097 default directory. However, if FULL is non-nil, they are absolute."
6099 (let* ((nondir (file-name-nondirectory pattern
))
6100 (dirpart (file-name-directory pattern
))
6101 ;; A list of all dirs that DIRPART specifies.
6102 ;; This can be more than one dir
6103 ;; if DIRPART contains wildcards.
6104 (dirs (if (and dirpart
6105 (string-match "[[*?]"
6106 (or (file-remote-p dirpart
'localname
)
6108 (mapcar 'file-name-as-directory
6109 (file-expand-wildcards (directory-file-name dirpart
)))
6113 (when (or (null dir
) ; Possible if DIRPART is not wild.
6114 (file-accessible-directory-p dir
))
6115 (let ((this-dir-contents
6116 ;; Filter out "." and ".."
6118 (mapcar #'(lambda (name)
6119 (unless (string-match "\\`\\.\\.?\\'"
6120 (file-name-nondirectory name
))
6122 (directory-files (or dir
".") full
6123 (wildcard-to-regexp nondir
))))))
6126 (if (and dir
(not full
))
6127 (mapcar #'(lambda (name) (concat dir name
))
6133 ;; Let Tramp know that `file-expand-wildcards' does not need an advice.
6134 (provide 'files
'(remote-wildcards))
6136 (defun list-directory (dirname &optional verbose
)
6137 "Display a list of files in or matching DIRNAME, a la `ls'.
6138 DIRNAME is globbed by the shell if necessary.
6139 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
6140 Actions controlled by variables `list-directory-brief-switches'
6141 and `list-directory-verbose-switches'."
6142 (interactive (let ((pfx current-prefix-arg
))
6143 (list (read-directory-name (if pfx
"List directory (verbose): "
6144 "List directory (brief): ")
6145 nil default-directory nil
)
6147 (let ((switches (if verbose list-directory-verbose-switches
6148 list-directory-brief-switches
))
6150 (or dirname
(setq dirname default-directory
))
6151 (setq dirname
(expand-file-name dirname
))
6152 (with-output-to-temp-buffer "*Directory*"
6153 (setq buffer standard-output
)
6154 (buffer-disable-undo standard-output
)
6155 (princ "Directory ")
6158 (with-current-buffer "*Directory*"
6159 (let ((wildcard (not (file-directory-p dirname
))))
6160 (insert-directory dirname switches wildcard
(not wildcard
)))))
6161 ;; Finishing with-output-to-temp-buffer seems to clobber default-directory.
6162 (with-current-buffer buffer
6163 (setq default-directory
6164 (if (file-directory-p dirname
)
6165 (file-name-as-directory dirname
)
6166 (file-name-directory dirname
))))))
6168 (defun shell-quote-wildcard-pattern (pattern)
6169 "Quote characters special to the shell in PATTERN, leave wildcards alone.
6171 PATTERN is assumed to represent a file-name wildcard suitable for the
6172 underlying filesystem. For Unix and GNU/Linux, each character from the
6173 set [ \\t\\n;<>&|()\\=`\\='\"#$] is quoted with a backslash; for DOS/Windows, all
6174 the parts of the pattern which don't include wildcard characters are
6175 quoted with double quotes.
6177 This function leaves alone existing quote characters (\\ on Unix and \"
6178 on Windows), so PATTERN can use them to quote wildcard characters that
6179 need to be passed verbatim to shell commands."
6182 ((memq system-type
'(ms-dos windows-nt cygwin
))
6183 ;; DOS/Windows don't allow `"' in file names. So if the
6184 ;; argument has quotes, we can safely assume it is already
6185 ;; quoted by the caller.
6186 (if (or (string-match "[\"]" pattern
)
6187 ;; We quote [&()#$`'] in case their shell is a port of a
6188 ;; Unixy shell. We quote [,=+] because stock DOS and
6189 ;; Windows shells require that in some cases, such as
6190 ;; passing arguments to batch files that use positional
6191 ;; arguments like %1.
6192 (not (string-match "[ \t;&()#$`',=+]" pattern
)))
6197 (while (string-match "[*?]+" pattern beg
)
6198 (setq end
(match-beginning 0)
6199 result
(concat result
(substring pattern beg end
)
6201 (substring pattern end
(match-end 0))
6204 (concat result
(substring pattern beg
) "\""))))
6207 (while (string-match "[ \t\n;<>&|()`'\"#$]" pattern beg
)
6209 (concat (substring pattern
0 (match-beginning 0))
6211 (substring pattern
(match-beginning 0)))
6212 beg
(1+ (match-end 0)))))
6216 (defvar insert-directory-program
(purecopy "ls")
6217 "Absolute or relative name of the `ls' program used by `insert-directory'.")
6219 (defcustom directory-free-space-program
(purecopy "df")
6220 "Program to get the amount of free space on a file system.
6221 We assume the output has the format of `df'.
6222 The value of this variable must be just a command name or file name;
6223 if you want to specify options, use `directory-free-space-args'.
6225 A value of nil disables this feature.
6227 If the function `file-system-info' is defined, it is always used in
6228 preference to the program given by this variable."
6229 :type
'(choice (string :tag
"Program") (const :tag
"None" nil
))
6232 (defcustom directory-free-space-args
6233 (purecopy (if (eq system-type
'darwin
) "-k" "-Pk"))
6234 "Options to use when running `directory-free-space-program'."
6238 (defun get-free-disk-space (dir)
6239 "Return the amount of free space on directory DIR's file system.
6240 The return value is a string describing the amount of free
6241 space (normally, the number of free 1KB blocks).
6243 This function calls `file-system-info' if it is available, or
6244 invokes the program specified by `directory-free-space-program'
6245 and `directory-free-space-args'. If the system call or program
6246 is unsuccessful, or if DIR is a remote directory, this function
6248 (unless (file-remote-p (expand-file-name dir
))
6249 ;; Try to find the number of free blocks. Non-Posix systems don't
6250 ;; always have df, but might have an equivalent system call.
6251 (if (fboundp 'file-system-info
)
6252 (let ((fsinfo (file-system-info dir
)))
6254 (format "%.0f" (/ (nth 2 fsinfo
) 1024))))
6255 (setq dir
(expand-file-name dir
))
6258 (when (and directory-free-space-program
6259 ;; Avoid failure if the default directory does
6260 ;; not exist (Bug#2631, Bug#3911).
6261 (let ((default-directory
6262 (locate-dominating-file dir
'file-directory-p
)))
6263 (eq (process-file directory-free-space-program
6265 directory-free-space-args
6266 (file-relative-name dir
))
6268 ;; Assume that the "available" column is before the
6269 ;; "capacity" column. Find the "%" and scan backward.
6270 (goto-char (point-min))
6272 (when (re-search-forward
6273 "[[:space:]]+[^[:space:]]+%[^%]*$"
6274 (line-end-position) t
)
6275 (goto-char (match-beginning 0))
6276 (let ((endpt (point)))
6277 (skip-chars-backward "^[:space:]")
6278 (buffer-substring-no-properties (point) endpt
)))))))))
6280 ;; The following expression replaces `dired-move-to-filename-regexp'.
6281 (defvar directory-listing-before-filename-regexp
6282 (let* ((l "\\([A-Za-z]\\|[^\0-\177]\\)")
6283 (l-or-quote "\\([A-Za-z']\\|[^\0-\177]\\)")
6284 ;; In some locales, month abbreviations are as short as 2 letters,
6285 ;; and they can be followed by ".".
6286 ;; In Breton, a month name can include a quote character.
6287 (month (concat l-or-quote l-or-quote
"+\\.?"))
6289 (yyyy "[0-9][0-9][0-9][0-9]")
6291 (HH:MM
"[ 0-2][0-9][:.][0-5][0-9]")
6292 (seconds "[0-6][0-9]\\([.,][0-9]+\\)?")
6293 (zone "[-+][0-2][0-9][0-5][0-9]")
6294 (iso-mm-dd "[01][0-9]-[0-3][0-9]")
6295 (iso-time (concat HH
:MM
"\\(:" seconds
"\\( ?" zone
"\\)?\\)?"))
6296 (iso (concat "\\(\\(" yyyy
"-\\)?" iso-mm-dd
"[ T]" iso-time
6297 "\\|" yyyy
"-" iso-mm-dd
"\\)"))
6298 (western (concat "\\(" month s
"+" dd
"\\|" dd
"\\.?" s month
"\\)"
6300 "\\(" HH
:MM
"\\|" yyyy
"\\)"))
6301 (western-comma (concat month s
"+" dd
"," s
"+" yyyy
))
6302 ;; Japanese MS-Windows ls-lisp has one-digit months, and
6303 ;; omits the Kanji characters after month and day-of-month.
6304 ;; On Mac OS X 10.3, the date format in East Asian locales is
6305 ;; day-of-month digits followed by month digits.
6308 (concat "\\(" mm l
"?" s dd l
"?" s
"+"
6309 "\\|" dd s mm s
"+" "\\)"
6310 "\\(" HH
:MM
"\\|" yyyy l
"?" "\\)")))
6311 ;; The "[0-9]" below requires the previous column to end in a digit.
6312 ;; This avoids recognizing `1 may 1997' as a date in the line:
6313 ;; -r--r--r-- 1 may 1997 1168 Oct 19 16:49 README
6315 ;; The "[BkKMGTPEZY]?" below supports "ls -alh" output.
6317 ;; For non-iso date formats, we add the ".*" in order to find
6318 ;; the last possible match. This avoids recognizing
6319 ;; `jservice 10 1024' as a date in the line:
6320 ;; drwxr-xr-x 3 jservice 10 1024 Jul 2 1997 esg-host
6322 ;; vc dired listings provide the state or blanks between file
6323 ;; permissions and date. The state is always surrounded by
6325 ;; -rw-r--r-- (modified) 2005-10-22 21:25 files.el
6326 ;; This is not supported yet.
6327 (purecopy (concat "\\([0-9][BkKMGTPEZY]? " iso
6328 "\\|.*[0-9][BkKMGTPEZY]? "
6329 "\\(" western
"\\|" western-comma
"\\|" east-asian
"\\)"
6331 "Regular expression to match up to the file name in a directory listing.
6332 The default value is designed to recognize dates and times
6333 regardless of the language.")
6335 (defvar insert-directory-ls-version
'unknown
)
6338 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
6339 ;; FULL-DIRECTORY-P is nil.
6340 ;; The single line of output must display FILE's name as it was
6341 ;; given, namely, an absolute path name.
6342 ;; - must insert exactly one line for each file if WILDCARD or
6343 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
6344 ;; before the file lines, plus optional text after the file lines.
6345 ;; Lines are delimited by "\n", so filenames containing "\n" are not
6347 ;; File lines should display the basename.
6348 ;; - must be consistent with
6349 ;; - functions dired-move-to-filename, (these two define what a file line is)
6350 ;; dired-move-to-end-of-filename,
6351 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
6352 ;; dired-insert-headerline
6353 ;; dired-after-subdir-garbage (defines what a "total" line is)
6354 ;; - variable dired-subdir-regexp
6355 ;; - may be passed "--dired" as the first argument in SWITCHES.
6356 ;; Filename handlers might have to remove this switch if their
6357 ;; "ls" command does not support it.
6358 (defun insert-directory (file switches
&optional wildcard full-directory-p
)
6359 "Insert directory listing for FILE, formatted according to SWITCHES.
6360 Leaves point after the inserted text.
6361 SWITCHES may be a string of options, or a list of strings
6362 representing individual options.
6363 Optional third arg WILDCARD means treat FILE as shell wildcard.
6364 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
6365 switches do not contain `d', so that a full listing is expected.
6367 This works by running a directory listing program
6368 whose name is in the variable `insert-directory-program'.
6369 If WILDCARD, it also runs the shell specified by `shell-file-name'.
6371 When SWITCHES contains the long `--dired' option, this function
6372 treats it specially, for the sake of dired. However, the
6373 normally equivalent short `-D' option is just passed on to
6374 `insert-directory-program', as any other option."
6375 ;; We need the directory in order to find the right handler.
6376 (let ((handler (find-file-name-handler (expand-file-name file
)
6377 'insert-directory
)))
6379 (funcall handler
'insert-directory file switches
6380 wildcard full-directory-p
)
6381 (let (result (beg (point)))
6383 ;; Read the actual directory using `insert-directory-program'.
6384 ;; RESULT gets the status code.
6385 (let* (;; We at first read by no-conversion, then after
6386 ;; putting text property `dired-filename, decode one
6387 ;; bunch by one to preserve that property.
6388 (coding-system-for-read 'no-conversion
)
6389 ;; This is to control encoding the arguments in call-process.
6390 (coding-system-for-write
6391 (and enable-multibyte-characters
6392 (or file-name-coding-system
6393 default-file-name-coding-system
))))
6396 ;; Run ls in the directory part of the file pattern
6397 ;; using the last component as argument.
6398 (let ((default-directory
6399 (if (file-name-absolute-p file
)
6400 (file-name-directory file
)
6401 (file-name-directory (expand-file-name file
))))
6402 (pattern (file-name-nondirectory file
)))
6403 ;; NB since switches is passed to the shell, be
6404 ;; careful of malicious values, eg "-l;reboot".
6405 ;; See eg dired-safe-switches-p.
6407 shell-file-name nil t nil
6409 (concat (if (memq system-type
'(ms-dos windows-nt
))
6411 "\\") ; Disregard Unix shell aliases!
6412 insert-directory-program
6414 (if (stringp switches
)
6416 (mapconcat 'identity switches
" "))
6418 ;; Quote some characters that have
6419 ;; special meanings in shells; but
6420 ;; don't quote the wildcards--we want
6421 ;; them to be special. We also
6422 ;; currently don't quote the quoting
6423 ;; characters in case people want to
6424 ;; use them explicitly to quote
6425 ;; wildcard characters.
6426 (shell-quote-wildcard-pattern pattern
))))
6427 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
6428 ;; directory if FILE is a symbolic link.
6429 (unless full-directory-p
6432 ((stringp switches
) (concat switches
" -d"))
6433 ((member "-d" switches
) switches
)
6434 (t (append switches
'("-d"))))))
6435 (apply 'call-process
6436 insert-directory-program nil t nil
6438 (if (listp switches
) switches
6439 (unless (equal switches
"")
6440 ;; Split the switches at any spaces so we can
6441 ;; pass separate options as separate args.
6442 (split-string switches
)))
6443 ;; Avoid lossage if FILE starts with `-'.
6446 (if (string-match "\\`~" file
)
6447 (setq file
(expand-file-name file
)))
6449 (if full-directory-p
6450 (concat (file-name-as-directory file
) ".")
6453 ;; If we got "//DIRED//" in the output, it means we got a real
6454 ;; directory listing, even if `ls' returned nonzero.
6455 ;; So ignore any errors.
6456 (when (if (stringp switches
)
6457 (string-match "--dired\\>" switches
)
6458 (member "--dired" switches
))
6461 (when (looking-at "//SUBDIRED//")
6463 (if (looking-at "//DIRED//")
6466 (when (and (not (eq 0 result
))
6467 (eq insert-directory-ls-version
'unknown
))
6468 ;; The first time ls returns an error,
6469 ;; find the version numbers of ls,
6470 ;; and set insert-directory-ls-version
6471 ;; to > if it is more than 5.2.1, < if it is less, nil if it
6472 ;; is equal or if the info cannot be obtained.
6473 ;; (That can mean it isn't GNU ls.)
6476 (call-process "ls" nil t nil
"--version")
6478 (if (string-match "ls (.*utils) \\([0-9.]*\\)$" version-out
)
6479 (let* ((version (match-string 1 version-out
))
6480 (split (split-string version
"[.]"))
6481 (numbers (mapcar 'string-to-number split
))
6484 (while (and (not comparison
) (or numbers min
))
6486 (setq comparison
'>))
6488 (setq comparison
'<))
6489 ((> (car numbers
) (car min
))
6490 (setq comparison
'>))
6491 ((< (car numbers
) (car min
))
6492 (setq comparison
'<))
6494 (setq numbers
(cdr numbers
)
6496 (setq insert-directory-ls-version
(or comparison
'=)))
6497 (setq insert-directory-ls-version nil
))))
6499 ;; For GNU ls versions 5.2.2 and up, ignore minor errors.
6500 (when (and (eq 1 result
) (eq insert-directory-ls-version
'>))
6503 ;; If `insert-directory-program' failed, signal an error.
6504 (unless (eq 0 result
)
6505 ;; Delete the error message it may have output.
6506 (delete-region beg
(point))
6507 ;; On non-Posix systems, we cannot open a directory, so
6508 ;; don't even try, because that will always result in
6509 ;; the ubiquitous "Access denied". Instead, show the
6510 ;; command line so the user can try to guess what went wrong.
6511 (if (and (file-directory-p file
)
6512 (memq system-type
'(ms-dos windows-nt
)))
6514 "Reading directory: \"%s %s -- %s\" exited with status %s"
6515 insert-directory-program
6516 (if (listp switches
) (concat switches
) switches
)
6518 ;; Unix. Access the file to get a suitable error.
6519 (access-file file
"Reading directory")
6520 (error "Listing directory failed but `access-file' worked")))
6522 (when (if (stringp switches
)
6523 (string-match "--dired\\>" switches
)
6524 (member "--dired" switches
))
6525 ;; The following overshoots by one line for an empty
6526 ;; directory listed with "--dired", but without "-a"
6527 ;; switch, where the ls output contains a
6528 ;; "//DIRED-OPTIONS//" line, but no "//DIRED//" line.
6529 ;; We take care of that case later.
6531 (when (looking-at "//SUBDIRED//")
6532 (delete-region (point) (progn (forward-line 1) (point)))
6534 (if (looking-at "//DIRED//")
6535 (let ((end (line-end-position))
6538 ;; Find all the lines that are error messages,
6539 ;; and record the bounds of each one.
6541 (while (< (point) linebeg
)
6542 (or (eql (following-char) ?\s
)
6543 (push (list (point) (line-end-position)) error-lines
))
6545 (setq error-lines
(nreverse error-lines
))
6546 ;; Now read the numeric positions of file names.
6548 (forward-word-strictly 1)
6550 (while (< (point) end
)
6551 (let ((start (insert-directory-adj-pos
6552 (+ beg
(read (current-buffer)))
6554 (end (insert-directory-adj-pos
6555 (+ beg
(read (current-buffer)))
6557 (if (memq (char-after end
) '(?
\n ?\s
))
6558 ;; End is followed by \n or by " -> ".
6559 (put-text-property start end
'dired-filename t
)
6560 ;; It seems that we can't trust ls's output as to
6561 ;; byte positions of filenames.
6562 (put-text-property beg
(point) 'dired-filename nil
)
6566 (delete-region (point) (progn (forward-line 1) (point))))
6567 ;; Take care of the case where the ls output contains a
6568 ;; "//DIRED-OPTIONS//"-line, but no "//DIRED//"-line
6569 ;; and we went one line too far back (see above).
6571 (if (looking-at "//DIRED-OPTIONS//")
6572 (delete-region (point) (progn (forward-line 1) (point)))))
6574 ;; Now decode what read if necessary.
6575 (let ((coding (or coding-system-for-read
6576 file-name-coding-system
6577 default-file-name-coding-system
6581 (when (and enable-multibyte-characters
6582 (not (memq (coding-system-base coding
)
6583 '(raw-text no-conversion
))))
6584 ;; If no coding system is specified or detection is
6585 ;; requested, detect the coding.
6586 (if (eq (coding-system-base coding
) 'undecided
)
6587 (setq coding
(detect-coding-region beg
(point) t
)))
6588 (if (not (eq (coding-system-base coding
) 'undecided
))
6591 (coding-system-change-eol-conversion coding
'unix
))
6592 (narrow-to-region beg
(point))
6593 (goto-char (point-min))
6596 val
(get-text-property (point) 'dired-filename
))
6597 (goto-char (next-single-property-change
6598 (point) 'dired-filename nil
(point-max)))
6599 ;; Force no eol conversion on a file name, so
6600 ;; that CR is preserved.
6601 (decode-coding-region pos
(point)
6602 (if val coding-no-eol coding
))
6604 (put-text-property pos
(point)
6605 'dired-filename t
)))))))
6607 (if full-directory-p
6608 ;; Try to insert the amount of free space.
6611 ;; First find the line to put it on.
6612 (when (re-search-forward "^ *\\(total\\)" nil t
)
6613 (let ((available (get-free-disk-space ".")))
6615 ;; Replace "total" with "used", to avoid confusion.
6616 (replace-match "total used in directory" nil nil nil
1)
6618 (insert " available " available
))))))))))
6620 (defun insert-directory-adj-pos (pos error-lines
)
6621 "Convert `ls --dired' file name position value POS to a buffer position.
6622 File name position values returned in ls --dired output
6623 count only stdout; they don't count the error messages sent to stderr.
6624 So this function converts to them to real buffer positions.
6625 ERROR-LINES is a list of buffer positions of error message lines,
6626 of the form (START END)."
6627 (while (and error-lines
(< (caar error-lines
) pos
))
6628 (setq pos
(+ pos
(- (nth 1 (car error-lines
)) (nth 0 (car error-lines
)))))
6632 (defun insert-directory-safely (file switches
6633 &optional wildcard full-directory-p
)
6634 "Insert directory listing for FILE, formatted according to SWITCHES.
6636 Like `insert-directory', but if FILE does not exist, it inserts a
6637 message to that effect instead of signaling an error."
6638 (if (file-exists-p file
)
6639 (insert-directory file switches wildcard full-directory-p
)
6640 ;; Simulate the message printed by `ls'.
6641 (insert (format "%s: No such file or directory\n" file
))))
6643 (defvar kill-emacs-query-functions nil
6644 "Functions to call with no arguments to query about killing Emacs.
6645 If any of these functions returns nil, killing Emacs is canceled.
6646 `save-buffers-kill-emacs' calls these functions, but `kill-emacs',
6647 the low level primitive, does not. See also `kill-emacs-hook'.")
6649 (defcustom confirm-kill-emacs nil
6650 "How to ask for confirmation when leaving Emacs.
6651 If nil, the default, don't ask at all. If the value is non-nil, it should
6652 be a predicate function; for example `yes-or-no-p'."
6653 :type
'(choice (const :tag
"Ask with yes-or-no-p" yes-or-no-p
)
6654 (const :tag
"Ask with y-or-n-p" y-or-n-p
)
6655 (const :tag
"Don't confirm" nil
)
6656 (function :tag
"Predicate function"))
6660 (defun save-buffers-kill-emacs (&optional arg
)
6661 "Offer to save each buffer, then kill this Emacs process.
6662 With prefix ARG, silently save all file-visiting buffers without asking.
6663 If there are active processes where `process-query-on-exit-flag'
6664 returns non-nil, asks whether processes should be killed.
6665 Runs the members of `kill-emacs-query-functions' in turn and stops
6666 if any returns nil. If `confirm-kill-emacs' is non-nil, calls it."
6668 (save-some-buffers arg t
)
6669 (let ((confirm confirm-kill-emacs
))
6671 (or (not (memq t
(mapcar (function
6672 (lambda (buf) (and (buffer-file-name buf
)
6673 (buffer-modified-p buf
))))
6675 (progn (setq confirm nil
)
6676 (yes-or-no-p "Modified buffers exist; exit anyway? ")))
6677 (or (not (fboundp 'process-list
))
6678 ;; process-list is not defined on MSDOS.
6679 (let ((processes (process-list))
6682 (and (memq (process-status (car processes
)) '(run stop open listen
))
6683 (process-query-on-exit-flag (car processes
))
6685 (setq processes
(cdr processes
)))
6687 (with-current-buffer-window
6688 (get-buffer-create "*Process List*") nil
6689 #'(lambda (window _value
)
6690 (with-selected-window window
6694 (yes-or-no-p "Active processes exist; kill them and exit anyway? "))
6695 (when (window-live-p window
)
6696 (quit-restore-window window
'kill
)))))
6697 (list-processes t
)))))
6698 ;; Query the user for other things, perhaps.
6699 (run-hook-with-args-until-failure 'kill-emacs-query-functions
)
6701 (funcall confirm
"Really exit Emacs? "))
6704 (defun save-buffers-kill-terminal (&optional arg
)
6705 "Offer to save each buffer, then kill the current connection.
6706 If the current frame has no client, kill Emacs itself.
6708 With prefix ARG, silently save all file-visiting buffers, then kill.
6710 If emacsclient was started with a list of filenames to edit, then
6711 only these files will be asked to be saved."
6713 (if (frame-parameter nil
'client
)
6714 (server-save-buffers-kill-terminal arg
)
6715 (save-buffers-kill-emacs arg
)))
6717 ;; We use /: as a prefix to "quote" a file name
6718 ;; so that magic file name handlers will not apply to it.
6720 (setq file-name-handler-alist
6721 (cons (cons (purecopy "\\`/:") 'file-name-non-special
)
6722 file-name-handler-alist
))
6724 ;; We depend on being the last handler on the list,
6725 ;; so that anything else which does need handling
6726 ;; has been handled already.
6727 ;; So it is safe for us to inhibit *all* magic file name handlers.
6729 (defun file-name-non-special (operation &rest arguments
)
6730 (let ((file-name-handler-alist nil
)
6732 (if (eq operation
'insert-directory
)
6733 (directory-file-name
6735 (unhandled-file-name-directory default-directory
)))
6737 ;; Get a list of the indices of the args which are file names.
6739 (cdr (or (assq operation
6740 ;; The first six are special because they
6741 ;; return a file name. We want to include the /:
6742 ;; in the return value.
6743 ;; So just avoid stripping it in the first place.
6744 '((expand-file-name . nil
)
6745 (file-name-directory . nil
)
6746 (file-name-as-directory . nil
)
6747 (directory-file-name . nil
)
6748 (file-name-sans-versions . nil
)
6749 (find-backup-file-name . nil
)
6750 ;; `identity' means just return the first arg
6751 ;; not stripped of its quoting.
6752 (substitute-in-file-name identity
)
6753 ;; `add' means add "/:" to the result.
6754 (file-truename add
0)
6755 (insert-file-contents insert-file-contents
0)
6756 ;; `unquote-then-quote' means set buffer-file-name
6757 ;; temporarily to unquoted filename.
6758 (verify-visited-file-modtime unquote-then-quote
)
6759 ;; List the arguments which are filenames.
6760 (file-name-completion 1)
6761 (file-name-all-completions 1)
6765 (make-symbolic-link 0 1)
6766 (add-name-to-file 0 1)))
6767 ;; For all other operations, treat the first argument only
6768 ;; as the file name.
6771 ;; Copy ARGUMENTS so we can replace elements in it.
6772 (arguments (copy-sequence arguments
)))
6773 (if (symbolp (car file-arg-indices
))
6774 (setq method
(pop file-arg-indices
)))
6775 ;; Strip off the /: from the file names that have it.
6777 (while (consp file-arg-indices
)
6778 (let ((pair (nthcdr (car file-arg-indices
) arguments
)))
6780 (string-match "\\`/:" (car pair
))
6782 (if (= (length (car pair
)) 2)
6784 (substring (car pair
) 2)))))
6785 (setq file-arg-indices
(cdr file-arg-indices
))))
6787 (`identity
(car arguments
))
6788 (`add
(concat "/:" (apply operation arguments
)))
6789 (`insert-file-contents
6790 (let ((visit (nth 1 arguments
)))
6792 (apply operation arguments
)
6793 (when (and visit buffer-file-name
)
6794 (setq buffer-file-name
(concat "/:" buffer-file-name
))))))
6795 (`unquote-then-quote
6796 (let ((buffer-file-name (substring buffer-file-name
2)))
6797 (apply operation arguments
)))
6799 (apply operation arguments
)))))
6801 ;; Symbolic modes and read-file-modes.
6803 (defun file-modes-char-to-who (char)
6804 "Convert CHAR to a numeric bit-mask for extracting mode bits.
6805 CHAR is in [ugoa] and represents the category of users (Owner, Group,
6806 Others, or All) for whom to produce the mask.
6807 The bit-mask that is returned extracts from mode bits the access rights
6808 for the specified category of users."
6809 (cond ((= char ?u
) #o4700
)
6810 ((= char ?g
) #o2070
)
6811 ((= char ?o
) #o1007
)
6812 ((= char ?a
) #o7777
)
6813 (t (error "%c: bad `who' character" char
))))
6815 (defun file-modes-char-to-right (char &optional from
)
6816 "Convert CHAR to a numeric value of mode bits.
6817 CHAR is in [rwxXstugo] and represents symbolic access permissions.
6818 If CHAR is in [Xugo], the value is taken from FROM (or 0 if omitted)."
6819 (or from
(setq from
0))
6820 (cond ((= char ?r
) #o0444
)
6821 ((= char ?w
) #o0222
)
6822 ((= char ?x
) #o0111
)
6823 ((= char ?s
) #o6000
)
6824 ((= char ?t
) #o1000
)
6825 ;; Rights relative to the previous file modes.
6826 ((= char ?X
) (if (= (logand from
#o111
) 0) 0 #o0111
))
6827 ((= char ?u
) (let ((uright (logand #o4700 from
)))
6828 (+ uright
(/ uright
#o10
) (/ uright
#o100
))))
6829 ((= char ?g
) (let ((gright (logand #o2070 from
)))
6830 (+ gright
(/ gright
#o10
) (* gright
#o10
))))
6831 ((= char ?o
) (let ((oright (logand #o1007 from
)))
6832 (+ oright
(* oright
#o10
) (* oright
#o100
))))
6833 (t (error "%c: bad right character" char
))))
6835 (defun file-modes-rights-to-number (rights who-mask
&optional from
)
6836 "Convert a symbolic mode string specification to an equivalent number.
6837 RIGHTS is the symbolic mode spec, it should match \"([+=-][rwxXstugo]*)+\".
6838 WHO-MASK is the bit-mask specifying the category of users to which to
6839 apply the access permissions. See `file-modes-char-to-who'.
6840 FROM (or 0 if nil) gives the mode bits on which to base permissions if
6841 RIGHTS request to add, remove, or set permissions based on existing ones,
6843 (let* ((num-rights (or from
0))
6844 (list-rights (string-to-list rights
))
6845 (op (pop list-rights
)))
6846 (while (memq op
'(?
+ ?- ?
=))
6849 (while (memq (setq char-right
(pop list-rights
))
6850 '(?r ?w ?x ?X ?s ?t ?u ?g ?o
))
6853 (file-modes-char-to-right char-right num-rights
))))
6854 (setq num-right
(logand who-mask num-right
)
6856 (cond ((= op ?
+) (logior num-rights num-right
))
6857 ((= op ?-
) (logand num-rights
(lognot num-right
)))
6858 (t (logior (logand num-rights
(lognot who-mask
)) num-right
)))
6862 (defun file-modes-symbolic-to-number (modes &optional from
)
6863 "Convert symbolic file modes to numeric file modes.
6864 MODES is the string to convert, it should match
6865 \"[ugoa]*([+-=][rwxXstugo]*)+,...\".
6866 See Info node `(coreutils)File permissions' for more information on this
6868 FROM (or 0 if nil) gives the mode bits on which to base permissions if
6869 MODES request to add, remove, or set permissions based on existing ones,
6872 (let ((case-fold-search nil
)
6873 (num-modes (or from
0)))
6874 (while (/= (string-to-char modes
) 0)
6875 (if (string-match "^\\([ugoa]*\\)\\([+=-][rwxXstugo]*\\)+\\(,\\|\\)" modes
)
6876 (let ((num-who (apply 'logior
0
6877 (mapcar 'file-modes-char-to-who
6878 (match-string 1 modes
)))))
6880 (setq num-who
(logior #o7000
(default-file-modes))))
6882 (file-modes-rights-to-number (substring modes
(match-end 1))
6884 modes
(substring modes
(match-end 3))))
6885 (error "Parse error in modes near `%s'" (substring modes
0))))
6888 (defun read-file-modes (&optional prompt orig-file
)
6889 "Read file modes in octal or symbolic notation and return its numeric value.
6890 PROMPT is used as the prompt, default to \"File modes (octal or symbolic): \".
6891 ORIG-FILE is the name of a file on whose mode bits to base returned
6892 permissions if what user types requests to add, remove, or set permissions
6893 based on existing mode bits, as in \"og+rX-w\"."
6894 (let* ((modes (or (if orig-file
(file-modes orig-file
) 0)
6895 (error "File not found")))
6896 (modestr (and (stringp orig-file
)
6897 (nth 8 (file-attributes orig-file
))))
6899 (and (stringp modestr
)
6900 (string-match "^.\\(...\\)\\(...\\)\\(...\\)$" modestr
)
6901 (replace-regexp-in-string
6903 (format "u=%s,g=%s,o=%s"
6904 (match-string 1 modestr
)
6905 (match-string 2 modestr
)
6906 (match-string 3 modestr
)))))
6907 (value (read-string (or prompt
"File modes (octal or symbolic): ")
6910 (if (string-match "^[0-7]+" value
)
6911 (string-to-number value
8)
6912 (file-modes-symbolic-to-number value modes
)))))
6914 (define-obsolete-variable-alias 'cache-long-line-scans
6915 'cache-long-scans
"24.4")
6917 ;; Trashcan handling.
6918 (defcustom trash-directory nil
6919 "Directory for `move-file-to-trash' to move files and directories to.
6920 This directory is only used when the function `system-move-file-to-trash'
6922 Relative paths are interpreted relative to `default-directory'.
6923 If the value is nil, Emacs uses a freedesktop.org-style trashcan."
6924 :type
'(choice (const nil
) directory
)
6928 (defvar trash--hexify-table
)
6930 (declare-function system-move-file-to-trash
"w32fns.c" (filename))
6932 (defun move-file-to-trash (filename)
6933 "Move the file (or directory) named FILENAME to the trash.
6934 When `delete-by-moving-to-trash' is non-nil, this function is
6935 called by `delete-file' and `delete-directory' instead of
6936 deleting files outright.
6938 If the function `system-move-file-to-trash' is defined, call it
6939 with FILENAME as an argument.
6940 Otherwise, if `trash-directory' is non-nil, move FILENAME to that
6942 Otherwise, trash FILENAME using the freedesktop.org conventions,
6943 like the GNOME, KDE and XFCE desktop environments. Emacs only
6944 moves files to \"home trash\", ignoring per-volume trashcans."
6945 (interactive "fMove file to trash: ")
6946 (cond (trash-directory
6947 ;; If `trash-directory' is non-nil, move the file there.
6948 (let* ((trash-dir (expand-file-name trash-directory
))
6949 (fn (directory-file-name (expand-file-name filename
)))
6950 (new-fn (expand-file-name (file-name-nondirectory fn
)
6952 ;; We can't trash a parent directory of trash-directory.
6953 (if (string-prefix-p fn trash-dir
)
6954 (error "Trash directory `%s' is a subdirectory of `%s'"
6955 trash-dir filename
))
6956 (unless (file-directory-p trash-dir
)
6957 (make-directory trash-dir t
))
6958 ;; Ensure that the trashed file-name is unique.
6959 (if (file-exists-p new-fn
)
6960 (let ((version-control t
)
6961 (backup-directory-alist nil
))
6962 (setq new-fn
(car (find-backup-file-name new-fn
)))))
6963 (let (delete-by-moving-to-trash)
6964 (rename-file fn new-fn
))))
6965 ;; If `system-move-file-to-trash' is defined, use it.
6966 ((fboundp 'system-move-file-to-trash
)
6967 (system-move-file-to-trash filename
))
6968 ;; Otherwise, use the freedesktop.org method, as specified at
6969 ;; http://freedesktop.org/wiki/Specifications/trash-spec
6971 (let* ((xdg-data-dir
6972 (directory-file-name
6973 (expand-file-name "Trash"
6974 (or (getenv "XDG_DATA_HOME")
6975 "~/.local/share"))))
6976 (trash-files-dir (expand-file-name "files" xdg-data-dir
))
6977 (trash-info-dir (expand-file-name "info" xdg-data-dir
))
6978 (fn (directory-file-name (expand-file-name filename
))))
6980 ;; Check if we have permissions to delete.
6981 (unless (file-writable-p (directory-file-name
6982 (file-name-directory fn
)))
6983 (error "Cannot move %s to trash: Permission denied" filename
))
6984 ;; The trashed file cannot be the trash dir or its parent.
6985 (if (string-prefix-p fn trash-files-dir
)
6986 (error "The trash directory %s is a subdirectory of %s"
6987 trash-files-dir filename
))
6988 (if (string-prefix-p fn trash-info-dir
)
6989 (error "The trash directory %s is a subdirectory of %s"
6990 trash-info-dir filename
))
6992 ;; Ensure that the trash directory exists; otherwise, create it.
6993 (with-file-modes #o700
6994 (unless (file-exists-p trash-files-dir
)
6995 (make-directory trash-files-dir t
))
6996 (unless (file-exists-p trash-info-dir
)
6997 (make-directory trash-info-dir t
)))
6999 ;; Try to move to trash with .trashinfo undo information
7002 (set-buffer-file-coding-system 'utf-8-unix
)
7003 (insert "[Trash Info]\nPath=")
7004 ;; Perform url-encoding on FN. For compatibility with
7005 ;; other programs (e.g. XFCE Thunar), allow literal "/"
7006 ;; for path separators.
7007 (unless (boundp 'trash--hexify-table
)
7008 (setq trash--hexify-table
(make-vector 256 nil
))
7009 (let ((unreserved-chars
7010 (list ?
/ ?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m
7011 ?n ?o ?p ?q ?r ?s ?t ?u ?v ?w ?x ?y ?z ?A
7012 ?B ?C ?D ?E ?F ?G ?H ?I ?J ?K ?L ?M ?N ?O
7013 ?P ?Q ?R ?S ?T ?U ?V ?W ?X ?Y ?Z ?
0 ?
1 ?
2
7014 ?
3 ?
4 ?
5 ?
6 ?
7 ?
8 ?
9 ?- ?_ ?. ?
! ?~ ?
* ?
'
7017 (aset trash--hexify-table byte
7018 (if (memq byte unreserved-chars
)
7019 (char-to-string byte
)
7020 (format "%%%02x" byte
))))))
7021 (mapc (lambda (byte)
7022 (insert (aref trash--hexify-table byte
)))
7023 (if (multibyte-string-p fn
)
7024 (encode-coding-string fn
'utf-8
)
7026 (insert "\nDeletionDate="
7027 (format-time-string "%Y-%m-%dT%T")
7030 ;; Attempt to make .trashinfo file, trying up to 5
7031 ;; times. The .trashinfo file is opened with O_EXCL,
7032 ;; as per trash-spec 0.7, even if that can be a problem
7033 ;; on old NFS versions...
7035 (base-fn (expand-file-name
7036 (file-name-nondirectory fn
)
7041 (setq info-fn
(expand-file-name
7042 (concat (file-name-nondirectory new-fn
)
7045 (unless (condition-case nil
7047 (write-region nil nil info-fn nil
7048 'quiet info-fn
'excl
)
7049 (setq tries
0 success t
))
7050 (file-already-exists nil
))
7051 (setq tries
(1- tries
))
7052 ;; Uniquify new-fn. (Some file managers do not
7053 ;; like Emacs-style backup file names---e.g. bug
7054 ;; 170956 in Konqueror bug tracker.)
7055 (setq new-fn
(make-temp-name (concat base-fn
"_")))))
7057 (error "Cannot move %s to trash: Lock failed" filename
))
7059 ;; Finally, try to move the file to the trashcan.
7060 (let ((delete-by-moving-to-trash nil
))
7061 (rename-file fn new-fn
)))))))))
7064 (define-key ctl-x-map
"\C-f" 'find-file
)
7065 (define-key ctl-x-map
"\C-r" 'find-file-read-only
)
7066 (define-key ctl-x-map
"\C-v" 'find-alternate-file
)
7067 (define-key ctl-x-map
"\C-s" 'save-buffer
)
7068 (define-key ctl-x-map
"s" 'save-some-buffers
)
7069 (define-key ctl-x-map
"\C-w" 'write-file
)
7070 (define-key ctl-x-map
"i" 'insert-file
)
7071 (define-key esc-map
"~" 'not-modified
)
7072 (define-key ctl-x-map
"\C-d" 'list-directory
)
7073 (define-key ctl-x-map
"\C-c" 'save-buffers-kill-terminal
)
7074 (define-key ctl-x-map
"\C-q" 'read-only-mode
)
7076 (define-key ctl-x-4-map
"f" 'find-file-other-window
)
7077 (define-key ctl-x-4-map
"r" 'find-file-read-only-other-window
)
7078 (define-key ctl-x-4-map
"\C-f" 'find-file-other-window
)
7079 (define-key ctl-x-4-map
"b" 'switch-to-buffer-other-window
)
7080 (define-key ctl-x-4-map
"\C-o" 'display-buffer
)
7082 (define-key ctl-x-5-map
"b" 'switch-to-buffer-other-frame
)
7083 (define-key ctl-x-5-map
"f" 'find-file-other-frame
)
7084 (define-key ctl-x-5-map
"\C-f" 'find-file-other-frame
)
7085 (define-key ctl-x-5-map
"r" 'find-file-read-only-other-frame
)
7086 (define-key ctl-x-5-map
"\C-o" 'display-buffer-other-frame
)
7088 ;;; files.el ends here