How can I make emacs automatically open binary files in hexl-mode? It's probably sufficient to define "binary" as "contains a null byte" (I suppose https://github.com/audreyr/binaryornot could be used if that ends up being an insufficient heuristic).

2 Answers 2


If you know the file extensions are working with, the best solution is to just use the auto-mode-alist to startup hexl-mode.

If not, and you take what you have said literally:

It's probably sufficient to define "binary" as "contains a null byte"

You can do this by adding a function that turns on hexl-mode if a file contain a null byte to the find-file-hooks.

Here is a implementation:

(defun buffer-binary-p (&optional buffer)
  "Return whether BUFFER or the current buffer is binary.

A binary buffer is defined as containing at least on null byte.

Returns either nil, or the position of the first null byte."
  (with-current-buffer (or buffer (current-buffer))
      (goto-char (point-min))
      (search-forward (string ?\x00) nil t 1))))

(defun hexl-if-binary ()
  "If `hexl-mode' is not already active, and the current buffer
is binary, activate `hexl-mode'."
  (unless (eq major-mode 'hexl-mode)
    (when (buffer-binary-p)

(add-hook 'find-file-hooks 'hexl-if-binary)
  • 1
    Awesome, this appears to work well.
    – asmeurer
    Commented Mar 25, 2015 at 17:08

I've tried Jordon's answer and it works well, however I'd like to recommend replacing hexl-if-binary (and the (add-hook)) with this:

(add-to-list 'magic-fallback-mode-alist '(buffer-binary-p . hexl-mode) t)

This way it only uses Hexl mode as a last resort if no other mode recognises the file. I prefer this because otherwise, image files open in Hexl mode rather than Image mode.

  • For me, this causes images to not load in hexl-mode in terminal emacs (which obviously doesn't support image mode).
    – asmeurer
    Commented Mar 9, 2021 at 23:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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