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