1 ;;; files.el --- file input and output commands for Emacs
3 ;; Copyright (C) 1985-1987, 1992-2012 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'ss 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 (eval-when-compile (require 'cl
))
33 (defvar font-lock-keywords
)
36 "Backups of edited data files."
39 (defgroup find-file nil
44 (defcustom delete-auto-save-files t
45 "Non-nil means delete auto-save file when a buffer is saved or killed.
47 Note that the auto-save file will not be deleted if the buffer is killed
48 when it has unsaved changes."
52 (defcustom directory-abbrev-alist
54 "Alist of abbreviations for file directories.
55 A list of elements of the form (FROM . TO), each meaning to replace
56 FROM with TO when it appears in a directory name. This replacement is
57 done when setting up the default directory of a newly visited file.
59 FROM is matched against directory names anchored at the first
60 character, so it should start with a \"\\\\`\", or, if directory
61 names cannot have embedded newlines, with a \"^\".
63 FROM and TO should be equivalent names, which refer to the
64 same directory. Do not use `~' in the TO strings;
65 they should be ordinary absolute directory names.
67 Use this feature when you have directories which you normally refer to
68 via absolute symbolic links. Make TO the name of the link, and FROM
69 the name it is linked to."
70 :type
'(repeat (cons :format
"%v"
77 (defcustom make-backup-files t
78 "Non-nil means make a backup of a file the first time it is saved.
79 This can be done by renaming the file or by copying.
81 Renaming means that Emacs renames the existing file so that it is a
82 backup file, then writes the buffer into a new file. Any other names
83 that the old file had will now refer to the backup file. The new file
84 is owned by you and its group is defaulted.
86 Copying means that Emacs copies the existing file into the backup
87 file, then writes the buffer on top of the existing file. Any other
88 names that the old file had will now refer to the new (edited) file.
89 The file's owner and group are unchanged.
91 The choice of renaming or copying is controlled by the variables
92 `backup-by-copying', `backup-by-copying-when-linked',
93 `backup-by-copying-when-mismatch' and
94 `backup-by-copying-when-privileged-mismatch'. See also `backup-inhibited'."
98 ;; Do this so that local variables based on the file name
99 ;; are not overridden by the major mode.
100 (defvar backup-inhibited nil
101 "Non-nil means don't make a backup, regardless of the other parameters.
102 This variable is intended for use by making it local to a buffer.
103 But it is local only if you make it local.")
104 (put 'backup-inhibited
'permanent-local t
)
106 (defcustom backup-by-copying nil
107 "Non-nil means always use copying to create backup files.
108 See documentation of variable `make-backup-files'."
112 (defcustom backup-by-copying-when-linked nil
113 "Non-nil means use copying to create backups for files with multiple names.
114 This causes the alternate names to refer to the latest version as edited.
115 This variable is relevant only if `backup-by-copying' is nil."
119 (defcustom backup-by-copying-when-mismatch t
120 "Non-nil means create backups by copying if this preserves owner or group.
121 Renaming may still be used (subject to control of other variables)
122 when it would not result in changing the owner or group of the file;
123 that is, for files which are owned by you and whose group matches
124 the default for a new file created there by you.
125 This variable is relevant only if `backup-by-copying' is nil."
129 (put 'backup-by-copying-when-mismatch
'permanent-local t
)
131 (defcustom backup-by-copying-when-privileged-mismatch
200
132 "Non-nil means create backups by copying to preserve a privileged owner.
133 Renaming may still be used (subject to control of other variables)
134 when it would not result in changing the owner of the file or if the owner
135 has a user id greater than the value of this variable. This is useful
136 when low-numbered uid's are used for special system users (such as root)
137 that must maintain ownership of certain files.
138 This variable is relevant only if `backup-by-copying' and
139 `backup-by-copying-when-mismatch' are nil."
140 :type
'(choice (const nil
) integer
)
143 (defvar backup-enable-predicate
'normal-backup-enable-predicate
144 "Predicate that looks at a file name and decides whether to make backups.
145 Called with an absolute file name as argument, it returns t to enable backup.")
147 (defcustom buffer-offer-save nil
148 "Non-nil in a buffer means always offer to save buffer on exit.
149 Do so even if the buffer is not visiting a file.
150 Automatically local in all buffers."
153 (make-variable-buffer-local 'buffer-offer-save
)
154 (put 'buffer-offer-save
'permanent-local t
)
156 (defcustom find-file-existing-other-name t
157 "Non-nil means find a file under alternative names, in existing buffers.
158 This means if any existing buffer is visiting the file you want
159 under another name, you get the existing buffer instead of a new buffer."
163 (defcustom find-file-visit-truename nil
164 "Non-nil means visit a file under its truename.
165 The truename of a file is found by chasing all links
166 both at the file level and at the levels of the containing directories."
169 (put 'find-file-visit-truename
'safe-local-variable
'booleanp
)
171 (defcustom revert-without-query nil
172 "Specify which files should be reverted without query.
173 The value is a list of regular expressions.
174 If the file name matches one of these regular expressions,
175 then `revert-buffer' reverts the file without querying
176 if the file has changed on disk and you have not edited the buffer."
177 :type
'(repeat regexp
)
180 (defvar buffer-file-number nil
181 "The device number and file number of the file visited in the current buffer.
182 The value is a list of the form (FILENUM DEVNUM).
183 This pair of numbers uniquely identifies the file.
184 If the buffer is visiting a new file, the value is nil.")
185 (make-variable-buffer-local 'buffer-file-number
)
186 (put 'buffer-file-number
'permanent-local t
)
188 (defvar buffer-file-numbers-unique
(not (memq system-type
'(windows-nt)))
189 "Non-nil means that `buffer-file-number' uniquely identifies files.")
191 (defvar buffer-file-read-only nil
192 "Non-nil if visited file was read-only when visited.")
193 (make-variable-buffer-local 'buffer-file-read-only
)
195 (defcustom small-temporary-file-directory
196 (if (eq system-type
'ms-dos
) (getenv "TMPDIR"))
197 "The directory for writing small temporary files.
198 If non-nil, this directory is used instead of `temporary-file-directory'
199 by programs that create small temporary files. This is for systems that
200 have fast storage with limited space, such as a RAM disk."
202 :initialize
'custom-initialize-delay
203 :type
'(choice (const nil
) directory
))
205 ;; The system null device. (Should reference NULL_DEVICE from C.)
206 (defvar null-device
(purecopy "/dev/null") "The system null device.")
208 (declare-function msdos-long-file-names
"msdos.c")
209 (declare-function w32-long-file-name
"w32proc.c")
210 (declare-function dired-get-filename
"dired" (&optional localp no-error-if-not-filep
))
211 (declare-function dired-unmark
"dired" (arg))
212 (declare-function dired-do-flagged-delete
"dired" (&optional nomessage
))
213 (declare-function dos-8
+3-filename
"dos-fns" (filename))
214 (declare-function view-mode-disable
"view" ())
215 (declare-function dosified-file-name
"dos-fns" (file-name))
217 (defvar file-name-invalid-regexp
218 (cond ((and (eq system-type
'ms-dos
) (not (msdos-long-file-names)))
220 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
221 "[+, ;=|<>\"?*]\\|\\[\\|\\]\\|" ; invalid characters
222 "[\000-\037]\\|" ; control characters
223 "\\(/\\.\\.?[^/]\\)\\|" ; leading dots
224 "\\(/[^/.]+\\.[^/.]*\\.\\)"))) ; more than a single dot
225 ((memq system-type
'(ms-dos windows-nt cygwin
))
227 (concat "^\\([^A-Z[-`a-z]\\|..+\\)?:\\|" ; colon except after drive
228 "[|<>\"?*\000-\037]"))) ; invalid characters
229 (t (purecopy "[\000]")))
230 "Regexp recognizing file names which aren't allowed by the filesystem.")
232 (defcustom file-precious-flag nil
233 "Non-nil means protect against I/O errors while saving files.
234 Some modes set this non-nil in particular buffers.
236 This feature works by writing the new contents into a temporary file
237 and then renaming the temporary file to replace the original.
238 In this way, any I/O error in writing leaves the original untouched,
239 and there is never any instant where the file is nonexistent.
241 Note that this feature forces backups to be made by copying.
242 Yet, at the same time, saving a precious file
243 breaks any hard links between it and other files.
245 This feature is advisory: for example, if the directory in which the
246 file is being saved is not writable, Emacs may ignore a non-nil value
247 of `file-precious-flag' and write directly into the file.
249 See also: `break-hardlink-on-save'."
253 (defcustom break-hardlink-on-save nil
254 "Non-nil means when saving a file that exists under several names
255 \(i.e., has multiple hardlinks), break the hardlink associated with
256 `buffer-file-name' and write to a new file, so that the other
257 instances of the file are not affected by the save.
259 If `buffer-file-name' refers to a symlink, do not break the symlink.
261 Unlike `file-precious-flag', `break-hardlink-on-save' is not advisory.
262 For example, if the directory in which a file is being saved is not
263 itself writable, then error instead of saving in some
264 hardlink-nonbreaking way.
266 See also `backup-by-copying' and `backup-by-copying-when-linked'."
271 (defcustom version-control nil
272 "Control use of version numbers for backup files.
273 When t, make numeric backup versions unconditionally.
274 When nil, make them for files that have some already.
275 The value `never' means do not make them."
276 :type
'(choice (const :tag
"Never" never
)
277 (const :tag
"If existing" nil
)
278 (other :tag
"Always" t
))
281 (put 'version-control
'safe-local-variable
282 (lambda (x) (or (booleanp x
) (equal x
'never
))))
284 (defcustom dired-kept-versions
2
285 "When cleaning directory, number of versions to keep."
290 (defcustom delete-old-versions nil
291 "If t, delete excess backup versions silently.
292 If nil, ask confirmation. Any other value prevents any trimming."
293 :type
'(choice (const :tag
"Delete" t
)
294 (const :tag
"Ask" nil
)
295 (other :tag
"Leave" other
))
298 (defcustom kept-old-versions
2
299 "Number of oldest versions to keep when a new numbered backup is made."
302 (put 'kept-old-versions
'safe-local-variable
'integerp
)
304 (defcustom kept-new-versions
2
305 "Number of newest versions to keep when a new numbered backup is made.
306 Includes the new backup. Must be > 0"
309 (put 'kept-new-versions
'safe-local-variable
'integerp
)
311 (defcustom require-final-newline nil
312 "Whether to add a newline automatically at the end of the file.
314 A value of t means do this only when the file is about to be saved.
315 A value of `visit' means do this right after the file is visited.
316 A value of `visit-save' means do it at both of those times.
317 Any other non-nil value means ask user whether to add a newline, when saving.
318 A value of nil means don't add newlines.
320 Certain major modes set this locally to the value obtained
321 from `mode-require-final-newline'."
322 :type
'(choice (const :tag
"When visiting" visit
)
323 (const :tag
"When saving" t
)
324 (const :tag
"When visiting or saving" visit-save
)
325 (const :tag
"Don't add newlines" nil
)
326 (other :tag
"Ask each time" ask
))
327 :group
'editing-basics
)
329 (defcustom mode-require-final-newline t
330 "Whether to add a newline at end of file, in certain major modes.
331 Those modes set `require-final-newline' to this value when you enable them.
332 They do so because they are often used for files that are supposed
333 to end in newlines, and the question is how to arrange that.
335 A value of t means do this only when the file is about to be saved.
336 A value of `visit' means do this right after the file is visited.
337 A value of `visit-save' means do it at both of those times.
338 Any other non-nil value means ask user whether to add a newline, when saving.
340 A value of nil means do not add newlines. That is a risky choice in this
341 variable since this value is used for modes for files that ought to have
342 final newlines. So if you set this to nil, you must explicitly check and
343 add a final newline, whenever you save a file that really needs one."
344 :type
'(choice (const :tag
"When visiting" visit
)
345 (const :tag
"When saving" t
)
346 (const :tag
"When visiting or saving" visit-save
)
347 (const :tag
"Don't add newlines" nil
)
348 (other :tag
"Ask each time" ask
))
349 :group
'editing-basics
352 (defcustom auto-save-default t
353 "Non-nil says by default do auto-saving of every file-visiting buffer."
357 (defcustom auto-save-file-name-transforms
358 `(("\\`/[^/]*:\\([^/]*/\\)*\\([^/]*\\)\\'"
359 ;; Don't put "\\2" inside expand-file-name, since it will be
360 ;; transformed to "/2" on DOS/Windows.
361 ,(concat temporary-file-directory
"\\2") t
))
362 "Transforms to apply to buffer file name before making auto-save file name.
363 Each transform is a list (REGEXP REPLACEMENT UNIQUIFY):
364 REGEXP is a regular expression to match against the file name.
365 If it matches, `replace-match' is used to replace the
366 matching part with REPLACEMENT.
367 If the optional element UNIQUIFY is non-nil, the auto-save file name is
368 constructed by taking the directory part of the replaced file-name,
369 concatenated with the buffer file name with all directory separators
370 changed to `!' to prevent clashes. This will not work
371 correctly if your filesystem truncates the resulting name.
373 All the transforms in the list are tried, in the order they are listed.
374 When one transform applies, its result is final;
375 no further transforms are tried.
377 The default value is set up to put the auto-save file into the
378 temporary directory (see the variable `temporary-file-directory') for
379 editing a remote file.
381 On MS-DOS filesystems without long names this variable is always
384 :type
'(repeat (list (string :tag
"Regexp") (string :tag
"Replacement")
385 (boolean :tag
"Uniquify")))
386 :initialize
'custom-initialize-delay
389 (defcustom save-abbrevs t
390 "Non-nil means save word abbrevs too when files are saved.
391 If `silently', don't ask the user before saving."
392 :type
'(choice (const t
) (const nil
) (const silently
))
395 (defcustom find-file-run-dired t
396 "Non-nil means allow `find-file' to visit directories.
397 To visit the directory, `find-file' runs `find-directory-functions'."
401 (defcustom find-directory-functions
'(cvs-dired-noselect dired-noselect
)
402 "List of functions to try in sequence to visit a directory.
403 Each function is called with the directory name as the sole argument
404 and should return either a buffer or nil."
405 :type
'(hook :options
(cvs-dired-noselect dired-noselect
))
408 ;; FIXME: also add a hook for `(thing-at-point 'filename)'
409 (defcustom file-name-at-point-functions
'(ffap-guess-file-name-at-point)
410 "List of functions to try in sequence to get a file name at point.
411 Each function should return either nil or a file name found at the
412 location of point in the current buffer."
413 :type
'(hook :options
(ffap-guess-file-name-at-point))
416 ;;;It is not useful to make this a local variable.
417 ;;;(put 'find-file-not-found-hooks 'permanent-local t)
418 (defvar find-file-not-found-functions nil
419 "List of functions to be called for `find-file' on nonexistent file.
420 These functions are called as soon as the error is detected.
421 Variable `buffer-file-name' is already set up.
422 The functions are called in the order given until one of them returns non-nil.")
423 (define-obsolete-variable-alias 'find-file-not-found-hooks
424 'find-file-not-found-functions
"22.1")
426 ;;;It is not useful to make this a local variable.
427 ;;;(put 'find-file-hooks 'permanent-local t)
428 (define-obsolete-variable-alias 'find-file-hooks
'find-file-hook
"22.1")
429 (defcustom find-file-hook nil
430 "List of functions to be called after a buffer is loaded from a file.
431 The buffer's local variables (if any) will have been processed before the
432 functions are called."
435 :options
'(auto-insert)
438 (defvar write-file-functions nil
439 "List of functions to be called before writing out a buffer to a file.
440 If one of them returns non-nil, the file is considered already written
441 and the rest are not called.
442 These hooks are considered to pertain to the visited file.
443 So any buffer-local binding of this variable is discarded if you change
444 the visited file name with \\[set-visited-file-name], but not when you
445 change the major mode.
447 This hook is not run if any of the functions in
448 `write-contents-functions' returns non-nil. Both hooks pertain
449 to how to save a buffer to file, for instance, choosing a suitable
450 coding system and setting mode bits. (See Info
451 node `(elisp)Saving Buffers'.) To perform various checks or
452 updates before the buffer is saved, use `before-save-hook'.")
453 (put 'write-file-functions
'permanent-local t
)
454 (define-obsolete-variable-alias 'write-file-hooks
'write-file-functions
"22.1")
456 (defvar local-write-file-hooks nil
)
457 (make-variable-buffer-local 'local-write-file-hooks
)
458 (put 'local-write-file-hooks
'permanent-local t
)
459 (make-obsolete-variable 'local-write-file-hooks
'write-file-functions
"22.1")
461 (defvar write-contents-functions nil
462 "List of functions to be called before writing out a buffer to a file.
463 If one of them returns non-nil, the file is considered already written
464 and the rest are not called and neither are the functions in
465 `write-file-functions'.
467 This variable is meant to be used for hooks that pertain to the
468 buffer's contents, not to the particular visited file; thus,
469 `set-visited-file-name' does not clear this variable; but changing the
470 major mode does clear it.
472 For hooks that _do_ pertain to the particular visited file, use
473 `write-file-functions'. Both this variable and
474 `write-file-functions' relate to how a buffer is saved to file.
475 To perform various checks or updates before the buffer is saved,
476 use `before-save-hook'.")
477 (make-variable-buffer-local 'write-contents-functions
)
478 (define-obsolete-variable-alias 'write-contents-hooks
479 'write-contents-functions
"22.1")
481 (defcustom enable-local-variables t
482 "Control use of local variables in files you visit.
483 The value can be t, nil, :safe, :all, or something else.
485 A value of t means file local variables specifications are obeyed
486 if all the specified variable values are safe; if any values are
487 not safe, Emacs queries you, once, whether to set them all.
488 \(When you say yes to certain values, they are remembered as safe.)
490 :safe means set the safe variables, and ignore the rest.
491 :all means set all variables, whether safe or not.
492 (Don't set it permanently to :all.)
493 A value of nil means always ignore the file local variables.
495 Any other value means always query you once whether to set them all.
496 \(When you say yes to certain values, they are remembered as safe, but
497 this has no effect when `enable-local-variables' is \"something else\".)
499 This variable also controls use of major modes specified in
502 The command \\[normal-mode], when used interactively,
503 always obeys file local variable specifications and the -*- line,
504 and ignores this variable."
506 :type
'(choice (const :tag
"Query Unsafe" t
)
507 (const :tag
"Safe Only" :safe
)
508 (const :tag
"Do all" :all
)
509 (const :tag
"Ignore" nil
)
510 (other :tag
"Query" other
))
513 ;; This is an odd variable IMO.
514 ;; You might wonder why it is needed, when we could just do:
515 ;; (set (make-local-variable 'enable-local-variables) nil)
516 ;; These two are not precisely the same.
517 ;; Setting this variable does not cause -*- mode settings to be
518 ;; ignored, whereas setting enable-local-variables does.
519 ;; Only three places in Emacs use this variable: tar and arc modes,
520 ;; and rmail. The first two don't need it. They already use
521 ;; inhibit-local-variables-regexps, which is probably enough, and
522 ;; could also just set enable-local-variables locally to nil.
523 ;; Them setting it has the side-effect that dir-locals cannot apply to
524 ;; eg tar files (?). FIXME Is this appropriate?
525 ;; AFAICS, rmail is the only thing that needs this, and the only
526 ;; reason it uses it is for BABYL files (which are obsolete).
527 ;; These contain "-*- rmail -*-" in the first line, which rmail wants
528 ;; to respect, so that find-file on a BABYL file will switch to
529 ;; rmail-mode automatically (this is nice, but hardly essential,
530 ;; since most people are used to explicitly running a command to
531 ;; access their mail; M-x gnus etc). Rmail files may happen to
532 ;; contain Local Variables sections in messages, which Rmail wants to
533 ;; ignore. So AFAICS the only reason this variable exists is for a
534 ;; minor convenience feature for handling of an obsolete Rmail file format.
535 (defvar local-enable-local-variables t
536 "Like `enable-local-variables' but meant for buffer-local bindings.
537 The meaningful values are nil and non-nil. The default is non-nil.
538 If a major mode sets this to nil, buffer-locally, then any local
539 variables list in a file visited in that mode will be ignored.
541 This variable does not affect the use of major modes specified
544 (defcustom enable-local-eval
'maybe
545 "Control processing of the \"variable\" `eval' in a file's local variables.
546 The value can be t, nil or something else.
547 A value of t means obey `eval' variables.
548 A value of nil means ignore them; anything else means query."
550 :type
'(choice (const :tag
"Obey" t
)
551 (const :tag
"Ignore" nil
)
552 (other :tag
"Query" other
))
555 ;; Avoid losing in versions where CLASH_DETECTION is disabled.
556 (or (fboundp 'lock-buffer
)
557 (defalias 'lock-buffer
'ignore
))
558 (or (fboundp 'unlock-buffer
)
559 (defalias 'unlock-buffer
'ignore
))
560 (or (fboundp 'file-locked-p
)
561 (defalias 'file-locked-p
'ignore
))
563 (defcustom view-read-only nil
564 "Non-nil means buffers visiting files read-only do so in view mode.
565 In fact, this means that all read-only buffers normally have
566 View mode enabled, including buffers that are read-only because
567 you visit a file you cannot alter, and buffers you make read-only
568 using \\[toggle-read-only]."
572 (defvar file-name-history nil
573 "History list of file names entered in the minibuffer.
575 Maximum length of the history list is determined by the value
576 of `history-length', which see.")
578 (put 'ange-ftp-completion-hook-function
'safe-magic t
)
579 (defun ange-ftp-completion-hook-function (op &rest args
)
580 "Provides support for ange-ftp host name completion.
581 Runs the usual ange-ftp hook, but only for completion operations."
582 ;; Having this here avoids the need to load ange-ftp when it's not
584 (if (memq op
'(file-name-completion file-name-all-completions
))
585 (apply 'ange-ftp-hook-function op args
)
586 (let ((inhibit-file-name-handlers
587 (cons 'ange-ftp-completion-hook-function
588 (and (eq inhibit-file-name-operation op
)
589 inhibit-file-name-handlers
)))
590 (inhibit-file-name-operation op
))
593 (declare-function dos-convert-standard-filename
"dos-fns.el" (filename))
594 (declare-function w32-convert-standard-filename
"w32-fns.el" (filename))
596 (defun convert-standard-filename (filename)
597 "Convert a standard file's name to something suitable for the OS.
598 This means to guarantee valid names and perhaps to canonicalize
601 FILENAME should be an absolute file name since the conversion rules
602 sometimes vary depending on the position in the file name. E.g. c:/foo
603 is a valid DOS file name, but c:/bar/c:/foo is not.
605 This function's standard definition is trivial; it just returns
606 the argument. However, on Windows and DOS, replace invalid
607 characters. On DOS, make sure to obey the 8.3 limitations.
608 In the native Windows build, turn Cygwin names into native names,
609 and also turn slashes into backslashes if the shell requires it (see
610 `w32-shell-dos-semantics').
612 See Info node `(elisp)Standard File Names' for more details."
614 ((eq system-type
'cygwin
)
615 (let ((name (copy-sequence filename
))
617 ;; Replace invalid filename characters with !
618 (while (string-match "[?*:<>|\"\000-\037]" name start
)
619 (aset name
(match-beginning 0) ?
!)
620 (setq start
(match-end 0)))
622 ((eq system-type
'windows-nt
)
623 (w32-convert-standard-filename filename
))
624 ((eq system-type
'ms-dos
)
625 (dos-convert-standard-filename filename
))
628 (defun read-directory-name (prompt &optional dir default-dirname mustmatch initial
)
629 "Read directory name, prompting with PROMPT and completing in directory DIR.
630 Value is not expanded---you must call `expand-file-name' yourself.
631 Default name to DEFAULT-DIRNAME if user exits with the same
632 non-empty string that was inserted by this function.
633 (If DEFAULT-DIRNAME is omitted, DIR combined with INITIAL is used,
634 or just DIR if INITIAL is nil.)
635 If the user exits with an empty minibuffer, this function returns
636 an empty string. (This can only happen if the user erased the
637 pre-inserted contents or if `insert-default-directory' is nil.)
638 Fourth arg MUSTMATCH non-nil means require existing directory's name.
639 Non-nil and non-t means also require confirmation after completion.
640 Fifth arg INITIAL specifies text to start with.
641 DIR should be an absolute directory name. It defaults to
642 the value of `default-directory'."
644 (setq dir default-directory
))
645 (read-file-name prompt dir
(or default-dirname
646 (if initial
(expand-file-name initial dir
)
653 "Show the current default directory."
655 (message "Directory %s" default-directory
))
658 "Value of the CDPATH environment variable, as a list.
659 Not actually set up until the first time you use it.")
661 (defun parse-colon-path (search-path)
662 "Explode a search path into a list of directory names.
663 Directories are separated by occurrences of `path-separator'
664 \(which is colon in GNU and GNU-like systems)."
665 ;; We could use split-string here.
667 (let (cd-list (cd-start 0) cd-colon
)
668 (setq search-path
(concat search-path path-separator
))
669 (while (setq cd-colon
(string-match path-separator search-path cd-start
))
672 (list (if (= cd-start cd-colon
)
674 (substitute-in-file-name
675 (file-name-as-directory
676 (substring search-path cd-start cd-colon
)))))))
677 (setq cd-start
(+ cd-colon
1)))
680 (defun cd-absolute (dir)
681 "Change current directory to given absolute file name DIR."
682 ;; Put the name into directory syntax now,
683 ;; because otherwise expand-file-name may give some bad results.
684 (setq dir
(file-name-as-directory dir
))
685 ;; We used to additionally call abbreviate-file-name here, for an
686 ;; unknown reason. Problem is that most buffers are setup
687 ;; without going through cd-absolute and don't call
688 ;; abbreviate-file-name on their default-directory, so the few that
689 ;; do end up using a superficially different directory.
690 (setq dir
(expand-file-name dir
))
691 (if (not (file-directory-p dir
))
692 (if (file-exists-p dir
)
693 (error "%s is not a directory" dir
)
694 (error "%s: no such directory" dir
))
695 (unless (file-executable-p dir
)
696 (error "Cannot cd to %s: Permission denied" dir
))
697 (setq default-directory dir
)
698 (setq list-buffers-directory dir
)))
701 "Make DIR become the current buffer's default directory.
702 If your environment includes a `CDPATH' variable, try each one of
703 that list of directories (separated by occurrences of
704 `path-separator') when resolving a relative directory name.
705 The path separator is colon in GNU and GNU-like systems."
708 ;; FIXME: There's a subtle bug in the completion below. Seems linked
709 ;; to a fundamental difficulty of implementing `predicate' correctly.
710 ;; The manifestation is that TAB may list non-directories in the case where
711 ;; those files also correspond to valid directories (if your cd-path is (A/
712 ;; B/) and you have A/a a file and B/a a directory, then both `a' and `a/'
713 ;; will be listed as valid completions).
714 ;; This is because `a' (listed because of A/a) is indeed a valid choice
715 ;; (which will lead to the use of B/a).
716 (minibuffer-with-setup-hook
718 (setq minibuffer-completion-table
719 (apply-partially #'locate-file-completion-table
721 (setq minibuffer-completion-predicate
723 (locate-file dir cd-path nil
724 (lambda (f) (and (file-directory-p f
) 'dir-ok
))))))
726 (setq cd-path
(or (parse-colon-path (getenv "CDPATH"))
728 (read-directory-name "Change default directory: "
729 default-directory default-directory
732 (setq cd-path
(or (parse-colon-path (getenv "CDPATH"))
735 (or (locate-file dir cd-path nil
736 (lambda (f) (and (file-directory-p f
) 'dir-ok
)))
737 (error "No such directory found via CDPATH environment variable"))))
739 (defun load-file (file)
740 "Load the Lisp file named FILE."
741 ;; This is a case where .elc makes a lot of sense.
742 (interactive (list (let ((completion-ignored-extensions
743 (remove ".elc" completion-ignored-extensions
)))
744 (read-file-name "Load file: "))))
745 (load (expand-file-name file
) nil nil t
))
747 (defun locate-file (filename path
&optional suffixes predicate
)
748 "Search for FILENAME through PATH.
749 If found, return the absolute file name of FILENAME, with its suffixes;
750 otherwise return nil.
751 PATH should be a list of directories to look in, like the lists in
752 `exec-path' or `load-path'.
753 If SUFFIXES is non-nil, it should be a list of suffixes to append to
754 file name when searching. If SUFFIXES is nil, it is equivalent to '(\"\").
755 Use '(\"/\") to disable PATH search, but still try the suffixes in SUFFIXES.
756 If non-nil, PREDICATE is used instead of `file-readable-p'.
758 This function will normally skip directories, so if you want it to find
759 directories, make sure the PREDICATE function returns `dir-ok' for them.
761 PREDICATE can also be an integer to pass to the `access' system call,
762 in which case file-name handlers are ignored. This usage is deprecated.
763 For compatibility, PREDICATE can also be one of the symbols
764 `executable', `readable', `writable', or `exists', or a list of
765 one or more of those symbols."
766 (if (and predicate
(symbolp predicate
) (not (functionp predicate
)))
767 (setq predicate
(list predicate
)))
768 (when (and (consp predicate
) (not (functionp predicate
)))
770 (logior (if (memq 'executable predicate
) 1 0)
771 (if (memq 'writable predicate
) 2 0)
772 (if (memq 'readable predicate
) 4 0))))
773 (locate-file-internal filename path suffixes predicate
))
775 (defun locate-file-completion-table (dirs suffixes string pred action
)
776 "Do completion for file names passed to `locate-file'."
778 ((file-name-absolute-p string
)
779 ;; FIXME: maybe we should use completion-file-name-table instead,
780 ;; tho at least for `load', the arg is passed through
781 ;; substitute-in-file-name for historical reasons.
782 (read-file-name-internal string pred action
))
783 ((eq (car-safe action
) 'boundaries
)
784 (let ((suffix (cdr action
)))
786 (length (file-name-directory string
))
787 (let ((x (file-name-directory suffix
)))
788 (if x
(1- (length x
)) (length suffix
))))))
791 ;; If we have files like "foo.el" and "foo.elc", we could load one of
792 ;; them with "foo.el", "foo.elc", or "foo", where just "foo" is the
793 ;; preferred way. So if we list all 3, that gives a lot of redundant
794 ;; entries for the poor soul looking just for "foo". OTOH, sometimes
795 ;; the user does want to pay attention to the extension. We try to
796 ;; diffuse this tension by stripping the suffix, except when the
797 ;; result is a single element (i.e. usually we only list "foo" unless
798 ;; it's the only remaining element in the list, in which case we do
799 ;; list "foo", "foo.elc" and "foo.el").
801 (suffix (concat (regexp-opt suffixes t
) "\\'"))
802 (string-dir (file-name-directory string
))
803 (string-file (file-name-nondirectory string
)))
806 (setq dir default-directory
))
807 (if string-dir
(setq dir
(expand-file-name string-dir dir
)))
808 (when (file-directory-p dir
)
809 (dolist (file (file-name-all-completions
811 (if (not (string-match suffix file
))
813 (push file fullnames
)
814 (push (substring file
0 (match-beginning 0)) names
)))))
815 ;; Switching from names to names+fullnames creates a non-monotonicity
816 ;; which can cause problems with things like partial-completion.
817 ;; To minimize the problem, filter out completion-regexp-list, so that
818 ;; M-x load-library RET t/x.e TAB finds some files. Also remove elements
819 ;; from `names' which only matched `string' when they still had
821 (setq names
(all-completions string names
))
822 ;; Remove duplicates of the first element, so that we can easily check
823 ;; if `names' really only contains a single element.
824 (when (cdr names
) (setcdr names
(delete (car names
) (cdr names
))))
826 ;; There's no more than one matching non-suffixed element, so expand
827 ;; the list by adding the suffixed elements as well.
828 (setq names
(nconc names fullnames
)))
829 (completion-table-with-context
830 string-dir names string-file pred action
)))))
832 (defun locate-file-completion (string path-and-suffixes action
)
833 "Do completion for file names passed to `locate-file'.
834 PATH-AND-SUFFIXES is a pair of lists, (DIRECTORIES . SUFFIXES)."
835 (locate-file-completion-table (car path-and-suffixes
)
836 (cdr path-and-suffixes
)
838 (make-obsolete 'locate-file-completion
'locate-file-completion-table
"23.1")
840 (defvar locate-dominating-stop-dir-regexp
841 (purecopy "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'")
842 "Regexp of directory names which stop the search in `locate-dominating-file'.
843 Any directory whose name matches this regexp will be treated like
844 a kind of root directory by `locate-dominating-file' which will stop its search
845 when it bumps into it.
846 The default regexp prevents fruitless and time-consuming attempts to find
847 special files in directories in which filenames are interpreted as hostnames,
848 or mount points potentially requiring authentication as a different user.")
850 ;; (defun locate-dominating-files (file regexp)
851 ;; "Look up the directory hierarchy from FILE for a file matching REGEXP.
852 ;; Stop at the first parent where a matching file is found and return the list
853 ;; of files that that match in this directory."
855 ;; ;; `user' is not initialized yet because `file' may not exist, so we may
856 ;; ;; have to walk up part of the hierarchy before we find the "initial UID".
858 ;; ;; Abbreviate, so as to stop when we cross ~/.
859 ;; (dir (abbreviate-file-name (file-name-as-directory file)))
862 ;; ;; As a heuristic, we stop looking up the hierarchy of
863 ;; ;; directories as soon as we find a directory belonging to
864 ;; ;; another user. This should save us from looking in
865 ;; ;; things like /net and /afs. This assumes that all the
866 ;; ;; files inside a project belong to the same user.
867 ;; (let ((prev-user user))
868 ;; (setq user (nth 2 (file-attributes dir)))
869 ;; (or (null prev-user) (equal user prev-user))))
870 ;; (if (setq files (condition-case nil
871 ;; (directory-files dir 'full regexp 'nosort)
873 ;; (throw 'found files)
875 ;; (setq dir (file-name-directory
876 ;; (directory-file-name dir))))
880 (defun locate-dominating-file (file name
)
881 "Look up the directory hierarchy from FILE for a file named NAME.
882 Stop at the first parent directory containing a file NAME,
883 and return the directory. Return nil if not found.
885 This function only tests if FILE exists. If you care about whether
886 it is readable, regular, etc., you should test the result."
887 ;; We used to use the above locate-dominating-files code, but the
888 ;; directory-files call is very costly, so we're much better off doing
889 ;; multiple calls using the code in here.
891 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
892 ;; `name' in /home or in /.
893 (setq file
(abbreviate-file-name file
))
895 ;; `user' is not initialized outside the loop because
896 ;; `file' may not exist, so we may have to walk up part of the
897 ;; hierarchy before we find the "initial UID". Note: currently unused
902 ;; FIXME: Disabled this heuristic because it is sometimes
904 ;; As a heuristic, we stop looking up the hierarchy of
905 ;; directories as soon as we find a directory belonging
906 ;; to another user. This should save us from looking in
907 ;; things like /net and /afs. This assumes that all the
908 ;; files inside a project belong to the same user.
909 ;; (let ((prev-user user))
910 ;; (setq user (nth 2 (file-attributes file)))
911 ;; (and prev-user (not (equal user prev-user))))
912 (string-match locate-dominating-stop-dir-regexp file
)))
913 (setq try
(file-exists-p (expand-file-name name file
)))
914 (cond (try (setq root file
))
915 ((equal file
(setq file
(file-name-directory
916 (directory-file-name file
))))
921 (defun executable-find (command)
922 "Search for COMMAND in `exec-path' and return the absolute file name.
923 Return nil if COMMAND is not found anywhere in `exec-path'."
924 ;; Use 1 rather than file-executable-p to better match the behavior of
926 (locate-file command exec-path exec-suffixes
1))
928 (defun load-library (library)
929 "Load the Emacs Lisp library named LIBRARY.
930 This is an interface to the function `load'. LIBRARY is searched
931 for in `load-path', both with and without `load-suffixes' (as
932 well as `load-file-rep-suffixes').
934 See Info node `(emacs)Lisp Libraries' for more details.
935 See `load-file' for a different interface to `load'."
937 (list (completing-read "Load library: "
938 (apply-partially 'locate-file-completion-table
940 (get-load-suffixes)))))
943 (defun file-remote-p (file &optional identification connected
)
944 "Test whether FILE specifies a location on a remote system.
945 A file is considered remote if accessing it is likely to
946 be slower or less reliable than accessing local files.
948 `file-remote-p' never opens a new remote connection. It can
949 only reuse a connection that is already open.
951 Return nil or a string identifying the remote connection
952 \(ideally a prefix of FILE). Return nil if FILE is a relative
955 When IDENTIFICATION is nil, the returned string is a complete
956 remote identifier: with components method, user, and host. The
957 components are those present in FILE, with defaults filled in for
958 any that are missing.
960 IDENTIFICATION can specify which part of the identification to
961 return. IDENTIFICATION can be the symbol `method', `user',
962 `host', or `localname'. Any other value is handled like nil and
963 means to return the complete identification. The string returned
964 for IDENTIFICATION `localname' can differ depending on whether
965 there is an existing connection.
967 If CONNECTED is non-nil, return an identification only if FILE is
968 located on a remote system and a connection is established to
971 Tip: You can use this expansion of remote identifier components
972 to derive a new remote file name from an existing one. For
973 example, if FILE is \"/sudo::/path/to/file\" then
975 \(concat \(file-remote-p FILE) \"/bin/sh\")
977 returns a remote file name for file \"/bin/sh\" that has the
978 same remote identifier as FILE but expanded; a name such as
979 \"/sudo:root@myhost:/bin/sh\"."
980 (let ((handler (find-file-name-handler file
'file-remote-p
)))
982 (funcall handler
'file-remote-p file identification connected
)
985 (defcustom remote-file-name-inhibit-cache
10
986 "Whether to use the remote file-name cache for read access.
987 When `nil', never expire cached values (caution)
988 When `t', never use the cache (safe, but may be slow)
989 A number means use cached values for that amount of seconds since caching.
991 The attributes of remote files are cached for better performance.
992 If they are changed outside of Emacs's control, the cached values
993 become invalid, and must be reread. If you are sure that nothing
994 other than Emacs changes the files, you can set this variable to `nil'.
996 If a remote file is checked regularly, it might be a good idea to
997 let-bind this variable to a value less than the interval between
998 consecutive checks. For example:
1000 (defun display-time-file-nonempty-p (file)
1001 (let ((remote-file-name-inhibit-cache (- display-time-interval 5)))
1002 (and (file-exists-p file)
1003 (< 0 (nth 7 (file-attributes (file-chase-links file)))))))"
1007 (const :tag
"Do not inhibit file name cache" nil
)
1008 (const :tag
"Do not use file name cache" t
)
1009 (integer :tag
"Do not use file name cache"
1010 :format
"Do not use file name cache older then %v seconds"
1013 (defun file-local-copy (file)
1014 "Copy the file FILE into a temporary file on this machine.
1015 Returns the name of the local copy, or nil, if FILE is directly
1017 ;; This formerly had an optional BUFFER argument that wasn't used by
1019 (let ((handler (find-file-name-handler file
'file-local-copy
)))
1021 (funcall handler
'file-local-copy file
)
1024 (defun file-truename (filename &optional counter prev-dirs
)
1025 "Return the truename of FILENAME.
1026 If FILENAME is not absolute, first expands it against `default-directory'.
1027 The truename of a file name is found by chasing symbolic links
1028 both at the level of the file and at the level of the directories
1029 containing it, until no links are left at any level.
1031 \(fn FILENAME)" ;; Don't document the optional arguments.
1032 ;; COUNTER and PREV-DIRS are only used in recursive calls.
1033 ;; COUNTER can be a cons cell whose car is the count of how many
1034 ;; more links to chase before getting an error.
1035 ;; PREV-DIRS can be a cons cell whose car is an alist
1036 ;; of truenames we've just recently computed.
1037 (cond ((or (string= filename
"") (string= filename
"~"))
1038 (setq filename
(expand-file-name filename
))
1039 (if (string= filename
"")
1040 (setq filename
"/")))
1041 ((and (string= (substring filename
0 1) "~")
1042 (string-match "~[^/]*/?" filename
))
1044 (substring filename
0 (match-end 0)))
1045 (rest (substring filename
(match-end 0))))
1046 (setq filename
(concat (expand-file-name first-part
) rest
)))))
1048 (or counter
(setq counter
(list 100)))
1050 ;; For speed, remove the ange-ftp completion handler from the list.
1051 ;; We know it's not needed here.
1052 ;; For even more speed, do this only on the outermost call.
1053 (file-name-handler-alist
1054 (if prev-dirs file-name-handler-alist
1055 (let ((tem (copy-sequence file-name-handler-alist
)))
1056 (delq (rassq 'ange-ftp-completion-hook-function tem
) tem
)))))
1057 (or prev-dirs
(setq prev-dirs
(list nil
)))
1059 ;; andrewi@harlequin.co.uk - none of the following code (except for
1060 ;; invoking the file-name handler) currently applies on Windows
1061 ;; (ie. there are no native symlinks), but there is an issue with
1062 ;; case differences being ignored by the OS, and short "8.3 DOS"
1063 ;; name aliases existing for all files. (The short names are not
1064 ;; reported by directory-files, but can be used to refer to files.)
1065 ;; It seems appropriate for file-truename to resolve these issues in
1066 ;; the most natural way, which on Windows is to call the function
1067 ;; `w32-long-file-name' - this returns the exact name of a file as
1068 ;; it is stored on disk (expanding short name aliases with the full
1069 ;; name in the process).
1070 (if (eq system-type
'windows-nt
)
1071 (let ((handler (find-file-name-handler filename
'file-truename
)))
1072 ;; For file name that has a special handler, call handler.
1073 ;; This is so that ange-ftp can save time by doing a no-op.
1075 (setq filename
(funcall handler
'file-truename filename
))
1076 ;; If filename contains a wildcard, newname will be the old name.
1077 (unless (string-match "[[*?]" filename
)
1078 ;; If filename exists, use the long name. If it doesn't exist,
1079 ;; drill down until we find a directory that exists, and use
1080 ;; the long name of that, with the extra non-existent path
1081 ;; components concatenated.
1082 (let ((longname (w32-long-file-name filename
))
1085 (setq filename longname
)
1086 ;; Include the preceding directory separator in the missing
1087 ;; part so subsequent recursion on the rest works.
1088 (setq missing
(concat "/" (file-name-nondirectory filename
)))
1089 (let ((length (length missing
)))
1091 (if (> length
(length filename
))
1093 (substring filename
0 (- length
)))))
1094 (setq filename
(concat (file-truename rest
) missing
))))))
1097 ;; If this file directly leads to a link, process that iteratively
1098 ;; so that we don't use lots of stack.
1100 (setcar counter
(1- (car counter
)))
1101 (if (< (car counter
) 0)
1102 (error "Apparent cycle of symbolic links for %s" filename
))
1103 (let ((handler (find-file-name-handler filename
'file-truename
)))
1104 ;; For file name that has a special handler, call handler.
1105 ;; This is so that ange-ftp can save time by doing a no-op.
1107 (setq filename
(funcall handler
'file-truename filename
)
1109 (let ((dir (or (file-name-directory filename
) default-directory
))
1111 ;; Get the truename of the directory.
1112 (setq dirfile
(directory-file-name dir
))
1113 ;; If these are equal, we have the (or a) root directory.
1114 (or (string= dir dirfile
)
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 (filename &optional wildcards
)
1446 "Edit file FILENAME but don't allow changes.
1447 Like \\[find-file], but marks buffer as read-only.
1448 Use \\[toggle-read-only] to permit editing."
1450 (find-file-read-args "Find file read-only: "
1451 (confirm-nonexistent-file-or-buffer)))
1452 (unless (or (and wildcards find-file-wildcards
1453 (not (string-match "\\`/:" filename
))
1454 (string-match "[[*?]" filename
))
1455 (file-exists-p filename
))
1456 (error "%s does not exist" filename
))
1457 (let ((value (find-file filename wildcards
)))
1458 (mapc (lambda (b) (with-current-buffer b
(toggle-read-only 1)))
1459 (if (listp value
) value
(list value
)))
1462 (defun find-file-read-only-other-window (filename &optional wildcards
)
1463 "Edit file FILENAME in another window but don't allow changes.
1464 Like \\[find-file-other-window], but marks buffer as read-only.
1465 Use \\[toggle-read-only] to permit editing."
1467 (find-file-read-args "Find file read-only other window: "
1468 (confirm-nonexistent-file-or-buffer)))
1469 (unless (or (and wildcards find-file-wildcards
1470 (not (string-match "\\`/:" filename
))
1471 (string-match "[[*?]" filename
))
1472 (file-exists-p filename
))
1473 (error "%s does not exist" filename
))
1474 (let ((value (find-file-other-window filename wildcards
)))
1475 (mapc (lambda (b) (with-current-buffer b
(toggle-read-only 1)))
1476 (if (listp value
) value
(list value
)))
1479 (defun find-file-read-only-other-frame (filename &optional wildcards
)
1480 "Edit file FILENAME in another frame but don't allow changes.
1481 Like \\[find-file-other-frame], but marks buffer as read-only.
1482 Use \\[toggle-read-only] to permit editing."
1484 (find-file-read-args "Find file read-only other frame: "
1485 (confirm-nonexistent-file-or-buffer)))
1486 (unless (or (and wildcards find-file-wildcards
1487 (not (string-match "\\`/:" filename
))
1488 (string-match "[[*?]" filename
))
1489 (file-exists-p filename
))
1490 (error "%s does not exist" filename
))
1491 (let ((value (find-file-other-frame filename wildcards
)))
1492 (mapc (lambda (b) (with-current-buffer b
(toggle-read-only 1)))
1493 (if (listp value
) value
(list value
)))
1496 (defun find-alternate-file-other-window (filename &optional wildcards
)
1497 "Find file FILENAME as a replacement for the file in the next window.
1498 This command does not select that window.
1500 See \\[find-file] for the possible forms of the FILENAME argument.
1502 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1503 expand wildcards (if any) and replace the file with multiple files."
1505 (save-selected-window
1507 (let ((file buffer-file-name
)
1511 (setq file-name
(file-name-nondirectory file
)
1512 file-dir
(file-name-directory file
)))
1513 (list (read-file-name
1514 "Find alternate file: " file-dir nil
1515 (confirm-nonexistent-file-or-buffer) file-name
)
1518 (find-file-other-window filename wildcards
)
1519 (save-selected-window
1521 (find-alternate-file filename wildcards
))))
1523 (defvar kill-buffer-hook
) ; from buffer.c
1525 (defun find-alternate-file (filename &optional wildcards
)
1526 "Find file FILENAME, select its buffer, kill previous buffer.
1527 If the current buffer now contains an empty file that you just visited
1528 \(presumably by mistake), use this command to visit the file you really want.
1530 See \\[find-file] for the possible forms of the FILENAME argument.
1532 Interactively, or if WILDCARDS is non-nil in a call from Lisp,
1533 expand wildcards (if any) and replace the file with multiple files.
1535 If the current buffer is an indirect buffer, or the base buffer
1536 for one or more indirect buffers, the other buffer(s) are not
1539 (let ((file buffer-file-name
)
1543 (setq file-name
(file-name-nondirectory file
)
1544 file-dir
(file-name-directory file
)))
1545 (list (read-file-name
1546 "Find alternate file: " file-dir nil
1547 (confirm-nonexistent-file-or-buffer) file-name
)
1549 (unless (run-hook-with-args-until-failure 'kill-buffer-query-functions
)
1551 (when (and (buffer-modified-p) buffer-file-name
)
1552 (if (yes-or-no-p (format "Buffer %s is modified; save it first? "
1555 (unless (yes-or-no-p "Kill and replace the buffer without saving it? ")
1556 (error "Aborted"))))
1557 (let ((obuf (current-buffer))
1558 (ofile buffer-file-name
)
1559 (onum buffer-file-number
)
1560 (odir dired-directory
)
1561 (otrue buffer-file-truename
)
1562 (oname (buffer-name)))
1563 ;; Run `kill-buffer-hook' here. It needs to happen before
1564 ;; variables like `buffer-file-name' etc are set to nil below,
1565 ;; because some of the hooks that could be invoked
1566 ;; (e.g., `save-place-to-alist') depend on those variables.
1568 ;; Note that `kill-buffer-hook' is not what queries whether to
1569 ;; save a modified buffer visiting a file. Rather, `kill-buffer'
1570 ;; asks that itself. Thus, there's no need to temporarily do
1571 ;; `(set-buffer-modified-p nil)' before running this hook.
1572 (run-hooks 'kill-buffer-hook
)
1573 ;; Okay, now we can end-of-life the old buffer.
1574 (if (get-buffer " **lose**")
1575 (kill-buffer " **lose**"))
1576 (rename-buffer " **lose**")
1580 ;; This prevents us from finding the same buffer
1581 ;; if we specified the same file again.
1582 (setq buffer-file-name nil
)
1583 (setq buffer-file-number nil
)
1584 (setq buffer-file-truename nil
)
1585 ;; Likewise for dired buffers.
1586 (setq dired-directory nil
)
1587 (find-file filename wildcards
))
1588 (when (eq obuf
(current-buffer))
1589 ;; This executes if find-file gets an error
1590 ;; and does not really find anything.
1591 ;; We put things back as they were.
1592 ;; If find-file actually finds something, we kill obuf below.
1593 (setq buffer-file-name ofile
)
1594 (setq buffer-file-number onum
)
1595 (setq buffer-file-truename otrue
)
1596 (setq dired-directory odir
)
1598 (rename-buffer oname
)))
1599 (unless (eq (current-buffer) obuf
)
1600 (with-current-buffer obuf
1601 ;; We already ran these; don't run them again.
1602 (let (kill-buffer-query-functions kill-buffer-hook
)
1603 (kill-buffer obuf
))))))
1605 (defun create-file-buffer (filename)
1606 "Create a suitably named buffer for visiting FILENAME, and return it.
1607 FILENAME (sans directory) is used unchanged if that name is free;
1608 otherwise a string <2> or <3> or ... is appended to get an unused name.
1609 Spaces at the start of FILENAME (sans directory) are removed."
1610 (let ((lastname (file-name-nondirectory filename
)))
1611 (if (string= lastname
"")
1612 (setq lastname filename
))
1614 (string-match "^ *\\(.*\\)" lastname
)
1615 (generate-new-buffer (match-string 1 lastname
)))))
1617 (defun generate-new-buffer (name)
1618 "Create and return a buffer with a name based on NAME.
1619 Choose the buffer's name using `generate-new-buffer-name'."
1620 (get-buffer-create (generate-new-buffer-name name
)))
1622 (defcustom automount-dir-prefix
(purecopy "^/tmp_mnt/")
1623 "Regexp to match the automounter prefix in a directory name."
1627 (defvar abbreviated-home-dir nil
1628 "The user's homedir abbreviated according to `directory-abbrev-alist'.")
1630 (defun abbreviate-file-name (filename)
1631 "Return a version of FILENAME shortened using `directory-abbrev-alist'.
1632 This also substitutes \"~\" for the user's home directory (unless the
1633 home directory is a root directory) and removes automounter prefixes
1634 \(see the variable `automount-dir-prefix')."
1635 ;; Get rid of the prefixes added by the automounter.
1637 (if (and automount-dir-prefix
1638 (string-match automount-dir-prefix filename
)
1639 (file-exists-p (file-name-directory
1640 (substring filename
(1- (match-end 0))))))
1641 (setq filename
(substring filename
(1- (match-end 0)))))
1642 ;; Avoid treating /home/foo as /home/Foo during `~' substitution.
1643 ;; To fix this right, we need a `file-name-case-sensitive-p'
1644 ;; function, but we don't have that yet, so just guess.
1645 (let ((case-fold-search
1646 (memq system-type
'(ms-dos windows-nt darwin cygwin
))))
1647 ;; If any elt of directory-abbrev-alist matches this name,
1648 ;; abbreviate accordingly.
1649 (dolist (dir-abbrev directory-abbrev-alist
)
1650 (if (string-match (car dir-abbrev
) filename
)
1652 (concat (cdr dir-abbrev
)
1653 (substring filename
(match-end 0))))))
1654 ;; Compute and save the abbreviated homedir name.
1655 ;; We defer computing this until the first time it's needed, to
1656 ;; give time for directory-abbrev-alist to be set properly.
1657 ;; We include a slash at the end, to avoid spurious matches
1658 ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
1659 (or abbreviated-home-dir
1660 (setq abbreviated-home-dir
1661 (let ((abbreviated-home-dir "$foo"))
1662 (concat "\\`" (abbreviate-file-name (expand-file-name "~"))
1665 ;; If FILENAME starts with the abbreviated homedir,
1666 ;; make it start with `~' instead.
1667 (if (and (string-match abbreviated-home-dir filename
)
1668 ;; If the home dir is just /, don't change it.
1669 (not (and (= (match-end 0) 1)
1670 (= (aref filename
0) ?
/)))
1671 ;; MS-DOS root directories can come with a drive letter;
1672 ;; Novell Netware allows drive letters beyond `Z:'.
1673 (not (and (memq system-type
'(ms-dos windows-nt cygwin
))
1675 (string-match "^[a-zA-`]:/$" filename
)))))
1678 (match-string 1 filename
)
1679 (substring filename
(match-end 0)))))
1682 (defun find-buffer-visiting (filename &optional predicate
)
1683 "Return the buffer visiting file FILENAME (a string).
1684 This is like `get-file-buffer', except that it checks for any buffer
1685 visiting the same file, possibly under a different name.
1686 If PREDICATE is non-nil, only buffers satisfying it are eligible,
1687 and others are ignored.
1688 If there is no such live buffer, return nil."
1689 (let ((predicate (or predicate
#'identity
))
1690 (truename (abbreviate-file-name (file-truename filename
))))
1691 (or (let ((buf (get-file-buffer filename
)))
1692 (when (and buf
(funcall predicate buf
)) buf
))
1693 (let ((list (buffer-list)) found
)
1694 (while (and (not found
) list
)
1695 (with-current-buffer (car list
)
1696 (if (and buffer-file-name
1697 (string= buffer-file-truename truename
)
1698 (funcall predicate
(current-buffer)))
1699 (setq found
(car list
))))
1700 (setq list
(cdr list
)))
1702 (let* ((attributes (file-attributes truename
))
1703 (number (nthcdr 10 attributes
))
1704 (list (buffer-list)) found
)
1705 (and buffer-file-numbers-unique
1706 (car-safe number
) ;Make sure the inode is not just nil.
1707 (while (and (not found
) list
)
1708 (with-current-buffer (car list
)
1709 (if (and buffer-file-name
1710 (equal buffer-file-number number
)
1711 ;; Verify this buffer's file number
1712 ;; still belongs to its file.
1713 (file-exists-p buffer-file-name
)
1714 (equal (file-attributes buffer-file-truename
)
1716 (funcall predicate
(current-buffer)))
1717 (setq found
(car list
))))
1718 (setq list
(cdr list
))))
1721 (defcustom find-file-wildcards t
1722 "Non-nil means file-visiting commands should handle wildcards.
1723 For example, if you specify `*.c', that would visit all the files
1724 whose names match the pattern."
1729 (defcustom find-file-suppress-same-file-warnings nil
1730 "Non-nil means suppress warning messages for symlinked files.
1731 When nil, Emacs prints a warning when visiting a file that is already
1732 visited, but with a different name. Setting this option to t
1733 suppresses this warning."
1738 (defcustom large-file-warning-threshold
10000000
1739 "Maximum size of file above which a confirmation is requested.
1740 When nil, never request confirmation."
1744 :type
'(choice integer
(const :tag
"Never request confirmation" nil
)))
1746 (defun abort-if-file-too-large (size op-type filename
)
1747 "If file SIZE larger than `large-file-warning-threshold', allow user to abort.
1748 OP-TYPE specifies the file operation being performed (for message to user)."
1749 (when (and large-file-warning-threshold size
1750 (> size large-file-warning-threshold
)
1751 (not (y-or-n-p (format "File %s is large (%dMB), really %s? "
1752 (file-name-nondirectory filename
)
1753 (/ size
1048576) op-type
))))
1756 (defun find-file-noselect (filename &optional nowarn rawfile wildcards
)
1757 "Read file FILENAME into a buffer and return the buffer.
1758 If a buffer exists visiting FILENAME, return that one, but
1759 verify that the file has not changed since visited or saved.
1760 The buffer is not selected, just returned to the caller.
1761 Optional second arg NOWARN non-nil means suppress any warning messages.
1762 Optional third arg RAWFILE non-nil means the file is read literally.
1763 Optional fourth arg WILDCARDS non-nil means do wildcard processing
1764 and visit all the matching files. When wildcards are actually
1765 used and expanded, return a list of buffers that are visiting
1768 (abbreviate-file-name
1769 (expand-file-name filename
)))
1770 (if (file-directory-p filename
)
1771 (or (and find-file-run-dired
1772 (run-hook-with-args-until-success
1773 'find-directory-functions
1774 (if find-file-visit-truename
1775 (abbreviate-file-name (file-truename filename
))
1777 (error "%s is a directory" filename
))
1780 (not (string-match "\\`/:" filename
))
1781 (string-match "[[*?]" filename
))
1782 (let ((files (condition-case nil
1783 (file-expand-wildcards filename t
)
1784 (error (list filename
))))
1785 (find-file-wildcards nil
))
1787 (find-file-noselect filename
)
1788 (mapcar #'find-file-noselect files
)))
1789 (let* ((buf (get-file-buffer filename
))
1790 (truename (abbreviate-file-name (file-truename filename
)))
1791 (attributes (file-attributes truename
))
1792 (number (nthcdr 10 attributes
))
1793 ;; Find any buffer for a file which has same truename.
1794 (other (and (not buf
) (find-buffer-visiting filename
))))
1795 ;; Let user know if there is a buffer with the same truename.
1799 find-file-suppress-same-file-warnings
1800 (string-equal filename
(buffer-file-name other
))
1801 (message "%s and %s are the same file"
1802 filename
(buffer-file-name other
)))
1803 ;; Optionally also find that buffer.
1804 (if (or find-file-existing-other-name find-file-visit-truename
)
1806 ;; Check to see if the file looks uncommonly large.
1807 (when (not (or buf nowarn
))
1808 (abort-if-file-too-large (nth 7 attributes
) "open" filename
))
1810 ;; We are using an existing buffer.
1813 (verify-visited-file-modtime buf
)
1814 (cond ((not (file-exists-p filename
))
1815 (setq nonexistent t
)
1816 (message "File %s no longer exists!" filename
))
1817 ;; Certain files should be reverted automatically
1818 ;; if they have changed on disk and not in the buffer.
1819 ((and (not (buffer-modified-p buf
))
1820 (let ((tail revert-without-query
)
1823 (if (string-match (car tail
) filename
)
1825 (setq tail
(cdr tail
)))
1827 (with-current-buffer buf
1828 (message "Reverting file %s..." filename
)
1830 (message "Reverting file %s...done" filename
)))
1832 (if (string= (file-name-nondirectory filename
)
1835 (if (buffer-modified-p buf
)
1836 "File %s changed on disk. Discard your edits? "
1837 "File %s changed on disk. Reread from disk? ")
1838 (file-name-nondirectory filename
))
1840 (if (buffer-modified-p buf
)
1841 "File %s changed on disk. Discard your edits in %s? "
1842 "File %s changed on disk. Reread from disk into %s? ")
1843 (file-name-nondirectory filename
)
1844 (buffer-name buf
))))
1845 (with-current-buffer buf
1846 (revert-buffer t t
)))))
1847 (with-current-buffer buf
1849 ;; Check if a formerly read-only file has become
1850 ;; writable and vice versa, but if the buffer agrees
1851 ;; with the new state of the file, that is ok too.
1852 (let ((read-only (not (file-writable-p buffer-file-name
))))
1853 (unless (or nonexistent
1854 (eq read-only buffer-file-read-only
)
1855 (eq read-only buffer-read-only
))
1858 (format "File %s is %s on disk. Change buffer mode? "
1860 (if read-only
"read-only" "writable"))))
1861 (y-or-n-p question
)))
1862 (setq buffer-read-only read-only
)))
1863 (setq buffer-file-read-only read-only
))
1865 (when (and (not (eq (not (null rawfile
))
1866 (not (null find-file-literally
))))
1868 ;; It is confusing to ask whether to visit
1869 ;; non-literally if they have the file in
1870 ;; hexl-mode or image-mode.
1871 (not (memq major-mode
'(hexl-mode image-mode
))))
1872 (if (buffer-modified-p)
1876 "The file %s is already visited normally,
1877 and you have edited the buffer. Now you have asked to visit it literally,
1878 meaning no coding system handling, format conversion, or local variables.
1879 Emacs can only visit a file in one way at a time.
1881 Do you want to save the file, and visit it literally instead? "
1882 "The file %s is already visited literally,
1883 meaning no coding system handling, format conversion, or local variables.
1884 You have edited the buffer. Now you have asked to visit the file normally,
1885 but Emacs can only visit a file in one way at a time.
1887 Do you want to save the file, and visit it normally instead? ")
1888 (file-name-nondirectory filename
)))
1891 (find-file-noselect-1 buf filename nowarn
1892 rawfile truename number
))
1897 Do you want to discard your changes, and visit the file literally now? "
1899 Do you want to discard your changes, and visit the file normally now? ")))
1900 (find-file-noselect-1 buf filename nowarn
1901 rawfile truename number
)
1902 (error (if rawfile
"File already visited non-literally"
1903 "File already visited literally"))))
1907 "The file %s is already visited normally.
1908 You have asked to visit it literally,
1909 meaning no coding system decoding, format conversion, or local variables.
1910 But Emacs can only visit a file in one way at a time.
1912 Do you want to revisit the file literally now? "
1913 "The file %s is already visited literally,
1914 meaning no coding system decoding, format conversion, or local variables.
1915 You have asked to visit it normally,
1916 but Emacs can only visit a file in one way at a time.
1918 Do you want to revisit the file normally now? ")
1919 (file-name-nondirectory filename
)))
1920 (find-file-noselect-1 buf filename nowarn
1921 rawfile truename number
)
1922 (error (if rawfile
"File already visited non-literally"
1923 "File already visited literally"))))))
1924 ;; Return the buffer we are using.
1926 ;; Create a new buffer.
1927 (setq buf
(create-file-buffer filename
))
1928 ;; find-file-noselect-1 may use a different buffer.
1929 (find-file-noselect-1 buf filename nowarn
1930 rawfile truename number
))))))
1932 (defun find-file-noselect-1 (buf filename nowarn rawfile truename number
)
1934 (with-current-buffer buf
1935 (kill-local-variable 'find-file-literally
)
1936 ;; Needed in case we are re-visiting the file with a different
1937 ;; text representation.
1938 (kill-local-variable 'buffer-file-coding-system
)
1939 (kill-local-variable 'cursor-type
)
1940 (let ((inhibit-read-only t
))
1942 (and (default-value 'enable-multibyte-characters
)
1944 (set-buffer-multibyte t
))
1947 (let ((inhibit-read-only t
))
1948 (insert-file-contents-literally 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 ;; Unconditionally set error
1958 (let ((inhibit-read-only t
))
1959 (insert-file-contents filename t
))
1961 (when (and (file-exists-p filename
)
1962 (not (file-readable-p filename
)))
1964 (signal 'file-error
(list "File is not readable"
1966 ;; Run find-file-not-found-functions until one returns non-nil.
1967 (or (run-hook-with-args-until-success 'find-file-not-found-functions
)
1968 ;; If they fail too, set error.
1970 ;; Record the file's truename, and maybe use that as visited name.
1971 (if (equal filename buffer-file-name
)
1972 (setq buffer-file-truename truename
)
1973 (setq buffer-file-truename
1974 (abbreviate-file-name (file-truename buffer-file-name
))))
1975 (setq buffer-file-number number
)
1976 (if find-file-visit-truename
1977 (setq buffer-file-name
(expand-file-name buffer-file-truename
)))
1978 ;; Set buffer's default directory to that of the file.
1979 (setq default-directory
(file-name-directory buffer-file-name
))
1980 ;; Turn off backup files for certain file names. Since
1981 ;; this is a permanent local, the major mode won't eliminate it.
1982 (and backup-enable-predicate
1983 (not (funcall backup-enable-predicate buffer-file-name
))
1985 (make-local-variable 'backup-inhibited
)
1986 (setq backup-inhibited t
)))
1989 (set-buffer-multibyte nil
)
1990 (setq buffer-file-coding-system
'no-conversion
)
1991 (set-buffer-major-mode buf
)
1992 (make-local-variable 'find-file-literally
)
1993 (setq find-file-literally t
))
1994 (after-find-file error
(not nowarn
)))
1997 (defun insert-file-contents-literally (filename &optional visit beg end replace
)
1998 "Like `insert-file-contents', but only reads in the file literally.
1999 A buffer may be modified in several ways after reading into the buffer,
2000 to Emacs features such as format decoding, character code
2001 conversion, `find-file-hook', automatic uncompression, etc.
2003 This function ensures that none of these modifications will take place."
2004 (let ((format-alist nil
)
2005 (after-insert-file-functions nil
)
2006 (coding-system-for-read 'no-conversion
)
2007 (coding-system-for-write 'no-conversion
)
2008 (find-buffer-file-type-function
2009 (if (fboundp 'find-buffer-file-type
)
2010 (symbol-function 'find-buffer-file-type
)
2012 (inhibit-file-name-handlers
2013 (append '(jka-compr-handler image-file-handler epa-file-handler
)
2014 inhibit-file-name-handlers
))
2015 (inhibit-file-name-operation 'insert-file-contents
))
2018 (fset 'find-buffer-file-type
(lambda (_filename) t
))
2019 (insert-file-contents filename visit beg end replace
))
2020 (if find-buffer-file-type-function
2021 (fset 'find-buffer-file-type find-buffer-file-type-function
)
2022 (fmakunbound 'find-buffer-file-type
)))))
2024 (defun insert-file-1 (filename insert-func
)
2025 (if (file-directory-p filename
)
2026 (signal 'file-error
(list "Opening input file" "file is a directory"
2028 ;; Check whether the file is uncommonly large
2029 (abort-if-file-too-large (nth 7 (file-attributes filename
)) "insert" filename
)
2030 (let* ((buffer (find-buffer-visiting (abbreviate-file-name (file-truename filename
))
2031 #'buffer-modified-p
))
2032 (tem (funcall insert-func filename
)))
2033 (push-mark (+ (point) (car (cdr tem
))))
2035 (message "File %s already visited and modified in buffer %s"
2036 filename
(buffer-name buffer
)))))
2038 (defun insert-file-literally (filename)
2039 "Insert contents of file FILENAME into buffer after point with no conversion.
2041 This function is meant for the user to run interactively.
2042 Don't call it from programs! Use `insert-file-contents-literally' instead.
2043 \(Its calling sequence is different; see its documentation)."
2044 (interactive "*fInsert file literally: ")
2045 (insert-file-1 filename
#'insert-file-contents-literally
))
2047 (defvar find-file-literally nil
2048 "Non-nil if this buffer was made by `find-file-literally' or equivalent.
2049 This has the `permanent-local' property, which takes effect if you
2050 make the variable buffer-local.")
2051 (put 'find-file-literally
'permanent-local t
)
2053 (defun find-file-literally (filename)
2054 "Visit file FILENAME with no conversion of any kind.
2055 Format conversion and character code conversion are both disabled,
2056 and multibyte characters are disabled in the resulting buffer.
2057 The major mode used is Fundamental mode regardless of the file name,
2058 and local variable specifications in the file are ignored.
2059 Automatic uncompression and adding a newline at the end of the
2060 file due to `require-final-newline' is also disabled.
2062 You cannot absolutely rely on this function to result in
2063 visiting the file literally. If Emacs already has a buffer
2064 which is visiting the file, you get the existing buffer,
2065 regardless of whether it was created literally or not.
2067 In a Lisp program, if you want to be sure of accessing a file's
2068 contents literally, you should create a temporary buffer and then read
2069 the file contents into it using `insert-file-contents-literally'."
2071 (list (read-file-name
2072 "Find file literally: " nil default-directory
2073 (confirm-nonexistent-file-or-buffer))))
2074 (switch-to-buffer (find-file-noselect filename nil t
)))
2076 (defun after-find-file (&optional error warn noauto
2077 _after-find-file-from-revert-buffer
2079 "Called after finding a file and by the default revert function.
2080 Sets buffer mode, parses local variables.
2081 Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
2082 error in reading the file. WARN non-nil means warn if there
2083 exists an auto-save file more recent than the visited file.
2084 NOAUTO means don't mess with auto-save mode.
2085 Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER is ignored
2086 \(see `revert-buffer-in-progress-p' for similar functionality).
2087 Fifth arg NOMODES non-nil means don't alter the file's modes.
2088 Finishes by calling the functions in `find-file-hook'
2089 unless NOMODES is non-nil."
2090 (setq buffer-read-only
(not (file-writable-p buffer-file-name
)))
2097 ((and error
(file-attributes buffer-file-name
))
2098 (setq buffer-read-only t
)
2099 (if (and (file-symlink-p buffer-file-name
)
2101 (file-chase-links buffer-file-name
))))
2102 "Symbolic link that points to nonexistent file"
2103 "File exists, but cannot be read"))
2104 ((not buffer-read-only
)
2106 ;; No need to warn if buffer is auto-saved
2107 ;; under the name of the visited file.
2108 (not (and buffer-file-name
2109 auto-save-visited-file-name
))
2110 (file-newer-than-file-p (or buffer-auto-save-file-name
2111 (make-auto-save-file-name))
2113 (format "%s has auto save data; consider M-x recover-this-file"
2114 (file-name-nondirectory buffer-file-name
))
2115 (setq not-serious t
)
2116 (if error
"(New file)" nil
)))
2118 (setq not-serious t
)
2119 "Note: file is write protected")
2120 ((file-attributes (directory-file-name default-directory
))
2121 "File not found and directory write-protected")
2122 ((file-exists-p (file-name-directory buffer-file-name
))
2123 (setq buffer-read-only nil
))
2125 (setq buffer-read-only nil
)
2126 "Use M-x make-directory RET RET to create the directory and its parents"))))
2129 (or not-serious
(sit-for 1 t
))))
2130 (when (and auto-save-default
(not noauto
))
2131 (auto-save-mode 1)))
2132 ;; Make people do a little extra work (C-x C-q)
2133 ;; before altering a backup file.
2134 (when (backup-file-name-p buffer-file-name
)
2135 (setq buffer-read-only t
))
2136 ;; When a file is marked read-only,
2137 ;; make the buffer read-only even if root is looking at it.
2138 (when (and (file-modes (buffer-file-name))
2139 (zerop (logand (file-modes (buffer-file-name)) #o222
)))
2140 (setq buffer-read-only t
))
2142 (when (and view-read-only view-mode
)
2143 (view-mode-disable))
2145 ;; If requested, add a newline at the end of the file.
2146 (and (memq require-final-newline
'(visit visit-save
))
2147 (> (point-max) (point-min))
2148 (/= (char-after (1- (point-max))) ?
\n)
2149 (not (and (eq selective-display t
)
2150 (= (char-after (1- (point-max))) ?
\r)))
2152 (goto-char (point-max))
2154 (when (and buffer-read-only
2156 (not (eq (get major-mode
'mode-class
) 'special
)))
2158 (run-hooks 'find-file-hook
)))
2160 (defmacro report-errors
(format &rest body
)
2161 "Eval BODY and turn any error into a FORMAT message.
2162 FORMAT can have a %s escape which will be replaced with the actual error.
2163 If `debug-on-error' is set, errors are not caught, so that you can
2165 Avoid using a large BODY since it is duplicated."
2166 (declare (debug t
) (indent 1))
2171 (error (message ,format
(prin1-to-string err
))))))
2173 (defun normal-mode (&optional find-file
)
2174 "Choose the major mode for this buffer automatically.
2175 Also sets up any specified local variables of the file.
2176 Uses the visited file name, the -*- line, and the local variables spec.
2178 This function is called automatically from `find-file'. In that case,
2179 we may set up the file-specified mode and local variables,
2180 depending on the value of `enable-local-variables'.
2181 In addition, if `local-enable-local-variables' is nil, we do
2182 not set local variables (though we do notice a mode specified with -*-.)
2184 `enable-local-variables' is ignored if you run `normal-mode' interactively,
2185 or from Lisp without specifying the optional argument FIND-FILE;
2186 in that case, this function acts as if `enable-local-variables' were t."
2188 (funcall (or (default-value 'major-mode
) 'fundamental-mode
))
2189 (let ((enable-local-variables (or (not find-file
) enable-local-variables
)))
2190 ;; FIXME this is less efficient than it could be, since both
2191 ;; s-a-m and h-l-v may parse the same regions, looking for "mode:".
2192 (report-errors "File mode specification error: %s"
2194 (report-errors "File local-variables error: %s"
2195 (hack-local-variables)))
2196 ;; Turn font lock off and on, to make sure it takes account of
2197 ;; whatever file local variables are relevant to it.
2198 (when (and font-lock-mode
2199 ;; Font-lock-mode (now in font-core.el) can be ON when
2200 ;; font-lock.el still hasn't been loaded.
2201 (boundp 'font-lock-keywords
)
2202 (eq (car font-lock-keywords
) t
))
2203 (setq font-lock-keywords
(cadr font-lock-keywords
))
2206 (if (fboundp 'ucs-set-table-for-input
) ; don't lose when building
2207 (ucs-set-table-for-input)))
2209 (defcustom auto-mode-case-fold t
2210 "Non-nil means to try second pass through `auto-mode-alist'.
2211 This means that if the first case-sensitive search through the alist fails
2212 to find a matching major mode, a second case-insensitive search is made.
2213 On systems with case-insensitive file names, this variable is ignored,
2214 since only a single case-insensitive search through the alist is made."
2219 (defvar auto-mode-alist
2220 ;; Note: The entries for the modes defined in cc-mode.el (c-mode,
2221 ;; c++-mode, java-mode and more) are added through autoload
2222 ;; directives in that file. That way is discouraged since it
2223 ;; spreads out the definition of the initial value.
2226 (cons (purecopy (car elt
)) (cdr elt
)))
2227 `(;; do this first, so that .html.pl is Polish html, not Perl
2228 ("\\.[sx]?html?\\(\\.[a-zA-Z_]+\\)?\\'" . html-mode
)
2229 ("\\.svgz?\\'" . image-mode
)
2230 ("\\.svgz?\\'" . xml-mode
)
2231 ("\\.x[bp]m\\'" . image-mode
)
2232 ("\\.x[bp]m\\'" . c-mode
)
2233 ("\\.p[bpgn]m\\'" . image-mode
)
2234 ("\\.tiff?\\'" . image-mode
)
2235 ("\\.gif\\'" . image-mode
)
2236 ("\\.png\\'" . image-mode
)
2237 ("\\.jpe?g\\'" . image-mode
)
2238 ("\\.te?xt\\'" . text-mode
)
2239 ("\\.[tT]e[xX]\\'" . tex-mode
)
2240 ("\\.ins\\'" . tex-mode
) ;Installation files for TeX packages.
2241 ("\\.ltx\\'" . latex-mode
)
2242 ("\\.dtx\\'" . doctex-mode
)
2243 ("\\.org\\'" . org-mode
)
2244 ("\\.el\\'" . emacs-lisp-mode
)
2245 ("Project\\.ede\\'" . emacs-lisp-mode
)
2246 ("\\.\\(scm\\|stk\\|ss\\|sch\\)\\'" . scheme-mode
)
2247 ("\\.l\\'" . lisp-mode
)
2248 ("\\.li?sp\\'" . lisp-mode
)
2249 ("\\.[fF]\\'" . fortran-mode
)
2250 ("\\.for\\'" . fortran-mode
)
2251 ("\\.p\\'" . pascal-mode
)
2252 ("\\.pas\\'" . pascal-mode
)
2253 ("\\.\\(dpr\\|DPR\\)\\'" . delphi-mode
)
2254 ("\\.ad[abs]\\'" . ada-mode
)
2255 ("\\.ad[bs].dg\\'" . ada-mode
)
2256 ("\\.\\([pP]\\([Llm]\\|erl\\|od\\)\\|al\\)\\'" . perl-mode
)
2257 ("Imakefile\\'" . makefile-imake-mode
)
2258 ("Makeppfile\\(?:\\.mk\\)?\\'" . makefile-makepp-mode
) ; Put this before .mk
2259 ("\\.makepp\\'" . makefile-makepp-mode
)
2260 ,@(if (memq system-type
'(berkeley-unix darwin
))
2261 '(("\\.mk\\'" . makefile-bsdmake-mode
)
2262 ("GNUmakefile\\'" . makefile-gmake-mode
)
2263 ("[Mm]akefile\\'" . makefile-bsdmake-mode
))
2264 '(("\\.mk\\'" . makefile-gmake-mode
) ; Might be any make, give Gnu the host advantage
2265 ("[Mm]akefile\\'" . makefile-gmake-mode
)))
2266 ("\\.am\\'" . makefile-automake-mode
)
2267 ;; Less common extensions come here
2268 ;; so more common ones above are found faster.
2269 ("\\.texinfo\\'" . texinfo-mode
)
2270 ("\\.te?xi\\'" . texinfo-mode
)
2271 ("\\.[sS]\\'" . asm-mode
)
2272 ("\\.asm\\'" . asm-mode
)
2273 ("\\.css\\'" . css-mode
)
2274 ("\\.mixal\\'" . mixal-mode
)
2275 ("\\.gcov\\'" . compilation-mode
)
2276 ;; Besides .gdbinit, gdb documents other names to be usable for init
2277 ;; files, cross-debuggers can use something like
2278 ;; .PROCESSORNAME-gdbinit so that the host and target gdbinit files
2279 ;; don't interfere with each other.
2280 ("/\\.[a-z0-9-]*gdbinit" . gdb-script-mode
)
2281 ("[cC]hange\\.?[lL]og?\\'" . change-log-mode
)
2282 ("[cC]hange[lL]og[-.][0-9]+\\'" . change-log-mode
)
2283 ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode
)
2284 ("\\.scm\\.[0-9]*\\'" . scheme-mode
)
2285 ("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode
)
2286 ("\\.bash\\'" . sh-mode
)
2287 ("\\(/\\|\\`\\)\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode
)
2288 ("\\(/\\|\\`\\)\\.\\(bash_logout\\|shrc\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode
)
2289 ("\\(/\\|\\`\\)\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode
)
2290 ("\\.m?spec\\'" . sh-mode
)
2291 ("\\.m[mes]\\'" . nroff-mode
)
2292 ("\\.man\\'" . nroff-mode
)
2293 ("\\.sty\\'" . latex-mode
)
2294 ("\\.cl[so]\\'" . latex-mode
) ;LaTeX 2e class option
2295 ("\\.bbl\\'" . latex-mode
)
2296 ("\\.bib\\'" . bibtex-mode
)
2297 ("\\.bst\\'" . bibtex-style-mode
)
2298 ("\\.sql\\'" . sql-mode
)
2299 ("\\.m[4c]\\'" . m4-mode
)
2300 ("\\.mf\\'" . metafont-mode
)
2301 ("\\.mp\\'" . metapost-mode
)
2302 ("\\.vhdl?\\'" . vhdl-mode
)
2303 ("\\.article\\'" . text-mode
)
2304 ("\\.letter\\'" . text-mode
)
2305 ("\\.i?tcl\\'" . tcl-mode
)
2306 ("\\.exp\\'" . tcl-mode
)
2307 ("\\.itk\\'" . tcl-mode
)
2308 ("\\.icn\\'" . icon-mode
)
2309 ("\\.sim\\'" . simula-mode
)
2310 ("\\.mss\\'" . scribe-mode
)
2311 ;; The Fortran standard does not say anything about file extensions.
2312 ;; .f90 was widely used for F90, now we seem to be trapped into
2313 ;; using a different extension for each language revision.
2314 ;; Anyway, the following extensions are supported by gfortran.
2315 ("\\.f9[05]\\'" . f90-mode
)
2316 ("\\.f0[38]\\'" . f90-mode
)
2317 ("\\.indent\\.pro\\'" . fundamental-mode
) ; to avoid idlwave-mode
2318 ("\\.\\(pro\\|PRO\\)\\'" . idlwave-mode
)
2319 ("\\.srt\\'" . srecode-template-mode
)
2320 ("\\.prolog\\'" . prolog-mode
)
2321 ("\\.tar\\'" . tar-mode
)
2322 ;; The list of archive file extensions should be in sync with
2323 ;; `auto-coding-alist' with `no-conversion' coding system.
2325 arc\\|zip\\|lzh\\|lha\\|zoo\\|[jew]ar\\|xpi\\|rar\\|7z\\|\
2326 ARC\\|ZIP\\|LZH\\|LHA\\|ZOO\\|[JEW]AR\\|XPI\\|RAR\\|7Z\\)\\'" . archive-mode
)
2327 ("\\.\\(sx[dmicw]\\|od[fgpst]\\|oxt\\)\\'" . archive-mode
) ;OpenOffice.org
2328 ("\\.\\(deb\\|[oi]pk\\)\\'" . archive-mode
) ; Debian/Opkg packages.
2329 ;; Mailer puts message to be edited in
2330 ;; /tmp/Re.... or Message
2331 ("\\`/tmp/Re" . text-mode
)
2332 ("/Message[0-9]*\\'" . text-mode
)
2333 ;; some news reader is reported to use this
2334 ("\\`/tmp/fol/" . text-mode
)
2335 ("\\.oak\\'" . scheme-mode
)
2336 ("\\.sgml?\\'" . sgml-mode
)
2337 ("\\.x[ms]l\\'" . xml-mode
)
2338 ("\\.dbk\\'" . xml-mode
)
2339 ("\\.dtd\\'" . sgml-mode
)
2340 ("\\.ds\\(ss\\)?l\\'" . dsssl-mode
)
2341 ("\\.js\\'" . js-mode
) ; javascript-mode would be better
2342 ("\\.json\\'" . js-mode
)
2343 ("\\.[ds]?vh?\\'" . verilog-mode
)
2344 ;; .emacs or .gnus or .viper following a directory delimiter in
2345 ;; Unix, MSDOG or VMS syntax.
2346 ("[]>:/\\]\\..*\\(emacs\\|gnus\\|viper\\)\\'" . emacs-lisp-mode
)
2347 ("\\`\\..*emacs\\'" . emacs-lisp-mode
)
2348 ;; _emacs following a directory delimiter
2350 ("[:/]_emacs\\'" . emacs-lisp-mode
)
2351 ("/crontab\\.X*[0-9]+\\'" . shell-script-mode
)
2352 ("\\.ml\\'" . lisp-mode
)
2353 ;; Linux-2.6.9 uses some different suffix for linker scripts:
2354 ;; "ld", "lds", "lds.S", "lds.in", "ld.script", and "ld.script.balo".
2355 ;; eCos uses "ld" and "ldi". Netbsd uses "ldscript.*".
2356 ("\\.ld[si]?\\'" . ld-script-mode
)
2357 ("ld\\.?script\\'" . ld-script-mode
)
2358 ;; .xs is also used for ld scripts, but seems to be more commonly
2359 ;; associated with Perl .xs files (C with Perl bindings). (Bug#7071)
2360 ("\\.xs\\'" . c-mode
)
2361 ;; Explained in binutils ld/genscripts.sh. Eg:
2362 ;; A .x script file is the default script.
2363 ;; A .xr script is for linking without relocation (-r flag). Etc.
2364 ("\\.x[abdsru]?[cnw]?\\'" . ld-script-mode
)
2365 ("\\.zone\\'" . dns-mode
)
2366 ("\\.soa\\'" . dns-mode
)
2367 ;; Common Lisp ASDF package system.
2368 ("\\.asd\\'" . lisp-mode
)
2369 ("\\.\\(asn\\|mib\\|smi\\)\\'" . snmp-mode
)
2370 ("\\.\\(as\\|mi\\|sm\\)2\\'" . snmpv2-mode
)
2371 ("\\.\\(diffs?\\|patch\\|rej\\)\\'" . diff-mode
)
2372 ("\\.\\(dif\\|pat\\)\\'" . diff-mode
) ; for MSDOG
2373 ("\\.[eE]?[pP][sS]\\'" . ps-mode
)
2374 ("\\.\\(?:PDF\\|DVI\\|OD[FGPST]\\|DOCX?\\|XLSX?\\|PPTX?\\|pdf\\|dvi\\|od[fgpst]\\|docx?\\|xlsx?\\|pptx?\\)\\'" . doc-view-mode-maybe
)
2375 ("configure\\.\\(ac\\|in\\)\\'" . autoconf-mode
)
2376 ("\\.s\\(v\\|iv\\|ieve\\)\\'" . sieve-mode
)
2377 ("BROWSE\\'" . ebrowse-tree-mode
)
2378 ("\\.ebrowse\\'" . ebrowse-tree-mode
)
2379 ("#\\*mail\\*" . mail-mode
)
2380 ("\\.g\\'" . antlr-mode
)
2381 ("\\.mod\\'" . m2-mode
)
2382 ("\\.ses\\'" . ses-mode
)
2383 ("\\.docbook\\'" . sgml-mode
)
2384 ("\\.com\\'" . dcl-mode
)
2385 ("/config\\.\\(?:bat\\|log\\)\\'" . fundamental-mode
)
2386 ;; Windows candidates may be opened case sensitively on Unix
2387 ("\\.\\(?:[iI][nN][iI]\\|[lL][sS][tT]\\|[rR][eE][gG]\\|[sS][yY][sS]\\)\\'" . conf-mode
)
2388 ("\\.\\(?:desktop\\|la\\)\\'" . conf-unix-mode
)
2389 ("\\.ppd\\'" . conf-ppd-mode
)
2390 ("java.+\\.conf\\'" . conf-javaprop-mode
)
2391 ("\\.properties\\(?:\\.[a-zA-Z0-9._-]+\\)?\\'" . conf-javaprop-mode
)
2392 ("\\`/etc/\\(?:DIR_COLORS\\|ethers\\|.?fstab\\|.*hosts\\|lesskey\\|login\\.?de\\(?:fs\\|vperm\\)\\|magic\\|mtab\\|pam\\.d/.*\\|permissions\\(?:\\.d/.+\\)?\\|protocols\\|rpc\\|services\\)\\'" . conf-space-mode
)
2393 ("\\`/etc/\\(?:acpid?/.+\\|aliases\\(?:\\.d/.+\\)?\\|default/.+\\|group-?\\|hosts\\..+\\|inittab\\|ksysguarddrc\\|opera6rc\\|passwd-?\\|shadow-?\\|sysconfig/.+\\)\\'" . conf-mode
)
2394 ;; ChangeLog.old etc. Other change-log-mode entries are above;
2395 ;; this has lower priority to avoid matching changelog.sgml etc.
2396 ("[cC]hange[lL]og[-.][-0-9a-z]+\\'" . change-log-mode
)
2397 ;; either user's dot-files or under /etc or some such
2398 ("/\\.?\\(?:gnokiirc\\|kde.*rc\\|mime\\.types\\|wgetrc\\)\\'" . conf-mode
)
2399 ;; alas not all ~/.*rc files are like this
2400 ("/\\.\\(?:enigma\\|gltron\\|gtk\\|hxplayer\\|net\\|neverball\\|qt/.+\\|realplayer\\|scummvm\\|sversion\\|sylpheed/.+\\|xmp\\)rc\\'" . conf-mode
)
2401 ("/\\.\\(?:gdbtkinit\\|grip\\|orbital/.+txt\\|rhosts\\|tuxracer/options\\)\\'" . conf-mode
)
2402 ("/\\.?X\\(?:default\\|resource\\|re\\)s\\>" . conf-xdefaults-mode
)
2403 ("/X11.+app-defaults/" . conf-xdefaults-mode
)
2404 ("/X11.+locale/.+/Compose\\'" . conf-colon-mode
)
2405 ;; this contains everything twice, with space and with colon :-(
2406 ("/X11.+locale/compose\\.dir\\'" . conf-javaprop-mode
)
2407 ;; Get rid of any trailing .n.m and try again.
2408 ;; This is for files saved by cvs-merge that look like .#<file>.<rev>
2409 ;; or .#<file>.<rev>-<rev> or VC's <file>.~<rev>~.
2410 ;; Using mode nil rather than `ignore' would let the search continue
2411 ;; through this list (with the shortened name) rather than start over.
2412 ("\\.~?[0-9]+\\.[0-9][-.0-9]*~?\\'" nil t
)
2413 ("\\.\\(?:orig\\|in\\|[bB][aA][kK]\\)\\'" nil t
)
2414 ;; This should come after "in" stripping (e.g. config.h.in).
2415 ;; *.cf, *.cfg, *.conf, *.config[.local|.de_DE.UTF8|...], */config
2416 ("[/.]c\\(?:on\\)?f\\(?:i?g\\)?\\(?:\\.[a-zA-Z0-9._-]+\\)?\\'" . conf-mode-maybe
)
2417 ;; The following should come after the ChangeLog pattern
2418 ;; for the sake of ChangeLog.1, etc.
2419 ;; and after the .scm.[0-9] and CVS' <file>.<rev> patterns too.
2420 ("\\.[1-9]\\'" . nroff-mode
)))
2421 "Alist of filename patterns vs corresponding major mode functions.
2422 Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
2423 \(NON-NIL stands for anything that is not nil; the value does not matter.)
2424 Visiting a file whose name matches REGEXP specifies FUNCTION as the
2425 mode function to use. FUNCTION will be called, unless it is nil.
2427 If the element has the form (REGEXP FUNCTION NON-NIL), then after
2428 calling FUNCTION (if it's not nil), we delete the suffix that matched
2429 REGEXP and search the list again for another match.
2431 The extensions whose FUNCTION is `archive-mode' should also
2432 appear in `auto-coding-alist' with `no-conversion' coding system.
2434 See also `interpreter-mode-alist', which detects executable script modes
2435 based on the interpreters they specify to run,
2436 and `magic-mode-alist', which determines modes based on file contents.")
2437 (put 'auto-mode-alist
'risky-local-variable t
)
2439 (defun conf-mode-maybe ()
2440 "Select Conf mode or XML mode according to start of file."
2444 (goto-char (point-min))
2445 (looking-at "<\\?xml \\|<!-- \\|<!DOCTYPE ")))
2449 (defvar interpreter-mode-alist
2450 ;; Note: The entries for the modes defined in cc-mode.el (awk-mode
2451 ;; and pike-mode) are added through autoload directives in that
2452 ;; file. That way is discouraged since it spreads out the
2453 ;; definition of the initial value.
2456 (cons (purecopy (car l
)) (cdr l
)))
2457 '(("perl" . perl-mode
)
2458 ("perl5" . perl-mode
)
2459 ("miniperl" . perl-mode
)
2461 ("wishx" . tcl-mode
)
2463 ("tclsh" . tcl-mode
)
2464 ("scm" . scheme-mode
)
2485 ("tail" . text-mode
)
2486 ("more" . text-mode
)
2487 ("less" . text-mode
)
2489 ("make" . makefile-gmake-mode
) ; Debian uses this
2490 ("guile" . scheme-mode
)
2491 ("clisp" . lisp-mode
)
2492 ("emacs" . emacs-lisp-mode
)))
2493 "Alist mapping interpreter names to major modes.
2494 This is used for files whose first lines match `auto-mode-interpreter-regexp'.
2495 Each element looks like (INTERPRETER . MODE).
2496 If INTERPRETER matches the name of the interpreter specified in the first line
2497 of a script, mode MODE is enabled.
2499 See also `auto-mode-alist'.")
2501 (define-obsolete-variable-alias 'inhibit-first-line-modes-regexps
2502 'inhibit-file-local-variables-regexps
"24.1")
2504 ;; TODO really this should be a list of modes (eg tar-mode), not regexps,
2505 ;; because we are duplicating info from auto-mode-alist.
2506 ;; TODO many elements of this list are also in auto-coding-alist.
2507 (defvar inhibit-local-variables-regexps
2508 (mapcar 'purecopy
'("\\.tar\\'" "\\.t[bg]z\\'"
2509 "\\.arc\\'" "\\.zip\\'" "\\.lzh\\'" "\\.lha\\'"
2510 "\\.zoo\\'" "\\.[jew]ar\\'" "\\.xpi\\'" "\\.rar\\'"
2512 "\\.sx[dmicw]\\'" "\\.odt\\'"
2513 "\\.tiff?\\'" "\\.gif\\'" "\\.png\\'" "\\.jpe?g\\'"))
2514 "List of regexps matching file names in which to ignore local variables.
2515 This includes `-*-' lines as well as trailing \"Local Variables\" sections.
2516 Files matching this list are typically binary file formats.
2517 They may happen to contain sequences that look like local variable
2518 specifications, but are not really, or they may be containers for
2519 member files with their own local variable sections, which are
2520 not appropriate for the containing file.
2521 See also `inhibit-local-variables-suffixes'.")
2523 (define-obsolete-variable-alias 'inhibit-first-line-modes-suffixes
2524 'inhibit-local-variables-suffixes
"24.1")
2526 (defvar inhibit-local-variables-suffixes nil
2527 "List of regexps matching suffixes to remove from file names.
2528 When checking `inhibit-local-variables-regexps', we first discard
2529 from the end of the file name anything that matches one of these regexps.")
2531 ;; TODO explicitly add case-fold-search t?
2532 (defun inhibit-local-variables-p ()
2533 "Return non-nil if file local variables should be ignored.
2534 This checks the file (or buffer) name against `inhibit-local-variables-regexps'
2535 and `inhibit-local-variables-suffixes'."
2536 (let ((temp inhibit-local-variables-regexps
)
2537 (name (if buffer-file-name
2538 (file-name-sans-versions buffer-file-name
)
2540 (while (let ((sufs inhibit-local-variables-suffixes
))
2541 (while (and sufs
(not (string-match (car sufs
) name
)))
2542 (setq sufs
(cdr sufs
)))
2544 (setq name
(substring name
0 (match-beginning 0))))
2546 (not (string-match (car temp
) name
)))
2547 (setq temp
(cdr temp
)))
2550 (defvar auto-mode-interpreter-regexp
2551 (purecopy "#![ \t]?\\([^ \t\n]*\
2552 /bin/env[ \t]\\)?\\([^ \t\n]+\\)")
2553 "Regexp matching interpreters, for file mode determination.
2554 This regular expression is matched against the first line of a file
2555 to determine the file's mode in `set-auto-mode'. If it matches, the file
2556 is assumed to be interpreted by the interpreter matched by the second group
2557 of the regular expression. The mode is then determined as the mode
2558 associated with that interpreter in `interpreter-mode-alist'.")
2560 (defvar magic-mode-alist nil
2561 "Alist of buffer beginnings vs. corresponding major mode functions.
2562 Each element looks like (REGEXP . FUNCTION) or (MATCH-FUNCTION . FUNCTION).
2563 After visiting a file, if REGEXP matches the text at the beginning of the
2564 buffer, or calling MATCH-FUNCTION returns non-nil, `normal-mode' will
2565 call FUNCTION rather than allowing `auto-mode-alist' to decide the buffer's
2568 If FUNCTION is nil, then it is not called. (That is a way of saying
2569 \"allow `auto-mode-alist' to decide for these files.\")")
2570 (put 'magic-mode-alist
'risky-local-variable t
)
2572 (defvar magic-fallback-mode-alist
2574 `((image-type-auto-detected-p . image-mode
)
2575 ("\\(PK00\\)?[P]K\003\004" . archive-mode
) ; zip
2576 ;; The < comes before the groups (but the first) to reduce backtracking.
2577 ;; TODO: UTF-16 <?xml may be preceded by a BOM 0xff 0xfe or 0xfe 0xff.
2578 ;; We use [ \t\r\n] instead of `\\s ' to make regex overflow less likely.
2579 (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
2580 (comment-re (concat "\\(?:!--" incomment-re
"*-->[ \t\r\n]*<\\)")))
2581 (concat "\\(?:<\\?xml[ \t\r\n]+[^>]*>\\)?[ \t\r\n]*<"
2583 "\\(?:!DOCTYPE[ \t\r\n]+[^>]*>[ \t\r\n]*<[ \t\r\n]*" comment-re
"*\\)?"
2584 "[Hh][Tt][Mm][Ll]"))
2586 ("<!DOCTYPE[ \t\r\n]+[Hh][Tt][Mm][Ll]" . html-mode
)
2587 ;; These two must come after html, because they are more general:
2588 ("<\\?xml " . xml-mode
)
2589 (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
2590 (comment-re (concat "\\(?:!--" incomment-re
"*-->[ \t\r\n]*<\\)")))
2591 (concat "[ \t\r\n]*<" comment-re
"*!DOCTYPE "))
2594 ("# xmcd " . conf-unix-mode
)))
2595 "Like `magic-mode-alist' but has lower priority than `auto-mode-alist'.
2596 Each element looks like (REGEXP . FUNCTION) or (MATCH-FUNCTION . FUNCTION).
2597 After visiting a file, if REGEXP matches the text at the beginning of the
2598 buffer, or calling MATCH-FUNCTION returns non-nil, `normal-mode' will
2599 call FUNCTION, provided that `magic-mode-alist' and `auto-mode-alist'
2600 have not specified a mode for this file.
2602 If FUNCTION is nil, then it is not called.")
2603 (put 'magic-fallback-mode-alist
'risky-local-variable t
)
2605 (defvar magic-mode-regexp-match-limit
4000
2606 "Upper limit on `magic-mode-alist' regexp matches.
2607 Also applies to `magic-fallback-mode-alist'.")
2609 (defun set-auto-mode (&optional keep-mode-if-same
)
2610 "Select major mode appropriate for current buffer.
2612 To find the right major mode, this function checks for a -*- mode tag
2613 checks for a `mode:' entry in the Local Variables section of the file,
2614 checks if it uses an interpreter listed in `interpreter-mode-alist',
2615 matches the buffer beginning against `magic-mode-alist',
2616 compares the filename against the entries in `auto-mode-alist',
2617 then matches the buffer beginning against `magic-fallback-mode-alist'.
2619 If `enable-local-variables' is nil, or if the file name matches
2620 `inhibit-local-variables-regexps', this function does not check
2621 for any mode: tag anywhere in the file. If `local-enable-local-variables'
2622 is nil, then the only mode: tag that can be relevant is a -*- one.
2624 If the optional argument KEEP-MODE-IF-SAME is non-nil, then we
2625 set the major mode only if that would change it. In other words
2626 we don't actually set it to the same mode the buffer already has."
2627 ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
2628 (let ((try-locals (not (inhibit-local-variables-p)))
2629 end done mode modes
)
2630 ;; Once we drop the deprecated feature where mode: is also allowed to
2631 ;; specify minor-modes (ie, there can be more than one "mode:"), we can
2632 ;; remove this section and just let (hack-local-variables t) handle it.
2633 ;; Find a -*- mode tag.
2635 (goto-char (point-min))
2636 (skip-chars-forward " \t\n")
2637 ;; Note by design local-enable-local-variables does not matter here.
2638 (and enable-local-variables
2640 (setq end
(set-auto-mode-1))
2641 (if (save-excursion (search-forward ":" end t
))
2642 ;; Find all specifications for the `mode:' variable
2643 ;; and execute them left to right.
2644 (while (let ((case-fold-search t
))
2645 (or (and (looking-at "mode:")
2646 (goto-char (match-end 0)))
2647 (re-search-forward "[ \t;]mode:" end t
)))
2648 (skip-chars-forward " \t")
2649 (let ((beg (point)))
2650 (if (search-forward ";" end t
)
2653 (skip-chars-backward " \t")
2654 (push (intern (concat (downcase (buffer-substring beg
(point))) "-mode"))
2656 ;; Simple -*-MODE-*- case.
2657 (push (intern (concat (downcase (buffer-substring (point) end
))
2660 ;; If we found modes to use, invoke them now, outside the save-excursion.
2663 (dolist (mode (nreverse modes
))
2664 (if (not (functionp mode
))
2665 (message "Ignoring unknown mode `%s'" mode
)
2667 (or (set-auto-mode-0 mode keep-mode-if-same
)
2668 ;; continuing would call minor modes again, toggling them off
2669 (throw 'nop nil
))))))
2670 ;; hack-local-variables checks local-enable-local-variables etc, but
2671 ;; we might as well be explicit here for the sake of clarity.
2673 enable-local-variables
2674 local-enable-local-variables
2676 (setq mode
(hack-local-variables t
))
2677 (not (memq mode modes
)) ; already tried and failed
2678 (if (not (functionp mode
))
2679 (message "Ignoring unknown mode `%s'" mode
)
2681 (set-auto-mode-0 mode keep-mode-if-same
)))
2682 ;; If we didn't, look for an interpreter specified in the first line.
2683 ;; As a special case, allow for things like "#!/bin/env perl", which
2684 ;; finds the interpreter anywhere in $PATH.
2686 (setq mode
(save-excursion
2687 (goto-char (point-min))
2688 (if (looking-at auto-mode-interpreter-regexp
)
2691 ;; Map interpreter name to a mode, signaling we're done at the
2693 done
(assoc (file-name-nondirectory mode
)
2694 interpreter-mode-alist
))
2695 ;; If we found an interpreter mode to use, invoke it now.
2697 (set-auto-mode-0 (cdr done
) keep-mode-if-same
)))
2698 ;; Next try matching the buffer beginning against magic-mode-alist.
2700 (if (setq done
(save-excursion
2701 (goto-char (point-min))
2703 (narrow-to-region (point-min)
2705 (+ (point-min) magic-mode-regexp-match-limit
)))
2706 (assoc-default nil magic-mode-alist
2710 (looking-at re
)))))))
2711 (set-auto-mode-0 done keep-mode-if-same
)))
2712 ;; Next compare the filename against the entries in auto-mode-alist.
2714 (if buffer-file-name
2715 (let ((name buffer-file-name
)
2716 (remote-id (file-remote-p buffer-file-name
)))
2717 ;; Remove backup-suffixes from file name.
2718 (setq name
(file-name-sans-versions name
))
2719 ;; Remove remote file name identification.
2720 (when (and (stringp remote-id
)
2721 (string-match (regexp-quote remote-id
) name
))
2722 (setq name
(substring name
(match-end 0))))
2724 ;; Find first matching alist entry.
2726 (if (memq system-type
'(windows-nt cygwin
))
2727 ;; System is case-insensitive.
2728 (let ((case-fold-search t
))
2729 (assoc-default name auto-mode-alist
2731 ;; System is case-sensitive.
2733 ;; First match case-sensitively.
2734 (let ((case-fold-search nil
))
2735 (assoc-default name auto-mode-alist
2737 ;; Fallback to case-insensitive match.
2738 (and auto-mode-case-fold
2739 (let ((case-fold-search t
))
2740 (assoc-default name auto-mode-alist
2745 (setq mode
(car mode
)
2746 name
(substring name
0 (match-beginning 0)))
2749 (set-auto-mode-0 mode keep-mode-if-same
)
2751 ;; Next try matching the buffer beginning against magic-fallback-mode-alist.
2753 (if (setq done
(save-excursion
2754 (goto-char (point-min))
2756 (narrow-to-region (point-min)
2758 (+ (point-min) magic-mode-regexp-match-limit
)))
2759 (assoc-default nil magic-fallback-mode-alist
2763 (looking-at re
)))))))
2764 (set-auto-mode-0 done keep-mode-if-same
)))))
2766 ;; When `keep-mode-if-same' is set, we are working on behalf of
2767 ;; set-visited-file-name. In that case, if the major mode specified is the
2768 ;; same one we already have, don't actually reset it. We don't want to lose
2769 ;; minor modes such as Font Lock.
2770 (defun set-auto-mode-0 (mode &optional keep-mode-if-same
)
2771 "Apply MODE and return it.
2772 If optional arg KEEP-MODE-IF-SAME is non-nil, MODE is chased of
2773 any aliases and compared to current major mode. If they are the
2774 same, do nothing and return nil."
2775 (unless (and keep-mode-if-same
2776 (eq (indirect-function mode
)
2777 (indirect-function major-mode
)))
2782 (defun set-auto-mode-1 ()
2783 "Find the -*- spec in the buffer.
2784 Call with point at the place to start searching from.
2785 If one is found, set point to the beginning and return the position
2786 of the end. Otherwise, return nil; may change point.
2787 The variable `inhibit-local-variables-regexps' can cause a -*- spec to
2788 be ignored; but `enable-local-variables' and `local-enable-local-variables'
2792 ;; Don't look for -*- if this file name matches any
2793 ;; of the regexps in inhibit-local-variables-regexps.
2794 (not (inhibit-local-variables-p))
2795 (search-forward "-*-" (line-end-position
2796 ;; If the file begins with "#!" (exec
2797 ;; interpreter magic), look for mode frobs
2798 ;; in the first two lines. You cannot
2799 ;; necessarily put them in the first line
2800 ;; of such a file without screwing up the
2801 ;; interpreter invocation. The same holds
2802 ;; for '\" in man pages (preprocessor
2803 ;; magic for the `man' program).
2804 (and (looking-at "^\\(#!\\|'\\\\\"\\)") 2)) t
)
2806 (skip-chars-forward " \t")
2808 (search-forward "-*-" (line-end-position) t
))
2811 (skip-chars-backward " \t")
2816 ;;; Handling file local variables
2818 (defvar ignored-local-variables
2819 '(ignored-local-variables safe-local-variable-values
2820 file-local-variables-alist dir-local-variables-alist
)
2821 "Variables to be ignored in a file's local variable spec.")
2822 (put 'ignored-local-variables
'risky-local-variable t
)
2824 (defvar hack-local-variables-hook nil
2825 "Normal hook run after processing a file's local variables specs.
2826 Major modes can use this to examine user-specified local variables
2827 in order to initialize other data structure based on them.")
2829 (defcustom safe-local-variable-values nil
2830 "List variable-value pairs that are considered safe.
2831 Each element is a cons cell (VAR . VAL), where VAR is a variable
2832 symbol and VAL is a value that is considered safe."
2837 (defcustom safe-local-eval-forms
2838 ;; This should be here at least as long as Emacs supports write-file-hooks.
2839 '((add-hook 'write-file-hooks
'time-stamp
)
2840 (add-hook 'write-file-functions
'time-stamp
)
2841 (add-hook 'before-save-hook
'time-stamp
))
2842 "Expressions that are considered safe in an `eval:' local variable.
2843 Add expressions to this list if you want Emacs to evaluate them, when
2844 they appear in an `eval' local variable specification, without first
2845 asking you for confirmation."
2848 :version
"24.1" ; added write-file-hooks
2849 :type
'(repeat sexp
))
2851 ;; Risky local variables:
2852 (mapc (lambda (var) (put var
'risky-local-variable t
))
2854 buffer-auto-save-file-name
2856 buffer-file-truename
2859 default-text-properties
2863 file-name-handler-alist
2872 minor-mode-map-alist
2873 minor-mode-overriding-map-alist
2876 overriding-local-map
2877 overriding-terminal-local-map
2881 unread-command-events
))
2883 ;; Safe local variables:
2885 ;; For variables defined by major modes, the safety declarations can go into
2886 ;; the major mode's file, since that will be loaded before file variables are
2889 ;; For variables defined by minor modes, put the safety declarations in the
2890 ;; file defining the minor mode after the defcustom/defvar using an autoload
2893 ;; ;;;###autoload(put 'variable 'safe-local-variable 'stringp)
2895 ;; Otherwise, when Emacs visits a file specifying that local variable, the
2896 ;; minor mode file may not be loaded yet.
2898 ;; For variables defined in the C source code the declaration should go here:
2901 '((buffer-read-only . booleanp
) ;; C source code
2902 (default-directory . stringp
) ;; C source code
2903 (fill-column . integerp
) ;; C source code
2904 (indent-tabs-mode . booleanp
) ;; C source code
2905 (left-margin . integerp
) ;; C source code
2906 (no-update-autoloads . booleanp
)
2907 (lexical-binding . booleanp
) ;; C source code
2908 (tab-width . integerp
) ;; C source code
2909 (truncate-lines . booleanp
) ;; C source code
2910 (word-wrap . booleanp
) ;; C source code
2911 (bidi-display-reordering . booleanp
))) ;; C source code
2912 (put (car pair
) 'safe-local-variable
(cdr pair
)))
2914 (put 'bidi-paragraph-direction
'safe-local-variable
2915 (lambda (v) (memq v
'(nil right-to-left left-to-right
))))
2917 (put 'c-set-style
'safe-local-eval-function t
)
2919 (defvar file-local-variables-alist nil
2920 "Alist of file-local variable settings in the current buffer.
2921 Each element in this list has the form (VAR . VALUE), where VAR
2922 is a file-local variable (a symbol) and VALUE is the value
2923 specified. The actual value in the buffer may differ from VALUE,
2924 if it is changed by the major or minor modes, or by the user.")
2925 (make-variable-buffer-local 'file-local-variables-alist
)
2926 (put 'file-local-variables-alist
'permanent-local t
)
2928 (defvar dir-local-variables-alist nil
2929 "Alist of directory-local variable settings in the current buffer.
2930 Each element in this list has the form (VAR . VALUE), where VAR
2931 is a directory-local variable (a symbol) and VALUE is the value
2932 specified in .dir-locals.el. The actual value in the buffer
2933 may differ from VALUE, if it is changed by the major or minor modes,
2935 (make-variable-buffer-local 'dir-local-variables-alist
)
2937 (defvar before-hack-local-variables-hook nil
2938 "Normal hook run before setting file-local variables.
2939 It is called after checking for unsafe/risky variables and
2940 setting `file-local-variables-alist', and before applying the
2941 variables stored in `file-local-variables-alist'. A hook
2942 function is allowed to change the contents of this alist.
2944 This hook is called only if there is at least one file-local
2947 (defun hack-local-variables-confirm (all-vars unsafe-vars risky-vars dir-name
)
2948 "Get confirmation before setting up local variable values.
2949 ALL-VARS is the list of all variables to be set up.
2950 UNSAFE-VARS is the list of those that aren't marked as safe or risky.
2951 RISKY-VARS is the list of those that are marked as risky.
2952 If these settings come from directory-local variables, then
2953 DIR-NAME is the name of the associated directory. Otherwise it is nil."
2956 (save-window-excursion
2957 (let* ((name (or dir-name
2958 (if buffer-file-name
2959 (file-name-nondirectory buffer-file-name
)
2960 (concat "buffer " (buffer-name)))))
2961 (offer-save (and (eq enable-local-variables t
)
2964 (if offer-save
'(?
! ?y ?n ?\s ?\C-g
) '(?y ?n ?\s ?\C-g
)))
2965 (buf (pop-to-buffer "*Local Variables*"))
2967 (set (make-local-variable 'cursor-type
) nil
)
2971 (insert "The local variables list in " name
2972 "\ncontains values that may not be safe (*)"
2974 ", and variables that are risky (**)."
2977 (insert "The local variables list in " name
2978 "\ncontains variables that are risky (**)."))
2980 (insert "A local variables list is specified in " name
".")))
2981 (insert "\n\nDo you want to apply it? You can type
2982 y -- to apply the local variables list.
2983 n -- to ignore the local variables list.")
2986 ! -- to apply the local variables list, and permanently mark these
2987 values (*) as safe (in the future, they will be set automatically.)\n\n")
2989 (dolist (elt all-vars
)
2990 (cond ((member elt unsafe-vars
)
2992 ((member elt risky-vars
)
2996 (princ (car elt
) buf
)
2998 ;; Make strings with embedded whitespace easier to read.
2999 (let ((print-escape-newlines t
))
3000 (prin1 (cdr elt
) buf
))
3003 (format "Please type %s%s: "
3004 (if offer-save
"y, n, or !" "y or n")
3005 (if (< (line-number-at-pos) (window-body-height))
3007 (push ?\C-v exit-chars
)
3008 ", or C-v to scroll")))
3009 (goto-char (point-min))
3011 (setq char
(read-char-choice prompt exit-chars t
))
3012 (when (eq char ?\C-v
)
3015 (error (goto-char (point-min))))
3018 (when (and offer-save
(= char ?
!) unsafe-vars
)
3019 (customize-push-and-save 'safe-local-variable-values unsafe-vars
))
3020 (memq char
'(?
! ?\s ?y
))))))
3022 (defun hack-local-variables-prop-line (&optional mode-only
)
3023 "Return local variables specified in the -*- line.
3024 Returns an alist of elements (VAR . VAL), where VAR is a variable
3025 and VAL is the specified value. Ignores any specification for
3026 `mode:' and `coding:' (which should have already been handled
3027 by `set-auto-mode' and `set-auto-coding', respectively).
3028 Return nil if the -*- line is malformed.
3030 If MODE-ONLY is non-nil, just returns the symbol specifying the
3031 mode, if there is one, otherwise nil."
3032 (catch 'malformed-line
3034 (goto-char (point-min))
3035 (let ((end (set-auto-mode-1))
3039 ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
3040 ;; Simple form: "-*- MODENAME -*-".
3042 (intern (concat (match-string 1) "-mode"))))
3044 ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
3045 ;; (last ";" is optional).
3046 ;; If MODE-ONLY, just check for `mode'.
3047 ;; Otherwise, parse the -*- line into the RESULT alist.
3048 (while (and (or (not mode-only
)
3051 (unless (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
3052 (message "Malformed mode-line")
3053 (throw 'malformed-line nil
))
3054 (goto-char (match-end 0))
3055 ;; There used to be a downcase here,
3056 ;; but the manual didn't say so,
3057 ;; and people want to set var names that aren't all lc.
3058 (let* ((key (intern (match-string 1)))
3059 (val (save-restriction
3060 (narrow-to-region (point) end
)
3061 (let ((read-circle nil
))
3062 (read (current-buffer)))))
3063 ;; It is traditional to ignore
3064 ;; case when checking for `mode' in set-auto-mode,
3065 ;; so we must do that here as well.
3066 ;; That is inconsistent, but we're stuck with it.
3067 ;; The same can be said for `coding' in set-auto-coding.
3068 (keyname (downcase (symbol-name key
))))
3070 (and (equal keyname
"mode")
3072 (intern (concat (downcase (symbol-name val
))
3074 (or (equal keyname
"coding")
3076 (push (cons (cond ((eq key
'eval
) 'eval
)
3077 ;; Downcase "Mode:".
3078 ((equal keyname
"mode") 'mode
)
3079 (t (indirect-variable key
)))
3082 (skip-chars-forward " \t;")))
3085 (defun hack-local-variables-filter (variables dir-name
)
3086 "Filter local variable settings, querying the user if necessary.
3087 VARIABLES is the alist of variable-value settings. This alist is
3088 filtered based on the values of `ignored-local-variables',
3089 `enable-local-eval', `enable-local-variables', and (if necessary)
3090 user interaction. The results are added to
3091 `file-local-variables-alist', without applying them.
3092 If these settings come from directory-local variables, then
3093 DIR-NAME is the name of the associated directory. Otherwise it is nil."
3094 ;; Find those variables that we may want to save to
3095 ;; `safe-local-variable-values'.
3096 (let (all-vars risky-vars unsafe-vars
)
3097 (dolist (elt variables
)
3098 (let ((var (car elt
))
3100 (cond ((memq var ignored-local-variables
)
3101 ;; Ignore any variable in `ignored-local-variables'.
3103 ;; Obey `enable-local-eval'.
3105 (when enable-local-eval
3107 (or (eq enable-local-eval t
)
3108 (hack-one-local-variable-eval-safep (eval (quote val
)))
3109 (safe-local-variable-p var val
)
3110 (push elt unsafe-vars
))))
3111 ;; Ignore duplicates (except `mode') in the present list.
3112 ((and (assq var all-vars
) (not (eq var
'mode
))) nil
)
3113 ;; Accept known-safe variables.
3114 ((or (memq var
'(mode unibyte coding
))
3115 (safe-local-variable-p var val
))
3116 (push elt all-vars
))
3117 ;; The variable is either risky or unsafe:
3118 ((not (eq enable-local-variables
:safe
))
3120 (if (risky-local-variable-p var val
)
3121 (push elt risky-vars
)
3122 (push elt unsafe-vars
))))))
3124 ;; Query, unless all vars are safe or user wants no querying.
3125 (or (and (eq enable-local-variables t
)
3128 (memq enable-local-variables
'(:all
:safe
))
3129 (hack-local-variables-confirm all-vars unsafe-vars
3130 risky-vars dir-name
))
3131 (dolist (elt all-vars
)
3132 (unless (memq (car elt
) '(eval mode
))
3134 (setq dir-local-variables-alist
3135 (assq-delete-all (car elt
) dir-local-variables-alist
)))
3136 (setq file-local-variables-alist
3137 (assq-delete-all (car elt
) file-local-variables-alist
)))
3138 (push elt file-local-variables-alist
)))))
3140 (defun hack-local-variables (&optional mode-only
)
3141 "Parse and put into effect this buffer's local variables spec.
3142 Uses `hack-local-variables-apply' to apply the variables.
3144 If MODE-ONLY is non-nil, all we do is check whether a \"mode:\"
3145 is specified, and return the corresponding mode symbol, or nil.
3146 In this case, we try to ignore minor-modes, and only return a
3149 If `enable-local-variables' or `local-enable-local-variables' is nil,
3150 this function does nothing. If `inhibit-local-variables-regexps'
3151 applies to the file in question, the file is not scanned for
3152 local variables, but directory-local variables may still be applied."
3153 ;; We don't let inhibit-local-variables-p influence the value of
3154 ;; enable-local-variables, because then it would affect dir-local
3155 ;; variables. We don't want to search eg tar files for file local
3156 ;; variable sections, but there is no reason dir-locals cannot apply
3157 ;; to them. The real meaning of inhibit-local-variables-p is "do
3158 ;; not scan this file for local variables".
3159 (let ((enable-local-variables
3160 (and local-enable-local-variables enable-local-variables
))
3163 (setq file-local-variables-alist nil
)
3164 (report-errors "Directory-local variables error: %s"
3165 ;; Note this is a no-op if enable-local-variables is nil.
3166 (hack-dir-local-variables)))
3167 ;; This entire function is basically a no-op if enable-local-variables
3168 ;; is nil. All it does is set file-local-variables-alist to nil.
3169 (when enable-local-variables
3170 ;; This part used to ignore enable-local-variables when mode-only
3171 ;; was non-nil. That was inappropriate, eg consider the
3172 ;; (artificial) example of:
3173 ;; (setq local-enable-local-variables nil)
3174 ;; Open a file foo.txt that contains "mode: sh".
3175 ;; It correctly opens in text-mode.
3176 ;; M-x set-visited-file name foo.c, and it incorrectly stays in text-mode.
3177 (unless (or (inhibit-local-variables-p)
3178 ;; If MODE-ONLY is non-nil, and the prop line specifies a
3179 ;; mode, then we're done, and have no need to scan further.
3180 (and (setq result
(hack-local-variables-prop-line mode-only
))
3182 ;; Look for "Local variables:" line in last page.
3184 (goto-char (point-max))
3185 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min))
3187 (when (let ((case-fold-search t
))
3188 (search-forward "Local Variables:" nil t
))
3189 (skip-chars-forward " \t")
3190 ;; suffix is what comes after "local variables:" in its line.
3191 ;; prefix is what comes before "local variables:" in its line.
3194 (regexp-quote (buffer-substring (point)
3195 (line-end-position)))
3198 (concat "^" (regexp-quote
3199 (buffer-substring (line-beginning-position)
3200 (match-beginning 0)))))
3204 (let ((startpos (point))
3206 (thisbuf (current-buffer)))
3208 (unless (let ((case-fold-search t
))
3210 (concat prefix
"[ \t]*End:[ \t]*" suffix
)
3212 ;; This used to be an error, but really all it means is
3213 ;; that this may simply not be a local-variables section,
3214 ;; so just ignore it.
3215 (message "Local variables list is not properly terminated"))
3217 (setq endpos
(point)))
3220 (insert-buffer-substring thisbuf startpos endpos
)
3221 (goto-char (point-min))
3222 (subst-char-in-region (point) (point-max) ?\^m ?
\n)
3224 ;; Discard the prefix.
3225 (if (looking-at prefix
)
3226 (delete-region (point) (match-end 0))
3227 (error "Local variables entry is missing the prefix"))
3229 ;; Discard the suffix.
3230 (if (looking-back suffix
)
3231 (delete-region (match-beginning 0) (point))
3232 (error "Local variables entry is missing the suffix"))
3234 (goto-char (point-min))
3236 (while (and (not (eobp))
3239 ;; Find the variable name; strip whitespace.
3240 (skip-chars-forward " \t")
3242 (skip-chars-forward "^:\n")
3243 (if (eolp) (error "Missing colon in local variables entry"))
3244 (skip-chars-backward " \t")
3245 (let* ((str (buffer-substring beg
(point)))
3246 (var (let ((read-circle nil
))
3249 (and (equal (downcase (symbol-name var
)) "mode")
3251 ;; Read the variable value.
3252 (skip-chars-forward "^:")
3254 (let ((read-circle nil
))
3255 (setq val
(read (current-buffer))))
3258 ;; Specifying minor-modes via mode: is
3259 ;; deprecated, but try to reject them anyway.
3262 (setq val2
(downcase (symbol-name val
)))))
3263 (setq result
(intern (concat val2
"-mode"))))
3264 (unless (eq var
'coding
)
3266 (push (cons (if (eq var
'eval
)
3268 (indirect-variable var
))
3271 (forward-line 1))))))))
3272 ;; Now we've read all the local variables.
3273 ;; If MODE-ONLY is non-nil, return whether the mode was specified.
3274 (if mode-only result
3275 ;; Otherwise, set the variables.
3276 (hack-local-variables-filter result nil
)
3277 (hack-local-variables-apply)))))
3279 (defun hack-local-variables-apply ()
3280 "Apply the elements of `file-local-variables-alist'.
3281 If there are any elements, runs `before-hack-local-variables-hook',
3282 then calls `hack-one-local-variable' to apply the alist elements one by one.
3283 Finishes by running `hack-local-variables-hook', regardless of whether
3284 the alist is empty or not.
3286 Note that this function ignores a `mode' entry if it specifies the same
3287 major mode as the buffer already has."
3288 (when file-local-variables-alist
3289 ;; Any 'evals must run in the Right sequence.
3290 (setq file-local-variables-alist
3291 (nreverse file-local-variables-alist
))
3292 (run-hooks 'before-hack-local-variables-hook
)
3293 (dolist (elt file-local-variables-alist
)
3294 (hack-one-local-variable (car elt
) (cdr elt
))))
3295 (run-hooks 'hack-local-variables-hook
))
3297 (defun safe-local-variable-p (sym val
)
3298 "Non-nil if SYM is safe as a file-local variable with value VAL.
3299 It is safe if any of these conditions are met:
3301 * There is a matching entry (SYM . VAL) in the
3302 `safe-local-variable-values' user option.
3304 * The `safe-local-variable' property of SYM is a function that
3305 evaluates to a non-nil value with VAL as an argument."
3306 (or (member (cons sym val
) safe-local-variable-values
)
3307 (let ((safep (get sym
'safe-local-variable
)))
3308 (and (functionp safep
)
3309 ;; If the function signals an error, that means it
3310 ;; can't assure us that the value is safe.
3311 (with-demoted-errors (funcall safep val
))))))
3313 (defun risky-local-variable-p (sym &optional _ignored
)
3314 "Non-nil if SYM could be dangerous as a file-local variable.
3315 It is dangerous if either of these conditions are met:
3317 * Its `risky-local-variable' property is non-nil.
3319 * Its name ends with \"hook(s)\", \"function(s)\", \"form(s)\", \"map\",
3320 \"program\", \"command(s)\", \"predicate(s)\", \"frame-alist\",
3321 \"mode-alist\", \"font-lock-(syntactic-)keyword*\",
3322 \"map-alist\", or \"bindat-spec\"."
3323 ;; If this is an alias, check the base name.
3325 (setq sym
(indirect-variable sym
))
3327 (or (get sym
'risky-local-variable
)
3328 (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|\
3329 -commands?$\\|-predicates?$\\|font-lock-keywords$\\|font-lock-keywords\
3330 -[0-9]+$\\|font-lock-syntactic-keywords$\\|-frame-alist$\\|-mode-alist$\\|\
3331 -map$\\|-map-alist$\\|-bindat-spec$" (symbol-name sym
))))
3333 (defun hack-one-local-variable-quotep (exp)
3334 (and (consp exp
) (eq (car exp
) 'quote
) (consp (cdr exp
))))
3336 (defun hack-one-local-variable-constantp (exp)
3337 (or (and (not (symbolp exp
)) (not (consp exp
)))
3340 (hack-one-local-variable-quotep exp
)))
3342 (defun hack-one-local-variable-eval-safep (exp)
3343 "Return t if it is safe to eval EXP when it is found in a file."
3344 (or (not (consp exp
))
3345 ;; Detect certain `put' expressions.
3346 (and (eq (car exp
) 'put
)
3347 (hack-one-local-variable-quotep (nth 1 exp
))
3348 (hack-one-local-variable-quotep (nth 2 exp
))
3349 (let ((prop (nth 1 (nth 2 exp
)))
3351 (cond ((memq prop
'(lisp-indent-hook
3352 lisp-indent-function
3353 scheme-indent-function
))
3354 ;; Only allow safe values (not functions).
3356 (and (hack-one-local-variable-quotep val
)
3357 (eq (nth 1 val
) 'defun
))))
3358 ((eq prop
'edebug-form-spec
)
3359 ;; Only allow indirect form specs.
3360 ;; During bootstrapping, edebug-basic-spec might not be
3362 (and (fboundp 'edebug-basic-spec
)
3363 (hack-one-local-variable-quotep val
)
3364 (edebug-basic-spec (nth 1 val
)))))))
3365 ;; Allow expressions that the user requested.
3366 (member exp safe-local-eval-forms
)
3367 ;; Certain functions can be allowed with safe arguments
3368 ;; or can specify verification functions to try.
3369 (and (symbolp (car exp
))
3370 ;; Allow (minor)-modes calls with no arguments.
3371 ;; This obsoletes the use of "mode:" for such things. (Bug#8613)
3372 (or (and (member (cdr exp
) '(nil (1) (0) (-1)))
3373 (string-match "-mode\\'" (symbol-name (car exp
))))
3374 (let ((prop (get (car exp
) 'safe-local-eval-function
)))
3377 (dolist (arg (cdr exp
))
3378 (unless (hack-one-local-variable-constantp arg
)
3385 (dolist (function prop
)
3386 (if (funcall function exp
)
3390 (defun hack-one-local-variable (var val
)
3391 "Set local variable VAR with value VAL.
3392 If VAR is `mode', call `VAL-mode' as a function unless it's
3393 already the major mode."
3394 (cond ((eq var
'mode
)
3395 (let ((mode (intern (concat (downcase (symbol-name val
))
3397 (unless (eq (indirect-function mode
)
3398 (indirect-function major-mode
))
3399 (if (memq mode minor-mode-list
)
3400 ;; A minor mode must be passed an argument.
3401 ;; Otherwise, if the user enables the minor mode in a
3402 ;; major mode hook, this would toggle it off.
3406 (save-excursion (eval val
)))
3408 ;; Make sure the string has no text properties.
3409 ;; Some text properties can get evaluated in various ways,
3410 ;; so it is risky to put them on with a local variable list.
3412 (set-text-properties 0 (length val
) nil val
))
3413 (set (make-local-variable var
) val
))))
3415 ;;; Handling directory-local variables, aka project settings.
3417 (defvar dir-locals-class-alist
'()
3418 "Alist mapping directory-local variable classes (symbols) to variable lists.")
3420 (defvar dir-locals-directory-cache
'()
3421 "List of cached directory roots for directory-local variable classes.
3422 Each element in this list has the form (DIR CLASS MTIME).
3423 DIR is the name of the directory.
3424 CLASS is the name of a variable class (a symbol).
3425 MTIME is the recorded modification time of the directory-local
3426 variables file associated with this entry. This time is a list
3427 of two integers (the same format as `file-attributes'), and is
3428 used to test whether the cache entry is still valid.
3429 Alternatively, MTIME can be nil, which means the entry is always
3432 (defsubst dir-locals-get-class-variables
(class)
3433 "Return the variable list for CLASS."
3434 (cdr (assq class dir-locals-class-alist
)))
3436 (defun dir-locals-collect-mode-variables (mode-variables variables
)
3437 "Collect directory-local variables from MODE-VARIABLES.
3438 VARIABLES is the initial list of variables.
3439 Returns the new list."
3440 (dolist (pair mode-variables variables
)
3441 (let* ((variable (car pair
))
3443 (slot (assq variable variables
)))
3444 ;; If variables are specified more than once, only use the last. (Why?)
3445 ;; The pseudo-variables mode and eval are different (bug#3430).
3446 (if (and slot
(not (memq variable
'(mode eval
))))
3448 ;; Need a new cons in case we setcdr later.
3449 (push (cons variable value
) variables
)))))
3451 (defun dir-locals-collect-variables (class-variables root variables
)
3452 "Collect entries from CLASS-VARIABLES into VARIABLES.
3453 ROOT is the root directory of the project.
3454 Return the new variables list."
3455 (let* ((file-name (buffer-file-name))
3456 (sub-file-name (if file-name
3457 ;; FIXME: Why not use file-relative-name?
3458 (substring file-name
(length root
)))))
3460 (dolist (entry class-variables variables
)
3461 (let ((key (car entry
)))
3464 ;; Don't include this in the previous condition, because we
3465 ;; want to filter all strings before the next condition.
3466 (when (and sub-file-name
3467 (>= (length sub-file-name
) (length key
))
3468 (string-prefix-p key sub-file-name
))
3469 (setq variables
(dir-locals-collect-variables
3470 (cdr entry
) root variables
))))
3472 (derived-mode-p key
))
3473 (let* ((alist (cdr entry
))
3474 (subdirs (assq 'subdirs alist
)))
3475 (if (or (not subdirs
)
3477 (setq alist
(delq subdirs alist
))
3479 ;; TODO someone might want to extend this to allow
3480 ;; integer values for subdir, where N means
3481 ;; variables apply to this directory and N levels
3482 ;; below it (0 == nil).
3483 (equal root default-directory
))
3484 (setq variables
(dir-locals-collect-mode-variables
3485 alist variables
))))))))
3487 ;; The file's content might be invalid (e.g. have a merge conflict), but
3488 ;; that shouldn't prevent the user from opening the file.
3489 (message ".dir-locals error: %s" (error-message-string err
))
3492 (defun dir-locals-set-directory-class (directory class
&optional mtime
)
3493 "Declare that the DIRECTORY root is an instance of CLASS.
3494 DIRECTORY is the name of a directory, a string.
3495 CLASS is the name of a project class, a symbol.
3496 MTIME is either the modification time of the directory-local
3497 variables file that defined this class, or nil.
3499 When a file beneath DIRECTORY is visited, the mode-specific
3500 variables from CLASS are applied to the buffer. The variables
3501 for a class are defined using `dir-locals-set-class-variables'."
3502 (setq directory
(file-name-as-directory (expand-file-name directory
)))
3503 (unless (assq class dir-locals-class-alist
)
3504 (error "No such class `%s'" (symbol-name class
)))
3505 (push (list directory class mtime
) dir-locals-directory-cache
))
3507 (defun dir-locals-set-class-variables (class variables
)
3508 "Map the type CLASS to a list of variable settings.
3509 CLASS is the project class, a symbol. VARIABLES is a list
3510 that declares directory-local variables for the class.
3511 An element in VARIABLES is either of the form:
3512 (MAJOR-MODE . ALIST)
3516 In the first form, MAJOR-MODE is a symbol, and ALIST is an alist
3517 whose elements are of the form (VARIABLE . VALUE).
3519 In the second form, DIRECTORY is a directory name (a string), and
3520 LIST is a list of the form accepted by the function.
3522 When a file is visited, the file's class is found. A directory
3523 may be assigned a class using `dir-locals-set-directory-class'.
3524 Then variables are set in the file's buffer according to the
3525 class' LIST. The list is processed in order.
3527 * If the element is of the form (MAJOR-MODE . ALIST), and the
3528 buffer's major mode is derived from MAJOR-MODE (as determined
3529 by `derived-mode-p'), then all the variables in ALIST are
3530 applied. A MAJOR-MODE of nil may be used to match any buffer.
3531 `make-local-variable' is called for each variable before it is
3534 * If the element is of the form (DIRECTORY . LIST), and DIRECTORY
3535 is an initial substring of the file's directory, then LIST is
3536 applied by recursively following these rules."
3537 (let ((elt (assq class dir-locals-class-alist
)))
3539 (setcdr elt variables
)
3540 (push (cons class variables
) dir-locals-class-alist
))))
3542 (defconst dir-locals-file
".dir-locals.el"
3543 "File that contains directory-local variables.
3544 It has to be constant to enforce uniform values
3545 across different environments and users.")
3547 (defun dir-locals-find-file (file)
3548 "Find the directory-local variables for FILE.
3549 This searches upward in the directory tree from FILE.
3550 It stops at the first directory that has been registered in
3551 `dir-locals-directory-cache' or contains a `dir-locals-file'.
3552 If it finds an entry in the cache, it checks that it is valid.
3553 A cache entry with no modification time element (normally, one that
3554 has been assigned directly using `dir-locals-set-directory-class', not
3555 set from a file) is always valid.
3556 A cache entry based on a `dir-locals-file' is valid if the modification
3557 time stored in the cache matches the current file modification time.
3558 If not, the cache entry is cleared so that the file will be re-read.
3560 This function returns either nil (no directory local variables found),
3561 or the matching entry from `dir-locals-directory-cache' (a list),
3562 or the full path to the `dir-locals-file' (a string) in the case
3563 of no valid cache entry."
3564 (setq file
(expand-file-name file
))
3565 (let* ((dir-locals-file-name
3566 (if (eq system-type
'ms-dos
)
3567 (dosified-file-name dir-locals-file
)
3569 (locals-file (locate-dominating-file file dir-locals-file-name
))
3571 ;; `locate-dominating-file' may have abbreviated the name.
3573 (setq locals-file
(expand-file-name dir-locals-file-name locals-file
)))
3574 ;; Find the best cached value in `dir-locals-directory-cache'.
3575 (dolist (elt dir-locals-directory-cache
)
3576 (when (and (eq t
(compare-strings file nil
(length (car elt
))
3579 '(windows-nt cygwin ms-dos
))))
3580 (> (length (car elt
)) (length (car dir-elt
))))
3581 (setq dir-elt elt
)))
3583 (or (null locals-file
)
3584 (<= (length (file-name-directory locals-file
))
3585 (length (car dir-elt
)))))
3586 ;; Found a potential cache entry. Check validity.
3587 ;; A cache entry with no MTIME is assumed to always be valid
3588 ;; (ie, set directly, not from a dir-locals file).
3589 ;; Note, we don't bother to check that there is a matching class
3590 ;; element in dir-locals-class-alist, since that's done by
3591 ;; dir-locals-set-directory-class.
3592 (if (or (null (nth 2 dir-elt
))
3593 (let ((cached-file (expand-file-name dir-locals-file-name
3595 (and (file-readable-p cached-file
)
3596 (equal (nth 2 dir-elt
)
3597 (nth 5 (file-attributes cached-file
))))))
3598 ;; This cache entry is OK.
3600 ;; This cache entry is invalid; clear it.
3601 (setq dir-locals-directory-cache
3602 (delq dir-elt dir-locals-directory-cache
))
3603 ;; Return the first existing dir-locals file. Might be the same
3604 ;; as dir-elt's, might not (eg latter might have been deleted).
3609 (defun dir-locals-read-from-file (file)
3610 "Load a variables FILE and register a new class and instance.
3611 FILE is the name of the file holding the variables to apply.
3612 The new class name is the same as the directory in which FILE
3613 is found. Returns the new class name."
3615 (insert-file-contents file
)
3616 (let* ((dir-name (file-name-directory file
))
3617 (class-name (intern dir-name
))
3618 (variables (let ((read-circle nil
))
3619 (read (current-buffer)))))
3620 (dir-locals-set-class-variables class-name variables
)
3621 (dir-locals-set-directory-class dir-name class-name
3622 (nth 5 (file-attributes file
)))
3625 (defun hack-dir-local-variables ()
3626 "Read per-directory local variables for the current buffer.
3627 Store the directory-local variables in `dir-local-variables-alist'
3628 and `file-local-variables-alist', without applying them."
3629 (when (and enable-local-variables
3630 (not (file-remote-p (or (buffer-file-name) default-directory
))))
3631 ;; Find the variables file.
3632 (let ((variables-file (dir-locals-find-file (or (buffer-file-name) default-directory
)))
3636 ((stringp variables-file
)
3637 (setq dir-name
(file-name-directory variables-file
)
3638 class
(dir-locals-read-from-file variables-file
)))
3639 ((consp variables-file
)
3640 (setq dir-name
(nth 0 variables-file
))
3641 (setq class
(nth 1 variables-file
))))
3644 (dir-locals-collect-variables
3645 (dir-locals-get-class-variables class
) dir-name nil
)))
3647 (dolist (elt variables
)
3648 (unless (memq (car elt
) '(eval mode
))
3649 (setq dir-local-variables-alist
3650 (assq-delete-all (car elt
) dir-local-variables-alist
)))
3651 (push elt dir-local-variables-alist
))
3652 (hack-local-variables-filter variables dir-name
)))))))
3654 (defun hack-dir-local-variables-non-file-buffer ()
3655 "Apply directory-local variables to a non-file buffer.
3656 For non-file buffers, such as Dired buffers, directory-local
3657 variables are looked for in `default-directory' and its parent
3659 (hack-dir-local-variables)
3660 (hack-local-variables-apply))
3663 (defcustom change-major-mode-with-file-name t
3664 "Non-nil means \\[write-file] should set the major mode from the file name.
3665 However, the mode will not be changed if
3666 \(1) a local variables list or the `-*-' line specifies a major mode, or
3667 \(2) the current major mode is a \"special\" mode,
3668 \ not suitable for ordinary files, or
3669 \(3) the new file name does not particularly specify any mode."
3671 :group
'editing-basics
)
3673 (defun set-visited-file-name (filename &optional no-query along-with-file
)
3674 "Change name of file visited in current buffer to FILENAME.
3675 This also renames the buffer to correspond to the new file.
3676 The next time the buffer is saved it will go in the newly specified file.
3677 FILENAME nil or an empty string means mark buffer as not visiting any file.
3678 Remember to delete the initial contents of the minibuffer
3679 if you wish to pass an empty string as the argument.
3681 The optional second argument NO-QUERY, if non-nil, inhibits asking for
3682 confirmation in the case where another buffer is already visiting FILENAME.
3684 The optional third argument ALONG-WITH-FILE, if non-nil, means that
3685 the old visited file has been renamed to the new name FILENAME."
3686 (interactive "FSet visited file name: ")
3687 (if (buffer-base-buffer)
3688 (error "An indirect buffer cannot visit a file"))
3689 (let (truename old-try-locals
)
3692 (if (string-equal filename
"")
3694 (expand-file-name filename
))))
3697 (setq truename
(file-truename filename
))
3698 (if find-file-visit-truename
3699 (setq filename truename
))))
3701 (let ((new-name (file-name-nondirectory filename
)))
3702 (if (string= new-name
"")
3703 (error "Empty file name"))))
3704 (let ((buffer (and filename
(find-buffer-visiting filename
))))
3705 (and buffer
(not (eq buffer
(current-buffer)))
3707 (not (y-or-n-p (format "A buffer is visiting %s; proceed? "
3710 (or (equal filename buffer-file-name
)
3712 (and filename
(lock-buffer filename
))
3714 (setq old-try-locals
(not (inhibit-local-variables-p))
3715 buffer-file-name filename
)
3716 (if filename
; make buffer name reflect filename.
3717 (let ((new-name (file-name-nondirectory buffer-file-name
)))
3718 (setq default-directory
(file-name-directory buffer-file-name
))
3719 ;; If new-name == old-name, renaming would add a spurious <2>
3720 ;; and it's considered as a feature in rename-buffer.
3721 (or (string= new-name
(buffer-name))
3722 (rename-buffer new-name t
))))
3723 (setq buffer-backed-up nil
)
3725 (clear-visited-file-modtime))
3726 ;; Abbreviate the file names of the buffer.
3729 (setq buffer-file-truename
(abbreviate-file-name truename
))
3730 (if find-file-visit-truename
3731 (setq buffer-file-name truename
))))
3732 (setq buffer-file-number
3734 (nthcdr 10 (file-attributes buffer-file-name
))
3736 ;; write-file-functions is normally used for things like ftp-find-file
3737 ;; that visit things that are not local files as if they were files.
3738 ;; Changing to visit an ordinary local file instead should flush the hook.
3739 (kill-local-variable 'write-file-functions
)
3740 (kill-local-variable 'local-write-file-hooks
)
3741 (kill-local-variable 'revert-buffer-function
)
3742 (kill-local-variable 'backup-inhibited
)
3743 ;; If buffer was read-only because of version control,
3744 ;; that reason is gone now, so make it writable.
3746 (setq buffer-read-only nil
))
3747 (kill-local-variable 'vc-mode
)
3748 ;; Turn off backup files for certain file names.
3749 ;; Since this is a permanent local, the major mode won't eliminate it.
3750 (and buffer-file-name
3751 backup-enable-predicate
3752 (not (funcall backup-enable-predicate buffer-file-name
))
3754 (make-local-variable 'backup-inhibited
)
3755 (setq backup-inhibited t
)))
3756 (let ((oauto buffer-auto-save-file-name
))
3757 ;; If auto-save was not already on, turn it on if appropriate.
3758 (if (not buffer-auto-save-file-name
)
3759 (and buffer-file-name auto-save-default
3761 ;; If auto save is on, start using a new name.
3762 ;; We deliberately don't rename or delete the old auto save
3763 ;; for the old visited file name. This is because perhaps
3764 ;; the user wants to save the new state and then compare with the
3765 ;; previous state from the auto save file.
3766 (setq buffer-auto-save-file-name
3767 (make-auto-save-file-name)))
3768 ;; Rename the old auto save file if any.
3769 (and oauto buffer-auto-save-file-name
3770 (file-exists-p oauto
)
3771 (rename-file oauto buffer-auto-save-file-name t
)))
3772 (and buffer-file-name
3773 (not along-with-file
)
3774 (set-buffer-modified-p t
))
3775 ;; Update the major mode, if the file name determines it.
3777 ;; Don't change the mode if it is special.
3778 (or (not change-major-mode-with-file-name
)
3779 (get major-mode
'mode-class
)
3780 ;; Don't change the mode if the local variable list specifies it.
3781 ;; The file name can influence whether the local variables apply.
3783 ;; h-l-v also checks it, but might as well be explicit.
3784 (not (inhibit-local-variables-p))
3785 (hack-local-variables t
))
3786 ;; TODO consider making normal-mode handle this case.
3787 (let ((old major-mode
))
3789 (or (eq old major-mode
)
3790 (hack-local-variables))))
3793 (defun write-file (filename &optional confirm
)
3794 "Write current buffer into file FILENAME.
3795 This makes the buffer visit that file, and marks it as not modified.
3797 If you specify just a directory name as FILENAME, that means to use
3798 the default file name but in that directory. You can also yank
3799 the default file name into the minibuffer to edit it, using \\<minibuffer-local-map>\\[next-history-element].
3801 If the buffer is not already visiting a file, the default file name
3802 for the output file is the buffer name.
3804 If optional second arg CONFIRM is non-nil, this function
3805 asks for confirmation before overwriting an existing file.
3806 Interactively, confirmation is required unless you supply a prefix argument."
3807 ;; (interactive "FWrite file: ")
3809 (list (if buffer-file-name
3810 (read-file-name "Write file: "
3812 (read-file-name "Write file: " default-directory
3814 (file-name-nondirectory (buffer-name))
3817 (not current-prefix-arg
)))
3818 (or (null filename
) (string-equal filename
"")
3820 ;; If arg is just a directory,
3821 ;; use the default file name, but in that directory.
3822 (if (file-directory-p filename
)
3823 (setq filename
(concat (file-name-as-directory filename
)
3824 (file-name-nondirectory
3825 (or buffer-file-name
(buffer-name))))))
3827 (file-exists-p filename
)
3828 (or (y-or-n-p (format "File `%s' exists; overwrite? " filename
))
3829 (error "Canceled")))
3830 (set-visited-file-name filename
(not confirm
))))
3831 (set-buffer-modified-p t
)
3832 ;; Make buffer writable if file is writable.
3833 (and buffer-file-name
3834 (file-writable-p buffer-file-name
)
3835 (setq buffer-read-only nil
))
3837 ;; It's likely that the VC status at the new location is different from
3838 ;; the one at the old location.
3839 (vc-find-file-hook))
3841 (defun backup-buffer ()
3842 "Make a backup of the disk file visited by the current buffer, if appropriate.
3843 This is normally done before saving the buffer the first time.
3845 A backup may be done by renaming or by copying; see documentation of
3846 variable `make-backup-files'. If it's done by renaming, then the file is
3847 no longer accessible under its old name.
3849 The value is non-nil after a backup was made by renaming.
3850 It has the form (MODES SELINUXCONTEXT BACKUPNAME).
3851 MODES is the result of `file-modes' on the original
3852 file; this means that the caller, after saving the buffer, should change
3853 the modes of the new file to agree with the old modes.
3854 SELINUXCONTEXT is the result of `file-selinux-context' on the original
3855 file; this means that the caller, after saving the buffer, should change
3856 the SELinux context of the new file to agree with the old context.
3857 BACKUPNAME is the backup file name, which is the old file renamed."
3858 (if (and make-backup-files
(not backup-inhibited
)
3859 (not buffer-backed-up
)
3860 (file-exists-p buffer-file-name
)
3861 (memq (aref (elt (file-attributes buffer-file-name
) 8) 0)
3863 (let ((real-file-name buffer-file-name
)
3864 backup-info backupname targets setmodes
)
3865 ;; If specified name is a symbolic link, chase it to the target.
3866 ;; Thus we make the backups in the directory where the real file is.
3867 (setq real-file-name
(file-chase-links real-file-name
))
3868 (setq backup-info
(find-backup-file-name real-file-name
)
3869 backupname
(car backup-info
)
3870 targets
(cdr backup-info
))
3871 ;; (if (file-directory-p buffer-file-name)
3872 ;; (error "Cannot save buffer in directory %s" buffer-file-name))
3875 (let ((delete-old-versions
3876 ;; If have old versions to maybe delete,
3877 ;; ask the user to confirm now, before doing anything.
3878 ;; But don't actually delete til later.
3880 (or (eq delete-old-versions t
) (eq delete-old-versions nil
))
3881 (or delete-old-versions
3882 (y-or-n-p (format "Delete excess backup versions of %s? "
3884 (modes (file-modes buffer-file-name
))
3885 (context (file-selinux-context buffer-file-name
)))
3886 ;; Actually write the back up file.
3888 (if (or file-precious-flag
3889 ; (file-symlink-p buffer-file-name)
3891 ;; Don't rename a suid or sgid file.
3892 (and modes
(< 0 (logand modes
#o6000
)))
3893 (not (file-writable-p (file-name-directory real-file-name
)))
3894 (and backup-by-copying-when-linked
3895 (> (file-nlinks real-file-name
) 1))
3896 (and (or backup-by-copying-when-mismatch
3897 (integerp backup-by-copying-when-privileged-mismatch
))
3898 (let ((attr (file-attributes real-file-name
)))
3899 (and (or backup-by-copying-when-mismatch
3900 (and (integerp (nth 2 attr
))
3901 (integerp backup-by-copying-when-privileged-mismatch
)
3902 (<= (nth 2 attr
) backup-by-copying-when-privileged-mismatch
)))
3904 (not (file-ownership-preserved-p real-file-name
)))))))
3905 (backup-buffer-copy real-file-name backupname modes context
)
3906 ;; rename-file should delete old backup.
3907 (rename-file real-file-name backupname t
)
3908 (setq setmodes
(list modes context backupname
)))
3910 ;; If trouble writing the backup, write it in
3911 ;; .emacs.d/%backup%.
3912 (setq backupname
(locate-user-emacs-file "%backup%~"))
3913 (message "Cannot write backup file; backing up in %s"
3916 (backup-buffer-copy real-file-name backupname modes context
)))
3917 (setq buffer-backed-up t
)
3918 ;; Now delete the old versions, if desired.
3919 (if delete-old-versions
3922 (delete-file (car targets
))
3924 (setq targets
(cdr targets
))))
3926 (file-error nil
))))))
3928 (defun backup-buffer-copy (from-name to-name modes context
)
3929 (let ((umask (default-file-modes)))
3932 ;; Create temp files with strict access rights. It's easy to
3933 ;; loosen them later, whereas it's impossible to close the
3934 ;; time-window of loose permissions otherwise.
3935 (set-default-file-modes ?
\700)
3936 (when (condition-case nil
3937 ;; Try to overwrite old backup first.
3938 (copy-file from-name to-name t t t
)
3940 (while (condition-case nil
3942 (when (file-exists-p to-name
)
3943 (delete-file to-name
))
3944 (copy-file from-name to-name nil t t
)
3946 (file-already-exists t
))
3947 ;; The file was somehow created by someone else between
3948 ;; `delete-file' and `copy-file', so let's try again.
3949 ;; rms says "I think there is also a possible race
3950 ;; condition for making backup files" (emacs-devel 20070821).
3953 (set-default-file-modes umask
)))
3955 (set-file-modes to-name
(logand modes
#o1777
)))
3957 (set-file-selinux-context to-name context
)))
3959 (defvar file-name-version-regexp
3960 "\\(?:~\\|\\.~[-[:alnum:]:#@^._]+\\(?:~[[:digit:]]+\\)?~\\)"
3961 ;; The last ~[[:digit]]+ matches relative versions in git,
3962 ;; e.g. `foo.js.~HEAD~1~'.
3963 "Regular expression matching the backup/version part of a file name.
3964 Used by `file-name-sans-versions'.")
3966 (defun file-name-sans-versions (name &optional keep-backup-version
)
3967 "Return file NAME sans backup versions or strings.
3968 This is a separate procedure so your site-init or startup file can
3970 If the optional argument KEEP-BACKUP-VERSION is non-nil,
3971 we do not remove backup version numbers, only true file version numbers.
3972 See also `file-name-version-regexp'."
3973 (let ((handler (find-file-name-handler name
'file-name-sans-versions
)))
3975 (funcall handler
'file-name-sans-versions name keep-backup-version
)
3977 (unless keep-backup-version
3978 (string-match (concat file-name-version-regexp
"\\'")
3981 (defun file-ownership-preserved-p (file)
3982 "Return t if deleting FILE and rewriting it would preserve the owner."
3983 (let ((handler (find-file-name-handler file
'file-ownership-preserved-p
)))
3985 (funcall handler
'file-ownership-preserved-p file
)
3986 (let ((attributes (file-attributes file
'integer
)))
3987 ;; Return t if the file doesn't exist, since it's true that no
3988 ;; information would be lost by an (attempted) delete and create.
3989 (or (null attributes
)
3990 (= (nth 2 attributes
) (user-uid))
3991 ;; Files created on Windows by Administrator (RID=500)
3992 ;; have the Administrators group (RID=544) recorded as
3993 ;; their owner. Rewriting them will still preserve the
3995 (and (eq system-type
'windows-nt
)
3996 (= (user-uid) 500) (= (nth 2 attributes
) 544)))))))
3998 (defun file-name-sans-extension (filename)
3999 "Return FILENAME sans final \"extension\".
4000 The extension, in a file name, is the part that follows the last `.',
4001 except that a leading `.', if any, doesn't count."
4003 (let ((file (file-name-sans-versions (file-name-nondirectory filename
)))
4005 (if (and (string-match "\\.[^.]*\\'" file
)
4006 (not (eq 0 (match-beginning 0))))
4007 (if (setq directory
(file-name-directory filename
))
4008 ;; Don't use expand-file-name here; if DIRECTORY is relative,
4009 ;; we don't want to expand it.
4010 (concat directory
(substring file
0 (match-beginning 0)))
4011 (substring file
0 (match-beginning 0)))
4014 (defun file-name-extension (filename &optional period
)
4015 "Return FILENAME's final \"extension\".
4016 The extension, in a file name, is the part that follows the last `.',
4017 excluding version numbers and backup suffixes,
4018 except that a leading `.', if any, doesn't count.
4019 Return nil for extensionless file names such as `foo'.
4020 Return the empty string for file names such as `foo.'.
4022 If PERIOD is non-nil, then the returned value includes the period
4023 that delimits the extension, and if FILENAME has no extension,
4026 (let ((file (file-name-sans-versions (file-name-nondirectory filename
))))
4027 (if (and (string-match "\\.[^.]*\\'" file
)
4028 (not (eq 0 (match-beginning 0))))
4029 (substring file
(+ (match-beginning 0) (if period
0 1)))
4033 (defcustom make-backup-file-name-function nil
4034 "A function to use instead of the default `make-backup-file-name'.
4035 A value of nil gives the default `make-backup-file-name' behavior.
4037 This could be buffer-local to do something special for specific
4038 files. If you define it, you may need to change `backup-file-name-p'
4039 and `file-name-sans-versions' too.
4041 See also `backup-directory-alist'."
4043 :type
'(choice (const :tag
"Default" nil
)
4044 (function :tag
"Your function")))
4046 (defcustom backup-directory-alist nil
4047 "Alist of filename patterns and backup directory names.
4048 Each element looks like (REGEXP . DIRECTORY). Backups of files with
4049 names matching REGEXP will be made in DIRECTORY. DIRECTORY may be
4050 relative or absolute. If it is absolute, so that all matching files
4051 are backed up into the same directory, the file names in this
4052 directory will be the full name of the file backed up with all
4053 directory separators changed to `!' to prevent clashes. This will not
4054 work correctly if your filesystem truncates the resulting name.
4056 For the common case of all backups going into one directory, the alist
4057 should contain a single element pairing \".\" with the appropriate
4060 If this variable is nil, or it fails to match a filename, the backup
4061 is made in the original file's directory.
4063 On MS-DOS filesystems without long names this variable is always
4066 :type
'(repeat (cons (regexp :tag
"Regexp matching filename")
4067 (directory :tag
"Backup directory name"))))
4069 (defun normal-backup-enable-predicate (name)
4070 "Default `backup-enable-predicate' function.
4071 Checks for files in `temporary-file-directory',
4072 `small-temporary-file-directory', and /tmp."
4073 (not (or (let ((comp (compare-strings temporary-file-directory
0 nil
4075 ;; Directory is under temporary-file-directory.
4076 (and (not (eq comp t
))
4077 (< comp
(- (length temporary-file-directory
)))))
4078 (let ((comp (compare-strings "/tmp" 0 nil
4080 ;; Directory is under /tmp.
4081 (and (not (eq comp t
))
4082 (< comp
(- (length "/tmp")))))
4083 (if small-temporary-file-directory
4084 (let ((comp (compare-strings small-temporary-file-directory
4087 ;; Directory is under small-temporary-file-directory.
4088 (and (not (eq comp t
))
4089 (< comp
(- (length small-temporary-file-directory
)))))))))
4091 (defun make-backup-file-name (file)
4092 "Create the non-numeric backup file name for FILE.
4093 Normally this will just be the file's name with `~' appended.
4094 Customization hooks are provided as follows.
4096 If the variable `make-backup-file-name-function' is non-nil, its value
4097 should be a function which will be called with FILE as its argument;
4098 the resulting name is used.
4100 Otherwise a match for FILE is sought in `backup-directory-alist'; see
4101 the documentation of that variable. If the directory for the backup
4102 doesn't exist, it is created."
4103 (if make-backup-file-name-function
4104 (funcall make-backup-file-name-function file
)
4105 (if (and (eq system-type
'ms-dos
)
4106 (not (msdos-long-file-names)))
4107 (let ((fn (file-name-nondirectory file
)))
4108 (concat (file-name-directory file
)
4109 (or (and (string-match "\\`[^.]+\\'" fn
)
4110 (concat (match-string 0 fn
) ".~"))
4111 (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn
)
4112 (concat (match-string 0 fn
) "~")))))
4113 (concat (make-backup-file-name-1 file
) "~"))))
4115 (defun make-backup-file-name-1 (file)
4116 "Subroutine of `make-backup-file-name' and `find-backup-file-name'."
4117 (let ((alist backup-directory-alist
)
4118 elt backup-directory abs-backup-directory
)
4120 (setq elt
(pop alist
))
4121 (if (string-match (car elt
) file
)
4122 (setq backup-directory
(cdr elt
)
4124 ;; If backup-directory is relative, it should be relative to the
4125 ;; file's directory. By expanding explicitly here, we avoid
4126 ;; depending on default-directory.
4127 (if backup-directory
4128 (setq abs-backup-directory
4129 (expand-file-name backup-directory
4130 (file-name-directory file
))))
4131 (if (and abs-backup-directory
(not (file-exists-p abs-backup-directory
)))
4133 (make-directory abs-backup-directory
'parents
)
4134 (file-error (setq backup-directory nil
4135 abs-backup-directory nil
))))
4136 (if (null backup-directory
)
4138 (if (file-name-absolute-p backup-directory
)
4140 (when (memq system-type
'(windows-nt ms-dos cygwin
))
4141 ;; Normalize DOSish file names: downcase the drive
4142 ;; letter, if any, and replace the leading "x:" with
4144 (or (file-name-absolute-p file
)
4145 (setq file
(expand-file-name file
))) ; make defaults explicit
4146 ;; Replace any invalid file-name characters (for the
4147 ;; case of backing up remote files).
4148 (setq file
(expand-file-name (convert-standard-filename file
)))
4149 (if (eq (aref file
1) ?
:)
4150 (setq file
(concat "/"
4152 (char-to-string (downcase (aref file
0)))
4153 (if (eq (aref file
2) ?
/)
4156 (substring file
2)))))
4157 ;; Make the name unique by substituting directory
4158 ;; separators. It may not really be worth bothering about
4159 ;; doubling `!'s in the original name...
4161 (subst-char-in-string
4163 (replace-regexp-in-string "!" "!!" file
))
4165 (expand-file-name (file-name-nondirectory file
)
4166 (file-name-as-directory abs-backup-directory
))))))
4168 (defun backup-file-name-p (file)
4169 "Return non-nil if FILE is a backup file name (numeric or not).
4170 This is a separate function so you can redefine it for customization.
4171 You may need to redefine `file-name-sans-versions' as well."
4172 (string-match "~\\'" file
))
4174 (defvar backup-extract-version-start
)
4176 ;; This is used in various files.
4177 ;; The usage of backup-extract-version-start is not very clean,
4178 ;; but I can't see a good alternative, so as of now I am leaving it alone.
4179 (defun backup-extract-version (fn)
4180 "Given the name of a numeric backup file, FN, return the backup number.
4181 Uses the free variable `backup-extract-version-start', whose value should be
4182 the index in the name where the version number begins."
4183 (if (and (string-match "[0-9]+~/?$" fn backup-extract-version-start
)
4184 (= (match-beginning 0) backup-extract-version-start
))
4185 (string-to-number (substring fn backup-extract-version-start -
1))
4188 (defun find-backup-file-name (fn)
4189 "Find a file name for a backup file FN, and suggestions for deletions.
4190 Value is a list whose car is the name for the backup file
4191 and whose cdr is a list of old versions to consider deleting now.
4192 If the value is nil, don't make a backup.
4193 Uses `backup-directory-alist' in the same way as does
4194 `make-backup-file-name'."
4195 (let ((handler (find-file-name-handler fn
'find-backup-file-name
)))
4196 ;; Run a handler for this function so that ange-ftp can refuse to do it.
4198 (funcall handler
'find-backup-file-name fn
)
4199 (if (or (eq version-control
'never
)
4200 ;; We don't support numbered backups on plain MS-DOS
4201 ;; when long file names are unavailable.
4202 (and (eq system-type
'ms-dos
)
4203 (not (msdos-long-file-names))))
4204 (list (make-backup-file-name fn
))
4205 (let* ((basic-name (make-backup-file-name-1 fn
))
4206 (base-versions (concat (file-name-nondirectory basic-name
)
4208 (backup-extract-version-start (length base-versions
))
4210 (number-to-delete 0)
4211 possibilities deserve-versions-p versions
)
4213 (setq possibilities
(file-name-all-completions
4215 (file-name-directory basic-name
))
4216 versions
(sort (mapcar #'backup-extract-version
4219 high-water-mark
(apply 'max
0 versions
)
4220 deserve-versions-p
(or version-control
4221 (> high-water-mark
0))
4222 number-to-delete
(- (length versions
)
4226 (file-error (setq possibilities nil
)))
4227 (if (not deserve-versions-p
)
4228 (list (make-backup-file-name fn
))
4229 (cons (format "%s.~%d~" basic-name
(1+ high-water-mark
))
4230 (if (and (> number-to-delete
0)
4231 ;; Delete nothing if there is overflow
4232 ;; in the number of versions to keep.
4233 (>= (+ kept-new-versions kept-old-versions -
1) 0))
4235 (format "%s.~%d~" basic-name n
))
4236 (let ((v (nthcdr kept-old-versions versions
)))
4237 (rplacd (nthcdr (1- number-to-delete
) v
) ())
4240 (defun file-nlinks (filename)
4241 "Return number of names file FILENAME has."
4242 (car (cdr (file-attributes filename
))))
4244 ;; (defun file-relative-name (filename &optional directory)
4245 ;; "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
4246 ;; This function returns a relative file name which is equivalent to FILENAME
4247 ;; when used with that default directory as the default.
4248 ;; If this is impossible (which can happen on MSDOS and Windows
4249 ;; when the file name and directory use different drive names)
4250 ;; then it returns FILENAME."
4252 ;; (let ((fname (expand-file-name filename)))
4253 ;; (setq directory (file-name-as-directory
4254 ;; (expand-file-name (or directory default-directory))))
4255 ;; ;; On Microsoft OSes, if FILENAME and DIRECTORY have different
4256 ;; ;; drive names, they can't be relative, so return the absolute name.
4257 ;; (if (and (or (eq system-type 'ms-dos)
4258 ;; (eq system-type 'cygwin)
4259 ;; (eq system-type 'windows-nt))
4260 ;; (not (string-equal (substring fname 0 2)
4261 ;; (substring directory 0 2))))
4263 ;; (let ((ancestor ".")
4264 ;; (fname-dir (file-name-as-directory fname)))
4265 ;; (while (and (not (string-match (concat "^" (regexp-quote directory)) fname-dir))
4266 ;; (not (string-match (concat "^" (regexp-quote directory)) fname)))
4267 ;; (setq directory (file-name-directory (substring directory 0 -1))
4268 ;; ancestor (if (equal ancestor ".")
4270 ;; (concat "../" ancestor))))
4271 ;; ;; Now ancestor is empty, or .., or ../.., etc.
4272 ;; (if (string-match (concat "^" (regexp-quote directory)) fname)
4273 ;; ;; We matched within FNAME's directory part.
4274 ;; ;; Add the rest of FNAME onto ANCESTOR.
4275 ;; (let ((rest (substring fname (match-end 0))))
4276 ;; (if (and (equal ancestor ".")
4277 ;; (not (equal rest "")))
4278 ;; ;; But don't bother with ANCESTOR if it would give us `./'.
4280 ;; (concat (file-name-as-directory ancestor) rest)))
4281 ;; ;; We matched FNAME's directory equivalent.
4284 (defun file-relative-name (filename &optional directory
)
4285 "Convert FILENAME to be relative to DIRECTORY (default: `default-directory').
4286 This function returns a relative file name which is equivalent to FILENAME
4287 when used with that default directory as the default.
4288 If FILENAME and DIRECTORY lie on different machines or on different drives
4289 on a DOS/Windows machine, it returns FILENAME in expanded form."
4292 (file-name-as-directory (expand-file-name (or directory
4293 default-directory
))))
4294 (setq filename
(expand-file-name filename
))
4295 (let ((fremote (file-remote-p filename
))
4296 (dremote (file-remote-p directory
)))
4297 (if ;; Conditions for separate trees
4299 ;; Test for different filesystems on DOS/Windows
4301 ;; Should `cygwin' really be included here? --stef
4302 (memq system-type
'(ms-dos cygwin windows-nt
))
4304 ;; Test for different drive letters
4305 (not (eq t
(compare-strings filename
0 2 directory
0 2)))
4306 ;; Test for UNCs on different servers
4307 (not (eq t
(compare-strings
4309 (if (string-match "\\`//\\([^:/]+\\)/" filename
)
4310 (match-string 1 filename
)
4311 ;; Windows file names cannot have ? in
4312 ;; them, so use that to detect when
4313 ;; neither FILENAME nor DIRECTORY is a
4318 (if (string-match "\\`//\\([^:/]+\\)/" directory
)
4319 (match-string 1 directory
)
4322 ;; Test for different remote file system identification
4323 (not (equal fremote dremote
)))
4325 (let ((ancestor ".")
4326 (filename-dir (file-name-as-directory filename
)))
4329 (eq t
(compare-strings filename-dir nil
(length directory
)
4330 directory nil nil case-fold-search
))
4331 (eq t
(compare-strings filename nil
(length directory
)
4332 directory nil nil case-fold-search
))))
4333 (setq directory
(file-name-directory (substring directory
0 -
1))
4334 ancestor
(if (equal ancestor
".")
4336 (concat "../" ancestor
))))
4337 ;; Now ancestor is empty, or .., or ../.., etc.
4338 (if (eq t
(compare-strings filename nil
(length directory
)
4339 directory nil nil case-fold-search
))
4340 ;; We matched within FILENAME's directory part.
4341 ;; Add the rest of FILENAME onto ANCESTOR.
4342 (let ((rest (substring filename
(length directory
))))
4343 (if (and (equal ancestor
".") (not (equal rest
"")))
4344 ;; But don't bother with ANCESTOR if it would give us `./'.
4346 (concat (file-name-as-directory ancestor
) rest
)))
4347 ;; We matched FILENAME's directory equivalent.
4350 (defun save-buffer (&optional args
)
4351 "Save current buffer in visited file if modified.
4352 Variations are described below.
4354 By default, makes the previous version into a backup file
4355 if previously requested or if this is the first save.
4356 Prefixed with one \\[universal-argument], marks this version
4357 to become a backup when the next save is done.
4358 Prefixed with two \\[universal-argument]'s,
4359 unconditionally makes the previous version into a backup file.
4360 Prefixed with three \\[universal-argument]'s, marks this version
4361 to become a backup when the next save is done,
4362 and unconditionally makes the previous version into a backup file.
4364 With a numeric argument of 0, never make the previous version
4367 If a file's name is FOO, the names of its numbered backup versions are
4368 FOO.~i~ for various integers i. A non-numbered backup file is called FOO~.
4369 Numeric backups (rather than FOO~) will be made if value of
4370 `version-control' is not the atom `never' and either there are already
4371 numeric versions of the file being backed up, or `version-control' is
4373 We don't want excessive versions piling up, so there are variables
4374 `kept-old-versions', which tells Emacs how many oldest versions to keep,
4375 and `kept-new-versions', which tells how many newest versions to keep.
4376 Defaults are 2 old versions and 2 new.
4377 `dired-kept-versions' controls dired's clean-directory (.) command.
4378 If `delete-old-versions' is nil, system will query user
4379 before trimming versions. Otherwise it does it silently.
4381 If `vc-make-backup-files' is nil, which is the default,
4382 no backup files are made for files managed by version control.
4383 (This is because the version control system itself records previous versions.)
4385 See the subroutine `basic-save-buffer' for more information."
4387 (let ((modp (buffer-modified-p))
4388 (make-backup-files (or (and make-backup-files
(not (eq args
0)))
4389 (memq args
'(16 64)))))
4390 (and modp
(memq args
'(16 64)) (setq buffer-backed-up nil
))
4391 ;; We used to display the message below only for files > 50KB, but
4392 ;; then Rmail-mbox never displays it due to buffer swapping. If
4393 ;; the test is ever re-introduced, be sure to handle saving of
4395 (if (and modp
(buffer-file-name))
4396 (message "Saving file %s..." (buffer-file-name)))
4398 (and modp
(memq args
'(4 64)) (setq buffer-backed-up nil
))))
4400 (defun delete-auto-save-file-if-necessary (&optional force
)
4401 "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
4402 Normally delete only if the file was written by this Emacs since
4403 the last real save, but optional arg FORCE non-nil means delete anyway."
4404 (and buffer-auto-save-file-name delete-auto-save-files
4405 (not (string= buffer-file-name buffer-auto-save-file-name
))
4406 (or force
(recent-auto-save-p))
4409 (delete-file buffer-auto-save-file-name
)
4411 (set-buffer-auto-saved))))
4413 (defvar auto-save-hook nil
4414 "Normal hook run just before auto-saving.")
4416 (defcustom before-save-hook nil
4417 "Normal hook that is run before a buffer is saved to its file."
4418 :options
'(copyright-update time-stamp
)
4422 (defcustom after-save-hook nil
4423 "Normal hook that is run after a buffer is saved to its file."
4424 :options
'(executable-make-buffer-file-executable-if-script-p)
4428 (defvar save-buffer-coding-system nil
4429 "If non-nil, use this coding system for saving the buffer.
4430 More precisely, use this coding system in place of the
4431 value of `buffer-file-coding-system', when saving the buffer.
4432 Calling `write-region' for any purpose other than saving the buffer
4433 will still use `buffer-file-coding-system'; this variable has no effect
4436 (make-variable-buffer-local 'save-buffer-coding-system
)
4437 (put 'save-buffer-coding-system
'permanent-local t
)
4439 (defun basic-save-buffer ()
4440 "Save the current buffer in its visited file, if it has been modified.
4441 The hooks `write-contents-functions' and `write-file-functions' get a chance
4442 to do the job of saving; if they do not, then the buffer is saved in
4443 the visited file in the usual way.
4444 Before and after saving the buffer, this function runs
4445 `before-save-hook' and `after-save-hook', respectively."
4447 (save-current-buffer
4448 ;; In an indirect buffer, save its base buffer instead.
4449 (if (buffer-base-buffer)
4450 (set-buffer (buffer-base-buffer)))
4451 (if (or (buffer-modified-p)
4452 ;; handle the case when no modification has been made but
4453 ;; the file disappeared since visited
4454 (and buffer-file-name
4455 (not (file-exists-p buffer-file-name
))))
4456 (let ((recent-save (recent-auto-save-p))
4458 ;; If buffer has no file name, ask user for one.
4459 (or buffer-file-name
4462 (read-file-name "File to save in: ") nil
)))
4463 (if (file-exists-p filename
)
4464 (if (file-directory-p filename
)
4465 ;; Signal an error if the user specified the name of an
4466 ;; existing directory.
4467 (error "%s is a directory" filename
)
4468 (unless (y-or-n-p (format "File `%s' exists; overwrite? "
4470 (error "Canceled")))
4471 ;; Signal an error if the specified name refers to a
4472 ;; non-existing directory.
4473 (let ((dir (file-name-directory filename
)))
4474 (unless (file-directory-p dir
)
4475 (if (file-exists-p dir
)
4476 (error "%s is not a directory" dir
)
4477 (error "%s: no such directory" dir
)))))
4478 (set-visited-file-name filename
)))
4479 (or (verify-visited-file-modtime (current-buffer))
4480 (not (file-exists-p buffer-file-name
))
4483 "%s has changed since visited or saved. Save anyway? "
4484 (file-name-nondirectory buffer-file-name
)))
4485 (error "Save not confirmed"))
4489 (and (> (point-max) (point-min))
4490 (not find-file-literally
)
4491 (/= (char-after (1- (point-max))) ?
\n)
4492 (not (and (eq selective-display t
)
4493 (= (char-after (1- (point-max))) ?
\r)))
4494 (or (eq require-final-newline t
)
4495 (eq require-final-newline
'visit-save
)
4496 (and require-final-newline
4498 (format "Buffer %s does not end in newline. Add one? "
4501 (goto-char (point-max))
4503 ;; Support VC version backups.
4505 (run-hooks 'before-save-hook
)
4506 (or (run-hook-with-args-until-success 'write-contents-functions
)
4507 (run-hook-with-args-until-success 'local-write-file-hooks
)
4508 (run-hook-with-args-until-success 'write-file-functions
)
4509 ;; If a hook returned t, file is already "written".
4510 ;; Otherwise, write it the usual way now.
4511 (setq setmodes
(basic-save-buffer-1)))
4512 ;; Now we have saved the current buffer. Let's make sure
4513 ;; that buffer-file-coding-system is fixed to what
4514 ;; actually used for saving by binding it locally.
4515 (if save-buffer-coding-system
4516 (setq save-buffer-coding-system last-coding-system-used
)
4517 (setq buffer-file-coding-system last-coding-system-used
))
4518 (setq buffer-file-number
4519 (nthcdr 10 (file-attributes buffer-file-name
)))
4523 (set-file-modes buffer-file-name
(car setmodes
))
4524 (set-file-selinux-context buffer-file-name
(nth 1 setmodes
)))
4526 ;; If the auto-save file was recent before this command,
4528 (delete-auto-save-file-if-necessary recent-save
)
4529 ;; Support VC `implicit' locking.
4531 (run-hooks 'after-save-hook
))
4532 (message "(No changes need to be saved)"))))
4534 ;; This does the "real job" of writing a buffer into its visited file
4535 ;; and making a backup file. This is what is normally done
4536 ;; but inhibited if one of write-file-functions returns non-nil.
4537 ;; It returns a value (MODES SELINUXCONTEXT BACKUPNAME), like backup-buffer.
4538 (defun basic-save-buffer-1 ()
4540 (if save-buffer-coding-system
4541 (let ((coding-system-for-write save-buffer-coding-system
))
4542 (basic-save-buffer-2))
4543 (basic-save-buffer-2))
4544 (if buffer-file-coding-system-explicit
4545 (setcar buffer-file-coding-system-explicit last-coding-system-used
)
4546 (setq buffer-file-coding-system-explicit
4547 (cons last-coding-system-used nil
)))))
4549 ;; This returns a value (MODES SELINUXCONTEXT BACKUPNAME), like backup-buffer.
4550 (defun basic-save-buffer-2 ()
4551 (let (tempsetmodes setmodes
)
4552 (if (not (file-writable-p buffer-file-name
))
4553 (let ((dir (file-name-directory buffer-file-name
)))
4554 (if (not (file-directory-p dir
))
4555 (if (file-exists-p dir
)
4556 (error "%s is not a directory" dir
)
4557 (error "%s: no such directory" dir
))
4558 (if (not (file-exists-p buffer-file-name
))
4559 (error "Directory %s write-protected" dir
)
4562 "File %s is write-protected; try to save anyway? "
4563 (file-name-nondirectory
4565 (setq tempsetmodes t
)
4566 (error "Attempt to save to a file which you aren't allowed to write"))))))
4567 (or buffer-backed-up
4568 (setq setmodes
(backup-buffer)))
4569 (let* ((dir (file-name-directory buffer-file-name
))
4570 (dir-writable (file-writable-p dir
)))
4571 (if (or (and file-precious-flag dir-writable
)
4572 (and break-hardlink-on-save
4573 (file-exists-p buffer-file-name
)
4574 (> (file-nlinks buffer-file-name
) 1)
4576 (error (concat (format
4577 "Directory %s write-protected; " dir
)
4578 "cannot break hardlink when saving")))))
4579 ;; Write temp name, then rename it.
4580 ;; This requires write access to the containing dir,
4581 ;; which is why we don't try it if we don't have that access.
4582 (let ((realname buffer-file-name
)
4584 (umask (default-file-modes))
4585 (old-modtime (visited-file-modtime)))
4586 ;; Create temp files with strict access rights. It's easy to
4587 ;; loosen them later, whereas it's impossible to close the
4588 ;; time-window of loose permissions otherwise.
4591 (clear-visited-file-modtime)
4592 (set-default-file-modes ?
\700)
4593 ;; Try various temporary names.
4594 ;; This code follows the example of make-temp-file,
4595 ;; but it calls write-region in the appropriate way
4596 ;; for saving the buffer.
4597 (while (condition-case ()
4601 (expand-file-name "tmp" dir
)))
4602 ;; Pass in nil&nil rather than point-min&max
4603 ;; cause we're saving the whole buffer.
4604 ;; write-region-annotate-functions may use it.
4605 (write-region nil nil
4606 tempname nil realname
4607 buffer-file-truename
'excl
)
4609 (file-already-exists t
))
4610 ;; The file was somehow created by someone else between
4611 ;; `make-temp-name' and `write-region', let's try again.
4615 (set-default-file-modes umask
)
4616 ;; If we failed, restore the buffer's modtime.
4618 (set-visited-file-modtime old-modtime
)))
4619 ;; Since we have created an entirely new file,
4620 ;; make sure it gets the right permission bits set.
4621 (setq setmodes
(or setmodes
4622 (list (or (file-modes buffer-file-name
)
4623 (logand ?
\666 umask
))
4624 (file-selinux-context buffer-file-name
)
4626 ;; We succeeded in writing the temp file,
4628 (rename-file tempname buffer-file-name t
))
4629 ;; If file not writable, see if we can make it writable
4630 ;; temporarily while we write it.
4631 ;; But no need to do so if we have just backed it up
4632 ;; (setmodes is set) because that says we're superseding.
4633 (cond ((and tempsetmodes
(not setmodes
))
4634 ;; Change the mode back, after writing.
4635 (setq setmodes
(list (file-modes buffer-file-name
)
4636 (file-selinux-context buffer-file-name
)
4638 (set-file-modes buffer-file-name
(logior (car setmodes
) 128))
4639 (set-file-selinux-context buffer-file-name
(nth 1 setmodes
)))))
4643 ;; Pass in nil&nil rather than point-min&max to indicate
4644 ;; we're saving the buffer rather than just a region.
4645 ;; write-region-annotate-functions may make us of it.
4646 (write-region nil nil
4647 buffer-file-name nil t buffer-file-truename
)
4649 ;; If we get an error writing the new file, and we made
4650 ;; the backup by renaming, undo the backing-up.
4651 (and setmodes
(not success
)
4653 (rename-file (nth 2 setmodes
) buffer-file-name t
)
4654 (setq buffer-backed-up nil
))))))
4657 (declare-function diff-no-select
"diff"
4658 (old new
&optional switches no-async buf
))
4660 (defvar save-some-buffers-action-alist
4663 (if (not enable-recursive-minibuffers
)
4664 (progn (display-buffer buf
)
4665 (setq other-window-scroll-buffer buf
))
4666 (view-buffer buf
(lambda (_) (exit-recursive-edit)))
4668 ;; Return nil to ask about BUF again.
4670 ,(purecopy "view this buffer"))
4672 (if (null (buffer-file-name buf
))
4673 (message "Not applicable: no file")
4674 (require 'diff
) ;for diff-no-select.
4675 (let ((diffbuf (diff-no-select (buffer-file-name buf
) buf
4677 (if (not enable-recursive-minibuffers
)
4678 (progn (display-buffer diffbuf
)
4679 (setq other-window-scroll-buffer diffbuf
))
4680 (view-buffer diffbuf
(lambda (_) (exit-recursive-edit)))
4682 ;; Return nil to ask about BUF again.
4684 ,(purecopy "view changes in this buffer")))
4685 "ACTION-ALIST argument used in call to `map-y-or-n-p'.")
4686 (put 'save-some-buffers-action-alist
'risky-local-variable t
)
4688 (defvar buffer-save-without-query nil
4689 "Non-nil means `save-some-buffers' should save this buffer without asking.")
4690 (make-variable-buffer-local 'buffer-save-without-query
)
4692 (defun save-some-buffers (&optional arg pred
)
4693 "Save some modified file-visiting buffers. Asks user about each one.
4694 You can answer `y' to save, `n' not to save, `C-r' to look at the
4695 buffer in question with `view-buffer' before deciding or `d' to
4696 view the differences using `diff-buffer-with-file'.
4698 This command first saves any buffers where `buffer-save-without-query' is
4699 non-nil, without asking.
4701 Optional argument (the prefix) non-nil means save all with no questions.
4702 Optional second argument PRED determines which buffers are considered:
4703 If PRED is nil, all the file-visiting buffers are considered.
4704 If PRED is t, then certain non-file buffers will also be considered.
4705 If PRED is a zero-argument function, it indicates for each buffer whether
4706 to consider it or not when called with that buffer current.
4708 See `save-some-buffers-action-alist' if you want to
4709 change the additional actions you can take on files."
4711 (save-window-excursion
4712 (let* (queried autosaved-buffers
4713 files-done abbrevs-done
)
4714 (dolist (buffer (buffer-list))
4715 ;; First save any buffers that we're supposed to save unconditionally.
4716 ;; That way the following code won't ask about them.
4717 (with-current-buffer buffer
4718 (when (and buffer-save-without-query
(buffer-modified-p))
4719 (push (buffer-name) autosaved-buffers
)
4721 ;; Ask about those buffers that merit it,
4722 ;; and record the number thus saved.
4726 ;; Note that killing some buffers may kill others via
4727 ;; hooks (e.g. Rmail and its viewing buffer).
4728 (and (buffer-live-p buffer
)
4729 (buffer-modified-p buffer
)
4730 (not (buffer-base-buffer buffer
))
4732 (buffer-file-name buffer
)
4736 (and buffer-offer-save
(> (buffer-size) 0)))))
4737 (or (not (functionp pred
))
4738 (with-current-buffer buffer
(funcall pred
)))
4742 (if (buffer-file-name buffer
)
4743 (format "Save file %s? "
4744 (buffer-file-name buffer
))
4745 (format "Save buffer %s? "
4746 (buffer-name buffer
))))))
4748 (with-current-buffer buffer
4751 '("buffer" "buffers" "save")
4752 save-some-buffers-action-alist
))
4753 ;; Maybe to save abbrevs, and record whether
4754 ;; we either saved them or asked to.
4755 (and save-abbrevs abbrevs-changed
4758 (eq save-abbrevs
'silently
)
4759 (y-or-n-p (format "Save abbrevs in %s? " abbrev-file-name
)))
4760 (write-abbrev-file nil
))
4761 ;; Don't keep bothering user if he says no.
4762 (setq abbrevs-changed nil
)
4763 (setq abbrevs-done t
)))
4764 (or queried
(> files-done
0) abbrevs-done
4766 ((null autosaved-buffers
)
4767 (message "(No files need saving)"))
4768 ((= (length autosaved-buffers
) 1)
4769 (message "(Saved %s)" (car autosaved-buffers
)))
4771 (message "(Saved %d files: %s)"
4772 (length autosaved-buffers
)
4773 (mapconcat 'identity autosaved-buffers
", "))))))))
4775 (defun not-modified (&optional arg
)
4776 "Mark current buffer as unmodified, not needing to be saved.
4777 With prefix ARG, mark buffer as modified, so \\[save-buffer] will save.
4779 It is not a good idea to use this function in Lisp programs, because it
4780 prints a message in the minibuffer. Instead, use `set-buffer-modified-p'."
4782 (message (if arg
"Modification-flag set"
4783 "Modification-flag cleared"))
4784 (set-buffer-modified-p arg
))
4786 (defun toggle-read-only (&optional arg
)
4787 "Change whether this buffer is read-only.
4788 With prefix argument ARG, make the buffer read-only if ARG is
4789 positive, otherwise make it writable. If buffer is read-only
4790 and `view-read-only' is non-nil, enter view mode.
4792 This function is usually the wrong thing to use in a Lisp program.
4793 It can have side-effects beyond changing the read-only status of a buffer
4794 \(e.g., enabling view mode), and does not affect read-only regions that
4795 are caused by text properties. To make a buffer read-only in Lisp code,
4796 set `buffer-read-only'. To ignore read-only status (whether due to text
4797 properties or buffer state) and make changes, temporarily bind
4798 `inhibit-read-only'."
4801 (if (> (prefix-numeric-value arg
) 0) buffer-read-only
4802 (not buffer-read-only
))) ; If buffer-read-only is set correctly,
4806 ((and buffer-read-only view-mode
)
4807 (View-exit-and-edit)
4808 (make-local-variable 'view-read-only
)
4809 (setq view-read-only t
)) ; Must leave view mode.
4810 ((and (not buffer-read-only
) view-read-only
4811 ;; If view-mode is already active, `view-mode-enter' is a nop.
4813 (not (eq (get major-mode
'mode-class
) 'special
)))
4815 (t (setq buffer-read-only
(not buffer-read-only
))
4816 (force-mode-line-update)))))
4818 (defun insert-file (filename)
4819 "Insert contents of file FILENAME into buffer after point.
4820 Set mark after the inserted text.
4822 This function is meant for the user to run interactively.
4823 Don't call it from programs! Use `insert-file-contents' instead.
4824 \(Its calling sequence is different; see its documentation)."
4825 (interactive "*fInsert file: ")
4826 (insert-file-1 filename
#'insert-file-contents
))
4828 (defun append-to-file (start end filename
)
4829 "Append the contents of the region to the end of file FILENAME.
4830 When called from a function, expects three arguments,
4831 START, END and FILENAME. START and END are normally buffer positions
4832 specifying the part of the buffer to write.
4833 If START is nil, that means to use the entire buffer contents.
4834 If START is a string, then output that string to the file
4835 instead of any buffer contents; END is ignored.
4837 This does character code conversion and applies annotations
4838 like `write-region' does."
4839 (interactive "r\nFAppend to file: ")
4840 (write-region start end filename t
))
4842 (defun file-newest-backup (filename)
4843 "Return most recent backup file for FILENAME or nil if no backups exist."
4844 ;; `make-backup-file-name' will get us the right directory for
4845 ;; ordinary or numeric backups. It might create a directory for
4846 ;; backups as a side-effect, according to `backup-directory-alist'.
4847 (let* ((filename (file-name-sans-versions
4848 (make-backup-file-name (expand-file-name filename
))))
4849 (file (file-name-nondirectory filename
))
4850 (dir (file-name-directory filename
))
4851 (comp (file-name-all-completions file dir
))
4855 (setq tem
(pop comp
))
4856 (cond ((and (backup-file-name-p tem
)
4857 (string= (file-name-sans-versions tem
) file
))
4858 (setq tem
(concat dir tem
))
4859 (if (or (null newest
)
4860 (file-newer-than-file-p tem newest
))
4861 (setq newest tem
)))))
4864 (defun rename-uniquely ()
4865 "Rename current buffer to a similar name not already taken.
4866 This function is useful for creating multiple shell process buffers
4867 or multiple mail buffers, etc.
4869 Note that some commands, in particular those based on `compilation-mode'
4870 \(`compile', `grep', etc.) will reuse the current buffer if it has the
4871 appropriate mode even if it has been renamed. So as well as renaming
4872 the buffer, you also need to switch buffers before running another
4873 instance of such commands."
4876 (let ((base-name (buffer-name)))
4877 (and (string-match "<[0-9]+>\\'" base-name
)
4878 (not (and buffer-file-name
4880 (file-name-nondirectory buffer-file-name
))))
4881 ;; If the existing buffer name has a <NNN>,
4882 ;; which isn't part of the file name (if any),
4883 ;; then get rid of that.
4884 (setq base-name
(substring base-name
0 (match-beginning 0))))
4885 (rename-buffer (generate-new-buffer-name base-name
))
4886 (force-mode-line-update))))
4888 (defun make-directory (dir &optional parents
)
4889 "Create the directory DIR and optionally any nonexistent parent dirs.
4890 If DIR already exists as a directory, signal an error, unless
4893 Interactively, the default choice of directory to create is the
4894 current buffer's default directory. That is useful when you have
4895 visited a file in a nonexistent directory.
4897 Noninteractively, the second (optional) argument PARENTS, if
4898 non-nil, says whether to create parent directories that don't
4899 exist. Interactively, this happens by default.
4901 If creating the directory or directories fail, an error will be
4904 (list (read-file-name "Make directory: " default-directory default-directory
4907 ;; If default-directory is a remote directory,
4908 ;; make sure we find its make-directory handler.
4909 (setq dir
(expand-file-name dir
))
4910 (let ((handler (find-file-name-handler dir
'make-directory
)))
4912 (funcall handler
'make-directory dir parents
)
4914 (make-directory-internal dir
)
4915 (let ((dir (directory-file-name (expand-file-name dir
)))
4917 (while (and (not (file-exists-p dir
))
4918 ;; If directory is its own parent, then we can't
4919 ;; keep looping forever
4921 (directory-file-name
4922 (file-name-directory dir
)))))
4923 (setq create-list
(cons dir create-list
)
4924 dir
(directory-file-name (file-name-directory dir
))))
4926 (make-directory-internal (car create-list
))
4927 (setq create-list
(cdr create-list
))))))))
4929 (defconst directory-files-no-dot-files-regexp
4930 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"
4931 "Regexp matching any file name except \".\" and \"..\".")
4933 (defun delete-directory (directory &optional recursive trash
)
4934 "Delete the directory named DIRECTORY. Does not follow symlinks.
4935 If RECURSIVE is non-nil, all files in DIRECTORY are deleted as well.
4936 TRASH non-nil means to trash the directory instead, provided
4937 `delete-by-moving-to-trash' is non-nil.
4939 When called interactively, TRASH is t if no prefix argument is
4940 given. With a prefix argument, TRASH is nil."
4942 (let* ((trashing (and delete-by-moving-to-trash
4943 (null current-prefix-arg
)))
4944 (dir (expand-file-name
4945 (read-directory-name
4947 "Move directory to trash: "
4948 "Delete directory: ")
4949 default-directory default-directory nil nil
))))
4951 (if (directory-files dir nil directory-files-no-dot-files-regexp
)
4953 (format "Directory `%s' is not empty, really %s? "
4954 dir
(if trashing
"trash" "delete")))
4956 (null current-prefix-arg
))))
4957 ;; If default-directory is a remote directory, make sure we find its
4958 ;; delete-directory handler.
4959 (setq directory
(directory-file-name (expand-file-name directory
)))
4960 (let ((handler (find-file-name-handler directory
'delete-directory
)))
4963 (funcall handler
'delete-directory directory recursive
))
4964 ((and delete-by-moving-to-trash trash
)
4965 ;; Only move non-empty dir to trash if recursive deletion was
4966 ;; requested. This mimics the non-`delete-by-moving-to-trash'
4967 ;; case, where the operation fails in delete-directory-internal.
4968 ;; As `move-file-to-trash' trashes directories (empty or
4969 ;; otherwise) as a unit, we do not need to recurse here.
4970 (if (and (not recursive
)
4971 ;; Check if directory is empty apart from "." and "..".
4973 directory
'full directory-files-no-dot-files-regexp
))
4974 (error "Directory is not empty, not moving to trash")
4975 (move-file-to-trash directory
)))
4976 ;; Otherwise, call ourselves recursively if needed.
4978 (if (and recursive
(not (file-symlink-p directory
)))
4979 (mapc (lambda (file)
4980 ;; This test is equivalent to
4981 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
4982 ;; but more efficient
4983 (if (eq t
(car (file-attributes file
)))
4984 (delete-directory file recursive nil
)
4985 (delete-file file nil
)))
4986 ;; We do not want to delete "." and "..".
4988 directory
'full directory-files-no-dot-files-regexp
)))
4989 (delete-directory-internal directory
)))))
4991 (defun file-equal-p (file1 file2
)
4992 "Return non-nil if files FILE1 and FILE2 name the same file.
4993 If FILE1 or FILE2 does not exist, the return value is unspecified."
4994 (let ((handler (or (find-file-name-handler file1
'file-equal-p
)
4995 (find-file-name-handler file2
'file-equal-p
))))
4997 (funcall handler
'file-equal-p file1 file2
)
4998 (let (f1-attr f2-attr
)
4999 (and (setq f1-attr
(file-attributes (file-truename file1
)))
5000 (setq f2-attr
(file-attributes (file-truename file2
)))
5001 (equal f1-attr f2-attr
))))))
5003 (defun file-subdir-of-p (dir1 dir2
)
5004 "Return non-nil if DIR1 is a subdirectory of DIR2.
5005 A directory is considered to be a subdirectory of itself.
5006 Return nil if top directory DIR2 is not an existing directory."
5007 (let ((handler (or (find-file-name-handler dir1
'file-subdir-of-p
)
5008 (find-file-name-handler dir2
'file-subdir-of-p
))))
5010 (funcall handler
'file-subdir-of-p dir1 dir2
)
5011 (when (file-directory-p dir2
) ; Top dir must exist.
5012 (setq dir1
(file-truename dir1
)
5013 dir2
(file-truename dir2
))
5014 (let ((ls1 (or (split-string dir1
"/" t
) '("/")))
5015 (ls2 (or (split-string dir2
"/" t
) '("/")))
5016 (root (if (string-match "\\`/" dir1
) "/" ""))
5018 (while (and ls1 ls2
(not mismatch
))
5019 (if (string-equal (car ls1
) (car ls2
))
5020 (setq root
(concat root
(car ls1
) "/"))
5025 (file-equal-p root dir2
)))))))
5027 (defun copy-directory (directory newname
&optional keep-time parents copy-contents
)
5028 "Copy DIRECTORY to NEWNAME. Both args must be strings.
5029 This function always sets the file modes of the output files to match
5030 the corresponding input file.
5032 The third arg KEEP-TIME non-nil means give the output files the same
5033 last-modified time as the old ones. (This works on only some systems.)
5035 A prefix arg makes KEEP-TIME non-nil.
5037 Noninteractively, the last argument PARENTS says whether to
5038 create parent directories if they don't exist. Interactively,
5039 this happens by default.
5041 If NEWNAME names an existing directory, copy DIRECTORY as a
5042 subdirectory there. However, if called from Lisp with a non-nil
5043 optional argument COPY-CONTENTS, copy the contents of DIRECTORY
5044 directly into NEWNAME instead."
5046 (let ((dir (read-directory-name
5047 "Copy directory: " default-directory default-directory t nil
)))
5049 (read-directory-name
5050 (format "Copy directory %s to: " dir
)
5051 default-directory default-directory nil nil
)
5052 current-prefix-arg t nil
)))
5053 (when (file-subdir-of-p newname directory
)
5054 (error "Cannot copy `%s' into its subdirectory `%s'"
5056 ;; If default-directory is a remote directory, make sure we find its
5057 ;; copy-directory handler.
5058 (let ((handler (or (find-file-name-handler directory
'copy-directory
)
5059 (find-file-name-handler newname
'copy-directory
))))
5061 (funcall handler
'copy-directory directory
5062 newname keep-time parents copy-contents
)
5064 ;; Compute target name.
5065 (setq directory
(directory-file-name (expand-file-name directory
))
5066 newname
(directory-file-name (expand-file-name newname
)))
5068 (cond ((not (file-directory-p newname
))
5069 ;; If NEWNAME is not an existing directory, create it;
5070 ;; that is where we will copy the files of DIRECTORY.
5071 (make-directory newname parents
))
5072 ;; If NEWNAME is an existing directory and COPY-CONTENTS
5073 ;; is nil, copy into NEWNAME/[DIRECTORY-BASENAME].
5074 ((not copy-contents
)
5075 (setq newname
(expand-file-name
5076 (file-name-nondirectory
5077 (directory-file-name directory
))
5079 (and (file-exists-p newname
)
5080 (not (file-directory-p newname
))
5081 (error "Cannot overwrite non-directory %s with a directory"
5083 (make-directory newname t
)))
5085 ;; Copy recursively.
5087 ;; We do not want to copy "." and "..".
5088 (directory-files directory
'full
5089 directory-files-no-dot-files-regexp
))
5090 (if (file-directory-p file
)
5091 (copy-directory file newname keep-time parents
)
5092 (let ((target (expand-file-name (file-name-nondirectory file
) newname
))
5093 (attrs (file-attributes file
)))
5094 (if (stringp (car attrs
)) ; Symbolic link
5095 (make-symbolic-link (car attrs
) target t
)
5096 (copy-file file target t keep-time
)))))
5098 ;; Set directory attributes.
5099 (let ((modes (file-modes directory
))
5100 (times (and keep-time
(nth 5 (file-attributes directory
)))))
5101 (if modes
(set-file-modes newname modes
))
5102 (if times
(set-file-times newname times
))))))
5104 (put 'revert-buffer-function
'permanent-local t
)
5105 (defvar revert-buffer-function nil
5106 "Function to use to revert this buffer, or nil to do the default.
5107 The function receives two arguments IGNORE-AUTO and NOCONFIRM,
5108 which are the arguments that `revert-buffer' received.")
5110 (put 'revert-buffer-insert-file-contents-function
'permanent-local t
)
5111 (defvar revert-buffer-insert-file-contents-function nil
5112 "Function to use to insert contents when reverting this buffer.
5113 Gets two args, first the nominal file name to use,
5114 and second, t if reading the auto-save file.
5116 The function you specify is responsible for updating (or preserving) point.")
5118 (defvar buffer-stale-function nil
5119 "Function to check whether a non-file buffer needs reverting.
5120 This should be a function with one optional argument NOCONFIRM.
5121 Auto Revert Mode passes t for NOCONFIRM. The function should return
5122 non-nil if the buffer should be reverted. A return value of
5123 `fast' means that the need for reverting was not checked, but
5124 that reverting the buffer is fast. The buffer is current when
5125 this function is called.
5127 The idea behind the NOCONFIRM argument is that it should be
5128 non-nil if the buffer is going to be reverted without asking the
5129 user. In such situations, one has to be careful with potentially
5130 time consuming operations.
5132 For more information on how this variable is used by Auto Revert mode,
5133 see Info node `(emacs)Supporting additional buffers'.")
5135 (defvar before-revert-hook nil
5136 "Normal hook for `revert-buffer' to run before reverting.
5137 If `revert-buffer-function' is used to override the normal revert
5138 mechanism, this hook is not used.")
5140 (defvar after-revert-hook nil
5141 "Normal hook for `revert-buffer' to run after reverting.
5142 Note that the hook value that it runs is the value that was in effect
5143 before reverting; that makes a difference if you have buffer-local
5146 If `revert-buffer-function' is used to override the normal revert
5147 mechanism, this hook is not used.")
5149 (defvar revert-buffer-in-progress-p nil
5150 "Non-nil if a `revert-buffer' operation is in progress, nil otherwise.
5151 This is true even if a `revert-buffer-function' is being used.")
5153 (defvar revert-buffer-internal-hook
)
5155 (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes
)
5156 "Replace current buffer text with the text of the visited file on disk.
5157 This undoes all changes since the file was visited or saved.
5158 With a prefix argument, offer to revert from latest auto-save file, if
5159 that is more recent than the visited file.
5161 This command also implements an interface for special buffers
5162 that contain text which doesn't come from a file, but reflects
5163 some other data instead (e.g. Dired buffers, `buffer-list'
5164 buffers). This is done via the variable `revert-buffer-function'.
5165 In these cases, it should reconstruct the buffer contents from the
5168 When called from Lisp, the first argument is IGNORE-AUTO; only offer
5169 to revert from the auto-save file when this is nil. Note that the
5170 sense of this argument is the reverse of the prefix argument, for the
5171 sake of backward compatibility. IGNORE-AUTO is optional, defaulting
5174 Optional second argument NOCONFIRM means don't ask for confirmation
5175 at all. (The variable `revert-without-query' offers another way to
5176 revert buffers without querying for confirmation.)
5178 Optional third argument PRESERVE-MODES non-nil means don't alter
5179 the files modes. Normally we reinitialize them using `normal-mode'.
5181 This function binds `revert-buffer-in-progress-p' non-nil while it operates.
5183 If the value of `revert-buffer-function' is non-nil, it is called to
5184 do all the work for this command. Otherwise, the hooks
5185 `before-revert-hook' and `after-revert-hook' are run at the beginning
5186 and the end, and if `revert-buffer-insert-file-contents-function' is
5187 non-nil, it is called instead of rereading visited file contents."
5189 ;; I admit it's odd to reverse the sense of the prefix argument, but
5190 ;; there is a lot of code out there which assumes that the first
5191 ;; argument should be t to avoid consulting the auto-save file, and
5192 ;; there's no straightforward way to encourage authors to notice a
5193 ;; reversal of the argument sense. So I'm just changing the user
5194 ;; interface, but leaving the programmatic interface the same.
5195 (interactive (list (not current-prefix-arg
)))
5196 (if revert-buffer-function
5197 (let ((revert-buffer-in-progress-p t
))
5198 (funcall revert-buffer-function ignore-auto noconfirm
))
5199 (with-current-buffer (or (buffer-base-buffer (current-buffer))
5201 (let* ((revert-buffer-in-progress-p t
)
5202 (auto-save-p (and (not ignore-auto
)
5203 (recent-auto-save-p)
5204 buffer-auto-save-file-name
5205 (file-readable-p buffer-auto-save-file-name
)
5207 "Buffer has been auto-saved recently. Revert from auto-save file? ")))
5208 (file-name (if auto-save-p
5209 buffer-auto-save-file-name
5211 (cond ((null file-name
)
5212 (error "Buffer does not seem to be associated with any file"))
5214 (and (not (buffer-modified-p))
5216 (dolist (regexp revert-without-query
)
5217 (when (string-match regexp file-name
)
5218 (throw 'found t
)))))
5219 (yes-or-no-p (format "Revert buffer from file %s? "
5221 (run-hooks 'before-revert-hook
)
5222 ;; If file was backed up but has changed since,
5223 ;; we should make another backup.
5224 (and (not auto-save-p
)
5225 (not (verify-visited-file-modtime (current-buffer)))
5226 (setq buffer-backed-up nil
))
5227 ;; Effectively copy the after-revert-hook status,
5228 ;; since after-find-file will clobber it.
5229 (let ((global-hook (default-value 'after-revert-hook
))
5230 (local-hook (when (local-variable-p 'after-revert-hook
)
5232 (inhibit-read-only t
))
5234 (revert-buffer-insert-file-contents-function
5235 (unless (eq buffer-undo-list t
)
5236 ;; Get rid of all undo records for this buffer.
5237 (setq buffer-undo-list nil
))
5238 ;; Don't make undo records for the reversion.
5239 (let ((buffer-undo-list t
))
5240 (funcall revert-buffer-insert-file-contents-function
5241 file-name auto-save-p
)))
5242 ((not (file-exists-p file-name
))
5243 (error (if buffer-file-number
5244 "File %s no longer exists!"
5245 "Cannot revert nonexistent file %s")
5247 ((not (file-readable-p file-name
))
5248 (error (if buffer-file-number
5249 "File %s no longer readable!"
5250 "Cannot revert unreadable file %s")
5253 ;; Bind buffer-file-name to nil
5254 ;; so that we don't try to lock the file.
5255 (let ((buffer-file-name nil
))
5259 (let ((coding-system-for-read
5260 ;; Auto-saved file should be read by Emacs's
5262 (if auto-save-p
'auto-save-coding
5263 (or coding-system-for-read
5265 buffer-file-coding-system-explicit
5266 (car buffer-file-coding-system-explicit
))))))
5267 (if (and (not enable-multibyte-characters
)
5268 coding-system-for-read
5269 (not (memq (coding-system-base
5270 coding-system-for-read
)
5271 '(no-conversion raw-text
))))
5272 ;; As a coding system suitable for multibyte
5273 ;; buffer is specified, make the current
5274 ;; buffer multibyte.
5275 (set-buffer-multibyte t
))
5277 ;; This force after-insert-file-set-coding
5278 ;; (called from insert-file-contents) to set
5279 ;; buffer-file-coding-system to a proper value.
5280 (kill-local-variable 'buffer-file-coding-system
)
5282 ;; Note that this preserves point in an intelligent way.
5284 (let ((buffer-file-format buffer-file-format
))
5285 (insert-file-contents file-name
(not auto-save-p
)
5287 (insert-file-contents file-name
(not auto-save-p
)
5289 ;; Recompute the truename in case changes in symlinks
5290 ;; have changed the truename.
5291 (setq buffer-file-truename
5292 (abbreviate-file-name (file-truename buffer-file-name
)))
5293 (after-find-file nil nil t nil preserve-modes
)
5294 ;; Run after-revert-hook as it was before we reverted.
5295 (setq-default revert-buffer-internal-hook global-hook
)
5297 (set (make-local-variable 'revert-buffer-internal-hook
)
5299 (kill-local-variable 'revert-buffer-internal-hook
))
5300 (run-hooks 'revert-buffer-internal-hook
))
5303 (defun recover-this-file ()
5304 "Recover the visited file--get contents from its last auto-save file."
5306 (recover-file buffer-file-name
))
5308 (defun recover-file (file)
5309 "Visit file FILE, but get contents from its last auto-save file."
5310 ;; Actually putting the file name in the minibuffer should be used
5312 ;; Not just because users often use the default.
5313 (interactive "FRecover file: ")
5314 (setq file
(expand-file-name file
))
5315 (if (auto-save-file-name-p (file-name-nondirectory file
))
5316 (error "%s is an auto-save file" (abbreviate-file-name file
)))
5317 (let ((file-name (let ((buffer-file-name file
))
5318 (make-auto-save-file-name))))
5319 (cond ((if (file-exists-p file
)
5320 (not (file-newer-than-file-p file-name file
))
5321 (not (file-exists-p file-name
)))
5322 (error "Auto-save file %s not current"
5323 (abbreviate-file-name file-name
)))
5324 ((save-window-excursion
5325 (with-output-to-temp-buffer "*Directory*"
5326 (buffer-disable-undo standard-output
)
5328 (let ((switches dired-listing-switches
))
5329 (if (file-symlink-p file
)
5330 (setq switches
(concat switches
" -L")))
5331 (set-buffer standard-output
)
5332 ;; Use insert-directory-safely, not insert-directory,
5333 ;; because these files might not exist. In particular,
5334 ;; FILE might not exist if the auto-save file was for
5335 ;; a buffer that didn't visit a file, such as "*mail*".
5336 ;; The code in v20.x called `ls' directly, so we need
5337 ;; to emulate what `ls' did in that case.
5338 (insert-directory-safely file switches
)
5339 (insert-directory-safely file-name switches
))))
5340 (yes-or-no-p (format "Recover auto save file %s? " file-name
)))
5341 (switch-to-buffer (find-file-noselect file t
))
5342 (let ((inhibit-read-only t
)
5343 ;; Keep the current buffer-file-coding-system.
5344 (coding-system buffer-file-coding-system
)
5345 ;; Auto-saved file should be read with special coding.
5346 (coding-system-for-read 'auto-save-coding
))
5348 (insert-file-contents file-name nil
)
5349 (set-buffer-file-coding-system coding-system
))
5350 (after-find-file nil nil t
))
5351 (t (error "Recover-file cancelled")))))
5353 (defun recover-session ()
5354 "Recover auto save files from a previous Emacs session.
5355 This command first displays a Dired buffer showing you the
5356 previous sessions that you could recover from.
5357 To choose one, move point to the proper line and then type C-c C-c.
5358 Then you'll be asked about a number of files to recover."
5360 (if (null auto-save-list-file-prefix
)
5361 (error "You set `auto-save-list-file-prefix' to disable making session files"))
5362 (let ((dir (file-name-directory auto-save-list-file-prefix
)))
5363 (unless (file-directory-p dir
)
5364 (make-directory dir t
))
5365 (unless (directory-files dir nil
5366 (concat "\\`" (regexp-quote
5367 (file-name-nondirectory
5368 auto-save-list-file-prefix
)))
5370 (error "No previous sessions to recover")))
5371 (let ((ls-lisp-support-shell-wildcards t
))
5372 (dired (concat auto-save-list-file-prefix
"*")
5373 (concat dired-listing-switches
" -t")))
5375 (goto-char (point-min))
5376 (or (looking-at " Move to the session you want to recover,")
5377 (let ((inhibit-read-only t
))
5378 ;; Each line starts with a space
5379 ;; so that Font Lock mode won't highlight the first character.
5380 (insert " Move to the session you want to recover,\n"
5381 " then type C-c C-c to select it.\n\n"
5382 " You can also delete some of these files;\n"
5383 " type d on a line to mark that file for deletion.\n\n"))))
5384 (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
5385 (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish
))
5387 (defun recover-session-finish ()
5388 "Choose one saved session to recover auto-save files from.
5389 This command is used in the special Dired buffer created by
5390 \\[recover-session]."
5392 ;; Get the name of the session file to recover from.
5393 (let ((file (dired-get-filename))
5395 (buffer (get-buffer-create " *recover*")))
5397 (dired-do-flagged-delete t
)
5399 (with-current-buffer buffer
5400 ;; Read in the auto-save-list file.
5402 (insert-file-contents file
)
5403 ;; Loop thru the text of that file
5404 ;; and get out the names of the files to recover.
5406 (let (thisfile autofile
)
5408 ;; This is a pair of lines for a non-file-visiting buffer.
5409 ;; Get the auto-save file name and manufacture
5410 ;; a "visited file name" from that.
5413 ;; If there is no auto-save file name, the
5414 ;; auto-save-list file is probably corrupted.
5417 (buffer-substring-no-properties
5419 (line-end-position)))
5423 (file-name-nondirectory autofile
)
5425 (file-name-directory autofile
))))
5427 ;; This pair of lines is a file-visiting
5428 ;; buffer. Use the visited file name.
5431 (buffer-substring-no-properties
5432 (point) (progn (end-of-line) (point))))
5435 (buffer-substring-no-properties
5436 (point) (progn (end-of-line) (point))))
5438 ;; Ignore a file if its auto-save file does not exist now.
5439 (if (and autofile
(file-exists-p autofile
))
5440 (setq files
(cons thisfile files
)))))
5441 (setq files
(nreverse files
))
5442 ;; The file contains a pair of line for each auto-saved buffer.
5443 ;; The first line of the pair contains the visited file name
5444 ;; or is empty if the buffer was not visiting a file.
5445 ;; The second line is the auto-save file name.
5447 (map-y-or-n-p "Recover %s? "
5450 (save-excursion (recover-file file
))
5452 "Failed to recover `%s'" file
)))
5454 '("file" "files" "recover"))
5455 (message "No files can be recovered from this session now")))
5456 (kill-buffer buffer
))))
5458 (defun kill-buffer-ask (buffer)
5459 "Kill BUFFER if confirmed."
5460 (when (yes-or-no-p (format "Buffer %s %s. Kill? "
5461 (buffer-name buffer
)
5462 (if (buffer-modified-p buffer
)
5463 "HAS BEEN EDITED" "is unmodified")))
5464 (kill-buffer buffer
)))
5466 (defun kill-some-buffers (&optional list
)
5467 "Kill some buffers. Asks the user whether to kill each one of them.
5468 Non-interactively, if optional argument LIST is non-nil, it
5469 specifies the list of buffers to kill, asking for approval for each one."
5472 (setq list
(buffer-list)))
5474 (let* ((buffer (car list
))
5475 (name (buffer-name buffer
)))
5476 (and name
; Can be nil for an indirect buffer
5477 ; if we killed the base buffer.
5478 (not (string-equal name
""))
5479 (/= (aref name
0) ?\s
)
5480 (kill-buffer-ask buffer
)))
5481 (setq list
(cdr list
))))
5483 (defun kill-matching-buffers (regexp &optional internal-too
)
5484 "Kill buffers whose name matches the specified REGEXP.
5485 The optional second argument indicates whether to kill internal buffers too."
5486 (interactive "sKill buffers matching this regular expression: \nP")
5487 (dolist (buffer (buffer-list))
5488 (let ((name (buffer-name buffer
)))
5489 (when (and name
(not (string-equal name
""))
5490 (or internal-too
(/= (aref name
0) ?\s
))
5491 (string-match regexp name
))
5492 (kill-buffer-ask buffer
)))))
5495 (defun rename-auto-save-file ()
5496 "Adjust current buffer's auto save file name for current conditions.
5497 Also rename any existing auto save file, if it was made in this session."
5498 (let ((osave buffer-auto-save-file-name
))
5499 (setq buffer-auto-save-file-name
5500 (make-auto-save-file-name))
5501 (if (and osave buffer-auto-save-file-name
5502 (not (string= buffer-auto-save-file-name buffer-file-name
))
5503 (not (string= buffer-auto-save-file-name osave
))
5504 (file-exists-p osave
)
5505 (recent-auto-save-p))
5506 (rename-file osave buffer-auto-save-file-name t
))))
5508 (defun make-auto-save-file-name ()
5509 "Return file name to use for auto-saves of current buffer.
5510 Does not consider `auto-save-visited-file-name' as that variable is checked
5511 before calling this function. You can redefine this for customization.
5512 See also `auto-save-file-name-p'."
5513 (if buffer-file-name
5514 (let ((handler (find-file-name-handler buffer-file-name
5515 'make-auto-save-file-name
)))
5517 (funcall handler
'make-auto-save-file-name
)
5518 (let ((list auto-save-file-name-transforms
)
5519 (filename buffer-file-name
)
5521 ;; Apply user-specified translations
5522 ;; to the file name.
5523 (while (and list
(not result
))
5524 (if (string-match (car (car list
)) filename
)
5525 (setq result
(replace-match (cadr (car list
)) t nil
5527 uniq
(car (cddr (car list
)))))
5528 (setq list
(cdr list
)))
5531 (setq filename
(concat
5532 (file-name-directory result
)
5533 (subst-char-in-string
5535 (replace-regexp-in-string "!" "!!"
5537 (setq filename result
)))
5539 (if (and (eq system-type
'ms-dos
)
5540 (not (msdos-long-file-names)))
5541 ;; We truncate the file name to DOS 8+3 limits
5542 ;; before doing anything else, because the regexp
5543 ;; passed to string-match below cannot handle
5544 ;; extensions longer than 3 characters, multiple
5545 ;; dots, and other atrocities.
5546 (let ((fn (dos-8+3-filename
5547 (file-name-nondirectory buffer-file-name
))))
5549 "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'"
5551 (concat (file-name-directory buffer-file-name
)
5552 "#" (match-string 1 fn
)
5553 "." (match-string 3 fn
) "#"))
5554 (concat (file-name-directory filename
)
5556 (file-name-nondirectory filename
)
5558 ;; Make sure auto-save file names don't contain characters
5559 ;; invalid for the underlying filesystem.
5560 (if (and (memq system-type
'(ms-dos windows-nt cygwin
))
5561 ;; Don't modify remote (ange-ftp) filenames
5562 (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" result
)))
5563 (convert-standard-filename result
)
5566 ;; Deal with buffers that don't have any associated files. (Mail
5567 ;; mode tends to create a good number of these.)
5569 (let ((buffer-name (buffer-name))
5572 ;; Restrict the characters used in the file name to those which
5573 ;; are known to be safe on all filesystems, url-encoding the
5575 ;; We do this on all platforms, because even if we are not
5576 ;; running on DOS/Windows, the current directory may be on a
5577 ;; mounted VFAT filesystem, such as a USB memory stick.
5578 (while (string-match "[^A-Za-z0-9-_.~#+]" buffer-name limit
)
5579 (let* ((character (aref buffer-name
(match-beginning 0)))
5581 ;; For multibyte characters, this will produce more than
5582 ;; 2 hex digits, so is not true URL encoding.
5583 (format "%%%02X" character
)))
5584 (setq buffer-name
(replace-match replacement t t buffer-name
))
5585 (setq limit
(1+ (match-end 0)))))
5586 ;; Generate the file name.
5591 (format "#%s#" buffer-name
)
5592 ;; Try a few alternative directories, to get one we can
5595 ((file-writable-p default-directory
) default-directory
)
5596 ((file-writable-p "/var/tmp/") "/var/tmp/")
5598 (if (and (memq system-type
'(ms-dos windows-nt cygwin
))
5599 ;; Don't modify remote (ange-ftp) filenames
5600 (not (string-match "^/\\w+@[-A-Za-z0-9._]+:" fname
)))
5601 ;; The call to convert-standard-filename is in case
5602 ;; buffer-name includes characters not allowed by the
5603 ;; DOS/Windows filesystems. make-temp-file writes to the
5604 ;; file it creates, so we must fix the file name _before_
5605 ;; make-temp-file is called.
5606 (convert-standard-filename fname
)
5609 ;; make-temp-file creates the file,
5610 ;; but we don't want it to exist until we do an auto-save.
5612 (delete-file file-name
)
5616 (defun auto-save-file-name-p (filename)
5617 "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
5618 FILENAME should lack slashes. You can redefine this for customization."
5619 (string-match "^#.*#$" filename
))
5621 (defun wildcard-to-regexp (wildcard)
5622 "Given a shell file name pattern WILDCARD, return an equivalent regexp.
5623 The generated regexp will match a filename only if the filename
5624 matches that wildcard according to shell rules. Only wildcards known
5625 by `sh' are supported."
5626 (let* ((i (string-match "[[.*+\\^$?]" wildcard
))
5627 ;; Copy the initial run of non-special characters.
5628 (result (substring wildcard
0 i
))
5629 (len (length wildcard
)))
5630 ;; If no special characters, we're almost done.
5633 (let ((ch (aref wildcard i
))
5641 (eq (aref wildcard
(1+ i
)) ?\
]))
5643 ((eq ch ?\
[) ; [...] maps to regexp char class
5648 ((eq (aref wildcard i
) ?
!) ; [!...] -> [^...]
5651 (if (eq (aref wildcard i
) ?\
])
5656 ((eq (aref wildcard i
) ?^
)
5657 ;; Found "[^". Insert a `\0' character
5658 ;; (which cannot happen in a filename)
5659 ;; into the character class, so that `^'
5660 ;; is not the first character after `[',
5661 ;; and thus non-special in a regexp.
5665 ((eq (aref wildcard i
) ?\
])
5666 ;; I don't think `]' can appear in a
5667 ;; character class in a wildcard, but
5668 ;; let's be general here.
5673 (prog1 ; copy everything upto next `]'.
5676 (setq j
(string-match
5678 (setq i
(if j
(1- j
) (1- len
)))))))
5680 ((eq ch ?
*) "[^\000]*")
5684 ((eq ch ?
\\) "\\\\") ; probably cannot happen...
5685 ((eq ch ??
) "[^\000]")
5686 (t (char-to-string ch
)))))
5688 ;; Shell wildcards should match the entire filename,
5689 ;; not its part. Make the regexp say so.
5690 (concat "\\`" result
"\\'")))
5692 (defcustom list-directory-brief-switches
5694 "Switches for `list-directory' to pass to `ls' for brief listing."
5698 (defcustom list-directory-verbose-switches
5700 "Switches for `list-directory' to pass to `ls' for verbose listing."
5704 (defun file-expand-wildcards (pattern &optional full
)
5705 "Expand wildcard pattern PATTERN.
5706 This returns a list of file names which match the pattern.
5708 If PATTERN is written as an absolute file name,
5709 the values are absolute also.
5711 If PATTERN is written as a relative file name, it is interpreted
5712 relative to the current default directory, `default-directory'.
5713 The file names returned are normally also relative to the current
5714 default directory. However, if FULL is non-nil, they are absolute."
5716 (let* ((nondir (file-name-nondirectory pattern
))
5717 (dirpart (file-name-directory pattern
))
5718 ;; A list of all dirs that DIRPART specifies.
5719 ;; This can be more than one dir
5720 ;; if DIRPART contains wildcards.
5721 (dirs (if (and dirpart
5722 (string-match "[[*?]"
5723 (or (file-remote-p dirpart
'localname
)
5725 (mapcar 'file-name-as-directory
5726 (file-expand-wildcards (directory-file-name dirpart
)))
5730 (when (or (null (car dirs
)) ; Possible if DIRPART is not wild.
5731 (and (file-directory-p (directory-file-name (car dirs
)))
5732 (file-readable-p (car dirs
))))
5733 (let ((this-dir-contents
5734 ;; Filter out "." and ".."
5736 (mapcar #'(lambda (name)
5737 (unless (string-match "\\`\\.\\.?\\'"
5738 (file-name-nondirectory name
))
5740 (directory-files (or (car dirs
) ".") full
5741 (wildcard-to-regexp nondir
))))))
5744 (if (and (car dirs
) (not full
))
5745 (mapcar (function (lambda (name) (concat (car dirs
) name
)))
5749 (setq dirs
(cdr dirs
)))
5752 ;; Let Tramp know that `file-expand-wildcards' does not need an advice.
5753 (provide 'files
'(remote-wildcards))
5755 (defun list-directory (dirname &optional verbose
)
5756 "Display a list of files in or matching DIRNAME, a la `ls'.
5757 DIRNAME is globbed by the shell if necessary.
5758 Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
5759 Actions controlled by variables `list-directory-brief-switches'
5760 and `list-directory-verbose-switches'."
5761 (interactive (let ((pfx current-prefix-arg
))
5762 (list (read-directory-name (if pfx
"List directory (verbose): "
5763 "List directory (brief): ")
5764 nil default-directory nil
)
5766 (let ((switches (if verbose list-directory-verbose-switches
5767 list-directory-brief-switches
))
5769 (or dirname
(setq dirname default-directory
))
5770 (setq dirname
(expand-file-name dirname
))
5771 (with-output-to-temp-buffer "*Directory*"
5772 (setq buffer standard-output
)
5773 (buffer-disable-undo standard-output
)
5774 (princ "Directory ")
5777 (with-current-buffer "*Directory*"
5778 (let ((wildcard (not (file-directory-p dirname
))))
5779 (insert-directory dirname switches wildcard
(not wildcard
)))))
5780 ;; Finishing with-output-to-temp-buffer seems to clobber default-directory.
5781 (with-current-buffer buffer
5782 (setq default-directory
5783 (if (file-directory-p dirname
)
5784 (file-name-as-directory dirname
)
5785 (file-name-directory dirname
))))))
5787 (defun shell-quote-wildcard-pattern (pattern)
5788 "Quote characters special to the shell in PATTERN, leave wildcards alone.
5790 PATTERN is assumed to represent a file-name wildcard suitable for the
5791 underlying filesystem. For Unix and GNU/Linux, each character from the
5792 set [ \\t\\n;<>&|()'\"#$] is quoted with a backslash; for DOS/Windows, all
5793 the parts of the pattern which don't include wildcard characters are
5794 quoted with double quotes.
5796 This function leaves alone existing quote characters (\\ on Unix and \"
5797 on Windows), so PATTERN can use them to quote wildcard characters that
5798 need to be passed verbatim to shell commands."
5801 ((memq system-type
'(ms-dos windows-nt cygwin
))
5802 ;; DOS/Windows don't allow `"' in file names. So if the
5803 ;; argument has quotes, we can safely assume it is already
5804 ;; quoted by the caller.
5805 (if (or (string-match "[\"]" pattern
)
5806 ;; We quote [&()#$'] in case their shell is a port of a
5807 ;; Unixy shell. We quote [,=+] because stock DOS and
5808 ;; Windows shells require that in some cases, such as
5809 ;; passing arguments to batch files that use positional
5810 ;; arguments like %1.
5811 (not (string-match "[ \t;&()#$',=+]" pattern
)))
5816 (while (string-match "[*?]+" pattern beg
)
5817 (setq end
(match-beginning 0)
5818 result
(concat result
(substring pattern beg end
)
5820 (substring pattern end
(match-end 0))
5823 (concat result
(substring pattern beg
) "\""))))
5826 (while (string-match "[ \t\n;<>&|()'\"#$]" pattern beg
)
5828 (concat (substring pattern
0 (match-beginning 0))
5830 (substring pattern
(match-beginning 0)))
5831 beg
(1+ (match-end 0)))))
5835 (defvar insert-directory-program
(purecopy "ls")
5836 "Absolute or relative name of the `ls' program used by `insert-directory'.")
5838 (defcustom directory-free-space-program
(purecopy "df")
5839 "Program to get the amount of free space on a file system.
5840 We assume the output has the format of `df'.
5841 The value of this variable must be just a command name or file name;
5842 if you want to specify options, use `directory-free-space-args'.
5844 A value of nil disables this feature.
5846 If the function `file-system-info' is defined, it is always used in
5847 preference to the program given by this variable."
5848 :type
'(choice (string :tag
"Program") (const :tag
"None" nil
))
5851 (defcustom directory-free-space-args
5852 (purecopy (if (eq system-type
'darwin
) "-k" "-Pk"))
5853 "Options to use when running `directory-free-space-program'."
5857 (defun get-free-disk-space (dir)
5858 "Return the amount of free space on directory DIR's file system.
5859 The return value is a string describing the amount of free
5860 space (normally, the number of free 1KB blocks).
5862 This function calls `file-system-info' if it is available, or
5863 invokes the program specified by `directory-free-space-program'
5864 and `directory-free-space-args'. If the system call or program
5865 is unsuccessful, or if DIR is a remote directory, this function
5867 (unless (file-remote-p dir
)
5868 ;; Try to find the number of free blocks. Non-Posix systems don't
5869 ;; always have df, but might have an equivalent system call.
5870 (if (fboundp 'file-system-info
)
5871 (let ((fsinfo (file-system-info dir
)))
5873 (format "%.0f" (/ (nth 2 fsinfo
) 1024))))
5874 (setq dir
(expand-file-name dir
))
5877 (when (and directory-free-space-program
5878 ;; Avoid failure if the default directory does
5879 ;; not exist (Bug#2631, Bug#3911).
5880 (let ((default-directory "/"))
5881 (eq (call-process directory-free-space-program
5883 directory-free-space-args
5886 ;; Assume that the "available" column is before the
5887 ;; "capacity" column. Find the "%" and scan backward.
5888 (goto-char (point-min))
5890 (when (re-search-forward
5891 "[[:space:]]+[^[:space:]]+%[^%]*$"
5892 (line-end-position) t
)
5893 (goto-char (match-beginning 0))
5894 (let ((endpt (point)))
5895 (skip-chars-backward "^[:space:]")
5896 (buffer-substring-no-properties (point) endpt
)))))))))
5898 ;; The following expression replaces `dired-move-to-filename-regexp'.
5899 (defvar directory-listing-before-filename-regexp
5900 (let* ((l "\\([A-Za-z]\\|[^\0-\177]\\)")
5901 (l-or-quote "\\([A-Za-z']\\|[^\0-\177]\\)")
5902 ;; In some locales, month abbreviations are as short as 2 letters,
5903 ;; and they can be followed by ".".
5904 ;; In Breton, a month name can include a quote character.
5905 (month (concat l-or-quote l-or-quote
"+\\.?"))
5907 (yyyy "[0-9][0-9][0-9][0-9]")
5909 (HH:MM
"[ 0-2][0-9][:.][0-5][0-9]")
5910 (seconds "[0-6][0-9]\\([.,][0-9]+\\)?")
5911 (zone "[-+][0-2][0-9][0-5][0-9]")
5912 (iso-mm-dd "[01][0-9]-[0-3][0-9]")
5913 (iso-time (concat HH
:MM
"\\(:" seconds
"\\( ?" zone
"\\)?\\)?"))
5914 (iso (concat "\\(\\(" yyyy
"-\\)?" iso-mm-dd
"[ T]" iso-time
5915 "\\|" yyyy
"-" iso-mm-dd
"\\)"))
5916 (western (concat "\\(" month s
"+" dd
"\\|" dd
"\\.?" s month
"\\)"
5918 "\\(" HH
:MM
"\\|" yyyy
"\\)"))
5919 (western-comma (concat month s
"+" dd
"," s
"+" yyyy
))
5920 ;; Japanese MS-Windows ls-lisp has one-digit months, and
5921 ;; omits the Kanji characters after month and day-of-month.
5922 ;; On Mac OS X 10.3, the date format in East Asian locales is
5923 ;; day-of-month digits followed by month digits.
5926 (concat "\\(" mm l
"?" s dd l
"?" s
"+"
5927 "\\|" dd s mm s
"+" "\\)"
5928 "\\(" HH
:MM
"\\|" yyyy l
"?" "\\)")))
5929 ;; The "[0-9]" below requires the previous column to end in a digit.
5930 ;; This avoids recognizing `1 may 1997' as a date in the line:
5931 ;; -r--r--r-- 1 may 1997 1168 Oct 19 16:49 README
5933 ;; The "[BkKMGTPEZY]?" below supports "ls -alh" output.
5935 ;; For non-iso date formats, we add the ".*" in order to find
5936 ;; the last possible match. This avoids recognizing
5937 ;; `jservice 10 1024' as a date in the line:
5938 ;; drwxr-xr-x 3 jservice 10 1024 Jul 2 1997 esg-host
5940 ;; vc dired listings provide the state or blanks between file
5941 ;; permissions and date. The state is always surrounded by
5943 ;; -rw-r--r-- (modified) 2005-10-22 21:25 files.el
5944 ;; This is not supported yet.
5945 (purecopy (concat "\\([0-9][BkKMGTPEZY]? " iso
5946 "\\|.*[0-9][BkKMGTPEZY]? "
5947 "\\(" western
"\\|" western-comma
"\\|" east-asian
"\\)"
5949 "Regular expression to match up to the file name in a directory listing.
5950 The default value is designed to recognize dates and times
5951 regardless of the language.")
5953 (defvar insert-directory-ls-version
'unknown
)
5956 ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
5957 ;; FULL-DIRECTORY-P is nil.
5958 ;; The single line of output must display FILE's name as it was
5959 ;; given, namely, an absolute path name.
5960 ;; - must insert exactly one line for each file if WILDCARD or
5961 ;; FULL-DIRECTORY-P is t, plus one optional "total" line
5962 ;; before the file lines, plus optional text after the file lines.
5963 ;; Lines are delimited by "\n", so filenames containing "\n" are not
5965 ;; File lines should display the basename.
5966 ;; - must be consistent with
5967 ;; - functions dired-move-to-filename, (these two define what a file line is)
5968 ;; dired-move-to-end-of-filename,
5969 ;; dired-between-files, (shortcut for (not (dired-move-to-filename)))
5970 ;; dired-insert-headerline
5971 ;; dired-after-subdir-garbage (defines what a "total" line is)
5972 ;; - variable dired-subdir-regexp
5973 ;; - may be passed "--dired" as the first argument in SWITCHES.
5974 ;; Filename handlers might have to remove this switch if their
5975 ;; "ls" command does not support it.
5976 (defun insert-directory (file switches
&optional wildcard full-directory-p
)
5977 "Insert directory listing for FILE, formatted according to SWITCHES.
5978 Leaves point after the inserted text.
5979 SWITCHES may be a string of options, or a list of strings
5980 representing individual options.
5981 Optional third arg WILDCARD means treat FILE as shell wildcard.
5982 Optional fourth arg FULL-DIRECTORY-P means file is a directory and
5983 switches do not contain `d', so that a full listing is expected.
5985 This works by running a directory listing program
5986 whose name is in the variable `insert-directory-program'.
5987 If WILDCARD, it also runs the shell specified by `shell-file-name'.
5989 When SWITCHES contains the long `--dired' option, this function
5990 treats it specially, for the sake of dired. However, the
5991 normally equivalent short `-D' option is just passed on to
5992 `insert-directory-program', as any other option."
5993 ;; We need the directory in order to find the right handler.
5994 (let ((handler (find-file-name-handler (expand-file-name file
)
5995 'insert-directory
)))
5997 (funcall handler
'insert-directory file switches
5998 wildcard full-directory-p
)
5999 (let (result (beg (point)))
6001 ;; Read the actual directory using `insert-directory-program'.
6002 ;; RESULT gets the status code.
6003 (let* (;; We at first read by no-conversion, then after
6004 ;; putting text property `dired-filename, decode one
6005 ;; bunch by one to preserve that property.
6006 (coding-system-for-read 'no-conversion
)
6007 ;; This is to control encoding the arguments in call-process.
6008 (coding-system-for-write
6009 (and enable-multibyte-characters
6010 (or file-name-coding-system
6011 default-file-name-coding-system
))))
6014 ;; Run ls in the directory part of the file pattern
6015 ;; using the last component as argument.
6016 (let ((default-directory
6017 (if (file-name-absolute-p file
)
6018 (file-name-directory file
)
6019 (file-name-directory (expand-file-name file
))))
6020 (pattern (file-name-nondirectory file
)))
6021 ;; NB since switches is passed to the shell, be
6022 ;; careful of malicious values, eg "-l;reboot".
6023 ;; See eg dired-safe-switches-p.
6025 shell-file-name nil t nil
6027 (concat (if (memq system-type
'(ms-dos windows-nt
))
6029 "\\") ; Disregard Unix shell aliases!
6030 insert-directory-program
6032 (if (stringp switches
)
6034 (mapconcat 'identity switches
" "))
6036 ;; Quote some characters that have
6037 ;; special meanings in shells; but
6038 ;; don't quote the wildcards--we want
6039 ;; them to be special. We also
6040 ;; currently don't quote the quoting
6041 ;; characters in case people want to
6042 ;; use them explicitly to quote
6043 ;; wildcard characters.
6044 (shell-quote-wildcard-pattern pattern
))))
6045 ;; SunOS 4.1.3, SVr4 and others need the "." to list the
6046 ;; directory if FILE is a symbolic link.
6047 (unless full-directory-p
6049 (if (stringp switches
)
6050 (concat switches
" -d")
6051 (add-to-list 'switches
"-d" 'append
))))
6052 (apply 'call-process
6053 insert-directory-program nil t nil
6055 (if (listp switches
) switches
6056 (unless (equal switches
"")
6057 ;; Split the switches at any spaces so we can
6058 ;; pass separate options as separate args.
6059 (split-string switches
)))
6060 ;; Avoid lossage if FILE starts with `-'.
6063 (if (string-match "\\`~" file
)
6064 (setq file
(expand-file-name file
)))
6066 (if full-directory-p
6067 (concat (file-name-as-directory file
) ".")
6070 ;; If we got "//DIRED//" in the output, it means we got a real
6071 ;; directory listing, even if `ls' returned nonzero.
6072 ;; So ignore any errors.
6073 (when (if (stringp switches
)
6074 (string-match "--dired\\>" switches
)
6075 (member "--dired" switches
))
6078 (when (looking-at "//SUBDIRED//")
6080 (if (looking-at "//DIRED//")
6083 (when (and (not (eq 0 result
))
6084 (eq insert-directory-ls-version
'unknown
))
6085 ;; The first time ls returns an error,
6086 ;; find the version numbers of ls,
6087 ;; and set insert-directory-ls-version
6088 ;; to > if it is more than 5.2.1, < if it is less, nil if it
6089 ;; is equal or if the info cannot be obtained.
6090 ;; (That can mean it isn't GNU ls.)
6093 (call-process "ls" nil t nil
"--version")
6095 (if (string-match "ls (.*utils) \\([0-9.]*\\)$" version-out
)
6096 (let* ((version (match-string 1 version-out
))
6097 (split (split-string version
"[.]"))
6098 (numbers (mapcar 'string-to-number split
))
6101 (while (and (not comparison
) (or numbers min
))
6103 (setq comparison
'>))
6105 (setq comparison
'<))
6106 ((> (car numbers
) (car min
))
6107 (setq comparison
'>))
6108 ((< (car numbers
) (car min
))
6109 (setq comparison
'<))
6111 (setq numbers
(cdr numbers
)
6113 (setq insert-directory-ls-version
(or comparison
'=)))
6114 (setq insert-directory-ls-version nil
))))
6116 ;; For GNU ls versions 5.2.2 and up, ignore minor errors.
6117 (when (and (eq 1 result
) (eq insert-directory-ls-version
'>))
6120 ;; If `insert-directory-program' failed, signal an error.
6121 (unless (eq 0 result
)
6122 ;; Delete the error message it may have output.
6123 (delete-region beg
(point))
6124 ;; On non-Posix systems, we cannot open a directory, so
6125 ;; don't even try, because that will always result in
6126 ;; the ubiquitous "Access denied". Instead, show the
6127 ;; command line so the user can try to guess what went wrong.
6128 (if (and (file-directory-p file
)
6129 (memq system-type
'(ms-dos windows-nt
)))
6131 "Reading directory: \"%s %s -- %s\" exited with status %s"
6132 insert-directory-program
6133 (if (listp switches
) (concat switches
) switches
)
6135 ;; Unix. Access the file to get a suitable error.
6136 (access-file file
"Reading directory")
6137 (error "Listing directory failed but `access-file' worked")))
6139 (when (if (stringp switches
)
6140 (string-match "--dired\\>" switches
)
6141 (member "--dired" switches
))
6142 ;; The following overshoots by one line for an empty
6143 ;; directory listed with "--dired", but without "-a"
6144 ;; switch, where the ls output contains a
6145 ;; "//DIRED-OPTIONS//" line, but no "//DIRED//" line.
6146 ;; We take care of that case later.
6148 (when (looking-at "//SUBDIRED//")
6149 (delete-region (point) (progn (forward-line 1) (point)))
6151 (if (looking-at "//DIRED//")
6152 (let ((end (line-end-position))
6155 ;; Find all the lines that are error messages,
6156 ;; and record the bounds of each one.
6158 (while (< (point) linebeg
)
6159 (or (eql (following-char) ?\s
)
6160 (push (list (point) (line-end-position)) error-lines
))
6162 (setq error-lines
(nreverse error-lines
))
6163 ;; Now read the numeric positions of file names.
6167 (while (< (point) end
)
6168 (let ((start (insert-directory-adj-pos
6169 (+ beg
(read (current-buffer)))
6171 (end (insert-directory-adj-pos
6172 (+ beg
(read (current-buffer)))
6174 (if (memq (char-after end
) '(?
\n ?\s
))
6175 ;; End is followed by \n or by " -> ".
6176 (put-text-property start end
'dired-filename t
)
6177 ;; It seems that we can't trust ls's output as to
6178 ;; byte positions of filenames.
6179 (put-text-property beg
(point) 'dired-filename nil
)
6183 (delete-region (point) (progn (forward-line 1) (point))))
6184 ;; Take care of the case where the ls output contains a
6185 ;; "//DIRED-OPTIONS//"-line, but no "//DIRED//"-line
6186 ;; and we went one line too far back (see above).
6188 (if (looking-at "//DIRED-OPTIONS//")
6189 (delete-region (point) (progn (forward-line 1) (point)))))
6191 ;; Now decode what read if necessary.
6192 (let ((coding (or coding-system-for-read
6193 file-name-coding-system
6194 default-file-name-coding-system
6198 (when (and enable-multibyte-characters
6199 (not (memq (coding-system-base coding
)
6200 '(raw-text no-conversion
))))
6201 ;; If no coding system is specified or detection is
6202 ;; requested, detect the coding.
6203 (if (eq (coding-system-base coding
) 'undecided
)
6204 (setq coding
(detect-coding-region beg
(point) t
)))
6205 (if (not (eq (coding-system-base coding
) 'undecided
))
6208 (coding-system-change-eol-conversion coding
'unix
))
6209 (narrow-to-region beg
(point))
6210 (goto-char (point-min))
6213 val
(get-text-property (point) 'dired-filename
))
6214 (goto-char (next-single-property-change
6215 (point) 'dired-filename nil
(point-max)))
6216 ;; Force no eol conversion on a file name, so
6217 ;; that CR is preserved.
6218 (decode-coding-region pos
(point)
6219 (if val coding-no-eol coding
))
6221 (put-text-property pos
(point)
6222 'dired-filename t
)))))))
6224 (if full-directory-p
6225 ;; Try to insert the amount of free space.
6228 ;; First find the line to put it on.
6229 (when (re-search-forward "^ *\\(total\\)" nil t
)
6230 (let ((available (get-free-disk-space ".")))
6232 ;; Replace "total" with "used", to avoid confusion.
6233 (replace-match "total used in directory" nil nil nil
1)
6235 (insert " available " available
))))))))))
6237 (defun insert-directory-adj-pos (pos error-lines
)
6238 "Convert `ls --dired' file name position value POS to a buffer position.
6239 File name position values returned in ls --dired output
6240 count only stdout; they don't count the error messages sent to stderr.
6241 So this function converts to them to real buffer positions.
6242 ERROR-LINES is a list of buffer positions of error message lines,
6243 of the form (START END)."
6244 (while (and error-lines
(< (caar error-lines
) pos
))
6245 (setq pos
(+ pos
(- (nth 1 (car error-lines
)) (nth 0 (car error-lines
)))))
6249 (defun insert-directory-safely (file switches
6250 &optional wildcard full-directory-p
)
6251 "Insert directory listing for FILE, formatted according to SWITCHES.
6253 Like `insert-directory', but if FILE does not exist, it inserts a
6254 message to that effect instead of signaling an error."
6255 (if (file-exists-p file
)
6256 (insert-directory file switches wildcard full-directory-p
)
6257 ;; Simulate the message printed by `ls'.
6258 (insert (format "%s: No such file or directory\n" file
))))
6260 (defvar kill-emacs-query-functions nil
6261 "Functions to call with no arguments to query about killing Emacs.
6262 If any of these functions returns nil, killing Emacs is canceled.
6263 `save-buffers-kill-emacs' calls these functions, but `kill-emacs',
6264 the low level primitive, does not. See also `kill-emacs-hook'.")
6266 (defcustom confirm-kill-emacs nil
6267 "How to ask for confirmation when leaving Emacs.
6268 If nil, the default, don't ask at all. If the value is non-nil, it should
6269 be a predicate function such as `yes-or-no-p'."
6270 :type
'(choice (const :tag
"Ask with yes-or-no-p" yes-or-no-p
)
6271 (const :tag
"Ask with y-or-n-p" y-or-n-p
)
6272 (const :tag
"Don't confirm" nil
))
6276 (defun save-buffers-kill-emacs (&optional arg
)
6277 "Offer to save each buffer, then kill this Emacs process.
6278 With prefix ARG, silently save all file-visiting buffers, then kill."
6280 (save-some-buffers arg t
)
6281 (and (or (not (memq t
(mapcar (function
6282 (lambda (buf) (and (buffer-file-name buf
)
6283 (buffer-modified-p buf
))))
6285 (yes-or-no-p "Modified buffers exist; exit anyway? "))
6286 (or (not (fboundp 'process-list
))
6287 ;; process-list is not defined on MSDOS.
6288 (let ((processes (process-list))
6291 (and (memq (process-status (car processes
)) '(run stop open listen
))
6292 (process-query-on-exit-flag (car processes
))
6294 (setq processes
(cdr processes
)))
6296 (progn (list-processes t
)
6297 (yes-or-no-p "Active processes exist; kill them and exit anyway? ")))))
6298 ;; Query the user for other things, perhaps.
6299 (run-hook-with-args-until-failure 'kill-emacs-query-functions
)
6300 (or (null confirm-kill-emacs
)
6301 (funcall confirm-kill-emacs
"Really exit Emacs? "))
6304 (defun save-buffers-kill-terminal (&optional arg
)
6305 "Offer to save each buffer, then kill the current connection.
6306 If the current frame has no client, kill Emacs itself.
6308 With prefix ARG, silently save all file-visiting buffers, then kill.
6310 If emacsclient was started with a list of filenames to edit, then
6311 only these files will be asked to be saved."
6313 (if (frame-parameter (selected-frame) 'client
)
6314 (server-save-buffers-kill-terminal arg
)
6315 (save-buffers-kill-emacs arg
)))
6317 ;; We use /: as a prefix to "quote" a file name
6318 ;; so that magic file name handlers will not apply to it.
6320 (setq file-name-handler-alist
6321 (cons (cons (purecopy "\\`/:") 'file-name-non-special
)
6322 file-name-handler-alist
))
6324 ;; We depend on being the last handler on the list,
6325 ;; so that anything else which does need handling
6326 ;; has been handled already.
6327 ;; So it is safe for us to inhibit *all* magic file name handlers.
6329 (defun file-name-non-special (operation &rest arguments
)
6330 (let ((file-name-handler-alist nil
)
6332 (if (eq operation
'insert-directory
)
6333 (directory-file-name
6335 (unhandled-file-name-directory default-directory
)))
6337 ;; Get a list of the indices of the args which are file names.
6339 (cdr (or (assq operation
6340 ;; The first six are special because they
6341 ;; return a file name. We want to include the /:
6342 ;; in the return value.
6343 ;; So just avoid stripping it in the first place.
6344 '((expand-file-name . nil
)
6345 (file-name-directory . nil
)
6346 (file-name-as-directory . nil
)
6347 (directory-file-name . nil
)
6348 (file-name-sans-versions . nil
)
6349 (find-backup-file-name . nil
)
6350 ;; `identity' means just return the first arg
6351 ;; not stripped of its quoting.
6352 (substitute-in-file-name identity
)
6353 ;; `add' means add "/:" to the result.
6354 (file-truename add
0)
6355 (insert-file-contents insert-file-contents
0)
6356 ;; `unquote-then-quote' means set buffer-file-name
6357 ;; temporarily to unquoted filename.
6358 (verify-visited-file-modtime unquote-then-quote
)
6359 ;; List the arguments which are filenames.
6360 (file-name-completion 1)
6361 (file-name-all-completions 1)
6365 (make-symbolic-link 0 1)
6366 (add-name-to-file 0 1)))
6367 ;; For all other operations, treat the first argument only
6368 ;; as the file name.
6371 ;; Copy ARGUMENTS so we can replace elements in it.
6372 (arguments (copy-sequence arguments
)))
6373 (if (symbolp (car file-arg-indices
))
6374 (setq method
(pop file-arg-indices
)))
6375 ;; Strip off the /: from the file names that have it.
6377 (while (consp file-arg-indices
)
6378 (let ((pair (nthcdr (car file-arg-indices
) arguments
)))
6380 (string-match "\\`/:" (car pair
))
6382 (if (= (length (car pair
)) 2)
6384 (substring (car pair
) 2)))))
6385 (setq file-arg-indices
(cdr file-arg-indices
))))
6387 (identity (car arguments
))
6388 (add (concat "/:" (apply operation arguments
)))
6389 (insert-file-contents
6390 (let ((visit (nth 1 arguments
)))
6392 (apply operation arguments
)
6393 (when (and visit buffer-file-name
)
6394 (setq buffer-file-name
(concat "/:" buffer-file-name
))))))
6396 (let ((buffer-file-name (substring buffer-file-name
2)))
6397 (apply operation arguments
)))
6399 (apply operation arguments
)))))
6401 ;; Symbolic modes and read-file-modes.
6403 (defun file-modes-char-to-who (char)
6404 "Convert CHAR to a numeric bit-mask for extracting mode bits.
6405 CHAR is in [ugoa] and represents the category of users (Owner, Group,
6406 Others, or All) for whom to produce the mask.
6407 The bit-mask that is returned extracts from mode bits the access rights
6408 for the specified category of users."
6409 (cond ((= char ?u
) #o4700
)
6410 ((= char ?g
) #o2070
)
6411 ((= char ?o
) #o1007
)
6412 ((= char ?a
) #o7777
)
6413 (t (error "%c: bad `who' character" char
))))
6415 (defun file-modes-char-to-right (char &optional from
)
6416 "Convert CHAR to a numeric value of mode bits.
6417 CHAR is in [rwxXstugo] and represents symbolic access permissions.
6418 If CHAR is in [Xugo], the value is taken from FROM (or 0 if omitted)."
6419 (or from
(setq from
0))
6420 (cond ((= char ?r
) #o0444
)
6421 ((= char ?w
) #o0222
)
6422 ((= char ?x
) #o0111
)
6423 ((= char ?s
) #o1000
)
6424 ((= char ?t
) #o6000
)
6425 ;; Rights relative to the previous file modes.
6426 ((= char ?X
) (if (= (logand from
#o111
) 0) 0 #o0111
))
6427 ((= char ?u
) (let ((uright (logand #o4700 from
)))
6428 (+ uright
(/ uright
#o10
) (/ uright
#o100
))))
6429 ((= char ?g
) (let ((gright (logand #o2070 from
)))
6430 (+ gright
(/ gright
#o10
) (* gright
#o10
))))
6431 ((= char ?o
) (let ((oright (logand #o1007 from
)))
6432 (+ oright
(* oright
#o10
) (* oright
#o100
))))
6433 (t (error "%c: bad right character" char
))))
6435 (defun file-modes-rights-to-number (rights who-mask
&optional from
)
6436 "Convert a symbolic mode string specification to an equivalent number.
6437 RIGHTS is the symbolic mode spec, it should match \"([+=-][rwxXstugo]*)+\".
6438 WHO-MASK is the bit-mask specifying the category of users to which to
6439 apply the access permissions. See `file-modes-char-to-who'.
6440 FROM (or 0 if nil) gives the mode bits on which to base permissions if
6441 RIGHTS request to add, remove, or set permissions based on existing ones,
6443 (let* ((num-rights (or from
0))
6444 (list-rights (string-to-list rights
))
6445 (op (pop list-rights
)))
6446 (while (memq op
'(?
+ ?- ?
=))
6449 (while (memq (setq char-right
(pop list-rights
))
6450 '(?r ?w ?x ?X ?s ?t ?u ?g ?o
))
6453 (file-modes-char-to-right char-right num-rights
))))
6454 (setq num-right
(logand who-mask num-right
)
6456 (cond ((= op ?
+) (logior num-rights num-right
))
6457 ((= op ?-
) (logand num-rights
(lognot num-right
)))
6458 (t (logior (logand num-rights
(lognot who-mask
)) num-right
)))
6462 (defun file-modes-symbolic-to-number (modes &optional from
)
6463 "Convert symbolic file modes to numeric file modes.
6464 MODES is the string to convert, it should match
6465 \"[ugoa]*([+-=][rwxXstugo]*)+,...\".
6466 See Info node `(coreutils)File permissions' for more information on this
6468 FROM (or 0 if nil) gives the mode bits on which to base permissions if
6469 MODES request to add, remove, or set permissions based on existing ones,
6472 (let ((case-fold-search nil
)
6473 (num-modes (or from
0)))
6474 (while (/= (string-to-char modes
) 0)
6475 (if (string-match "^\\([ugoa]*\\)\\([+=-][rwxXstugo]*\\)+\\(,\\|\\)" modes
)
6476 (let ((num-who (apply 'logior
0
6477 (mapcar 'file-modes-char-to-who
6478 (match-string 1 modes
)))))
6480 (setq num-who
(default-file-modes)))
6482 (file-modes-rights-to-number (substring modes
(match-end 1))
6484 modes
(substring modes
(match-end 3))))
6485 (error "Parse error in modes near `%s'" (substring modes
0))))
6488 (defun read-file-modes (&optional prompt orig-file
)
6489 "Read file modes in octal or symbolic notation and return its numeric value.
6490 PROMPT is used as the prompt, default to `File modes (octal or symbolic): '.
6491 ORIG-FILE is the name of a file on whose mode bits to base returned
6492 permissions if what user types requests to add, remove, or set permissions
6493 based on existing mode bits, as in \"og+rX-w\"."
6494 (let* ((modes (or (if orig-file
(file-modes orig-file
) 0)
6495 (error "File not found")))
6496 (modestr (and (stringp orig-file
)
6497 (nth 8 (file-attributes orig-file
))))
6499 (and (stringp modestr
)
6500 (string-match "^.\\(...\\)\\(...\\)\\(...\\)$" modestr
)
6501 (replace-regexp-in-string
6503 (format "u=%s,g=%s,o=%s"
6504 (match-string 1 modestr
)
6505 (match-string 2 modestr
)
6506 (match-string 3 modestr
)))))
6507 (value (read-string (or prompt
"File modes (octal or symbolic): ")
6510 (if (string-match "^[0-7]+" value
)
6511 (string-to-number value
8)
6512 (file-modes-symbolic-to-number value modes
)))))
6515 ;; Trashcan handling.
6516 (defcustom trash-directory nil
6517 "Directory for `move-file-to-trash' to move files and directories to.
6518 This directory is only used when the function `system-move-file-to-trash'
6520 Relative paths are interpreted relative to `default-directory'.
6521 If the value is nil, Emacs uses a freedesktop.org-style trashcan."
6522 :type
'(choice (const nil
) directory
)
6526 (defvar trash--hexify-table
)
6528 (declare-function system-move-file-to-trash
"w32fns.c" (filename))
6530 (defun move-file-to-trash (filename)
6531 "Move the file (or directory) named FILENAME to the trash.
6532 When `delete-by-moving-to-trash' is non-nil, this function is
6533 called by `delete-file' and `delete-directory' instead of
6534 deleting files outright.
6536 If the function `system-move-file-to-trash' is defined, call it
6537 with FILENAME as an argument.
6538 Otherwise, if `trash-directory' is non-nil, move FILENAME to that
6540 Otherwise, trash FILENAME using the freedesktop.org conventions,
6541 like the GNOME, KDE and XFCE desktop environments. Emacs only
6542 moves files to \"home trash\", ignoring per-volume trashcans."
6543 (interactive "fMove file to trash: ")
6544 (cond (trash-directory
6545 ;; If `trash-directory' is non-nil, move the file there.
6546 (let* ((trash-dir (expand-file-name trash-directory
))
6547 (fn (directory-file-name (expand-file-name filename
)))
6548 (new-fn (expand-file-name (file-name-nondirectory fn
)
6550 ;; We can't trash a parent directory of trash-directory.
6551 (if (string-match fn trash-dir
)
6552 (error "Trash directory `%s' is a subdirectory of `%s'"
6553 trash-dir filename
))
6554 (unless (file-directory-p trash-dir
)
6555 (make-directory trash-dir t
))
6556 ;; Ensure that the trashed file-name is unique.
6557 (if (file-exists-p new-fn
)
6558 (let ((version-control t
)
6559 (backup-directory-alist nil
))
6560 (setq new-fn
(car (find-backup-file-name new-fn
)))))
6561 (let (delete-by-moving-to-trash)
6562 (rename-file fn new-fn
))))
6563 ;; If `system-move-file-to-trash' is defined, use it.
6564 ((fboundp 'system-move-file-to-trash
)
6565 (system-move-file-to-trash filename
))
6566 ;; Otherwise, use the freedesktop.org method, as specified at
6567 ;; http://freedesktop.org/wiki/Specifications/trash-spec
6569 (let* ((xdg-data-dir
6570 (directory-file-name
6571 (expand-file-name "Trash"
6572 (or (getenv "XDG_DATA_HOME")
6573 "~/.local/share"))))
6574 (trash-files-dir (expand-file-name "files" xdg-data-dir
))
6575 (trash-info-dir (expand-file-name "info" xdg-data-dir
))
6576 (fn (directory-file-name (expand-file-name filename
))))
6578 ;; Check if we have permissions to delete.
6579 (unless (file-writable-p (directory-file-name
6580 (file-name-directory fn
)))
6581 (error "Cannot move %s to trash: Permission denied" filename
))
6582 ;; The trashed file cannot be the trash dir or its parent.
6583 (if (string-match fn trash-files-dir
)
6584 (error "The trash directory %s is a subdirectory of %s"
6585 trash-files-dir filename
))
6586 (if (string-match fn trash-info-dir
)
6587 (error "The trash directory %s is a subdirectory of %s"
6588 trash-info-dir filename
))
6590 ;; Ensure that the trash directory exists; otherwise, create it.
6591 (let ((saved-default-file-modes (default-file-modes)))
6594 (set-default-file-modes #o700
)
6595 (unless (file-exists-p trash-files-dir
)
6596 (make-directory trash-files-dir t
))
6597 (unless (file-exists-p trash-info-dir
)
6598 (make-directory trash-info-dir t
)))
6599 (set-default-file-modes saved-default-file-modes
)))
6601 ;; Try to move to trash with .trashinfo undo information
6604 (set-buffer-file-coding-system 'utf-8-unix
)
6605 (insert "[Trash Info]\nPath=")
6606 ;; Perform url-encoding on FN. For compatibility with
6607 ;; other programs (e.g. XFCE Thunar), allow literal "/"
6608 ;; for path separators.
6609 (unless (boundp 'trash--hexify-table
)
6610 (setq trash--hexify-table
(make-vector 256 nil
))
6611 (let ((unreserved-chars
6612 (list ?
/ ?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m
6613 ?n ?o ?p ?q ?r ?s ?t ?u ?v ?w ?x ?y ?z ?A
6614 ?B ?C ?D ?E ?F ?G ?H ?I ?J ?K ?L ?M ?N ?O
6615 ?P ?Q ?R ?S ?T ?U ?V ?W ?X ?Y ?Z ?
0 ?
1 ?
2
6616 ?
3 ?
4 ?
5 ?
6 ?
7 ?
8 ?
9 ?- ?_ ?. ?
! ?~ ?
* ?
'
6619 (aset trash--hexify-table byte
6620 (if (memq byte unreserved-chars
)
6621 (char-to-string byte
)
6622 (format "%%%02x" byte
))))))
6623 (mapc (lambda (byte)
6624 (insert (aref trash--hexify-table byte
)))
6625 (if (multibyte-string-p fn
)
6626 (encode-coding-string fn
'utf-8
)
6628 (insert "\nDeletionDate="
6629 (format-time-string "%Y-%m-%dT%T")
6632 ;; Attempt to make .trashinfo file, trying up to 5
6633 ;; times. The .trashinfo file is opened with O_EXCL,
6634 ;; as per trash-spec 0.7, even if that can be a problem
6635 ;; on old NFS versions...
6637 (base-fn (expand-file-name
6638 (file-name-nondirectory fn
)
6643 (setq info-fn
(expand-file-name
6644 (concat (file-name-nondirectory new-fn
)
6647 (unless (condition-case nil
6649 (write-region nil nil info-fn nil
6650 'quiet info-fn
'excl
)
6651 (setq tries
0 success t
))
6652 (file-already-exists nil
))
6653 (setq tries
(1- tries
))
6654 ;; Uniquify new-fn. (Some file managers do not
6655 ;; like Emacs-style backup file names---e.g. bug
6656 ;; 170956 in Konqueror bug tracker.)
6657 (setq new-fn
(make-temp-name (concat base-fn
"_")))))
6659 (error "Cannot move %s to trash: Lock failed" filename
))
6661 ;; Finally, try to move the file to the trashcan.
6662 (let ((delete-by-moving-to-trash nil
))
6663 (rename-file fn new-fn
)))))))))
6666 (define-key ctl-x-map
"\C-f" 'find-file
)
6667 (define-key ctl-x-map
"\C-r" 'find-file-read-only
)
6668 (define-key ctl-x-map
"\C-v" 'find-alternate-file
)
6669 (define-key ctl-x-map
"\C-s" 'save-buffer
)
6670 (define-key ctl-x-map
"s" 'save-some-buffers
)
6671 (define-key ctl-x-map
"\C-w" 'write-file
)
6672 (define-key ctl-x-map
"i" 'insert-file
)
6673 (define-key esc-map
"~" 'not-modified
)
6674 (define-key ctl-x-map
"\C-d" 'list-directory
)
6675 (define-key ctl-x-map
"\C-c" 'save-buffers-kill-terminal
)
6676 (define-key ctl-x-map
"\C-q" 'toggle-read-only
)
6678 (define-key ctl-x-4-map
"f" 'find-file-other-window
)
6679 (define-key ctl-x-4-map
"r" 'find-file-read-only-other-window
)
6680 (define-key ctl-x-4-map
"\C-f" 'find-file-other-window
)
6681 (define-key ctl-x-4-map
"b" 'switch-to-buffer-other-window
)
6682 (define-key ctl-x-4-map
"\C-o" 'display-buffer
)
6684 (define-key ctl-x-5-map
"b" 'switch-to-buffer-other-frame
)
6685 (define-key ctl-x-5-map
"f" 'find-file-other-frame
)
6686 (define-key ctl-x-5-map
"\C-f" 'find-file-other-frame
)
6687 (define-key ctl-x-5-map
"r" 'find-file-read-only-other-frame
)
6688 (define-key ctl-x-5-map
"\C-o" 'display-buffer-other-frame
)
6690 ;;; files.el ends here