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