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).
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
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)
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.