9

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

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) 
1
  • 1
    Awesome, this appears to work well. Commented Mar 25, 2015 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.

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.