Output alists with dotted pair notation in .dir-locals.el
[emacs.git] / lisp / hexl.el
blob230b64d9f239beb64acf735707fbc904f9aece58
1 ;;; hexl.el --- edit a file in a hex dump format using the hexl filter -*- lexical-binding: t -*-
3 ;; Copyright (C) 1989, 1994, 1998, 2001-2018 Free Software Foundation,
4 ;; Inc.
6 ;; Author: Keith Gabryelski <ag@wheaties.ai.mit.edu>
7 ;; Maintainer: emacs-devel@gnu.org
8 ;; Keywords: data
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; This package implements a major mode for editing binary files. It uses
28 ;; a program called hexl, supplied with the GNU Emacs distribution, that
29 ;; can filter a binary into an editable format or from the format back into
30 ;; binary. For full instructions, invoke `hexl-mode' on an empty buffer and
31 ;; do M-x `describe-mode'.
33 ;; NOTE: Remember to change `hexl-program' or `hexl-options' if needed.
35 ;; Currently hexl only supports big endian hex output with 16 bit
36 ;; grouping.
38 ;; -iso in `hexl-options' will allow iso characters to display in the
39 ;; ASCII region of the screen (if your Emacs supports this) instead of
40 ;; changing them to dots.
42 ;;; Code:
44 (require 'eldoc)
45 (eval-when-compile (require 'cl-lib))
48 ;; vars here
51 (defgroup hexl nil
52 "Edit a file in a hex dump format using the hexl filter."
53 :group 'data)
55 (defcustom hexl-bits 16
56 "The bit grouping that hexl will use."
57 :type '(choice (const 8 )
58 (const 16)
59 (const 32)
60 (const 64))
61 :version "24.3")
63 (defcustom hexl-program "hexl"
64 "The program that will hexlify and dehexlify its stdin.
65 `hexl-program' will always be concatenated with `hexl-options'
66 and \"-de\" when dehexlifying a buffer."
67 :type 'string)
69 (defcustom hexl-iso ""
70 "If your Emacs can handle ISO characters, this should be set to
71 \"-iso\" otherwise it should be \"\"."
72 :type 'string)
74 (defcustom hexl-options (format "-hex %s" hexl-iso)
75 "Space separated options to `hexl-program' that suit your needs.
76 Quoting cannot be used, so the arguments cannot themselves contain spaces.
77 If you wish to set the `-group-by-X-bits' options, set `hexl-bits' instead,
78 as that will override any bit grouping options set here."
79 :type 'string)
81 (defcustom hexl-follow-ascii t
82 "If non-nil then highlight the ASCII character corresponding to point."
83 :type 'boolean
84 :version "20.3")
86 (defcustom hexl-mode-hook '(hexl-follow-line hexl-activate-ruler)
87 "Normal hook run when entering Hexl mode."
88 :type 'hook
89 :options '(hexl-follow-line hexl-activate-ruler eldoc-mode))
91 (defface hexl-address-region
92 '((t (:inherit header-line)))
93 "Face used in address area of Hexl mode buffer.")
95 (defface hexl-ascii-region
96 '((t (:inherit header-line)))
97 "Face used in ASCII area of Hexl mode buffer.")
99 (defvar-local hexl-max-address 0
100 "Maximum offset into hexl buffer.")
102 (defvar hexl-mode-map
103 (let ((map (make-keymap)))
104 ;; Make all self-inserting keys go through hexl-self-insert-command,
105 ;; because we need to convert them to unibyte characters before
106 ;; inserting them into the buffer.
107 (define-key map [remap self-insert-command] 'hexl-self-insert-command)
109 (define-key map "\C-m" 'hexl-self-insert-command)
110 (define-key map [left] 'hexl-backward-char)
111 (define-key map [right] 'hexl-forward-char)
112 (define-key map [up] 'hexl-previous-line)
113 (define-key map [down] 'hexl-next-line)
114 (define-key map [M-left] 'hexl-backward-short)
115 (define-key map [?\e left] 'hexl-backward-short)
116 (define-key map [M-right] 'hexl-forward-short)
117 (define-key map [?\e right] 'hexl-forward-short)
118 (define-key map [next] 'hexl-scroll-up)
119 (define-key map [prior] 'hexl-scroll-down)
120 (define-key map [home] 'hexl-beginning-of-line)
121 (define-key map [end] 'hexl-end-of-line)
122 (define-key map [C-home] 'hexl-beginning-of-buffer)
123 (define-key map [C-end] 'hexl-end-of-buffer)
124 (define-key map [deletechar] 'undefined)
125 (define-key map [deleteline] 'undefined)
126 (define-key map [insertline] 'undefined)
127 (define-key map [S-delete] 'undefined)
128 (define-key map "\177" 'undefined)
130 (define-key map "\C-a" 'hexl-beginning-of-line)
131 (define-key map "\C-b" 'hexl-backward-char)
132 (define-key map "\C-d" 'undefined)
133 (define-key map "\C-e" 'hexl-end-of-line)
134 (define-key map "\C-f" 'hexl-forward-char)
136 (if (not (memq (key-binding (char-to-string help-char))
137 '(help-command ehelp-command)))
138 (define-key map (char-to-string help-char) 'undefined))
140 (define-key map "\C-k" 'undefined)
141 (define-key map "\C-n" 'hexl-next-line)
142 (define-key map "\C-o" 'undefined)
143 (define-key map "\C-p" 'hexl-previous-line)
144 (define-key map "\C-q" 'hexl-quoted-insert)
145 (define-key map "\C-t" 'undefined)
146 (define-key map "\C-v" 'hexl-scroll-up)
147 (define-key map "\C-w" 'undefined)
148 (define-key map "\C-y" 'undefined)
150 (fset 'hexl-ESC-prefix (copy-keymap 'ESC-prefix))
151 (define-key map "\e" 'hexl-ESC-prefix)
152 (define-key map "\e\C-a" 'hexl-beginning-of-512b-page)
153 (define-key map "\e\C-b" 'hexl-backward-short)
154 (define-key map "\e\C-d" 'hexl-insert-decimal-char)
155 (define-key map "\e\C-e" 'hexl-end-of-512b-page)
156 (define-key map "\e\C-f" 'hexl-forward-short)
157 (define-key map "\e\C-i" 'undefined)
158 (define-key map "\e\C-j" 'undefined)
159 (define-key map "\e\C-k" 'undefined)
160 (define-key map "\e\C-o" 'hexl-insert-octal-char)
161 (define-key map "\e\C-q" 'undefined)
162 (define-key map "\e\C-t" 'undefined)
163 (define-key map "\e\C-x" 'hexl-insert-hex-char)
164 (define-key map "\eb" 'hexl-backward-word)
165 (define-key map "\ec" 'undefined)
166 (define-key map "\ed" 'undefined)
167 (define-key map "\ef" 'hexl-forward-word)
168 (define-key map "\eg" 'hexl-goto-hex-address)
169 (define-key map "\ei" 'undefined)
170 (define-key map "\ej" 'hexl-goto-address)
171 (define-key map "\ek" 'undefined)
172 (define-key map "\el" 'undefined)
173 (define-key map "\eq" 'undefined)
174 (define-key map "\es" 'undefined)
175 (define-key map "\et" 'undefined)
176 (define-key map "\eu" 'undefined)
177 (define-key map "\ev" 'hexl-scroll-down)
178 (define-key map "\ey" 'undefined)
179 (define-key map "\ez" 'undefined)
180 (define-key map "\e<" 'hexl-beginning-of-buffer)
181 (define-key map "\e>" 'hexl-end-of-buffer)
183 (fset 'hexl-C-c-prefix (copy-keymap mode-specific-map))
184 (define-key map "\C-c" 'hexl-C-c-prefix)
185 (define-key map "\C-c\C-c" 'hexl-mode-exit)
187 (fset 'hexl-C-x-prefix (copy-keymap 'Control-X-prefix))
188 (define-key map "\C-x" 'hexl-C-x-prefix)
189 (define-key map "\C-x[" 'hexl-beginning-of-1k-page)
190 (define-key map "\C-x]" 'hexl-end-of-1k-page)
191 (define-key map "\C-x\C-p" 'undefined)
192 (define-key map "\C-x\C-s" 'hexl-save-buffer)
193 (define-key map "\C-x\C-t" 'undefined)
194 map))
196 ;; Variable declarations for suppressing warnings from the byte-compiler.
197 (defvar ruler-mode)
198 (defvar ruler-mode-ruler-function)
199 (defvar hl-line-mode)
200 (defvar hl-line-range-function)
201 (defvar hl-line-face)
203 ;; Variables where the original values are stored to.
204 (defvar hexl-mode--old-var-vals ())
205 (make-variable-buffer-local 'hexl-mode--old-var-vals)
207 (defvar hexl-ascii-overlay nil
208 "Overlay used to highlight ASCII element corresponding to current point.")
209 (make-variable-buffer-local 'hexl-ascii-overlay)
211 (defvar hexl-font-lock-keywords
212 '(("^\\([0-9a-f]+:\\).\\{40\\} \\(.+$\\)"
213 ;; "^\\([0-9a-f]+:\\).+ \\(.+$\\)"
214 (1 'hexl-address-region t t)
215 (2 'hexl-ascii-region t t)))
216 "Font lock keywords used in `hexl-mode'.")
218 (defun hexl-rulerize (string bits)
219 (let ((size (/ bits 4)) (strlen (length string)) (pos 0) (ruler ""))
220 (while (< pos strlen)
221 (setq ruler (concat ruler " " (substring string pos (+ pos size))))
222 (setq pos (+ pos size)))
223 (substring ruler 1) ))
225 (defvar hexl-rulers
226 (mapcar
227 (lambda (bits)
228 (cons bits
229 (concat " 87654321 "
230 (hexl-rulerize "00112233445566778899aabbccddeeff" bits)
231 " 0123456789abcdef")))
232 '(8 16 32 64)))
233 ;; routines
235 (put 'hexl-mode 'mode-class 'special)
237 ;; 10 chars for the "address: "
238 ;; 32 chars for the hexlified bytes
239 ;; 1 char for the space
240 ;; 16 chars for the character display
241 ;; X chars for the spaces (128 bits divided by the hexl-bits)
242 ;; 1 char for the newline.
243 (defun hexl-line-displen ()
244 "The length of a hexl display line (varies with `hexl-bits')."
245 (+ 60 (/ 128 (or hexl-bits 16))))
247 ;;;###autoload
248 (defun hexl-mode (&optional arg)
249 "\\<hexl-mode-map>A mode for editing binary files in hex dump format.
250 This is not an ordinary major mode; it alters some aspects
251 of the current mode's behavior, but not all; also, you can exit
252 Hexl mode and return to the previous mode using `hexl-mode-exit'.
254 This function automatically converts a buffer into the hexl format
255 using the function `hexlify-buffer'.
257 Each line in the buffer has an \"address\" (displayed in hexadecimal)
258 representing the offset into the file that the characters on this line
259 are at and 16 characters from the file (displayed as hexadecimal
260 values grouped every `hexl-bits' bits, and as their ASCII values).
262 If any of the characters (displayed as ASCII characters) are
263 unprintable (control or meta characters) they will be replaced by
264 periods.
266 If `hexl-mode' is invoked with an argument the buffer is assumed to be
267 in hexl format.
269 A sample format:
271 HEX ADDR: 0011 2233 4455 6677 8899 aabb ccdd eeff ASCII-TEXT
272 -------- ---- ---- ---- ---- ---- ---- ---- ---- ----------------
273 00000000: 5468 6973 2069 7320 6865 786c 2d6d 6f64 This is hexl-mod
274 00000010: 652e 2020 4561 6368 206c 696e 6520 7265 e. Each line re
275 00000020: 7072 6573 656e 7473 2031 3620 6279 7465 presents 16 byte
276 00000030: 7320 6173 2068 6578 6164 6563 696d 616c s as hexadecimal
277 00000040: 2041 5343 4949 0a61 6e64 2070 7269 6e74 ASCII.and print
278 00000050: 6162 6c65 2041 5343 4949 2063 6861 7261 able ASCII chara
279 00000060: 6374 6572 732e 2020 416e 7920 636f 6e74 cters. Any cont
280 00000070: 726f 6c20 6f72 206e 6f6e 2d41 5343 4949 rol or non-ASCII
281 00000080: 2063 6861 7261 6374 6572 730a 6172 6520 characters.are
282 00000090: 6469 7370 6c61 7965 6420 6173 2070 6572 displayed as per
283 000000a0: 696f 6473 2069 6e20 7468 6520 7072 696e iods in the prin
284 000000b0: 7461 626c 6520 6368 6172 6163 7465 7220 table character
285 000000c0: 7265 6769 6f6e 2e0a region..
287 Movement is as simple as movement in a normal Emacs text buffer.
288 Most cursor movement bindings are the same: use \\[hexl-backward-char], \\[hexl-forward-char], \\[hexl-next-line], and \\[hexl-previous-line]
289 to move the cursor left, right, down, and up.
291 Advanced cursor movement commands (ala \\[hexl-beginning-of-line], \\[hexl-end-of-line], \\[hexl-beginning-of-buffer], and \\[hexl-end-of-buffer]) are
292 also supported.
294 There are several ways to change text in hexl mode:
296 ASCII characters (character between space (0x20) and tilde (0x7E)) are
297 bound to self-insert so you can simply type the character and it will
298 insert itself (actually overstrike) into the buffer.
300 \\[hexl-quoted-insert] followed by another keystroke allows you to insert the key even if
301 it isn't bound to self-insert. An octal number can be supplied in place
302 of another key to insert the octal number's ASCII representation.
304 \\[hexl-insert-hex-char] will insert a given hexadecimal value (if it is between 0 and 0xFF)
305 into the buffer at the current point.
307 \\[hexl-insert-octal-char] will insert a given octal value (if it is between 0 and 0377)
308 into the buffer at the current point.
310 \\[hexl-insert-decimal-char] will insert a given decimal value (if it is between 0 and 255)
311 into the buffer at the current point.
313 \\[hexl-mode-exit] will exit `hexl-mode'.
315 Note: saving the file with any of the usual Emacs commands
316 will actually convert it back to binary format while saving.
318 You can use \\[hexl-find-file] to visit a file in Hexl mode.
320 \\[describe-bindings] for advanced commands."
321 (interactive "p")
322 (unless (eq major-mode 'hexl-mode)
323 (let ((modified (buffer-modified-p))
324 (inhibit-read-only t)
325 (original-point (- (point) (point-min))))
326 (and (eobp) (not (bobp))
327 (setq original-point (1- original-point)))
328 ;; If `hexl-mode' is invoked with an argument the buffer is assumed to
329 ;; be in hexl format.
330 (when (memq arg '(1 nil))
331 ;; If the buffer's EOL type is -dos, we need to account for
332 ;; extra CR characters added when hexlify-buffer writes the
333 ;; buffer to a file.
334 ;; FIXME: This doesn't take into account multibyte coding systems.
335 (when (eq (coding-system-eol-type buffer-file-coding-system) 1)
336 (setq original-point (+ (count-lines (point-min) (point))
337 original-point))
338 (or (bolp) (setq original-point (1- original-point))))
339 (hexlify-buffer)
340 (restore-buffer-modified-p modified))
341 (setq hexl-max-address
342 (+ (* (/ (1- (buffer-size)) (hexl-line-displen)) 16) 15))
343 (condition-case nil
344 (hexl-goto-address original-point)
345 (error nil)))
347 (let ((max-address hexl-max-address))
348 (major-mode-suspend)
349 (setq hexl-max-address max-address))
351 (use-local-map hexl-mode-map)
353 (setq-local mode-name "Hexl")
354 (setq-local isearch-search-fun-function #'hexl-isearch-search-function)
355 (setq-local major-mode 'hexl-mode)
357 ;; (set-syntax-table (standard-syntax-table))
359 (add-hook 'write-contents-functions #'hexl-save-buffer nil t)
361 (setq-local require-final-newline nil)
364 (setq-local font-lock-defaults '(hexl-font-lock-keywords t))
366 (setq-local revert-buffer-function #'hexl-revert-buffer-function)
367 (add-hook 'change-major-mode-hook #'hexl-maybe-dehexlify-buffer nil t)
369 ;; Set a callback function for eldoc.
370 (add-function :before-until (local 'eldoc-documentation-function)
371 #'hexl-print-current-point-info)
372 (eldoc-add-command-completions "hexl-")
373 (eldoc-remove-command "hexl-save-buffer"
374 "hexl-current-address")
376 (if hexl-follow-ascii (hexl-follow-ascii-mode 1)))
377 (run-mode-hooks 'hexl-mode-hook))
380 (defun hexl-isearch-search-function ()
381 (if (and (not isearch-regexp) (not isearch-regexp-function))
382 (lambda (string &optional bound noerror count)
383 (funcall
384 (if isearch-forward 're-search-forward 're-search-backward)
385 (let ((textre
386 (if (> (length string) 80)
387 (regexp-quote string)
388 (mapconcat (lambda (c) (regexp-quote (string c))) string
389 "\\(?:\n\\(?:[:a-f0-9]+ \\)+ \\)?"))))
390 (if (string-match "\\` ?\\([a-f0-9]+ \\)*[a-f0-9]+ ?\\'" string)
391 (concat textre "\\|"
392 (mapconcat 'regexp-quote (split-string string " ")
393 " \\(?: .+\n[a-f0-9]+: \\)?"))
394 textre))
395 bound noerror count))
396 (isearch-search-fun-default)))
398 (defvar hexl-in-save-buffer nil)
400 (defun hexl-save-buffer ()
401 "Save a hexl format buffer as binary in visited file if modified."
402 (interactive)
403 (if hexl-in-save-buffer nil
404 (restore-buffer-modified-p
405 (if (buffer-modified-p)
406 (let ((buf (generate-new-buffer " hexl"))
407 (name (buffer-name))
408 (start (point-min))
409 (end (point-max))
410 modified)
411 (with-current-buffer buf
412 (insert-buffer-substring name start end)
413 (set-buffer name)
414 (dehexlify-buffer)
415 ;; Prevent infinite recursion.
416 (let ((hexl-in-save-buffer t))
417 (save-buffer))
418 (setq modified (buffer-modified-p))
419 (delete-region (point-min) (point-max))
420 (insert-buffer-substring buf start end)
421 (kill-buffer buf)
422 modified))
423 (message "(No changes need to be saved)")
424 nil))
425 ;; Return t to indicate we have saved t
428 ;;;###autoload
429 (defun hexl-find-file (filename)
430 "Edit file FILENAME as a binary file in hex dump format.
431 Switch to a buffer visiting file FILENAME, creating one if none exists,
432 and edit the file in `hexl-mode'."
433 (interactive
434 (list
435 (let ((completion-ignored-extensions nil))
436 (read-file-name "Filename: " nil nil 'ret-must-match))))
437 ;; Ignore the user's setting of default major-mode.
438 (cl-letf (((default-value 'major-mode) 'fundamental-mode))
439 (find-file-literally filename))
440 (if (not (eq major-mode 'hexl-mode))
441 (hexl-mode)))
443 (defun hexl-revert-buffer-function (_ignore-auto _noconfirm)
444 ;; FIXME: We don't obey revert-buffer-preserve-modes!
445 (let ((coding-system-for-read 'no-conversion)
446 revert-buffer-function)
447 ;; Call the original `revert-buffer' without code conversion; also
448 ;; prevent it from changing the major mode to normal-mode, which
449 ;; calls `set-auto-mode'.
450 (revert-buffer nil nil t)
451 ;; A couple of hacks are necessary here:
452 ;; 1. change the major-mode to one other than hexl-mode since the
453 ;; function `hexl-mode' does nothing if the current major-mode is
454 ;; already hexl-mode.
455 ;; 2. reset change-major-mode-hook in case that `hexl-mode'
456 ;; previously added hexl-maybe-dehexlify-buffer to it.
457 (remove-hook 'change-major-mode-hook #'hexl-maybe-dehexlify-buffer t)
458 (setq major-mode 'fundamental-mode)
459 (hexl-mode)))
461 (defun hexl-mode-exit (&optional arg)
462 "Exit Hexl mode, returning to previous mode.
463 With arg, don't unhexlify buffer."
464 (interactive "p")
465 (if (or (eq arg 1) (not arg))
466 (let ((modified (buffer-modified-p))
467 (inhibit-read-only t)
468 (original-point (1+ (hexl-current-address))))
469 (dehexlify-buffer)
470 (remove-hook 'write-contents-functions #'hexl-save-buffer t)
471 (restore-buffer-modified-p modified)
472 (goto-char original-point)
473 ;; Maybe adjust point for the removed CR characters.
474 (when (eq (coding-system-eol-type buffer-file-coding-system) 1)
475 (setq original-point (- original-point
476 (count-lines (point-min) (point))))
477 (or (bobp) (setq original-point (1+ original-point))))
478 (goto-char original-point)))
480 (remove-hook 'change-major-mode-hook #'hexl-maybe-dehexlify-buffer t)
481 (major-mode-restore))
483 (defun hexl-maybe-dehexlify-buffer ()
484 "Convert a hexl format buffer to binary.
485 Ask the user for confirmation."
486 (if (y-or-n-p "Convert contents back to binary format? ")
487 (let ((modified (buffer-modified-p))
488 (inhibit-read-only t)
489 (original-point (1+ (hexl-current-address))))
490 (dehexlify-buffer)
491 (remove-hook 'write-contents-functions #'hexl-save-buffer t)
492 (restore-buffer-modified-p modified)
493 (goto-char original-point))))
495 (defun hexl-current-address (&optional validate)
496 "Return current hexl-address."
497 (interactive)
498 (let ((current-column
499 (- (% (- (point) (point-min) -1) (hexl-line-displen)) 11))
500 (hexl-address 0))
501 (if (< current-column 0)
502 (if validate
503 (error "Point is not on a character in the file")
504 (setq current-column 0)))
505 (setq hexl-address
506 (+ (* (/ (- (point) (point-min) -1)
507 (hexl-line-displen)) 16)
508 (if (>= current-column (- (hexl-ascii-start-column) 10))
509 (- current-column (- (hexl-ascii-start-column) 10))
510 (/ (- current-column
511 (/ current-column (1+ (/ hexl-bits 4)))) 2))))
512 (when (called-interactively-p 'interactive)
513 (message "Current address is %d/0x%08x" hexl-address hexl-address))
514 hexl-address))
516 (defun hexl-print-current-point-info ()
517 "Return current hexl-address in string.
518 This function is intended to be used as eldoc callback."
519 (let ((addr (hexl-current-address)))
520 (format "Current address is %d/0x%08x" addr addr)))
522 (defun hexl-ascii-start-column ()
523 "Column at which the ASCII portion of the hexl display starts."
524 (+ 43 (/ 128 hexl-bits)))
526 (defun hexl-address-to-marker (address)
527 "Return buffer position for ADDRESS."
528 (interactive "nAddress: ")
529 (let ((N (* (% address 16) 2)))
530 (+ (* (/ address 16) (hexl-line-displen)) ; hexl line no * display length
531 10 ; 10 chars for the "address: " prefix
532 (point-min) ; base offset (point usually starts at 1, not 0)
533 (+ N (/ N (/ hexl-bits 4))) )) ) ; char offset into hexl display line
535 (defun hexl-goto-address (address)
536 "Go to hexl-mode (decimal) address ADDRESS.
537 Signal error if ADDRESS is out of range."
538 (interactive "nAddress: ")
539 (if (or (< address 0) (> address hexl-max-address))
540 (error "Out of hexl region"))
541 (goto-char (hexl-address-to-marker address)))
543 (defun hexl-goto-hex-address (hex-address)
544 "Go to Hexl mode address (hex string) HEX-ADDRESS.
545 Signal error if HEX-ADDRESS is out of range."
546 (interactive "sHex Address: ")
547 (hexl-goto-address (hexl-hex-string-to-integer hex-address)))
549 (defun hexl-hex-string-to-integer (hex-string)
550 "Return decimal integer for HEX-STRING."
551 (interactive "sHex number: ")
552 (let ((hex-num 0))
553 (while (not (equal hex-string ""))
554 (setq hex-num (+ (* hex-num 16)
555 (hexl-hex-char-to-integer (string-to-char hex-string))))
556 (setq hex-string (substring hex-string 1)))
557 hex-num))
559 (defun hexl-octal-string-to-integer (octal-string)
560 "Return decimal integer for OCTAL-STRING."
561 (interactive "sOctal number: ")
562 (let ((oct-num 0))
563 (while (not (equal octal-string ""))
564 (setq oct-num (+ (* oct-num 8)
565 (hexl-oct-char-to-integer
566 (string-to-char octal-string))))
567 (setq octal-string (substring octal-string 1)))
568 oct-num))
570 ;; move point functions
572 (defun hexl-backward-char (arg)
573 "Move to left ARG bytes (right if ARG negative) in Hexl mode."
574 (interactive "p")
575 (hexl-goto-address (- (hexl-current-address) arg)))
577 (defun hexl-forward-char (arg)
578 "Move to right ARG bytes (left if ARG negative) in Hexl mode."
579 (interactive "p")
580 (hexl-goto-address (+ (hexl-current-address) arg)))
582 (defun hexl-backward-short (arg)
583 "Move to left ARG shorts (right if ARG negative) in Hexl mode."
584 (interactive "p")
585 (hexl-goto-address (let ((address (hexl-current-address)))
586 (if (< arg 0)
587 (progn
588 (setq arg (- arg))
589 (while (> arg 0)
590 (setq address
591 (if (> address hexl-max-address)
592 (progn
593 (message "End of buffer.")
594 hexl-max-address)
595 (if (equal address (logior address 3))
596 (+ address 4)
597 (logior address 3))))
598 (setq arg (1- arg)))
599 (setq address
600 (if (> address hexl-max-address)
601 (progn
602 (message "End of buffer.")
603 hexl-max-address)
604 (logior address 3))))
605 (while (> arg 0)
606 (if (not (equal address (logand address -4)))
607 (setq address (logand address -4))
608 (if (not (equal address 0))
609 (setq address (- address 4))
610 (message "Beginning of buffer.")))
611 (setq arg (1- arg))))
612 address)))
614 (defun hexl-forward-short (arg)
615 "Move to right ARG shorts (left if ARG negative) in Hexl mode."
616 (interactive "p")
617 (hexl-backward-short (- arg)))
619 (defun hexl-backward-word (arg)
620 "Move to left ARG words (right if ARG negative) in Hexl mode."
621 (interactive "p")
622 (hexl-goto-address (let ((address (hexl-current-address)))
623 (if (< arg 0)
624 (progn
625 (setq arg (- arg))
626 (while (> arg 0)
627 (setq address
628 (if (> address hexl-max-address)
629 (progn
630 (message "End of buffer.")
631 hexl-max-address)
632 (if (equal address (logior address 7))
633 (+ address 8)
634 (logior address 7))))
635 (setq arg (1- arg)))
636 (setq address
637 (if (> address hexl-max-address)
638 (progn
639 (message "End of buffer.")
640 hexl-max-address)
641 (logior address 7))))
642 (while (> arg 0)
643 (if (not (equal address (logand address -8)))
644 (setq address (logand address -8))
645 (if (not (equal address 0))
646 (setq address (- address 8))
647 (message "Beginning of buffer.")))
648 (setq arg (1- arg))))
649 address)))
651 (defun hexl-forward-word (arg)
652 "Move to right ARG words (left if ARG negative) in Hexl mode."
653 (interactive "p")
654 (hexl-backward-word (- arg)))
656 (defun hexl-previous-line (arg)
657 "Move vertically up ARG lines [16 bytes] (down if ARG negative) in Hexl mode.
658 If there is no byte at the target address move to the last byte in that line."
659 (interactive "p")
660 (hexl-next-line (- arg)))
662 (defun hexl-next-line (arg)
663 "Move vertically down ARG lines [16 bytes] (up if ARG negative) in Hexl mode.
664 If there is no byte at the target address move to the last byte in that line."
665 (interactive "p")
666 (hexl-goto-address (let ((address (+ (hexl-current-address) (* arg 16))))
667 (if (and (< arg 0) (< address 0))
668 (progn (message "Out of hexl region.")
669 (setq address
670 (% (hexl-current-address) 16)))
671 (if (and (> address hexl-max-address)
672 (< (% hexl-max-address 16) (% address 16)))
673 (setq address hexl-max-address)
674 (if (> address hexl-max-address)
675 (progn (message "Out of hexl region.")
676 (setq
677 address
678 (+ (logand hexl-max-address -16)
679 (% (hexl-current-address) 16)))))))
680 address)))
682 (defun hexl-beginning-of-buffer (arg)
683 "Move to the beginning of the hexl buffer.
684 Leaves `hexl-mark' at previous position.
685 With prefix arg N, puts point N bytes of the way from the true beginning."
686 (interactive "p")
687 (push-mark)
688 (hexl-goto-address (+ 0 (1- arg))))
690 (defun hexl-end-of-buffer (arg)
691 "Go to `hexl-max-address' minus ARG."
692 (interactive "p")
693 (push-mark)
694 (hexl-goto-address (- hexl-max-address (1- arg))))
696 (defun hexl-beginning-of-line ()
697 "Goto beginning of line in Hexl mode."
698 (interactive)
699 (goto-char (+ (* (/ (point) (hexl-line-displen)) (hexl-line-displen)) 11)))
701 (defun hexl-end-of-line ()
702 "Goto end of line in Hexl mode."
703 (interactive)
704 (hexl-goto-address (let ((address (logior (hexl-current-address) 15)))
705 (if (> address hexl-max-address)
706 (setq address hexl-max-address))
707 address)))
709 (defun hexl-scroll-down (arg)
710 "Scroll hexl buffer window upward ARG lines; or near full window if no ARG."
711 (interactive "P")
712 (setq arg (if (null arg)
713 (1- (window-height))
714 (prefix-numeric-value arg)))
715 (hexl-scroll-up (- arg)))
717 (defun hexl-scroll-up (arg)
718 "Scroll hexl buffer window upward ARG lines; or near full window if no ARG.
719 If there's no byte at the target address, move to the first or last line."
720 (interactive "P")
721 (setq arg (if (null arg)
722 (1- (window-height))
723 (prefix-numeric-value arg)))
724 (let* ((movement (* arg 16))
725 (address (hexl-current-address))
726 (dest (+ address movement)))
727 (cond
728 ;; If possible, try to stay at the same offset from the beginning
729 ;; of the 16-byte group, even if we move to the first or last
730 ;; group.
731 ((and (> dest hexl-max-address)
732 (>= (% hexl-max-address 16) (% address 16)))
733 (setq dest (+ (logand hexl-max-address -16) (% address 16))))
734 ((> dest hexl-max-address)
735 (setq dest hexl-max-address))
736 ((< dest 0)
737 (setq dest (% address 16))))
738 (if (/= dest (+ address movement))
739 (message "Out of hexl region."))
740 (hexl-goto-address dest)
741 (recenter 0)))
743 (defun hexl-beginning-of-1k-page ()
744 "Go to beginning of 1KB boundary."
745 (interactive)
746 (hexl-goto-address (logand (hexl-current-address) -1024)))
748 (defun hexl-end-of-1k-page ()
749 "Go to end of 1KB boundary."
750 (interactive)
751 (hexl-goto-address
752 (max hexl-max-address (logior (hexl-current-address) 1023))))
754 (defun hexl-beginning-of-512b-page ()
755 "Go to beginning of 512 byte boundary."
756 (interactive)
757 (hexl-goto-address (logand (hexl-current-address) -512)))
759 (defun hexl-end-of-512b-page ()
760 "Go to end of 512 byte boundary."
761 (interactive)
762 (hexl-goto-address
763 (max hexl-max-address (logior (hexl-current-address) 511))))
765 (defun hexl-quoted-insert (arg)
766 "Read next input character and insert it.
767 Useful for inserting control characters and non-ASCII characters given their
768 numerical code.
769 You may also type octal digits, to insert a character with that code."
770 (interactive "p")
771 (hexl-insert-multibyte-char (read-quoted-char) arg))
773 ;00000000: 0011 2233 4455 6677 8899 aabb ccdd eeff 0123456789ABCDEF
775 (defun hexl-options (&optional test)
776 "Combine `hexl-bits' with `hexl-options', altering `hexl-options' as needed
777 to produce the command line options to pass to the hexl command."
778 (let ((opts (or test hexl-options)))
779 (when (memq hexl-bits '(8 16 32 64))
780 (when (string-match "\\(.*\\)-group-by-[0-9]+-bits\\(.*\\)" opts)
781 (setq opts (concat (match-string 1 opts)
782 (match-string 2 opts))))
783 (setq opts (format "%s -group-by-%d-bits " opts hexl-bits)) )
784 opts))
786 ;;;###autoload
787 (defun hexlify-buffer ()
788 "Convert a binary buffer to hexl format.
789 This discards the buffer's undo information."
790 (interactive)
791 (and (consp buffer-undo-list)
792 (or (y-or-n-p "Converting to hexl format discards undo info; ok? ")
793 (error "Aborted"))
794 (setq buffer-undo-list nil))
795 ;; Don't decode text in the ASCII part of `hexl' program output.
796 (let ((coding-system-for-read 'raw-text)
797 (coding-system-for-write buffer-file-coding-system)
798 (buffer-undo-list t))
799 (apply 'call-process-region (point-min) (point-max)
800 (expand-file-name hexl-program exec-directory)
801 t t nil
802 ;; Manually encode the args, otherwise they're encoded using
803 ;; coding-system-for-write (i.e. buffer-file-coding-system) which
804 ;; may not be what we want (e.g. utf-16 on a non-utf-16 system).
805 (mapcar (lambda (s)
806 (if (not (multibyte-string-p s)) s
807 (encode-coding-string s locale-coding-system)))
808 (split-string (hexl-options))))
809 (if (> (point) (hexl-address-to-marker hexl-max-address))
810 (hexl-goto-address hexl-max-address))))
812 (defun dehexlify-buffer ()
813 "Convert a hexl format buffer to binary.
814 This discards the buffer's undo information."
815 (interactive)
816 (and (consp buffer-undo-list)
817 (or (y-or-n-p "Converting from hexl format discards undo info; ok? ")
818 (error "Aborted"))
819 (setq buffer-undo-list nil))
820 (let ((coding-system-for-write 'raw-text)
821 (coding-system-for-read buffer-file-coding-system)
822 (buffer-undo-list t))
823 (apply 'call-process-region (point-min) (point-max)
824 (expand-file-name hexl-program exec-directory)
825 t t nil "-de" (split-string (hexl-options)))))
827 (defun hexl-char-after-point ()
828 "Return char for ASCII hex digits at point."
829 (hexl-htoi (char-after (point))
830 (char-after (1+ (point)))))
832 (defun hexl-htoi (lh rh)
833 "Hex (char) LH (char) RH to integer."
834 (+ (* (hexl-hex-char-to-integer lh) 16)
835 (hexl-hex-char-to-integer rh)))
837 (defun hexl-hex-char-to-integer (character)
838 "Take a char and return its value as if it was a hex digit."
839 (if (and (>= character ?0) (<= character ?9))
840 (- character ?0)
841 (let ((ch (logior character 32)))
842 (if (and (>= ch ?a) (<= ch ?f))
843 (- ch (- ?a 10))
844 (error "Invalid hex digit `%c'" ch)))))
846 (defun hexl-oct-char-to-integer (character)
847 "Take a char and return its value as if it was an octal digit."
848 (if (and (>= character ?0) (<= character ?7))
849 (- character ?0)
850 (error "Invalid octal digit `%c'" character)))
852 (defun hexl-printable-character (ch)
853 "Return a displayable string for character CH."
854 (format "%c" (if (equal hexl-iso "")
855 (if (or (< ch 32) (>= ch 127))
858 (if (or (< ch 32) (and (>= ch 127) (< ch 160)))
860 ch))))
862 (defun hexl-insert-multibyte-char (ch num)
863 "Insert a possibly multibyte character CH NUM times.
865 Non-ASCII characters are first encoded with `buffer-file-coding-system',
866 and their encoded form is inserted byte by byte."
867 (let ((charset (char-charset ch))
868 (coding (if (or (null buffer-file-coding-system)
869 ;; coding-system-type equals t means undecided.
870 (eq (coding-system-type buffer-file-coding-system) t))
871 (default-value 'buffer-file-coding-system)
872 buffer-file-coding-system)))
873 (cond ((and (> ch 0) (< ch 256))
874 (hexl-insert-char ch num))
875 ((eq charset 'unknown)
876 (error
877 "0x%x -- invalid character code; use \\[hexl-insert-hex-string]"
878 ch))
880 (let ((encoded (encode-coding-char ch coding))
881 (internal (string-as-unibyte (char-to-string ch)))
882 internal-hex)
883 ;; If encode-coding-char returns nil, it means our character
884 ;; cannot be safely encoded with buffer-file-coding-system.
885 ;; In that case, we offer to insert the internal representation
886 ;; of that character, byte by byte.
887 (when (null encoded)
888 (setq internal-hex
889 (mapconcat (function (lambda (c) (format "%x" c)))
890 internal " "))
891 (if (yes-or-no-p
892 (format-message
893 "Insert char 0x%x's internal representation \"%s\"? "
894 ch internal-hex))
895 (setq encoded internal)
896 (error
897 "Can't encode `0x%x' with this buffer's coding system; %s"
899 (substitute-command-keys "try \\[hexl-insert-hex-string]"))))
900 (while (> num 0)
901 (mapc
902 (function (lambda (c) (hexl-insert-char c 1))) encoded)
903 (setq num (1- num))))))))
905 (defun hexl-self-insert-command (arg)
906 "Insert this character.
907 Interactively, with a numeric argument, insert this character that many times.
909 Non-ASCII characters are first encoded with `buffer-file-coding-system',
910 and their encoded form is inserted byte by byte."
911 (interactive "p")
912 (hexl-insert-multibyte-char last-command-event arg))
914 (defun hexl-insert-char (ch num)
915 "Insert the character CH NUM times in a hexl buffer.
917 CH must be a unibyte character whose value is between 0 and 255."
918 (if (or (< ch 0) (> ch 255))
919 (error "Invalid character 0x%x -- must be in the range [0..255]" ch))
920 (let ((address (hexl-current-address t)))
921 (while (> num 0)
922 (let ((hex-position (hexl-address-to-marker address))
923 (ascii-position
924 (+ (* (/ address 16) (hexl-line-displen))
925 (hexl-ascii-start-column)
926 (point-min)
927 (% address 16)))
928 at-ascii-position)
929 (if (= (point) ascii-position)
930 (setq at-ascii-position t))
931 (goto-char hex-position)
932 (delete-char 2)
933 (insert (format "%02x" ch))
934 (goto-char ascii-position)
935 (delete-char 1)
936 (insert (hexl-printable-character ch))
937 (or (eq address hexl-max-address)
938 (setq address (1+ address)))
939 (hexl-goto-address address)
940 (if at-ascii-position
941 (progn
942 (beginning-of-line)
943 (forward-char (hexl-ascii-start-column))
944 (forward-char (% address 16)))))
945 (setq num (1- num)))))
947 ;; hex conversion
949 (defun hexl-insert-hex-char (arg)
950 "Insert a character given by its hexadecimal code ARG times at point."
951 (interactive "p")
952 (let ((num (hexl-hex-string-to-integer (read-string "Hex number: "))))
953 (if (< num 0)
954 (error "Hex number out of range")
955 (hexl-insert-multibyte-char num arg))))
957 (defun hexl-insert-hex-string (str arg)
958 "Insert hexadecimal string STR at point ARG times.
959 Embedded whitespace, dashes, and periods in the string are ignored."
960 (interactive "sHex string: \np")
961 (setq str (replace-regexp-in-string "[- \t.]" "" str))
962 (let ((chars '()))
963 (let ((len (length str))
964 (idx 0))
965 (if (eq (logand len 1) 1)
966 (let ((num (hexl-hex-string-to-integer (substring str 0 1))))
967 (setq chars (cons num chars))
968 (setq idx 1)))
969 (while (< idx len)
970 (let* ((nidx (+ idx 2))
971 (num (hexl-hex-string-to-integer (substring str idx nidx))))
972 (setq chars (cons num chars))
973 (setq idx nidx))))
974 (setq chars (nreverse chars))
975 (while (> arg 0)
976 (let ((chars chars))
977 (while chars
978 (hexl-insert-char (car chars) 1)
979 (setq chars (cdr chars))))
980 (setq arg (- arg 1)))))
982 (defun hexl-insert-decimal-char (arg)
983 "Insert a character given by its decimal code ARG times at point."
984 (interactive "p")
985 (let ((num (string-to-number (read-string "Decimal Number: "))))
986 (if (< num 0)
987 (error "Decimal number out of range")
988 (hexl-insert-multibyte-char num arg))))
990 (defun hexl-insert-octal-char (arg)
991 "Insert a character given by its octal code ARG times at point."
992 (interactive "p")
993 (let ((num (hexl-octal-string-to-integer (read-string "Octal Number: "))))
994 (if (< num 0)
995 (error "Decimal number out of range")
996 (hexl-insert-multibyte-char num arg))))
998 (define-minor-mode hexl-follow-ascii-mode
999 "Minor mode to follow ASCII in current Hexl buffer.
1001 When following is enabled, the ASCII character corresponding to the
1002 element under the point is highlighted.
1003 The default activation is controlled by `hexl-follow-ascii'."
1004 :global nil
1005 (if hexl-follow-ascii-mode
1006 ;; turn it on
1007 (progn
1008 (unless hexl-ascii-overlay
1009 (setq hexl-ascii-overlay (make-overlay (point) (point)))
1010 (overlay-put hexl-ascii-overlay 'face 'highlight))
1011 (add-hook 'post-command-hook #'hexl-follow-ascii-find nil t))
1012 ;; turn it off
1013 (when hexl-ascii-overlay
1014 (delete-overlay hexl-ascii-overlay)
1015 (setq hexl-ascii-overlay nil))
1016 (remove-hook 'post-command-hook #'hexl-follow-ascii-find t)))
1018 (define-minor-mode hexl-follow-ascii
1019 "Toggle following ASCII in Hexl buffers.
1020 Like `hexl-follow-ascii-mode' but remembers the choice globally."
1021 :global t
1022 (let ((on-p (if arg
1023 (> (prefix-numeric-value arg) 0)
1024 (not hexl-ascii-overlay))))
1025 (hexl-follow-ascii-mode (if on-p 1 -1))
1026 ;; Remember this choice globally for later use.
1027 (setq hexl-follow-ascii hexl-follow-ascii-mode)))
1029 (defun hexl-activate-ruler ()
1030 "Activate `ruler-mode'."
1031 (require 'ruler-mode)
1032 (setq-local ruler-mode-ruler-function #'hexl-mode-ruler)
1033 (ruler-mode 1))
1035 (defun hexl-follow-line ()
1036 "Activate `hl-line-mode'."
1037 (require 'hl-line)
1038 (setq-local hl-line-range-function #'hexl-highlight-line-range)
1039 (setq-local hl-line-face 'highlight) ;FIXME: Why?
1040 (hl-line-mode 1))
1042 (defun hexl-highlight-line-range ()
1043 "Return the range of address region for the point.
1044 This function is assumed to be used as callback function for `hl-line-mode'."
1045 (cons
1046 (line-beginning-position)
1047 ;; 9 stands for (length "87654321:")
1048 (+ (line-beginning-position) 9)))
1050 (defun hexl-follow-ascii-find ()
1051 "Find and highlight the ASCII element corresponding to current point."
1052 (let ((pos (+ (hexl-ascii-start-column)
1053 (- (point) (current-column))
1054 (mod (hexl-current-address) 16))))
1055 (move-overlay hexl-ascii-overlay pos (1+ pos))
1058 (defun hexl-mode-ruler ()
1059 "Return a string ruler for Hexl mode."
1060 (let* ((highlight (mod (hexl-current-address) 16))
1061 (s (cdr (assq hexl-bits hexl-rulers)))
1062 (pos 0)
1063 (lnum-width
1064 (if display-line-numbers
1065 (round (line-number-display-width 'columns))
1066 0)))
1067 (set-text-properties 0 (length s) nil s)
1068 (when (> lnum-width 0)
1069 (setq s (concat (make-string lnum-width ? ) s))
1070 (setq pos (+ pos lnum-width)))
1071 ;; Turn spaces in the header into stretch specs so they work
1072 ;; regardless of the header-line face.
1073 (while (string-match "[ \t]+" s pos)
1074 (setq pos (match-end 0))
1075 (put-text-property (match-beginning 0) pos 'display
1076 ;; Assume fixed-size chars
1077 `(space :align-to ,(1- pos))
1079 ;; Highlight the current column.
1080 (let ( (offset (+ (* 2 highlight) (/ (* 8 highlight) hexl-bits))) )
1081 (if (> lnum-width 0) (setq offset (+ offset lnum-width)))
1082 (put-text-property (+ 11 offset) (+ 13 offset) 'face 'highlight s))
1083 ;; Highlight the current ascii column
1084 (put-text-property (+ (hexl-ascii-start-column) lnum-width highlight 1)
1085 (+ (hexl-ascii-start-column) lnum-width highlight 2)
1086 'face 'highlight s)
1089 ;; startup stuff.
1091 (easy-menu-define hexl-menu hexl-mode-map "Hexl Mode menu"
1092 `("Hexl"
1093 :help "Hexl-specific Features"
1095 ["Backward short" hexl-backward-short
1096 :help "Move to left a short"]
1097 ["Forward short" hexl-forward-short
1098 :help "Move to right a short"]
1099 ["Backward word" hexl-backward-short
1100 :help "Move to left a word"]
1101 ["Forward word" hexl-forward-short
1102 :help "Move to right a word"]
1104 ["Beginning of 512b page" hexl-beginning-of-512b-page
1105 :help "Go to beginning of 512 byte boundary"]
1106 ["End of 512b page" hexl-end-of-512b-page
1107 :help "Go to end of 512 byte boundary"]
1108 ["Beginning of 1K page" hexl-beginning-of-1k-page
1109 :help "Go to beginning of 1KB boundary"]
1110 ["End of 1K page" hexl-end-of-1k-page
1111 :help "Go to end of 1KB boundary"]
1113 ["Go to address" hexl-goto-address
1114 :help "Go to hexl-mode (decimal) address"]
1115 ["Go to address" hexl-goto-hex-address
1116 :help "Go to hexl-mode (hex string) address"]
1118 ["Insert decimal char" hexl-insert-decimal-char
1119 :help "Insert a character given by its decimal code"]
1120 ["Insert hex char" hexl-insert-hex-char
1121 :help "Insert a character given by its hexadecimal code"]
1122 ["Insert octal char" hexl-insert-octal-char
1123 :help "Insert a character given by its octal code"]
1125 ["Exit hexl mode" hexl-mode-exit
1126 :help "Exit hexl mode returning to previous mode"]))
1128 (provide 'hexl)
1130 ;;; hexl.el ends here