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).
Asked
Active
Viewed 1,983 times
2 Answers
5
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))
(save-excursion
(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'."
(interactive)
(unless (eq major-mode 'hexl-mode)
(when (buffer-binary-p)
(hexl-mode))))
(add-hook 'find-file-hooks 'hexl-if-binary)

Jordon Biondo
- 12,332
- 2
- 41
- 62
-
1Awesome, this appears to work well. – asmeurer Mar 25 '15 at 17:08
2
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.

bewilderex63
- 140
- 3
-
For me, this causes images to not load in hexl-mode in terminal emacs (which obviously doesn't support image mode). – asmeurer Mar 09 '21 at 23:20