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