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