;;  bit-mode.el
;;  $Id: bit-mode.el,v 1.2 2002/09/14 20:34:39 euske Exp $


; * public domain * by 1@2ch

;; .bit ファイルを編集するモード
;;    M-p : 前の文字へ
;;    M-n : 次の文字へ
;;    M-k : 1カラム消去
;;    M-i : 1カラム挿入

;STARTCHAR 0
;ENCODING 0
;SWIDTH 960 0
;DWIDTH 6 0
;BBX 6 12 0 -2
;BITMAP
;......
;.@....
;..@@..
;......
;ENDCHAR

(setq auto-mode-alist
      (append auto-mode-alist
	      '(("\\.bit\\'" . bit-mode) 
		("\\.bit0\\'" . bit-mode) 
		("\\.bit1\\'" . bit-mode))))

(defvar bit-mode-map nil)
(if (not bit-mode-map)
    (progn
      (setq bit-mode-map (make-sparse-keymap))
      (define-key bit-mode-map "\M-p" 'bit-prev-adjusted)
      (define-key bit-mode-map "\M-n" 'bit-next-adjusted)
      (define-key bit-mode-map "\M-k" 'bit-delete-column)
      (define-key bit-mode-map "\M-i" 'bit-insert-column)))

(defun point+ (x) (+ (point) x))
(defun point- (x) (- (point) x))

(defun bit-mode () "bit-mode" (interactive)
  (kill-all-local-variables)
  (use-local-map bit-mode-map)
  (setq mode-name "Bit")
  (setq major-mode 'bit-mode)
  (run-hooks 'bit-mode-hook))

(defun bit-adjust-bbx (n)
  (re-search-backward "^BBX +\\([0-9]+\\) +\\([0-9]+\\)")
  (replace-match
   (concat "BBX " (number-to-string
		   (+ n (string-to-number (match-string 1)))) " \\2")))
(defun bit-beginning ()
  (let ((m (make-marker)))
    (re-search-forward "^ENDCHAR")
    (setq m (set-marker m (match-beginning 0)))
    (re-search-backward "^BITMAP")
    (next-line 1)
    m))

(defun bit-bitmapp ()
  (memq (char-after (point- (current-column))) '(10 46 64)))

(defun bit-delete-column () (interactive)
  (save-excursion
    (let* ((x (current-column))
	   (m (bit-beginning)))
      (while (< (point) m)
	(beginning-of-line)
	(goto-char (point+ x))
	(delete-char 1)
	(next-line 1)))
    (bit-adjust-bbx -1)))

(defun bit-insert-column () (interactive)
  (save-excursion
    (let* ((x (current-column))
	   (m (bit-beginning)))
      (while (< (point) m)
	(beginning-of-line)
	(goto-char (point+ x))
	(insert ".")
	(next-line 1)))
    (bit-adjust-bbx 1)))

(defun bit-prev-adjusted () (interactive)
  (re-search-backward "# ADJUSTED")
  (re-search-backward "# ADJUSTED")
  (re-search-forward "^BITMAP")
  (beginning-of-line)
  (next-line 1)
  (recenter))

(defun bit-next-adjusted () (interactive)
  (re-search-forward "# ADJUSTED")
  (re-search-forward "^BITMAP")
  (beginning-of-line)
  (next-line 1)
  (recenter))
