;; Support incremental search using keyboard.el

;; sample setting:
;; (add-hook 'isearch-mode-hook 'keyboard-isearch-mode-setup)
;; (add-hook 'isearch-mode-end-hook 'keyboard-isearch-mode-cleanup)

(defvar keyboard-isearch-mode-iso-map nil)
(defvar keyboard-isearch-mode-sjis-map nil)
(defvar keyboard-isearch-mode-local-iso-map nil)
(defvar keyboard-isearch-mode-local-sjis-map nil)

(if keyboard-isearch-mode-iso-map
    nil
  (setq keyboard-isearch-mode-iso-map (cons 'keymap isearch-mode-map)
	keyboard-isearch-mode-sjis-map (cons 'keymap isearch-mode-map))
  (keyboard-define-global-map-iso keyboard-isearch-mode-iso-map)
  (keyboard-define-global-map-sjis keyboard-isearch-mode-sjis-map)
  (setq keyboard-isearch-mode-local-iso-map
	(cons 'keymap keyboard-isearch-mode-iso-map)
	keyboard-isearch-mode-local-sjis-map
	(cons 'keymap keyboard-isearch-mode-sjis-map))
  (keyboard-define-local-map-iso keyboard-isearch-mode-local-iso-map)
  (keyboard-define-local-map-sjis keyboard-isearch-mode-local-sjis-map))


(defun keyboard-self-insert-do-isearch (char)
  (let ((string (char-to-string char)))
    (isearch-process-search-string string string)))

;; local keymap used by isearch.el.  In GNU Emacs 19.28 or earlier,
;; overriding-local-map was used.  In GNU Emacs 19.29 or later,
;; overriding-terminal-local-map is used.
(defun keyboard-use-local-map-do-isearch (map)
  (setq overriding-terminal-local-map map))

(defun keyboard-current-local-map-do-isearch ()
  overriding-terminal-local-map)

(defun keyboard-local-map-do-isearch ()
  (keyboard-select-keymap nil
			  keyboard-isearch-mode-local-sjis-map
			  keyboard-isearch-mode-local-iso-map))


(defun keyboard-isearch-mode-global-map ()
  (keyboard-select-keymap nil
			  keyboard-isearch-mode-sjis-map
			  keyboard-isearch-mode-iso-map))

;;;###autoload
(defun keyboard-isearch-mode-setup ()
  (setq overriding-terminal-local-map
	(keyboard-isearch-mode-global-map)
	keyboard-self-insert-function 
	(function keyboard-self-insert-do-isearch)
	keyboard-use-local-map-function 
	(function keyboard-use-local-map-do-isearch)
	keyboard-current-local-map-function
	(function keyboard-current-local-map-do-isearch)
	keyboard-local-map-function 
	(function keyboard-local-map-do-isearch)))

;;;###autoload
(defun keyboard-isearch-mode-cleanup ()
  (setq keyboard-self-insert-function
	(function keyboard-self-insert-do-insert)
	keyboard-use-local-map-function
	(function keyboard-use-local-map-do-insert)
	keyboard-current-local-map-function
	(function keyboard-current-local-map-do-insert)
	keyboard-local-map-function 
	(function keyboard-local-map-do-insert)))
