8

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

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
    Awesome, this appears to work well. – asmeurer Mar 25 '15 at 17:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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