;;; Version: $Id: my_lisp_init.el,v 1.89 2007/11/27 05:36:51 kurihara Exp $
;;; Last Modified: $Date: 2007/11/27 05:36:51 $
;;;

;; (setq stack-trace-on-error t)
;; (defun kerr (str)
;;   (save-excursion
;;     (set-buffer "*scratch*")
;;     (insert-string str)))


;; apel の前に、default の load-path がないと、
;; apel 内部のプログラムが優先されてしまうことがある。
;; time-stamp.el は、apel の中にもあり、apel のものは古いので、
;; 問題がおきる。
(let (apels sorted-path)
  (while load-path
    (let ((head (car load-path)))
      (if (string-match "/apel" head)
          (setq apels (cons head apels))
        (setq sorted-path (cons head sorted-path)))
      (setq load-path (cdr load-path))))
  (setq load-path (append sorted-path apels)))

(setq load-path
      ;; load-path に、マシンローカルの e-lisp があるので、
      ;; ~/ucvs 以下を優先させるべき。
      (append (list
               "~/lisp"
               "~/lisp/emacs-wget"
;;                "~/lisp/mule-ucs"
;;                "~/lisp/mule-ucs/jisx0213"
               "~/ucvs/share/emacs/site-lisp/apel"
               "~/ucvs/share/emacs/site-lisp/emu"
               "~/ucvs/share/emacs/site-lisp/flim"
               "~/ucvs/share/emacs/site-lisp/semi"
               "~/ucvs/share/emacs/site-lisp/wl"
               "~/ucvs/share/emacs/site-lisp/mew"
               "~/ucvs/share/emacs/site-lisp/w3m"
               "~/ucvs/share/emacs/site-lisp/skk"
               "~/ucvs/share/emacs/site-lisp/sdic"
;;                "~/ucvs/share/emacs/site-lisp/navi2ch"
               "~/ucvs/share/emacs/site-lisp/ruby"
               ;;"~/ucvs/share/emacs/site-lisp/yatex"
               ;;"~/ucvs/share/emacs/site-lisp/psgml"
;;                "~/ucvs/share/emacs/site-lisp/lookup"
               "~/ucvs/share/emacs/site-lisp"
               )
              load-path
              (list
               "/usr/local/share/emacs/site-lisp"
               )
              ))

;; 初期設定
(load "my_lisp_private")
(setq user-full-name "Kenichi Kurihara")
(set-language-environment "Japanese")
(set-default-coding-systems 'euc-jp)
(prefer-coding-system 'euc-jp)
(if (eq system-type 'darwin)
    (progn
      (set-selection-coding-system 'shift_jis-mac)
      ;; dired-mode で日本語が通る(mac)
      (setq file-name-coding-system 'utf-8))
  (setq file-name-coding-system 'euc-jp))
;; (set-keyboard-coding-system 'euc-jp)
(set-terminal-coding-system 'euc-jp)
(setq default-process-coding-system (cons 'euc-jp 'euc-jp))

(when (fboundp 'utf-translate-cjk-mode)
;;   (provide 'un-define) ;; require 'un-define を、無意味にする
;;                        ;; un-define に定義されている関数が必要なこともある。
  (utf-translate-cjk-mode t)
;;  (require 'utf-8)
;;  (utf-translace-cjk-load-tables)
  )
(eval-after-load "subst-jis" '(load "subst-jisx0208ex"))

;; mac じゃなければ、メニューバーがないので、時計を表示
(if (not (eq system-type 'darwin))
    (display-time))

;;;
;;; for CarbonEmacs
;;; 基本的な設定を行うので、init file の前半に置く必要がある
;;;
(when (eq window-system 'mac)
  (load "my_lisp_carbon-emacs"))

;;; -------------------------------ここから-------------------------------
;;; global-key-bind
;;; 
(global-unset-key "\C-q")
;(global-unset-key "\M-h")

(global-set-key "\C-qh" 'help-command)
(global-set-key "\C-qsb" 'ispell-buffer)
(global-set-key "\C-qsw" (lambda () 
                           (interactive)
                           (ispell-word) (message "use M-$ instead.")))
(global-set-key "\C-qsr" 'ispell-region)
(global-set-key "\C-qc" 'cvs-examine)

;; ;; バッファを切替えるのにC-x eでelectric-buffer-listを使う。
;; (global-set-key "\C-xe" 'electric-buffer-list)
;; C-x C-b -> list-buffers

(global-set-key "\M-\C-b" 'iswitchb-buffer)

;; C-o で動的略語展開
(global-set-key "\C-o" 'dabbrev-expand)

;; M-" で、"" を挿入
(global-set-key "\M-\"" (lambda ()
                          (interactive)
                          (insert "\"\"")
                          (backward-char)))

;; 大文字、小文字変換 ; デフォルトはそれぞれ、引数なし。
(global-set-key "\M-u" (lambda () (interactive) (upcase-word -1)))
(global-set-key "\M-l" (lambda () (interactive) (downcase-word -1)))

;; find-file-other-window
(global-set-key "\C-x\M-f" 'find-file-other-window)

;; C-h でバックスペース
(global-set-key "\C-h" 'backward-delete-char-untabify)

;; isearch時に、C-hでdelete-char
(define-key isearch-mode-map "\C-h" 'isearch-delete-char)

;; C-q j で目的の行にジャンプ -> num G in viper
;; (global-set-key "\C-qj" 'goto-line)

;; C-, で15行逆にスクロール
(global-set-key [?\C-,] '(lambda () (interactive) (previous-line 15)))

;; C-. で15行スクロール
(global-set-key [?\C-.] '(lambda () (interactive) (next-line 15)))

;; C-< で7字戻る
;(global-set-key [?\C-<] '(lambda () (interactive) (backward-char 7)))

;; C-> で7字進む
;(global-set-key [?\C->] '(lambda () (interactive) (forward-char 7)))

;; M-o で次のウィンドウ
(global-set-key "\M-o" '(lambda () (interactive) (other-window 1)))

;; M-C-o で次のウィンドウ逆順
(global-set-key "\M-\C-o" '(lambda () (interactive) (other-window -1)))

;; (global-set-key "\M-\C-f" 'windmove-right)
;; (global-set-key "\M-\C-b" 'windmove-left)
;; (global-set-key "\M-\C-p" 'windmove-up)
;; (global-set-key "\M-\C-n" 'windmove-down)

;; 選択範囲を右にインデント
;; M-x increase-left-margin と同じ
(global-set-key [?\C-}] 'increase-left-margin)

;; 選択範囲を左にインデント
(global-set-key [?\C-{] 'decrease-left-margin)

;; Carbon ではない Mac 上の Emacs でクリップボード
(when (and (not (eq window-system 'mac))
           (eq system-type 'darwin))
  (autoload 'paste-from-mac "my_lisp_lazy-loads" "paste from mac" t)
  (autoload 'copy-to-mac "my_lisp_lazy-loads" "copy to mac" t)
  (setq interprogram-cut-function 'copy-to-mac)
  (global-set-key "\M-V" 'paste-from-mac))

(autoload 'my-concat-paragraph-en
  "my_lisp_lazy-loads" "concat lines in the paragraph" t)
(global-set-key "\M-Q" 'my-concat-paragraph-en)

;; ホイールマウスを使わない。
;; デフォルトで、unbind だが、何故かビープ音がなるので、無益な関数をbind
;; (global-set-key [mouse-4] (function (lambda () (interactive))))
;; (global-set-key [mouse-5] (function (lambda () (interactive))))
;; 以下は動かない
;; (defadvice other-window (after inhibit-wheel activate)
;;   (function (lambda () (mouse-wheel-mode -1))))



;;; -------------------------------ここから-------------------------------
;;; emacs 標準のライブラリ
;;;
;; emacsclient
(server-start)
(if (eq window-system 'x)
    (add-hook 'server-switch-hook 'raise-frame))

;; 日本語を含む文章でも動的略称展開をうまく動かす
(eval-after-load "dabbrev" '(load "my_lisp_dabbrev.el"))

(setq
 ;; confirm when leaving emacs
 confirm-kill-emacs 'y-or-n-p
 ;; beep を止めて、flash screen にする。
 visible-bell t
 ;; max-lisp-eval-depth の default は 300。wl で巨大なフォルダを s all
 ;; すると 300 を越えてしまう。
 max-lisp-eval-depth 1000
 ;; default は 1000
 max-specpdl-size 3000
 temporary-file-directory "~/tmp/"
 ;; Find-File 等で、ignore-case な補完
 completion-ignore-case t
 read-file-name-completion-ignore-case t
 ;; ispell, flyspell のため。これを設定しないと、
 ;; 環境変数 LANG から言語が決まる。
 ispell-dictionary "english"
 ;; 日本語を含む文章の ps-print
 ps-multibyte-buffer 'non-latin-printer
 ;; signature-file
 ;; signature-file-name "~/vctrl/signature"
 ;; version-controll されているファイルのシンボリックリンクを辿るかどうか
 vc-follow-symlinks t
 ;; emacs が file.~version~ のようなファイルを作らなくなる。
 ;; emacs から cvs を使う場合は、このファイルがあると動作が高速。
 vc-cvs-stay-local nil
 ;; スクロールする行数を1にする
 scroll-conservatively 100
 ;; いつもスクロールを一行にするには、scroll-step より、scroll-conservatively を
 ;; 設定するべき。
;;  scroll-step 1
 ;; プロセス通信する時にpipeを使う, ptyを使わない (man 等のため)
 ;; tramp は nil でないと動かないようだ (10.2)
 ;; 10.3 からはバグが直ったので、デフォルトのままの t 方がよい。
 ;; 気が付いたら、デフォルトが nil になっていた。(mac, 21.3.50, 2/4 2005)
 ;; process-connection-type nil
 ;; StartupMessageを表示しない
 inhibit-startup-message t
 ;; garbage collectionの頻度を減らして、速度向上
 ;; デフォルトは400000
 gc-cons-threshold 1000000
 ;; 縦分割画面で、長い行をwrapさせる。
 truncate-partial-width-windows nil
 ;; hoge.txt~のようなバックアップファイルを作らない
 backup-inhibited t
 ;; ignored-extensions like fignore
 completion-ignored-extensions (cons ".rtf" ;; rtf は emacs で開かない
                                     ;; pdf は、よく添付することがある。
                                     (remove ".dvi"
                                             (remove ".pdf"
                                                     completion-ignored-extensions)))
 ;; browse-url
 browse-url-browser-function (cond ((eq system-type 'darwin)
                                    'browse-url-default-macosx-browser)
                                   ;;(window-system 'browse-url-mozilla)
                                   (window-system 'w3m-browse-url)
                                   (t 'w3m-browse-url))
 ;; キーリピートにカーソルを追随させる;; 副作用があるらしい...
 redisplay-dont-pause t
 ;; line-number-mode
 ;; 表示する line の制限。 詳しくは、helpを
 line-number-display-limit-width 80000
 ;; auto-mode-alist
 auto-mode-alist (append
                  '(("\\.pl$" . prolog-mode)
                    ("\\.plist$" . sgml-mode)
                    ("\\.psm$" . prolog-mode) ;; for prism
                    ("\\.zsh$" . shell-script-mode)
                    ("\\.plt$" . gnuplot-mode)
                    ("\\.m$" . matlab-mode)
                    )
                  auto-mode-alist) ;; 上を優先するので、append の順番に注意
 ;; info path
 Info-additional-directory-list '("~/ucvs/info" "/sw/share/info")
 ;; compile の時に、自動的にスクロール
 compilation-scroll-output t
 ;; コンパイルウィンドウの高さを指定
 compilation-window-height 8
 ;; non-nil で、undo が redo しない
 undo-no-redo t
 )

(autoload 'find-file-as-su "my_lisp_lazy-loads" "find file as su" t)

;; yes or not を y or n にする
(fset 'yes-or-no-p 'y-or-n-p)

;; 画像ファイルを表示
;(auto-image-file-mode t)

;; ホイールマウスを使う; デフォルトで、on
;;(mouse-wheel-mode t)

;; ファイルを開いた時に以前いた行に移動する
(setq-default save-place t)
(require 'saveplace)

;; #! で始まるファイルを実行ファイルにする
(add-hook 'after-save-hook
          'executable-make-buffer-file-executable-if-script-p)

(when window-system
  ;; マウスでモードラインをいじれないようにする does not work
;;   (let (mode-line-in-global-map cdr-mode-line-in-global-map)
;;     (if (setq mode-line-in-global-map (assoc 'mode-line global-map))
;;         (if (setq cdr-mode-line-in-global-map (cdr mode-line-in-global-map))
;;             (setcdr cdr-mode-line-in-global-map nil))))
  ;; mode-line に、position を表す、--% を表示しない
  (let ((help-echo
         "mouse-1: select (drag to resize), mouse-2: delete others, mouse-3: delete this"))
    (setq mode-line-position
          `((size-indication-mode
             (8 ,(propertize " of %I" 'help-echo help-echo)))
            (line-number-mode
             ((column-number-mode
               (10 ,(propertize " (%l,%c)" 'help-echo help-echo))
               (6 ,(propertize " L%l" 'help-echo help-echo))))
             ((column-number-mode
               (5 ,(propertize " C%c" 'help-echo help-echo))))))))
  ;; foreとbackとカーソルのカラー ; resourcesでも設定可能
  ;; window-system の時のみ指定する。そうでないと、
  ;; -nw の時に、white がグレーになる。理由はおってないので、不明。
  (setq default-frame-alist
        (append '((left-fringe . 0)
                  (right-fringe . 0))
                default-frame-alist
                '((foreground-color . "white")
                  ;;(background-color . "#111111")
                  (background-color . "#000000")
                  (mouse-color . "white")
                  ;;(border-color . "white")
                  ;;(scroll-bar-width . 10)
                  (cursor-color . "yellow"))))
  (setq initial-frame-alist default-frame-alist)
  (setq frame-title-format "%b")
  ;; scroll-bar
  ;;(set-face-background 'scroll-bar "LightGoldenrod4")
  (set-face-foreground 'scroll-bar "dark orange")
  ;;(set-scroll-bar-mode 'right)
  ;; fringe
  (set-face-background 'fringe "gray15")
  (set-face-foreground 'fringe "yellow")
  ;; tooltip
  (set-face-foreground 'tooltip "orange")
  (set-face-background 'tooltip "black")
  ;; modeline
  (set-face-attribute 'mode-line nil
                      :background "AntiqueWhite1"
                      :foreground "red4"
;;                       :weight 'bold
                      :box '(:line-width -1 :color "white")
                      )
  (when (facep 'mode-line-inactive)
    (set-face-attribute 'modeline-inactive nil
                        :inherit 'mode-line
                        :background "grey10"
                        :foreground "grey30"
                        :box '(:line-width -1 :color "grey")
                        )))

;; dired-mode
(defun dired-up-directory-after-kill ()
  "Call 'dired-up-directory' after calling '(kill-buffer (current-buffer))'."
  (interactive)
  (let ((buf (current-buffer)))
    (dired-up-directory)
    (kill-buffer buf)))
(defun dired-advertised-find-file-after-kill ()
  "Call 'dired-advertised-find-file' after calling '(kill-buffer (current-buffer))'."
  (interactive)
  (let ((buf (current-buffer)))
    (dired-advertised-find-file)
    (kill-buffer buf)))
(add-hook 'dired-load-hook
          (require 'dired-x)
          )
(defun my-dired-mode-hook-fun ()
  (setq
   ;; C-x C-j に dired-jump を割当てる。 dired-jump は、current buffer を dired で開く。
   dired-bind-jump nil
   dired-bind-man nil
   dired-bind-info nil
   dired-guess-shell-alist-user
   (remq nil 
         (list
          (if (eq window-system 'mac) 
              (list "\\.\\(pdf\\|jpg\\|tiff\\|html\\|htm\\|eps\\)$" "open"))
          (list "\\.tex$" "latex" "platex")
          (list "\\.dvi$" "xdvi -display :0.0 ? &" "dvips" "dvipdfmx")
          (list "\\.ps$" "open" "ps2pdf" "lpr")
          ))
   dired-recursive-copies 'ask
   dired-recursive-deletes 'ask
   dired-listing-switches "-alh"
   )
  (set-face-foreground 'dired-marked "GreenYellow")
  (define-key dired-mode-map "\M-o" nil) ;; load-hook では、駄目なことがある
  (define-key dired-mode-map "\M-^" 'dired-up-directory-after-kill)
  (define-key dired-mode-map "\M-\C-m" 'dired-advertised-find-file-after-kill)
  (define-key dired-mode-map "\C-co" 'dired-omit-mode)
  (if (my-locate-file ".tex" (pwd))
      (add-to-list 'dired-omit-extensions ".log")
    (setq dired-omit-extensions (remove ".log" dired-omit-extensions)))
  (dired-omit-mode 1) ;; dot file や、.o ファイル が省略される
  )
(defun my-locate-file (suffix dir)
  ;; return non-nil or nil
  (with-temp-buffer
    (goto-char (point-min))
    (call-process "ls" nil t t (expand-file-name dir))
    (goto-char (point-min))
    (search-forward-regexp (concat "^.*" suffix "$") (point-max) t)))

    

(add-hook 'dired-mode-hook
          'my-dired-mode-hook-fun)


;; font-lock mode カラーモード
(require 'font-lock)
(global-font-lock-mode 1)
(add-hook 'font-lock-mode-hook 
          '(lambda ()
             (set-face-foreground 'font-lock-builtin-face "violet")
             (set-face-foreground 'font-lock-comment-face "#ff2222")
             (set-face-foreground 'font-lock-string-face  "sandy brown")
             (set-face-foreground 'font-lock-keyword-face "skyblue")
             (set-face-foreground 'font-lock-constant-face "dark orange")
             (set-face-foreground 'font-lock-function-name-face "skyblue")
             (set-face-foreground 'font-lock-variable-name-face "dark orange")
             (set-face-foreground 'font-lock-type-face "LightSeaGreen")
             (set-face-foreground 'font-lock-warning-face "skyblue")
             (set-face-bold-p 'font-lock-function-name-face t)
             (set-face-bold-p 'font-lock-warning-face nil)
             ))

;; show-paren-mode
(add-hook 'show-paren-mode-hook
          (lambda ()
            (set-face-background 'show-paren-match-face "DarkGoldenrod4")))
(add-hook 'find-file-hooks
          (lambda ()
            (show-paren-mode t))); 起動の時間を軽減

;; abbrev
(setq abbrev-file-name "~/ucvs/etc/abbrev_defs"
      save-abbrevs t)
(quietly-read-abbrev-file)

;; カーソルの点滅をやめる
(blink-cursor-mode 0)

;; メニューバーを表示しない ; Xdefaultsでも設定してある。
(menu-bar-mode 0) ; -nw の時のために設定

;; ツールバーを表示しない
;; (tool-bar-mode 0) ;; リソースで対応すると、フレームの高さが上下しないでよい。

;; 行をハイライト
(if window-system
    (progn
      (require 'highline)
      (highline-mode)
      (setq highline-face '((t (:background "#222222"))))
      ))

;; インデント関係
;; (setq standard-indent 4) ; default は 4
(add-hook 'find-file-hooks 
          (lambda () 
            ;; indent-tabs-mode は buffer local
            (if (or (memq major-mode '(change-log-mode))
                    (string-match "^makefile.*mode$" (prin1-to-string major-mode)))
                (setq indent-tabs-mode t)
              (setq indent-tabs-mode nil)) ; tab の代わりに space を使用
            ;;(setq tab-width 4)
            ))

;; 選択範囲について
;; 
;; macのような範囲選択のキーバインドを実現する
;; transient と、delete-selection も設定する
;;(pc-selection-mode)
;; 選択範囲に色を付ける
(set-face-background 'region "RoyalBlue4")
(transient-mark-mode 1)
;; ハイライトされていなくても、選択範囲が存在する
(setq mark-even-if-inactive t)
;; ペーストする時に選択範囲があれば、それを上書き
;;(delete-selection-mode 1)

;;;
;;; Wo-Man; M-x woman
;;; うまく動かない。Mac OS X 10.3.7 + Emacs 21.3.50 2004-11-17
;; (setq woman-use-own-frame nil)
;; (setq woman-cache-filename "~/.woman.cache")

;;;
;;; diff-mode
;;;
(eval-when-compile
  (load "diff-mode"))
(add-hook 'diff-mode-hook
          (lambda ()
            (define-key diff-mode-map "\M-o" nil)))

;;;
;;; byte-compile
;;;
(eval-after-load "bytecomp"
  '(lambda ()
     ;; byte-compile で、warning する項目
     ;; default -> t -> all
     ;; key: redefine callargs free-vars unresolved obsolete noruntime
     ;;      cl-functions interactive-only
     (setq byte-compile-warnings '(redefine callargs free-vars unresolved 
                                            obsolete cl-functions))))

;;;
;;; make-file-mode
;;;
(add-hook 'makefile-mode-hook
          '(lambda ()
             (define-key makefile-mode-map "\C-c\C-u" 'uncomment-region)))

;;; -------------------------------ここから-------------------------------
;;; 外部 elisp ライブラリ
;;;


;;; sesion.el
(require 'session)
(add-hook 'after-init-hook 'session-initialize)

;;; redo
(require 'redo)
(define-key global-map "\C-\M-_" 'redo)
;; C-x ESC ESC は、コマンドの redo。ちなみに、redo 中に M-n, M-p で履歴
;; を移動可能。


;;;
;:; 自作の小物
;;;
(autoload 'open "my_lisp_lazy-loads" "open a file with OSX native app" t)


;;; 物理行移動
(autoload 'physical-line-mode "physical-line" "" t)
;(add-hook 'find-file-hooks 'physical-line-mode )


;;; gnuplot
(autoload 'gnuplot-mode "gnuplot" "" t)

;; eijiro @ alc
(autoload 'ejr "my_lisp_lazy-loads" "C-u M-x w3m-search ejr" t)

;;;
;;; lookup.el
;;;
;; (autoload 'lookup "lookup" nil t)
;; (autoload 'lookup-region "lookup" nil t)
;; (autoload 'lookup-pattern "lookup" nil t)
;; (setq lookup-search-agents
;; ;;       '((ndtp "localhost" :appendix "/usr/local/share/dict/appendix/chujiten")
;;       '((ndtp "localhost")
;;         (ndspell)
;;         )
;;       lookup-use-bitmap nil; # default t
;;       )

;; (autoload 'lookup-entry-search-pattern "lookup-entry" nil t)
;; 最初に M-x lookup する必要がある。理由はおいかけてないので、不明。
;; おそらく、辞書の選択等の設定が必要ということ。
;; (global-set-key "\C-ql" 'lookup-entry-search-pattern)


;;;
;;; windows.elカスタム
;;;
(eval-when-compile
  (require 'windows))
;; windowsのプレフィックスを変更; 順序が重要
(defvar win:switch-prefix "\C-q\C-w")
(require 'windows)
(define-key global-map win:switch-prefix win:switch-map)
(define-key global-map "\C-xc" 'see-you-again)
(win:startup-with-window)
;; ウィンドウの切替に frame を使わない
(setq win:use-frame nil)
;; 新規ウィンドウの位置を(0, 0)に
;(setq win:new-frame-offset-x 0)
;(setq win:new-frame-offset-y 0)
;; (defun my-init-windows ()
;;   (require 'windows)
;;   (define-key global-map win:switch-prefix win:switch-map)
;;   (define-key global-map "\C-xc" 'see-you-again)
;;   (setq win:use-frame nil)
;;   (win:startup-with-window)
;;   ;; ウィンドウの切替に frame を使わない
;;   (win:switch-window 1 t t);; 一旦、[1]に移動
;;   )

;; C-q C-s で、ウィンドウを保存 == C-q C-w C-r s
(global-set-key "\C-q\C-s"
                (lambda ()
                  (interactive)
;;                   (my-init-windows)
                  (win:save-window win:current-config)))
;; C-q C-r で、ウィンドウをリジューム
(global-set-key "\C-q\C-r"
                (lambda ()
                  (interactive)
;;                   (my-init-windows)
                  (win-resume-menu)))

;; (defadvice win:update-mode-line (after make-color activate)
;;   (put-text-property 1 (- (length win:mode-string) 1)
;;                   'face '(:foreground "red3" :weight bold)
;;                   win:mode-string))



;;; emacs-wget
(eval-when-compile
  ;;(require 'w3m)
  (require 'wget))
(autoload 'wget "wget" "wget interface for Emacs." t)
(autoload 'wget-web-page "wget" "wget interface to download whole web page." t)
(add-hook 'wget-load-hook
          (lambda ()
            (load "w3m-wget")
            (setq wget-basic-options '("-v"))))
(add-hook 'w3m-mode-hook
          (lambda ()
            (load "w3m-wget")))

;;; tramp
;;;
;;; syntax: /sato:.emacs
;;;
;; tramp は、find-file の時に、syntax が tarmp ならば、auto-load される。
;(require 'tramp)
(setq tramp-default-method "sshx"
      tramp-verbose 5)
;; (defun tramp ()
;;   (interactive)
;;   (require 'tramp))

;;;
;;; minibuf-isearch
;;;
;; mini-buffer内で tcsh のように、C-rで履歴のインクリメンタルサーチ
;; (add-hook 'minibuffer-setup-hook
;;           (lambda ()
;;             (require 'minibuf-isearch))) ; 結局、起動時に読まれる
(require 'minibuf-isearch)
(setq minibuf-isearch-use-migemo nil
      minibuf-isearch-treat-filecache nil)

;; (add-hook 'minibuf-isearch-mode-hook
;;           (lambda () (require 'filecache)))

;; ;;;
;; ;;; filecache
;; ;;;
;; (setq file-cache t)
;; (file-cache-add-directory-recursively "~/Documents") ;; this takes long time
;; (file-cache-add-directory-recursively "~/work") ;; this takes long time as well


;;;
;;; viper ; session.el の後に読まないと session が効かなくなるようだ
;;;
(setq viper-custom-file-name "~/lisp/my_lisp_viper-custom.el"
      viper-ESC-key "\e"
      viper-mode t)
(require 'viper)
(when (facep 'viper-minibuffer-emacs)
  (set-face-foreground 'viper-minibuffer-emacs "white")
  (set-face-background 'viper-minibuffer-emacs "black"))
(setq viper-emacs-state-mode-list (append viper-emacs-state-mode-list
                                          '(occur-mode
                                            todo-mode
                                            shell-mode
                                            term-mode
                                            wl-folder-mode
                                            wl-summary-mode
                                            wl-template-mode
                                            ))
      viper-vi-state-mode-list (append viper-vi-state-mode-list
                                       '(wl-draft-mode
                                         apropos-mode
                                         )))
(define-key viper-insert-basic-map "\C-d" 'delete-char)
(add-hook 'viper-vi-state-hook
          '(lambda ()
             ;; vi-state でカーソルの色を変える。
             ;; この変数は内部変数なので、ただ setq しても駄目
             (setq viper-vi-state-cursor-color "dark orange")
             ))
(add-hook 'viper-emacs-state-hook
          '(lambda ()
             ;; vi-state でカーソルの色を変える。
             ;; この変数は内部変数なので、ただ setq しても駄目
             (set-cursor-color "yellow")
             ))

;; viper を読んだ後に、minor-mode の keymap を define するものは、
;; harness を設定しないと、define がうまくいかない。
(viper-harness-minor-mode "mime-edit")
(viper-harness-minor-mode "abbrev")


;;;
;;; iswitchb
;;;
(iswitchb-mode 1)
(iswitchb-default-keybindings)
(setq iswitchb-default-method 'samewindow)

;; mouse-avoidance-mode
;(require 'avoid)
;(mouse-avoidance-mode `banish) ;マウスをフレームの右端に移動させる
;(mouse-avoidance-mode `exile)

;;; ruby-mode
(eval-when-compile (require 'ruby-mode))
(autoload 'ruby-mode "ruby-mode"
  "Mode for editing ruby source files" t)
(setq auto-mode-alist
      (append '(("\\.rb$" . ruby-mode)) auto-mode-alist))
(add-hook 'ruby-mode-hook
          (lambda ()
            ;; spell-checking for comments
            (flyspell-prog-mode)
            (define-key ruby-mode-map "\C-c\C-c" 'comment-region)
            (define-key ruby-mode-map "\C-c\C-u" 'uncomment-region)))

;;; mmm-mode
(require 'mmm-auto)
(setq mmm-global-mode 'maybe)
;; (set-face-background 'mmm-default-submode-face "gray10")
(set-face-background 'mmm-default-submode-face nil) ;背景色を付けない
(mmm-add-classes
 '((embedded-css
    :submode css-mode
    :front-offset 2
    :front "<style\[^>\]*>"
    :back "</style>")))
(mmm-add-classes
 '((embedded-js
    :submode javascript-mode
    :front-offset 0
    :front "<script\[^>\]*>"
    :back "</script>")))
(mmm-add-mode-ext-class nil "\\.html\\'" 'embedded-css)
(mmm-add-mode-ext-class nil "\\.xml\\'" 'embedded-css)
(mmm-add-mode-ext-class nil "\\.html\\'" 'embedded-js)
(mmm-add-mode-ext-class nil "\\.xml\\'" 'embedded-js)

;;; javascript-mode
(add-to-list 'auto-mode-alist '("\\.js\\'" . javascript-mode))
(autoload 'javascript-mode "javascript" nil t)
(setq javascript-indent-level 2
      javascript-auto-indent-flag nil)
(add-hook 'javascript-mode-hook
          (lambda ()
            ;; spell-checking for comments
            (flyspell-prog-mode)
            (define-key javascript-mode-map "\C-c\C-c" 'comment-region)
            (define-key javascript-mode-map "\C-c\C-u" 'uncomment-region)))

;;; css-mode
(add-to-list 'auto-mode-alist '("\\.css\\'" . css-mode))
(autoload 'css-mode "css-mode" nil t)
(add-hook 'css-mode-hook
          (lambda ()
            ;; spell-checking for comments
            (flyspell-prog-mode)
            (define-key css-mode-map "\C-c\C-c" 'comment-region)
            (define-key css-mode-map "\C-c\C-u" 'uncomment-region)))

;;; time-stamp
;;;
(eval-when-compile (require 'time-stamp))
(setq time-stamp-active nil
      ;; Last Update, 最終更新日 -> st-lab
      ;; last update -> nifty + st-lab/kurihara
      time-stamp-start "\\(last update : Nov. 27, 2007\\|Last Update: \\|最終更新日: \\)"
      time-stamp-line-limit 10000
      time-stamp-format "%3b. %02d, %04y"
      time-stamp-end "\\(</\\|\n\\)"
      ;; time-stamp は、system-time-locale の影響を受ける
      system-time-locale "C") 

;;; html-mode
;;;
(add-hook 'html-mode-hook
          '(lambda ()
             (flyspell-mode)
             (define-key html-mode-map "\C-c\C-c" 'comment-region)
             (define-key html-mode-map "\C-c\C-u" 'uncomment-region)
             (make-variable-buffer-local 'time-stamp-active)
             (setq time-stamp-active t)))
(add-hook 'write-file-hooks
          (lambda () (if (eq major-mode 'html-mode) (time-stamp))))


;;; html-mode
;;;
(add-hook 'sgml-mode-hook
          '(lambda ()
             (flyspell-mode)
             (define-key sgml-mode-map "\C-c\C-c" 'comment-region)
             (define-key sgml-mode-map "\C-c\C-u" 'uncomment-region)
             ))


;;; sh-mode ; shell-script-mode
;;;
(add-hook 'sh-mode-hook
          '(lambda ()
             ;; spell-checking for comments
             (flyspell-prog-mode)
             (define-key sh-mode-map "\C-c\C-c" 'comment-region)
             (define-key sh-mode-map "\C-c\C-u" 'uncomment-region)))

;; (add-hook 'after-save-hook
;;          '(lambda ()
;;             (if (and (eq major-mode 'sh-mode)
;;                      (string-match "zshrc" (buffer-file-name)))
;;                 (if (not (eq (call-process-shell-command "zcompile"  ; command
;;                                                          nil         ; input file
;;                                                          "*zcompile*"; output buffer
;;                                                          nil         ; redisplay the output buffer
;;                                                          (buffer-file-name) ; arguments...
;;                                                          )
;;                              0))
;;                     (message "Failed in compiling zshrc")))))

;;; shell-mode
(autoload 'shell-new "my_lisp_shell")
(eval-after-load "shell"
  '(require 'my_lisp_shell))

(autoload 'todo "my_lisp_lazy-loads" "todo" t)

;;; change-log
;; (setq change-log-default-name "~/ChangeLog")

;;; emacs-lisp-mode
(add-hook 'emacs-lisp-mode-hook
          '(lambda ()
             (require 'my_lisp_elisp)
             ;; spell-checking for comments
             (unless (eq major-mode 'lisp-interaction-mode)
               (flyspell-prog-mode))
             ))

;;; cc-mode
(eval-when-compile
  (require 'my_lisp_cc-mode))
(autoload 'my-c-mode-common-hook "my_lisp_cc-mode")
(add-hook 'c-mode-common-hook
          (lambda ()
            (my-c-mode-common-hook)
            ))

;;; Mew
;; (setq mew-rc-file "my_lisp_mew")
;; (autoload 'mew "mew" nil t)
;; (autoload 'mew-send "mew" nil t)

;; ;; Optional setup (Read Mail menu for Emacs 21):
;; (if (boundp 'read-mail-command)
;;     (setq read-mail-command 'mew))

;; ;; Optional setup (e.g. C-xm for sending a message):
;; (autoload 'mew-user-agent-compose "mew" nil t)
;; (if (boundp 'mail-user-agent)
;;     (setq mail-user-agent 'mew-user-agent))
;; (if (fboundp 'define-mail-user-agent)
;;     (define-mail-user-agent
;;       'mew-user-agent
;;       'mew-user-agent-compose
;;       'mew-draft-send-message
;;       'mew-draft-kill
;;       'mew-send-hook))

;;; Wanderlust
;;;
;; autoload
(autoload 'wl "wl" "Wanderlust" t)
(autoload 'wl-draft "wl-draft" "Write draft with Wanderlust." t)
;; wanderlust を emacs の標準 mail-user-agent として設定する
(autoload 'wl-user-agent-compose "wl-draft" nil t)
(define-mail-user-agent
  'wl-user-agent
  'wl-user-agent-compose
  'wl-draft-send
  'wl-draft-kill
  'mail-send-hook)
(setq mail-user-agent 'wl-user-agent
      ;; icon, addresses は init-hook 以前に設定しなければいけない
      wl-icon-directory "~/ucvs/share/emacs/21.3/etc/wl"
      wl-address-file "~/lisp/addresses"
      ;; folders に、shimbun が含まれていると、w3m もロードされる。
      wl-folders-file "~/lisp/folders"
      wl-init-file "my_lisp_wl")

;;; skk.el
;;;
(eval-when-compile
  (require 'skk-autoloads)
  (require 'skk)
  (require 'my_lisp_skk))
; 基本的な設定を自動でしてくれる
; (require 'skk-setup)

;; wanderlust の起動後に skk を起動すると、free variable だと
;; 怒られるのを回避
(defvar skk-isearch-switch nil)

;; 基本の設定
(global-set-key "\C-x\C-j" 
                (lambda ()
                  (interactive)
                  (require 'skk-autoloads)
                  (skk-mode)))
(setq skk-init-file "my_lisp_skk")

;;; sdic-mode 用の設定
;;; sdic:和訳、日本語訳辞書
;;;
;; 読み込み
(autoload 'sdic-describe-word "sdic" "英単語の意味を調べる" t nil)
(autoload 'sdic-describe-word-at-point "sdic" 
  "カーソルの位置の英単語の意味を調べる" t nil)

;; キーバインド
(global-set-key "\C-qw" 'sdic-describe-word)
;(global-set-key "\C-qW" 'sdic-describe-word-at-point)
(eval-after-load "sdic"
  '(load "my_lisp_sdic"))

;;;
;;; word-count-mode
;;;
(autoload 'word-count-mode "word-count"
          "Minor mode to count words." t nil)
(global-set-key "\M-+" 'word-count-mode)

;;;
;;; term-mode
;;;
(eval-when-compile
  (require 'my_lisp_term))
(autoload 'my-term-advice "my_lisp_term")
(autoload 'my-term-init "my_lisp_term")
(autoload 'my-term-eval-after-load "my_lisp_term")
(eval-after-load "term" '(my-term-eval-after-load))
(add-hook 'term-load-hook
          (lambda ()
            (my-term-init)))
(defadvice term (after my-term-init activate)
  (my-term-advice))
(global-set-key "\C-q\C-t" 'term)

;;; my_lisp_w3m.el
;;;
;; (eval-when-compile
;;   (require 'w3m)
;;   (load "my_lisp_w3m"))
;;; 読み込み
(autoload 'w3m "w3m" "Interface for w3m on Emacs." t)
(autoload 'w3m-find-file "w3m" "w3m interface function for local file." t)
(autoload 'w3m-browse-url "w3m" "Ask a WWW browser to show a URL." t)
(autoload 'w3m-search "w3m-search" "Search QUERY using SEARCH-ENGINE." t)
(autoload 'w3m-namazu "w3m-namazu" "Search indexed files with Namazu." t)
;(autoload 'w3m-weather "w3m-weather" "Display weather report." t)
;(autoload 'w3m-antenna "w3m-antenna" "Report chenge of WEB sites." t)

;;; add-hook
(eval-after-load "w3m"
  '(require 'my_lisp_w3m))

;;; octet
(autoload 'octet-find-file "octet" "open octet files" t)
(eval-after-load "octet"
  '(progn
     (require 'w3m)
     (setq octet-suffix-type-alist (append '(("rtf" . rtf))
                                           octet-suffix-type-alist)
           ;;octet-type-filter-alist (append '((rtf octet-filter-call1
           ;;"unrtf" ("--text") text))
           octet-type-filter-alist (append '((rtf octet-filter-call1
                                                  "unrtf"  () html-u8))
                                           octet-type-filter-alist)
           )))

;;; navi2ch
;;;
;; (eval-when-compile
;;   (require 'navi2ch)
;;   (load "my_lisp_navi2ch"))
;; (autoload 'navi2ch "navi2ch" "navi2ch" t)
;; (add-hook 'navi2ch-before-startup-hook 
;;        (lambda ()
;;          (load "my_lisp_navi2ch")
;;          (my-navi2ch-hook)))

;;; tex-mode
(eval-when-compile (require 'tex-mode))
(add-hook 'tex-mode-hook
          (lambda ()
            (flyspell-mode)
            ;; emacs-21.4 以降で仕様される、tex-mode の上付きや下付きを
            ;; 抑制
            (setq font-lock-maximum-decoration 
                  '((tex-mode . 2) (latex-mode . 2) (t . t)))
            ;; keybind
            (define-key tex-mode-map "\C-cc" 'compile)
            (define-key tex-mode-map "\C-c\C-j" 'xdvi-jump-to-line)
            (define-key tex-mode-map "\C-c\C-c" 'comment-region)
            (define-key tex-mode-map "\C-c\C-u" 'uncomment-region)
            ;; 以下、TeX source special のための設定
            (require 'xdvi-search) ; 必須
            (setq xdvi-version-number 22040000)
            (when (eq window-system 'mac)
              (setq xdvi-display "-display :0.0"))
            (unless server-process
              (server-start)) ; emacsclient により xdvi -> Emacs
            ))

;;; prolog-mode
(eval-after-load "prolog"
  '(progn
     (define-key prolog-mode-map "\C-c\C-c" 'comment-region)
     (define-key prolog-mode-map "\C-c\C-u" 'uncomment-region)))

;;; htmlize
;;;
(eval-when-compile (require 'htmlize))
;; (setq htmlize-output-type 'font);; 'css is the default.
(setq htmlize-output-type 'css)
(autoload 'htmlize-buffer "htmlize" "make a html file from the buffer" t)

;;; psgml
;;;
;; (autoload 'sgml-mode "psgml" "Major mode to edit SGML files." t)
;; (setq auto-mode-alist
;;       (append (list (cons "\\.xml\\'" 'xml-mode))
;;               auto-mode-alist))
;; (autoload 'xml-mode "psgml" "Major mode to edit XML files." t)
;; ;; face を使用する; sgml-mode は、parse して、初めて色がつく。-> sgml-parse-prolog
;; (setq sgml-set-face t)
;; (setq sgml-markup-faces '((start-tag  . font-lock-keyword-face)
;;                           (end-tag    . font-lock-keyword-face)
;;                           (comment    . font-lock-comment-face)
;;                           (ignored    . font-lock-comment-face)
;;                           (pi         . font-lock-keyword-face)
;;                           (sgml       . font-lock-keyword-face)
;;                           (doctype    . font-lock-constant-face)
;;                           (entity     . font-lock-string-face)
;;                           (shortref   . bold)))
;; (add-hook 'sgml-mode-hook
;;           (lambda ()
;;             (setq ;;sgml-omittag t ;; タグの省略は有効
;;              ;;sgml-shorttag nil ;; タグの短縮は無効
;;              ;; タグを省略した場合に省略したタグが存在するものとして
;;              ;;タグの記述を可能にする
;;              ;;sgml-omittag-transparent t 
;;              ;;sgml-indent-step 2 ; default は 2
;;              ;;要素名は小文字
;;              ;;sgml-general-insert-case 'lower
;;              sgml-general-insert-case 'upper
;;              ;; インデントを行う
;;              sgml-indent-data 
;;              )))

;;;
;;; migemo
;;;
(when (locate-library "migemo")
  (setq migemo-directory "~/ucvs/share/migemo")
  (load "migemo")
;;   (migemo-init)
  ;;C-q m で migemo-toggle
  (autoload 'my-interactive-migemo-toggle "my_lisp_lazy-loads" "toggle migemo" t)
  (global-set-key "\C-qm" 'my-interactive-migemo-toggle)
  (setq
   ;; 正規表現のリストをキャッシュとして保存
   migemo-use-pattern-alist nil
   migemo-use-frequent-pattern-alist nil
   ;; リストの長さ。デフォルトは 512
   migemo-pattern-alist-length 1024
   ;; isearch を開始する長さ
   migemo-isearch-min-length 2)
  )

;;; matlab-mode
(autoload 'matlab-mode "matlab" "Enter Matlab mode." t)
(eval-after-load "matlab"
  '(progn
     (setq matlab-auto-fill nil
           matlab-indent-level 2
           )
     (define-key matlab-mode-map "\C-c\C-c" 'comment-region)
     (define-key matlab-mode-map "\C-c\C-u" 'uncomment-region)))
;; spell-checking for comments
(add-hook 'matlab-mode-hook 'flyspell-prog-mode)

;;;; YaTeX (野鳥)
;; yatex-mode を起動させる設定
;; (setq auto-mode-alist 
;;       (cons (cons "\\.tex$" 'yatex-mode) auto-mode-alist))
;; (autoload 'yatex-mode "yatex" "Yet Another LaTeX mode" t)

;; 文章作成時の漢字コードの設定
;; 1 = Shift_JIS, 2 = ISO-2022-JP, 3 = EUC-JP
;; default は 2
;; (setq YaTeX-kanji-code 3) ; euc-jp
;; (setq YaTeX-use-AMS-LaTeX t)
;; (add-hook 'yatex-mode-hook
;;        (lambda ()
;;          (define-key YaTeX-mode-map "\C-cc" 'compile)
;;          (define-key YaTeX-mode-map "\C-c\C-c" 'comment-region)
;;          (define-key YaTeX-mode-map "\C-c\C-u" 'uncomment-region)))