2009/09/20

半角文字で全角文字をisearch

emacs-w3mを使っている時等、たまに全角のアルファベット・数字が出て来る。そんな場合に半角文字でisearchを行ってもsearch結果に出て来なくてちょっと困っていたので、elispを書いてみた。

;;; begin
(defconst *zenkaku-list*
'((?a . ?a) (?b . ?b) (?c . ?c) (?d . ?d)
(?e . ?e) (?f . ?f) (?g . ?g) (?h . ?h)
(?i . ?i) (?j . ?j) (?k . ?k) (?l . ?l)
(?m . ?m) (?n . ?n) (?o . ?o) (?p . ?p)
(?q . ?q) (?r . ?r) (?s . ?s) (?t . ?t)
(?u . ?u) (?v . ?v) (?w . ?w) (?x . ?x)
(?y . ?y) (?z . ?z)
(?A . ?A) (?B . ?B) (?C . ?C) (?D . ?D)
(?E . ?E) (?F . ?F) (?G . ?G) (?H . ?H)
(?I . ?I) (?J . ?J) (?K . ?K) (?L . ?L)
(?M . ?M) (?N . ?N) (?O . ?O) (?P . ?P)
(?Q . ?Q) (?R . ?R) (?S . ?S) (?T . ?T)
(?U . ?U) (?V . ?V) (?W . ?W) (?X . ?X)
(?Y . ?Y) (?Z . ?Z)
(?0 . ?0) (?1 . ?1) (?2 . ?2) (?3 . ?3)
(?4 . ?4) (?5 . ?5) (?6 . ?6) (?7 . ?7)
(?8 . ?8) (?9 . ?9)))

(defun my-get-hankaku-zenkaku-regexp (target-string)
(let ((case-fold-search nil)
(target-string-length (length target-string))
(target-string-new "")
char-current
matchp
(x 0))
(while (< x target-string-length)
(setq char-current (elt target-string x))
(setq matchp nil)
(dolist (pair *zenkaku-list*)
(if (char-equal (car pair) char-current)
(progn
(setq target-string-new
(format "%s\\(%s\\|%s\\)"
target-string-new (string char-current) (string (cdr pair))))
(setq matchp t))))
(if (not matchp)
(setq target-string-new (format "%s%s" target-string-new (string char-current))))
(setq x (1+ x)))
target-string-new))

(defun my-re-search-zenkaku-by-hankaku-forward (search-string &optional bound noerror count)
(re-search-forward (my-get-hankaku-zenkaku-regexp search-string) bound noerror count))

(defun my-re-search-zenkaku-by-hankaku-backward (search-string &optional bound noerror count)
(re-search-backward (my-get-hankaku-zenkaku-regexp search-string) bound noerror count))

(defun my-isearch-zenkaku-by-hankaku ()
(if isearch-forward 'my-re-search-zenkaku-by-hankaku-forward 'my-re-search-zenkaku-by-hankaku-backward))

(setq isearch-search-fun-function 'my-isearch-zenkaku-by-hankaku)

;;; end