Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I make Emacs give me a warning if I am about to open a file that does not contain text?

Example: When I edit a c++ source code in file test.cpp and compile it as an executable test in the same directory, i often accidentally open the binary file test.

share|improve this question

migrated from Jan 2 '12 at 23:19

This question came from our site for professional and enthusiast programmers.

Emacs cannot warn you that a file does not contain text unless it either does open it (so that it can see what the contents are), or otherwise asks some other program to find out (perhaps using something like the Unix file command).

The problem with the latter approach is that Emacs can handle many kinds of binary file, so you would then need that external program to also know which kinds of binary file Emacs recognises, including support added by add-on libraries, which can vary dynamically and per-user.

I don't think there are any good options there.

What is it specifically that you are trying to avoid?


As the required test for the given example is based only upon filenames, the following would be a viable approach.

(defvar my-find-file-check-source-extensions
  '(".cpp" ".cc"))

(defadvice find-file-read-args (after my-find-file-read-args-check-source)
  (let* ((filename (car ad-return-value))
          (catch 'source-file-exists
            (mapc (lambda (ext)
                    (let ((source-filename (concat filename ext)))
                      (when (file-exists-p source-filename)
                        (throw 'source-file-exists source-filename))))

    (and source-filename
         (not (y-or-n-p (format "Source file %s detected. Are you sure you \
want to open %s? " source-filename filename)))
         (error "find-file aborted by user"))))

(ad-activate 'find-file-read-args)
share|improve this answer
I edited by question by adding an example. – ggg Jan 2 '12 at 1:43
Code added..... – phils Mar 7 '13 at 7:16

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.