.emacs-my
author Oleksandr Gavenko <gavenkoa@gmail.com>
Mon, 14 Nov 2011 10:21:35 +0200
changeset 825 92790cbc5fd2
parent 824 0e9a1d493295
child 826 869bc1369aca
permissions -rw-r--r--
Set 'user-nick' if it was not defined in ~/.emacs-auth or somewhere.

;; -*- mode: emacs-lisp; coding: utf-8; fill-column: 78 -*-
;;
;; Written by Oleksandr Gavenko <gavenkoa@gmail.com>, 2008-2010.
;;
;; This file formed from parts and ideas from many sites/docs and
;; placed in public domain.
;;
;; Config file for GNU Emacs.
;;
;; For load order see README.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "recentf")

(setq recentf-save-file "~/.recentf")
(when (eq system-type 'cygwin)
  (setq recentf-save-file "~/.recentf-cygwin")
  )
(require 'recentf)
;; Prevent TRAMP to login on remote host when loading.
;; Its take time and ask passwords!
(setq recentf-auto-cleanup 'never)
(recentf-mode t)
(setq recentf-max-saved-items 1000)
(global-set-key (kbd "\e\eq")  'recentf-open-files)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "revert buffer")

(global-set-key [f5]    'revert-buffer)
(setq revert-without-query (quote (".*")))
(setq auto-revert-interval 2)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "debugging")

;; Shut off message buffer by setting nil.
(setq message-log-max 512)

;; Prevent Emacs from loading 'default.el', which loaded after '.emacs'.
;; Also '-q' prevent loading your init file.
(setq inhibit-default-init nil)         ; t/nil

(defun my-debug (mode)
  "With prefix enable debug backtrace when problems occur else disable."
  (interactive "P")
  (when mode
    ;; (setq debug-on-signal t)
    (setq mode t))
  (setq debug-on-error mode)
  ;; Get trace when press C-g.
  (setq debug-on-quit mode)
  )

(my-debug nil)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "user info")

;; Set following in ~/.emacs-auth:
;; (setq user-full-name "Oleksandr Gavenko")
;; (setq user-mail-address "gavenkoa@gmail.com")
;; (setq user-nick "gavenkoa")

(unless (and (boundp 'user-nick) (stringp user-nick))
  (setq user-nick (user-login-name)) )
(setenv "ORGANIZATION" (concat user-full-name " <" user-mail-address  ">"))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "my defun, defmacro, defvar")

(defmacro my-filter (condfunc list)
  "Construct list with elements from LIST which satisfy CONDFUNC."
  `(let (r)
     (mapc (lambda (item)
             (when (,condfunc item)
               (if r
                   (nconc r (cons item nil))
                 (setq r (cons item nil)))))
           ,list)
     r))

(defun my-fold (f x list)
  "Recursively applies (F i j) to LIST starting with X.
For example, (fold F X '(1 2 3)) computes (F (F (F X 1) 2) 3)."
  (let ((li list) (x2 x))
    (while li
      (setq x2 (funcall f x2 (pop li)))
      )
    x2
    ) )

(unless (fboundp 'ignore-errors)
  (defmacro ignore-errors (&rest body)
    "Execute BODY; if an error occurs, return nil.
Otherwise, return result of last form in BODY."
    (declare (debug t) (indent 0))
    `(condition-case nil (progn ,@body) (error nil)))
  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "mode groups")

(defmacro my-defun-rename-symb-tree (name doc func)
  "Travel by TREE and applies FUNC to each symbol."
  `(defun ,name (tree)
     ,doc
     (cond
      ((symbolp tree)
       (,func tree)
       )
      ((listp tree)
       (mapcar ',name tree)
       )
      (t (error "Only tree of symbols allowed."))
      )))

(my-defun-rename-symb-tree
 my-feature2mode
 "Convert TREE of features to TREE of modes for these features. Single symbol allowed."
 (lambda (symb) (intern (concat (symbol-name symb) "-mode"))))

(my-defun-rename-symb-tree
 my-mode2hook
 "Convert TREE of modes to TREE of hooks for these modes. Single symbol allowed."
 (lambda (symb) (intern (concat (symbol-name symb) "-hook")))
 )

(my-defun-rename-symb-tree
 my-mode2modemap
 "Convert TREE of modes to TREE of keymaps for these modes. Single symbol allowed."
 (lambda (symb) (intern (concat (symbol-name symb) "-map")))
 )

(defvar my-devel-mode-list
  '(
    sh-mode script-mode tcl-mode
    c-mode c++-mode java-mode js-mode
    python-mode
    lisp-mode
    emacs-lisp-mode
    makefile-mode makefile-gmake-mode
    nsis-mode
    bat-generic-mode
    html-mode
    LilyPond-mode
    )
  "List of development modes.")

(defvar my-devel-mode-hook-list
   (my-mode2hook my-devel-mode-list)
  "List of development mode hooks.")

(defvar my-scroll-margin-mode-list
  '(
    vc-dir-mode
    recentf-dialog-mode
    org-agenda-grid-mode           ; XXX for this item not worked!
    log-view-mode
    dired-mode
    compilation-mode
    )
  "List of modes for enabling scroll margin.")

(defvar my-scroll-margin-mode-hook-list
  (my-mode2hook my-scroll-margin-mode-list)
  "List of mode hooks for enabling scroll margin.")

(defvar my-text-mode-list
  '(
    text-mode
    outline-mode
    rst-mode
    diff-mode
    dict-c5-mode
    )
  "List of text modes.")

(defvar my-text-mode-hook-list
  (my-mode2hook my-text-mode-list)
  "List of text mode hooks.")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "appearance")

;; To maximize frame on full screen, not work with Windows Emacs 21.4.
;; And maked different height with Emacs 22.3 and 23.1.
;; (setq initial-frame-alist '((fullscreen . fullboth)))

(setq display-buffer-reuse-frames t)

;; Next code work with Emacs 21.4, 22.3, 23.1.
(when window-system
  (let (
        (px (display-pixel-width))
        (py (display-pixel-height))
        (fx (frame-char-width))
        (fy (frame-char-height))
        tx ty
        )
    ;; Next formulas discovered empiric on Windows host with default font.
    (setq tx (- (/ px fx) 7))
    (setq ty (- (/ py fy) 4))
    (setq initial-frame-alist '((top . 2) (left . 2)))
    (add-to-list 'initial-frame-alist (cons 'width tx))
    (add-to-list 'initial-frame-alist (cons 'height ty))
    ) )

(menu-bar-mode -1)
(when window-system
  (mouse-avoidance-mode 'animate)
  (scroll-bar-mode 1)
  (tool-bar-mode -1)
  (defun my-popup-menu ()
    (interactive)
    (mouse-popup-menubar
     (list (list (/ (display-pixel-width) 2) 10) (get-buffer-window (buffer-name)))
     nil)
    )
  (global-set-key [f10] 'my-popup-menu)
  (global-set-key [apps] 'my-popup-menu)
  (global-set-key [menu] 'my-popup-menu)
  (when (>= emacs-major-version 22) (tooltip-mode -1))
  )

;; Prefer horizontal windows splitting.
(when (>= emacs-major-version 23)
  (setq split-height-threshold nil)
  (setq split-width-threshold nil)
  )

(setq frame-title-format "EMACS: %b")

(setq default-header-line-format nil)
;; (setq default-mode-line-format nil)

(setq default-left-fringe-width nil)
(setq default-right-fringe-width nil)
(setq default-left-margin-width nil)
(setq default-right-margin-width nil)

(setq default-line-spacing nil)

(setq default-truncate-lines nil)

;; show column & line numbers in status bar
(setq column-number-mode t)
(setq line-number-mode t)
(setq size-indication-mode t)

;; Also useful such format: (setq display-time-format " %H:%M %d-%m-%y ")
(setq display-time-24hr-format t)
(setq display-time-day-and-date nil)
(setq display-time-default-load-average nil)
(display-time)                          ; display-time-mode

(when window-system
  (set-background-color "white")
  (set-foreground-color "black")
  (set-cursor-color "brown")
  ;; (set-mouse-color "white")
  (setq cursor-type 'box)           ; box, hollow, bar, hbar
  ;;(setq blink-matching-delay 0.01)
  (blink-cursor-mode 1)
  (setq use-file-dialog t)
  (setq use-dialog-box t)
  ;; (set-face-font 'default "7x14")
  )

;; See what I am typing immediately (for keystroke in minibuffer).
(setq echo-keystrokes 0.2)

(fset 'yes-or-no-p 'y-or-n-p)

(when (boundp 'confirm-kill-emacs)
  (setq confirm-kill-emacs 'y-or-n-p))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "silent runing")

;; (setq inhibit-splash-screen t) ; nonexist on 21.4.1
(setq inhibit-startup-message t)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "shell, bash, Cygwin, MSYS")

(defvar my-use-windows-shell nil
  "If t 'cmdproxy.exe' will be used as shell. Affect on M-x shell like
  commands. If nil, 'sh' will be used." )

(defun follow-cygwin-symlink ()
  "Follow new-style (and also UCS-16) Cygwin symlinks."
  (save-excursion
    (goto-char 0)
    (when (looking-at "!<symlink>\xff\xfe")
      (find-alternate-file
       (substring
        (decode-coding-string
         (buffer-substring (match-end 0) (point-max))
         'utf-16-le)
        0 -1)                           ; -1 for stripping final \0.
       ))))

(when (eq system-type 'windows-nt)
  (ignore-errors
    (require 'cygwin-mount)
    (cygwin-mount-activate)
    )
  (add-hook 'find-file-hook 'follow-cygwin-symlink)
  ;; Workaround for Cygwin shell, when set 'CYGWIN=noglob'. By default 'shell-quote-argument'
  ;; quoted by double '\' chars this cause failure.
  (defun shell-quote-argument (argument)
    (concat "'" argument "'")
    )
  ;; Workaround for Cygwin when 'shell-file-name' is 'bash'.
  (setq null-device "/dev/null")
  ;; Use shell from Cygwin/MinGW.
  (setq shell-file-name "bash")
  (setenv "SHELL" "/bin/bash")
  (modify-coding-system-alist 'process "bash" '(cp1251-unix . cp1251-unix))
  )

(when (eq window-system 'w32)
  ;; Fix 'starttls.el' on native Windows Emacs with gnutls-cli from Cygwin.
  ;; 'gnutls-cli' run with '-s' opt and process wait for SIGALRM.
  ;; But build-in native Emacs 'kill' command can not send such Cygwin
  ;; specific sygnal. So 'starttls-negotiate-gnutls' function infinitely
  ;; wait for 'gnutls-cli' output.
  (defadvice signal-process (around cygwin (process sigcode))
    "Use 'kill.exe' instead build-in Emacs 'kill'."
    (if (eq sigcode 'SIGALRM)
        (shell-command
         (format "kill.exe -s SIGALRM %d"
                 (if (processp process) (process-id process) process)))
      ad-do-it
      ))
  (ad-activate 'signal-process)
  (modify-coding-system-alist 'process "gnutls-cli" '(binary . binary))
  )

(ansi-color-for-comint-mode-on)

(setq explicit-bash-args '("-i"))
(setq explicit-sh-args '("-i"))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "whitespaces")

(setq default-indicate-empty-lines t)
(setq default-indicate-buffer-boundaries 'left)

;; (setq-default show-trailing-whitespace t)
(defun my-show-trailing-whitespace ()
  (setq show-trailing-whitespace t)
  )
(mapc (lambda (hook) (add-hook hook 'my-show-trailing-whitespace))
      (append my-devel-mode-hook-list my-text-mode-hook-list))

(setq next-line-add-newlines nil)

;; See also 'mode-require-final-newline'.
(add-hook 'text-mode-hook (lambda () (setq require-final-newline nil)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "server")

(when (and (>= emacs-major-version 22) (not (eq system-type 'cygwin)))
  (require 'server)
  (when (and (= emacs-major-version 23) (>= emacs-minor-version 1) (<= emacs-minor-version 2) (equal window-system 'w32))
    (defun server-ensure-safe-dir (dir) "Noop" t)) ; Suppress error directory ~/.emacs.d/server is unsafe on windows.
  (when (or (= emacs-major-version 22) (not (eq (server-running-p server-name) t)))
    (server-start))
  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "standart/general settings")

;; Try to speed things up, especially in VM.
(setq gc-cons-threshold 2000000)

;; Default 'command-history' length too short (in Emacs 23.2 is 30).
(setq history-length 200)

;; Don't beep in my headphones!
(setq ring-bell-function '(lambda () "Empty ring-bell-function." nil))
(setq visible-bell t) ; With default ring-bell-function in text terminal
                      ; revert screen if press [end] or [home]

;; Prompt before evaluating local bits of lisp.  This stops people
;; putting things at the end of files which delete all your files!
(setq enable-local-variables t
      enable-local-eval      1)

(setq kill-whole-line t)

(setq view-read-only t)

(setq read-quoted-char-radix 16)

(when (and (>= emacs-major-version 22) (not (eq system-type 'darwin)))
  (setq standard-display-table (make-display-table))
  (let ( (i ?\x80) hex hi low )
    (while (<= i ?\xff)
      (setq hex (format "%x" i))
      (setq hi (elt hex 0))
      (setq low (elt hex 1))
      (aset standard-display-table (unibyte-char-to-multibyte i)
            (vector (make-glyph-code ?\\ 'escape-glyph)
                    (make-glyph-code ?x 'escape-glyph)
                    (make-glyph-code hi 'escape-glyph)
                    (make-glyph-code low 'escape-glyph)))
      (setq i (+ i 1))))
  )

;; generic-define-* before (require 'generic-x) allow load all useful extra modes.
(setq generic-define-mswindows-modes t)
(setq generic-define-unix-modes t)
(require 'generic-x)

;; The following commands are usually disabled by default. Enable them...
(put 'eval-expression  'disabled nil)
(put 'downcase-region  'disabled nil)
(put 'upcase-region    'disabled nil)
(put 'narrow-to-page   'disabled nil)
(put 'narrow-to-region 'disabled nil)
(put 'scroll-left      'disabled nil)

(setq
 use-dialog-box t
 x-gtk-show-hidden-files t
 )

(defun my-prevent-kill-buffer ()
  (if (equal (buffer-name) "*scratch*") nil t))
(add-to-list 'kill-buffer-query-functions 'my-prevent-kill-buffer)

(define-key global-map "\C-ct" (lambda nil (interactive) (switch-to-buffer "*scratch*")))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "switching, creating, selecting buffers")

(iswitchb-mode 1)
(setq iswitchb-buffer-ignore
      '("^ "
        "^\*Buffer"
        "^\*Completions\*"
        "^\*tramp"
        "^\*Dired log\*"
        "^\*Quail Completions\*"
        "^\*Disabled Command\*"
        "^TAGS"
        ))

(require 'uniquify)
(setq uniquify-buffer-name-style 'post-forward)
(setq uniquify-separator "|")
(setq uniquify-after-kill-buffer-p t)

;; buffer-menu better then buffer-list, but ibuffer much better.
(global-set-key "\C-x\C-b" 'ibuffer)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "scrolling")

(defvar my-scroll-margin 4)

(setq-default
 ;; Set to zero as this recomment documentation.
 scroll-step 0
 ;; If the value is greater than 100, redisplay will never recenter point, but
 ;; will always scroll just enough text to bring point into view
 scroll-conservatively 1000
 scroll-preserve-screen-position t
 )

;; Set margin only for desired modes! Do not frustrate calendar any more.
(make-variable-buffer-local 'scroll-margin)
(mapc (lambda (hook) (add-hook hook (lambda nil (setq scroll-margin my-scroll-margin))))
      ;; TODO its good invoke delete-dups for list, but delete-dups not exist in Emacs 21.4
      (append my-text-mode-hook-list my-devel-mode-hook-list my-scroll-margin-mode-hook-list) )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "chars, unicode")

(defun my-print-unicode (&optional start end)
  "Print UNICODE table."
  (interactive "nstart: \nnend: ")
  (switch-to-buffer (get-buffer-create "*UNICODE*"))
  (erase-buffer)
  (let ( (i start) )
    (while (<= i end)
      (insert (format "%s: U+%04x, %s\n" (char-to-string i) i (get-char-code-property i 'name)))
      (setq i (1+ i))
      )))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "search, isearch, occur")

(setq case-fold-search t)

(setq query-replace-highlight t)        ; highlight during query
(setq search-highlight t)               ; highlight incremental search

;; Make old Emacs key binding like in Emacs 23.x.
(when (< emacs-major-version 23)
  (global-set-key (kbd "M-s o") 'occur)
  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "grep, find")

;; -ls produce very noisy output:
;; (setq find-ls-option '("-ls" . ""))
;; So I use next expression, which work with GNU find, I replace %s with '0'
;; to avoid unnecessary sys calls and this make output aligned by column:
(setq find-ls-option '("-printf ' -rw-rw-rw- 0 %AY-%Am-%Ad %AH:%AM %p\n'" . ""))

;; Do not set t because some grep do not has --color options.
(setq grep-highlight-matches nil)
(setq grep-use-null-device nil)

(eval-after-load 'grep
  '(progn
     (add-to-list 'grep-find-ignored-directories "build" t)
     (add-to-list 'grep-find-ignored-directories "dist" t)
     (add-to-list 'grep-find-ignored-directories "lib" t)
     (add-to-list 'grep-find-ignored-directories "_build" t)
     (add-to-list 'grep-find-ignored-directories "_dist" t)
     (add-to-list 'grep-find-ignored-directories "_lib" t)

     (when (boundp 'grep-find-ignored-files)
       (add-to-list 'grep-find-ignored-files "*TAGS")
       (add-to-list 'grep-find-ignored-files "GPATH")
       )
     ))
(global-set-key [f7] 'rgrep)
(global-set-key [M-f7] 'rgrep)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "syntax highlighting")

(setq font-lock-maximum-decoration t)
(global-font-lock-mode 1)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "highlight selected text")

(delete-selection-mode 1)

(when (<= emacs-major-version 23)
  ;; 1/-1, when the mark is active, the region is highlighted.
  (transient-mark-mode 1)

  ;; Order of next items is important, (assignment must done before pc-selection-mode enabled).
  (require 'pc-select)
  (setq pc-select-selection-keys-only t)  ; To avoid some key bindings as F6, etc.
  (setq pc-select-meta-moves-sexps t)
  (cond
   ((= emacs-major-version 21) (pc-selection-mode))
   ((>= emacs-major-version 22) (pc-selection-mode 1))
   )
  )

(when (eq window-system 'x)
  (setq x-select-enable-clipboard t)    ; for Emacs 21.2.1 and newer
  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "highlighting current line")

(when window-system
  (custom-set-faces '(hl-line ((t (:inherit highlight :background "light yellow")))))
  (global-hl-line-mode 1)
  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "paren, braces")

(show-paren-mode 1) ; Parenthesis matching via highlighting.
(setq show-paren-style (quote parenthesis))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "keyboard, mouse")

;; cyrillic-jis-russian  for 567 is :,.
;; cyrillic-jcuken  for SHIFT 567 is :,.
;; russian-computer for SHIFT 567 is %^&
(if (>= emacs-major-version 22)
    (setq default-input-method 'russian-computer)
  (setq default-input-method 'cyrillic-jcuken))
;; (pc-bindings-mode) ; Myself define keybinding, see

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "completion")

;; I remove partial-completion-mode because it depricated in Emacs 24.0.
;; Completion controled by 'completion-styles' variable.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "mouse")

;; Scroll Bar gets dragged by mouse butn 1
(global-set-key [vertical-scroll-bar down-mouse-1] 'scroll-bar-drag)
;; Paste at point NOT at cursor
(setq mouse-yank-at-point t)
(when window-system
  (mouse-wheel-mode 1)
  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "key binding, short-keys")

(global-set-key [home]    'beginning-of-line)
(global-set-key [end]     'end-of-line)
(global-set-key [C-home] 'beginning-of-buffer)
(global-set-key [C-end]  'end-of-buffer)
(global-set-key [C-delete]  'kill-word)
(global-set-key [delete]     'delete-char)
;; (global-set-key [backspace]  'backward-delete-char-untabify) ; not work properly in *info* mode

;; setting some f[1-12] keys
(global-set-key [f1]    'help)
(global-set-key [f2]    'save-buffer)
;; (global-set-key [xxx]    'ediff-buffers)
(global-set-key [f4]    'ispell-buffer)
(global-set-key [S-f6]  'rename-buffer)
(global-set-key [f8]    'kill-this-buffer)
(global-set-key (kbd "C-x C-k") 'kill-this-buffer)
(global-set-key [M-f4]  'save-buffers-kill-emacs)
(global-set-key [f6]    'toggle-truncate-lines)

;; frames, windows manipulation, switch buffers
(global-set-key [?\C-x right] 'next-buffer)
(global-set-key [?\C-x left]  'previous-buffer)

(global-set-key (kbd "\e\eg") 'goto-line)
(global-set-key (kbd "\e\er") 'query-replace-regexp)

;; Disable suspend. It ugly.
(when window-system
  (global-set-key (kbd "C-z") nil))
(global-set-key (kbd "C-x C-z") nil)

;; (global-set-key [language-change] 'ignore)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "coding system, charset, locale, lang")

;; Emacs 23.1 no longer need codepage-setup.
(when (<= emacs-major-version 22)
  (codepage-setup 866)
  (codepage-setup 1251)
  )

;; Comment because prefer-coding-system will be ignored.
;; (setq-default coding-system-for-read  'cp1251-dos)
;; (setq-default coding-system-for-write 'cp1251-dos)

;; (setq locale-coding-system  'cp1251-dos)
;; (set-language-environment 'UTF-8)
;; (set-terminal-coding-system 'cp1251)
;; (set-keyboard-coding-system 'cp1251)

(modify-coding-system-alist 'file "\\.el" 'iso-2022-7bit)
(cond
 ((equal window-system 'w32)          ; also (string-equal system-type "windows-nt")
  (set-selection-coding-system 'utf-16-le-dos)
  (setq-default buffer-file-coding-system 'cp1251)
  (setq default-file-name-coding-system 'cp1251)
  (setq default-process-coding-system '(cp1251 . cp1251))
  )
 ((equal window-system 'x)
  (prefer-coding-system 'utf-8-unix)
  (setq selection-coding-system 'compound-text-with-extensions)
  (setq x-select-request-type '(UTF8_STRING COMPOUND_TEXT TEXT STRING))
  (modify-coding-system-alist 'process ".*" 'utf-8-unix)
  )
 ((eq system-type 'cygwin)
  (when (string-match "1251\\'" (getenv "LANG"))
    (prefer-coding-system 'cp1251-unix)
    (prefer-coding-system 'utf-8-unix)
    (modify-coding-system-alist 'process ".*" 'cp1251-unix)
    )
  )
 ((eq system-type 'darwin)
  nil
  )
 (t
  (prefer-coding-system 'cp1251-dos)
  (prefer-coding-system 'utf-8-unix)
  (modify-coding-system-alist 'process ".*" 'utf-8-unix)
  )
 )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "open file, ffap, dired")

(setq-default save-place t)
(require 'saveplace)

(require 'dired)

(require 'ffap)
(ffap-bindings)

;; I usually mistype "C-x C-f" to "C-x d" or "C-x C-d", so always use find-file,
;; because when file if directory find-file load dired, if regular file open it.
(global-set-key (kbd "C-x C-f") 'find-file-at-point)
(global-set-key (kbd "C-x C-d") 'find-file-at-point)
(global-set-key (kbd "C-x d") 'find-file-at-point)

;; Stop 'ffap' in Dired as its suggestion is inconvenient.
(define-key dired-mode-map (kbd "C-x C-f") 'find-file)
(define-key dired-mode-map (kbd "C-x C-d") 'find-file)
(define-key dired-mode-map (kbd "C-x d") 'find-file)

(setq dired-dwim-target t)
;; dangerous
;; (setq
;;  dired-recursive-copies 'top
;;  dired-recursive-deletes 'top)

(defun my-dired-up-dir ()
  "'Reuse' buffer if enter to dir or open new buffer if enter to file."
  (interactive)
  ;; (dired-current-directory) always end with trailing '/' char.
  (let* ( (dir (dired-current-directory)) (i (- (length dir) 2)) upperdir )
    (while (and
            (>= i 0)
            (not (equal (aref dir i) ?/)) )
      (setq i (- i 1))
      )
    (setq upperdir (substring dir 0 (+ i 1)))
    (when (file-directory-p upperdir)
      (find-alternate-file upperdir)
      (dired-goto-file dir)
      )
    ))
(define-key dired-mode-map (kbd "<backspace>") 'my-dired-up-dir)

(defun my-dired-enter-to-dir ()
  "'Reuse' buffer if enter to dir or open new buffer if enter to file."
  (interactive)
  (let ( (file (dired-get-file-for-visit)) )
    (if (file-directory-p file)
        (find-alternate-file file)
      (find-file file)
      )))
(define-key dired-mode-map (kbd "<return>")
  'my-dired-enter-to-dir)

;; Make behaviour same as in GUI.
(unless window-system
  (define-key dired-mode-map (kbd "DEL") 'my-dired-up-dir)
  (define-key dired-mode-map (kbd "RET") 'my-dired-enter-to-dir)
  )

(when (>= emacs-major-version 22)
  ;; Enable 'a' command.
  (put 'dired-find-alternate-file 'disabled nil)
  )

(defun my-file-name-tmp-p (file)
  (string-match
   `,(concat
    "\\(?:^#.*#\\|~\\|^.?\\.diff\\|"
    "\\." (regexp-opt '("base" "local" "orig" "other" "log" "stackdump" "rej"))
    "\\)\\'")
   (file-name-nondirectory file)))

(defun my-dired-flag-tmp-files ()
  "Flag all temporary files for deletion."
  (interactive)
  (dired-mark-if
   (let ( (fn (dired-get-filename 'verbatim t)) )
     (and fn (my-file-name-tmp-p fn)) )
   "backup file"
   )
  )

(define-key dired-mode-map (kbd "`") 'my-dired-flag-tmp-files)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "ls-lisp, dired ls")

;; If non-nil - use 'insert-directory-program', which I dislike.
(setq ls-lisp-use-insert-directory-program nil)
(setq ls-lisp-ignore-case t)
(setq ls-lisp-dirs-first t)
(if (memq system-type '(windows-nt cygwin))
    (setq ls-lisp-verbosity nil)
  (setq  ls-lisp-verbosity '(links uid gid)))
;; Force use 'ls-lisp-format-time-list'.
(setq ls-lisp-use-localized-time-format t)
(setq ls-lisp-format-time-list
      '("%Y-%m-%d %H:%M:%S"
        "%Y-%m-%d %H:%M   "))
(require 'ls-lisp)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "compression, archive")

(require 'jka-compr) ; Automatic decompression, hooks for tar-mode.
(when (fboundp 'auto-compression-mode)
  (auto-compression-mode 1))

(modify-coding-system-alist 'file "\\.\\(war\\|ear\\|sar\\|egg\\)\\'" 'no-conversion)

(add-to-list 'auto-mode-alist '("\\.\\(war\\|ear\\|sar\\|egg\\)\\'" . archive-mode))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "image, png, svg")

(when (fboundp 'auto-image-file-mode)
  (auto-image-file-mode 1))
(eval-after-load 'image-file
  '(progn
     ;; Exclude .svg image from supported image list, as Emacs doesn't come
     ;; with SVG shared library.
     (setq image-file-name-extensions (remove "svg" image-file-name-extensions))
     ;; Re-initialize the image-file handler.
     (auto-image-file-mode t)
     ))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "minibuffer")

(require 'icomplete) ; Interactive completion in minibuffer.
(icomplete-mode 1)

(mapc (lambda (ext) (add-to-list 'completion-ignored-extensions ext))
      '(
        ".class" "~" ".aux"
        ".o" ".obj" ".map" ".lib" ".lo" ".la" ".a" ".bin" ".exe"
        ;; Place dir at end to appear at the start of completion-ignored-extensions.
        "CVS/" ".hg/" ".svn/" ".git/" ".bzr/"
        ) )
(setq read-file-name-completion-ignore-case t)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "url")

;; http://tools.ietf.org/html/rfc3986
;; http://en.wikipedia.org/wiki/Percent-encoding
(defun my-percent-decode (str)
  (decode-coding-string
   (let* ( (s (split-string str "%")) )
     (my-fold
      'concat
      (car s)
      (mapcar
       (lambda (x)
         (concat (unibyte-string (string-to-number (substring x 0 2) 16)) (substring x 2)))
       (cdr s))
      )) 'utf-8))

(defun my-percent-decode-region (arg beg end)
  "Convert percent encoded string to native."
  (interactive "P\nr")
  (let ( (result (my-percent-decode (buffer-substring-no-properties beg end))) )
    (if (not arg)
        (message result)
      (delete-region beg end)
      (insert result))
    ) )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "browser")

(cond
 ((equal window-system 'w32)
  (setq browse-url-browser-function 'browse-url-default-windows-browser))
 ((boundp 'debian-emacs-flavor)
  (setq browse-url-browser-function 'browse-url-firefox))
 (t
  (setq browse-url-browser-function 'browse-url-mozilla)))

(defun my-cygwin-search (str)
  "Search for Cygwin package on-line."
  (interactive (list (read-input "Search for Cygwin package on-line: ")))
  (browse-url (format "http://cygwin.com/cgi-bin2/package-grep.cgi?grep=%s" str))
  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "calendar")

;; (setq mark-holidays-in-calendar t)
;; (setq all-christian-calendar-holidays t)
;; (setq calendar-date-display-form (quote ((format "%04s-%02d-%02d" year (string-to-int month) (string-to-int day)))))
;; (setq calendar-time-display-form (quote (24-hours ":" minutes (if time-zone " (") time-zone (if time-zone ")"))))
(setq calendar-week-start-day 1)
(setq european-calendar-style t)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "standard hooks")

(add-hook 'write-file-hooks 'time-stamp)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "logging, logs")

(defun my-auto-revert-tail-mode-hook ()
  (when (string-match "/var/log/\\|\\.log\\'"
                      (buffer-file-name (current-buffer)))
    (auto-revert-tail-mode 1)
    ))
(add-hook 'find-file-hook 'my-auto-revert-tail-mode-hook)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "auto-fill")

(setq-default fill-column 78)

(defvar my-fill-column 100
  "I use greater value then 78 for comment in prog source.")

;; By default used American convention - sentence and with two spaces. Change
;; it to one space. Has affect on filling and M-a, M-e commands.
(setq sentence-end-double-space nil)

;; Turn on auto-fill mode
(add-hook 'html-mode-hook 'turn-on-auto-fill)
(add-hook 'text-mode-hook 'turn-on-auto-fill)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "cacl, calculator")

(setq-default calc-group-digits t)
(setq-default calc-group-char "'")

(defun my-calc-eval-region (arg beg end)
  "Calculate the region and display the result in the echo area.
With prefix ARG non-nil, insert the result at the end of region."
  (interactive "P\nr")
  (require 'calc)
  (let* ((expr (buffer-substring-no-properties beg end))
         (result (calc-eval expr)))
    (if (null arg)
        (message "%s = %s" expr result)
      (goto-char end)
      (save-excursion
        (insert result)))))

;; ----------------------------------------------------------------
(message "rst, reStructuredText")

;; Maintaining the table of contents up-to-date.
(add-hook 'rst-adjust-hook 'rst-toc-update)

(unless window-system
  (eval-after-load 'rst
    '(progn
       (custom-set-faces
        '(rst-level-1-face ((t (:background "yellow"))) t)
        '(rst-level-2-face ((t (:background "yellow"))) t)
        '(rst-level-3-face ((t (:background "yellow"))) t)
        '(rst-level-4-face ((t (:background "yellow"))) t)
        '(rst-level-5-face ((t (:background "yellow"))) t)
        '(rst-level-6face ((t (:background "yellow"))) t)
        ) ) ) )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "TeX, LaTeX")

(setq tex-run-command "initex")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "AUC TeX")

;(add-hook 'LaTeX-mode-hook 'LaTeX-install-toolbar)
;; (setq TeX-parse-self t)             ; Enable parse on load.
;; (setq TeX-auto-save t)              ; Enable parse on save.
;; Query for master file. If you often use \include or \input, you should make AUCTEX aware of the
;; multi-file document structure.
(setq-default TeX-master nil)

;(setq TeX-PDF-mode t)
;(setq TeX-interactive-mode t)
;(setq TeX-source-specials-mode 1)

;;; some more menu entries in the command list:
;;; see tex-mik.el from package auctex: %v is defined in tex-mik.el
;;; other variables are defined in tex.el from auctex
;;; the meaning of some auctex-varibles:
        ;symbols defined in tex.el and tex-mik.el:
        ;%b name slave tex-file  %t name master tex-file
        ;%d dvi-file  %f ps-file
        ;%l "latex --src-specials"
        ;%n line number  %p printcommand  %q "lpq"
        ;%r (TeX-style-check TeX-print-style)
        ;%s master-file-name without extention
        ;%v yap command view line
;(eval-after-load "tex"
;  '(progn
;     (add-to-list 'TeX-command-list
;         (list "->PS landscape for pdf"
;           "dvips %d -N0 -Ppdf -G0 -T 297mm,210mm -o %f "
;           'TeX-run-command nil t))
;     (add-to-list 'TeX-command-list
;         (list "All Texify run-viewer"
;           "texify --tex-opt=--src --run-viewer --clean %s.tex"
;           'TeX-run-command nil t))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "reftex")

;; Reftex is included with Emacs 21.1.

;; (autoload 'reftex-mode     "reftex" "RefTeX Minor Mode" t)
;; (autoload 'turn-on-reftex  "reftex" "RefTeX Minor Mode" nil)
;; (autoload 'reftex-citation "reftex-cite" "Make citation" nil)
;; (autoload 'reftex-index-phrase-mode "reftex-index" "Phrase mode" t)
;; (add-hook 'LaTeX-mode-hook 'turn-on-reftex)   ; with AUCTeX LaTeX mode
;; (add-hook 'latex-mode-hook 'turn-on-reftex)   ; with Emacs latex mode

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "PreviewLatex")

;(load "preview-latex.el" nil t t)

;(add-hook 'LaTeX-mode-hook #'LaTeX-preview-setup)
;(autoload 'LaTeX-preview-setup "preview")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "Info")

(unless (getenv "INFOPATH")
  (setenv "INFOPATH" "~/usr/share/info:"))

;; Assume that cygwin-mount already activated.
(when (featurep 'cygwin-mount)
  (setenv "INFOPATH" "/usr/share/info/:~/usr/share/info/:")
  ;; Redefine path-separator to UNIX to update Info-directory-list.
  (let ( (path-separator ":") )
    (require 'info)
    (info-initialize)
    ))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "man, woman")

;; Assume that cygwin-mount already activated.
(when (featurep 'cygwin-mount)
  (let ( (path (expand-file-name "~")) )
    (when (string-match "\\([c-z]\\):/" path)
      (setenv "MANPATH" (concat "/cygdrive/" (substring path 0 1) "/" (substring path 3) "/usr/share/man/:"))
      ) ))

(setq woman-use-own-frame nil)
(setq woman-fill-frame t)
;; I prefer EN man pages.
(setq manual-program "LANG=C man")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "comint")

;; If non-nil, add a `/' to completed directories, ` ' to file names.
(setq comint-completion-addsuffix t)
;; Non-nil means go to the end of the line before sending input.
(setq comint-eol-on-send t)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "spell, ispell, aspell, flyspell")

;; Settings for spelling done in '.emacs-autogen'.

(add-hook 'log-edit-mode-hook 'flyspell-mode)

;; (setq-default ispell-extra-args  '("--sug-mode=ultra"))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "dict, dictd, dictionary")

(when (fboundp 'dict-c5-mode)
  (add-to-list 'auto-mode-alist '("\\.dict-c5$" . dict-c5-mode))
  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "remember-mode")

(when (>= emacs-major-version 23)
  (require 'remember))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "org-mode, GTD, PIM, organize, todo")

(when (>= emacs-major-version 22)
  (require 'org))

;; XXX org-todo-keywords '((sequence "TODO" "START" "|" "DONE")) for org-version 4.67c
;; XXX (setq org-todo-keywords '("TODO" "START" "DONE")) for org-version 6.05b
(when (or (featurep 'org) (featurep 'org-install))
  (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
  (setq org-directory "~/devel/my-devel/gtd")
  (setq
   org-default-notes-file nil
   org-agenda-ndays 31
   org-deadline-warning-days 7
   org-agenda-show-all-dates t
   org-agenda-format-date "%Y-%m-%d, %A %e %B"
   org-agenda-skip-deadline-if-done t
   org-agenda-skip-scheduled-if-done t
   org-agenda-start-on-weekday nil
   org-reverse-note-order t
   org-hide-leading-stars t
   org-tags-column 64
   )
  (setq my-org-agenda-todo-file (concat org-directory "/TODO.org"))
  (setq my-org-agenda-note-file (concat org-directory "/NOTE.org"))
  (setq org-agenda-files `(,my-org-agenda-todo-file ,my-org-agenda-note-file))
  (define-key global-map "\C-ca" 'org-agenda)
  (define-key global-map "\C-ce" (lambda nil (interactive) (find-file my-org-agenda-note-file)))

  ;; My tags for remember buffer.
  (setq org-tag-persistent-alist
        '(
          ("ADMIN" . ?a)
          ("BLOG" . ?b)
          ("DEVEL" . ?d)
          ("LIFE" . ?l)
          ("MISC" . ?m)
          ("JOB" . ?j)
          ("PROJECT" . ?p)
          ("READ" . ?r)
          ("SEE" . ?s)
          ))

  (when (or (featurep 'remember) (fboundp 'remember))
    (setq remember-annotation-functions '(org-remember-annotation))
    (setq remember-handler-functions '(org-remember-handler))
    (add-hook 'remember-mode-hook 'org-remember-apply-template)
    (define-key global-map "\C-cr" 'org-remember)
    (setq org-remember-templates
          ;; With one item org-mode do not prompt choose template.
          `(
            ("todo" ?t "* TODO %?" ,my-org-agenda-todo-file)
            ;; ("note" ?n "* %?\n" ,my-org-agenda-note-file)
            ))
    (setq org-remember-store-without-prompt t)
    (org-remember-insinuate)
    )

  ;; (setq org-todo-keyword-faces
  ;;       '(("TODO" . (:foreground "red" :weight bold))
  ;;         ("WAIT" . (:foreground "orange" :weight bold))
  ;;         ("DONE" . (:foreground "green" :weight bold))) )
  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "TODO, XXX, FIXME highlight")
;; Show blanks and FIXME
;; http://www.emacswiki.org/cgi-bin/wiki/EightyColumnRule

(defface my-tab-face
  '((t :background "gray"))
  "Face for showing TABs."
  :group 'basic-faces)

(defface my-contrasty-face
  '((t :background "pink" :foreground "red" :weight bold))
  "Font for showing conflicts."
  :group 'basic-faces)

(dolist (mode (append my-devel-mode-list my-text-mode-list))
  (font-lock-add-keywords
   mode
   `(
     ("\t+" 0 'my-tab-face t)
     ( ,(concat "\\<\\(" (regexp-opt '("TODO" "FIX" "FIXME" "HACK" "XXX")) ":?\\)\\>") 1 'font-lock-warning-face t)
     ("\\(=\\|<\\|>\\)\\{7,\\}" 0 'my-contrasty-face t)
     ;; 64 times, for highlight C-u C-u C-u <key>
     ("\\([^[:space:]]\\)\\1\\{63\\}" 0 'my-contrasty-face t)
     ))
  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "fortune")
(setq fortune-file "~/XXX")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "mail, message")

(setq mail-user-agent 'message-user-agent)

(setq message-citation-line-format "On %Y-%m-%d, %N wrote:
")
(setq message-citation-line-function 'message-insert-formatted-citation-line)

(setq mail-signature t)
(setq mail-signature-file "~/.signature")
;; (add-hook 'mail-setup-hook 'fortune-to-signature)

;; (setq mail-from-style 'angles)

(setq mail-personal-alias-file "~/.mailrc")
;; Initialize from your mail aliases file...
(setq mail-aliases t)
(require 'ecomplete)
(setq message-mail-alias-type '(abbrev ecomplete))

(eval-after-load 'message
  '(progn
     (require 'mailabbrev)
     (define-key message-mode-map "\e\t" 'mail-abbrev-complete-alias)
     ))

(defun my-message-setup-routine ()
  (flyspell-mode 1)
  )
(add-hook 'message-setup-hook 'my-message-setup-routine)

;; Kill message buffer after mail send. You always can use C-c C-s to preserve it.
(setq message-kill-buffer-on-exit t)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "smtp, smtpmail")

(when (boundp 'smtpmail-smtp-server)
  (require 'smtpmail)
  (setq
   ;; If you use the default mail user agent.
   send-mail-function 'smtpmail-send-it
   ;; If you use Message or Gnus.
   message-send-mail-function 'smtpmail-send-it
   )
  )
;; (setq smtpmail-debug-verb t)
;; (setq smtpmail-debug-info t)

(defun my-message-mode-hook ()
  (setq fill-column 78)
  (turn-on-auto-fill)
  )
(add-hook 'message-mode-hook 'my-message-mode-hook)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "gnus, mh-e")

(setq gnus-site-init-file "~/.gnus.el")

;; Store gnus specific files to '~/.gnus'.
(setq
 gnus-directory "~/.gnus"
 gnus-agent-directory "~/.gnus/agent/"
 gnus-article-save-directory "~/.gnus/saved"
 gnus-kill-files-directory "~/.gnus/scores"
 gnus-cache-directory "~/.gnus/cache"
 mail-source-directory "~/.gnus/mail"
 message-directory "~/.gnus/mail"
 message-auto-save-directory "~/.gnus/autosave"
 ;; message-signature-directory
 mailcap-download-directory  "~/.gnus/mailcap"
 nnml-directory "~/.gnus/nnml-mail"
 spam-directory "~/.gnus/spam/"
 smime-certificate-directory "~/.gnus/certs/"
 nnfolder-directory "~/.gnus/archive"
 nnfolder-active-file "~/.gnus/archive/active"
)

;; Remove gnus-ignored-newsgroups to show all GMail folders.
(setq gnus-ignored-newsgroups nil)

;; (require 'spam)
;; (setq gnus-spam-process-newsgroups
;;       '(("^gmane\\."
;;          ((spam spam-use-gmane)))))

(setq
 gnus-novice-user nil
 gnus-expert-user nil
 gnus-interactive-catchup t
 gnus-interactive-exit t
 )

(setq
 gnus-read-active-file nil
 gnus-check-new-newsgroups nil
 gnus-check-bogus-newsgroups nil
 )

;; If you're spooling in overlapping mbox folders, you probably want to delete
;; all messages with duplicate message IDs.
(setq nnmail-treat-duplicates 'delete)

;; Do not use the html part of a message, use the text part if possible!
(setq mm-discouraged-alternatives '("text/html" "text/richtext"))

(add-hook 'gnus-group-mode-hook 'gnus-topic-mode)

(setq
 gnus-posting-styles
 '(
   (".*"
    (organization "At home.")
    (signature-file "~/.signature")
    )
   ))

;; `gnus-group-line-format', `gnus-summary-line-format',
;; `gnus-server-line-format', `gnus-topic-line-format',
;; `gnus-group-mode-line-format', `gnus-summary-mode-line-format',
;; `gnus-article-mode-line-format', `gnus-server-mode-line-format',
;; `gnus-summary-pick-line-format'.

(when window-system
  (setq
   gnus-sum-thread-tree-false-root ""
   gnus-sum-thread-tree-indent " "
   gnus-sum-thread-tree-leaf-with-other "├► "
   gnus-sum-thread-tree-root ""
   gnus-sum-thread-tree-single-leaf "└► "
   gnus-sum-thread-tree-vertical "│"
   ))

(setq gnus-user-date-format-alist '((t . "%Y-%m-%d %H:%M")))
(setq gnus-summary-line-format "%U%R%z %&user-date; %B %[%-22,22f%] %s\n")
(setq gnus-summary-mode-line-format "Gnus: %p %Z")

(setq gnus-article-time-format "%Y-%m-%d %T%z %a")
(setq gnus-article-date-headers '(combined-lapsed user-defined))

;; gnus-visible-headers
(setq
 gnus-sorted-header-list
 '(
   "^From:"
   "^Subject:"
   "^Summary:"
   "^Keywords:"
   "^Newsgroups:"
   "^Followup-To:"
   "^To:"
   "^Cc:"
   "^Organization:"
   "^Date:"
   "^User-Agent:"
   "^X-Mailer:"
   "^X-Newsreader:"
   ))

(setq
 gnus-show-threads t
 gnus-thread-sort-functions '(gnus-thread-sort-by-date gnus-thread-sort-by-total-score)
 )

;; Scoring, adaptive score.
(setq
 gnus-use-scoring t
 gnus-save-score t
 gnus-use-adaptive-scoring t
 gnus-score-expiry-days 60
 gnus-decay-scores t
 gnus-default-adaptive-score-alist
 '(
   (gnus-unread-mark)
   (gnus-ticked-mark (subject 5))
   (gnus-dormant-mark (subject 5))
   (gnus-del-mark (from -2) (subject -5))
   (gnus-read-mark (from 2) (subject 1))
   (gnus-killed-mark (subject -5))
   (gnus-catchup-mark (subject -1))
   (gnus-kill-file-mark (from -9999))
   )
 )
;; Increase the score for followups to a sent article.
(eval-after-load 'gnus-score
  '(progn
     (add-hook 'message-sent-hook 'gnus-score-followup-article)
     (add-hook 'message-sent-hook 'gnus-score-followup-thread)
     ))

;; (setq gnus-home-score-file
;;       ;; All groups that match the regexp `"\\.emacs"'
;;       '(("\\.emacs" "emacs.SCORE")
;;         ;; All the comp groups in one score file
;;         ("^comp" "comp.SCORE")))

;; (setq imap-log t)

;; (setq mail-user-agent 'mh-e-user-agent)

(custom-set-faces '(gnus-summary-cancelled ((t (:foreground "plum" :background nil)))) )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "bbdb")

(setq
 bbdb-offer-save 1
 bbdb-use-pop-up t
 bbdb-electric-p t
 bbdb-popup-target-lines  1
 )

(setq bbdb-complete-name-full-completion t)
(setq bbdb-completion-type 'primary-or-name)
(setq bbdb-complete-name-allow-cycling t)

(setq bbdb-file "~/.gnus/bbdb")

;; (bbdb-initialize 'gnus 'message)
;; (bbdb-insinuate-message)
;; (add-hook 'gnus-startup-hook 'bbdb-insinuate-gnus)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "jabber")

(autoload 'jabber-connect-all "jabber")

(setq
 jabber-history-enabled t
 jabber-use-global-history nil
 jabber-backlog-number 40
 jabber-backlog-days 30
 jabber-alert-presence-message-function (lambda (who oldstatus newstatus statustext) nil)
 )

(eval-after-load 'jabber
  '(progn
    ;; Redefine standard binding for sending message form RET to C-RET.
    (define-key jabber-chat-mode-map (kbd "RET") 'newline)
    (define-key jabber-chat-mode-map [C-return] 'jabber-chat-buffer-send)
    ;; fsm used in emacs jabber
    (when (featurep 'fsm)
      (setq fsm-debug nil)                  ; Disable *fsm-debug* buffer.
      )
    ;; Handle Emacs exit.
    (add-hook 'kill-emacs-hook 'jabber-disconnect)
    ))

(setq my-chat-prompt "[%t] %n>\n")
(setq
 jabber-chat-foreign-prompt-format my-chat-prompt
 jabber-chat-local-prompt-format my-chat-prompt
 jabber-groupchat-prompt-format my-chat-prompt
 jabber-muc-private-foreign-prompt-format "[%t] %g/%n>\n"
 )

(let ( (mgs-list '("Я тутачки, а где Вы меня ожидали?"
                   "Software Development == Church Development. Step 1. Build it. Step 2. Pray."
                   "Great books aren't written – they're rewritten."
                   "А любит Б, Б любит С, что делать A? Найти другую Б!")) )
  (random t)
  (setq jabber-default-show (nth (random (length mgs-list)) mgs-list))
  (setq jabber-default-status (nth (random (length mgs-list)) mgs-list))
  )

(defvar my-jabber-users nil
  "Assoc list of jabber user group. Keys are strings, values are lists of JIDs.")

(defun my-jabber-send (group)
  "GROUP is keys from `my-jabber-users'"
  (interactive
   (list (completing-read "Select group: " my-jabber-users))
   )
  (let (
        (msg (if (use-region-p)
                 (buffer-substring (region-beginning) (region-end))
               (buffer-string)))
        (jc (jabber-read-account))
        )
    (deactivate-mark)
    (mapc
     (lambda (user)
       (jabber-send-message jc user "" msg "normal")
       )
     (cdr (assoc group my-jabber-users))
     )
    )
  )

(global-set-key (kbd "C-x C-j C-s") 'my-jabber-send)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "rcirc")

;; Turn on logging everything to a special buffer, for debugging.
;; (setq rcirc-debug-flag t)

(add-hook 'rcirc-mode-hook (lambda () (rcirc-track-minor-mode 1)))
(setq rcirc-time-format "%H:%M ")
(defun rcirc-handler-301 (process cmd sender args)
  "/away message handler.")

(setq rcirc-default-server "irc.freenode.net")
(setq rcirc-default-port 6667)
(setq rcirc-default-nick user-nick)
(setq rcirc-default-user-full-name user-full-name)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "erc")

;; (add-to-list 'erc-modules 'notify)
;; (setq erc-notify-list '(""))

;; Take off noise message.
(setq erc-track-exclude-types '("JOIN" "PART" "QUIT" "NICK" "MODE"))

(setq erc-current-nick-highlight-type 'nick-or-keyword)
(setq erc-track-use-faces t)

(setq erc-server-coding-system 'utf-8)
(setq erc-encoding-coding-alist
      '(
        ("^icq-" . cp1251)
        ))

(setq erc-autojoin-channels-alist '(("freenode.net" "#emacs")))

(setq
 erc-server-auto-reconnect t
 erc-server-reconnect-timeout 60
 erc-server-reconnect-attempts 2
 )

;; Kill buffers for channels after /part
;; (setq erc-kill-buffer-on-part t)
;; Kill buffers for private queries after quitting the server
;; (setq erc-kill-queries-on-quit t)
;; Kill buffers for server messages after quitting the server
;; (setq erc-kill-server-buffer-on-quit t)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "vc-mode, VCS, version control, cvs, svn, mercurial, hg, bazaar, bzr, git, fossil")

;; `-b' switch to ignore changes in whitespaces.
;; (setq vc-git-diff-switches "-b")
;; (setq vc-diff-switches "-b")

(when (equal window-system 'w32)
  (modify-coding-system-alist 'process "cvs" '(cp1251-dos . cp1251-dos))
  (modify-coding-system-alist 'process "svn" '(cp1251 . cp1251))
  (setq vc-svn-checkin-switches '("--encoding" "UTF-8"))
  )

(when window-system
  (setq
   vc-annotate-very-old-color "#0b5b20"
   vc-annotate-background "white"
   vc-annotate-color-map
   '(
     (20 .  "#EE0000")
     (40 .  "#E0800D")
     (60 .  "#D3001A")
     (80 .  "#C68027")
     (100 . "#B90034")
     (120 . "#AB8042")
     (140 . "#9E004F")
     (160 . "#91805C")
     (180 . "#840069")
     (200 . "#778077")
     (220 . "#690084")
     (240 . "#5C8091")
     (260 . "#4F009E")
     (280 . "#4280AB")
     (300 . "#3400B9")
     (320 . "#2780C6")
     (340 . "#1A00D3")
     (360 . "#0D80E0")))
  )

(defun my-log-edit-mode-hook ()
  (setq fill-column 78)
  )
(add-hook 'log-edit-mode-hook 'my-log-edit-mode-hook t)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "psvn")

(setq svn-status-verbose t)
(setq svn-status-hide-unmodified t)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "DVC")

(when (featurep 'dvc-emacs)
  (setq dvc-tips-enabled nil)
  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "devel, prog, programming")

(which-func-mode 1)

(add-to-list 'auto-mode-alist '("\\.cu$" . c-mode))

(defun my-c++-header-file-p ()
  "Return non-nil, if in a C++ header."
  (and (string-match "\\.h$"
                     (or (buffer-file-name)
                         (buffer-name)))
       (save-excursion
         (re-search-forward "\\_<class\\_>" nil t))))

(when (>= emacs-major-version 22)
  (add-to-list 'magic-mode-alist '(my-c++-header-file-p . c++-mode))
  )

(setq-default comment-style (quote indent))
(setq-default comment-column 44)
(setq-default comment-fill-column my-fill-column)

(mapc (lambda (hook) (add-hook hook (lambda () (setq fill-column my-fill-column)) ))
      (append my-devel-mode-hook-list my-text-mode-hook-list))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "diff, patch, ediff, emerge")

(setq diff-switches "-u")

(setq ediff-diff-options "")
(setq ediff-custom-diff-options "-u")

(when window-system
  (eval-after-load 'diff-mode
    '(progn
       (set-face-foreground 'diff-added-face "DarkGreen")
       (set-face-foreground 'diff-removed-face "DarkRed")
  )))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "indenting")

(setq standard-indent 4)
(setq c-basic-offset 4)
(setq sh-basic-offset 2)
(setq sgml-basic-offset 4)

;; TAB (tab settings)
(setq-default tab-width 4)
(setq-default indent-tabs-mode nil)     ; spaces instead of tabs by default
(setq tab-always-indent t)
(setq c-tab-always-indent t)
(let ( (line-width 400) i )
  (setq i (* (ceiling line-width 4) 4))
  (setq tab-stop-list nil)
  (while (>= i 0)
    (setq tab-stop-list (cons i tab-stop-list))
    (setq i (- i 4))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "compile")

;; Prompt for compilation command.
(setq compilation-read-command 1)
(setq compile-auto-highlight t)
(setq compile-command "make ")
(when (eq system-type 'berkeley-unix)
  (setq compile-command "gmake "))
;; With '1' compilation window shall scroll down, with `first-error' stops scrolling at the first error.
(setq compilation-scroll-output 1)
(setq compilation-ask-about-save t)

;; Show error in EN locale to easy search how fix problem in docs and Internet.
(setq compilation-environment '("LANG=C"))

(eval-after-load 'compile
  '(progn
     ;; My funny error messages.
     (add-to-list 'compilation-error-regexp-alist '("^\\( +\\[csc\\] \\|\\)\\(.*\\)(\\([0-9]*\\),\\([0-9]*\\)):" 2 3 4))
     (add-to-list 'compilation-error-regexp-alist '("^ *\\(.*\\)(\\([0-9]*\\)) +:" 1 2))
     (add-to-list 'compilation-error-regexp-alist '("^\"?\\([^\"]*\\)\"?,\\([0-9]*\\) .*\\[.*\\]: " 1 2)) ; KEIL compiler
     (when (boundp 'compilation-mode-font-lock-keywords)
       (add-to-list 'compilation-mode-font-lock-keywords '("\\(/[Oo][Uu][Tt]:[^[:blank:]]+\\)" . 1))
       (add-to-list 'compilation-mode-font-lock-keywords '("[[:blank:]]\\(/F[oe][^[:blank:]]+\\)" . 1))
       )
     ))

(defvar my-comint-send-hist-list nil
  "History list for `my-comint-send-string'."
  )
(defun my-comint-send-string (string)
  "Send string to comint buffers. Useful for *compilation* read-only buffer.
Automaticaly append final newline."
  (interactive
   (list (read-input "Type string: " nil 'my-comint-send-hist-list))
   )
  (comint-send-string (get-buffer-process (current-buffer)) (concat string "\n"))
  )
(eval-after-load 'compile
  '(progn
     (define-key compilation-mode-map [C-return] 'my-comint-send-string)
     ))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "TAGS, etags, ctags, GNU GLOBAL")

;; One of 'tags-table-list' or 'tags-file-name' control which TAGS files to
;; use.

(ignore-errors
  (require 'etags-table)
  (setq etags-table-search-up-depth 8)
  (require 'etags-select)
  (global-set-key "\M-." 'etags-select-find-tag)
  )

(setq tags-add-tables t)
(global-set-key "\M-\r" 'complete-tag)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "CEDET, semantic")

;; For debug use 'semantic-debug-idle-function' and 'semantic-debug-idle-work-function'.

(unless (featurep 'cedet)
  (when (or
         (and (= emacs-major-version 23) (>= emacs-minor-version 2))
         (>= emacs-minor-version 24)
         )
    (semantic-mode 1)
    ) )

(when (featurep 'cedet)
  (global-ede-mode t)
  (global-semantic-idle-summary-mode 1)
  (global-semantic-idle-scheduler-mode 1)
  (setq semantic-idle-scheduler-idle-time 1) ; 1 sec.
  (global-semantic-decoration-mode 1)
  (global-semantic-mru-bookmark-mode 1)
  ;; (setq semantic-stickyfunc-sticky-classes '(function type variable include package))
  (global-semantic-stickyfunc-mode -1)
  (global-semantic-idle-completions-mode -1)

  (setq semantic-idle-scheduler-work-idle-time 60)
  ;; (setq semantic-idle-work-parse-neighboring-files-flag nil)

  ;; semantic-dependency-system-include-path, semantic-customize-system-include-path

  ;; file local project unloaded system recursive
  (setq-mode-local c-mode semanticdb-find-default-throttle '(file))
  (add-hook 'c-mode-hook (lambda nil (semantic-add-system-include "~/.emacs.d/include" 'c-mode)))
  (add-hook 'c-mode-hook (lambda nil (semantic-add-system-include "~/.emacs.d/include" 'c++-mode)))
  (global-semanticdb-minor-mode 1)

  ;; (add-to-list 'ede-locate-setup-options 'ede-locate-idutils)
  ;; (add-to-list 'ede-locate-setup-options 'ede-locate-global)

  ;; (ignore-errors (require 'cedet-idutils))
  ;; (when (ignore-errors (require 'cedet-global))
  ;;   (semanticdb-enable-gnu-global-databases 'c-mode)
  ;;   (semanticdb-enable-gnu-global-databases 'c++-mode)
  ;;   )

  (global-set-key (kbd "C-c , .") 'semantic-ia-fast-jump)
  (global-set-key (kbd "C-c , d") 'semantic-ia-show-doc)
  (global-set-key (kbd "C-c , D") 'semantic-ia-describe-class)
  (global-set-key (kbd "C-c , c") 'semantic-ia-complete-symbol-menu)
  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "imenu")

(defun my-imenu-to-menubar ()
  (imenu-add-menubar-index)
  (run-hooks 'menu-bar-update-hook)
  )

(require 'imenu)
(mapc (lambda (hook) (add-hook hook 'my-imenu-to-menubar))
      my-devel-mode-hook-list)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "windows inf files for driver installin")

(add-to-list 'auto-mode-alist '("\\.inf\\'" . conf-mode))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "makefile, make")

(add-to-list 'auto-mode-alist '("\\(Makefile\\|Makefile\\..+\\)\\'" . makefile-gmake-mode) t)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "asm, assembler")

;; (setq-default asm-comment-char 59)
(add-hook 'asm-mode-hook '(lambda () (setq comment-start "/*") (setq comment-end "*/")) t)

(add-to-list 'auto-mode-alist '("\\.\\([sS]79\\|[sS]\\)\\'" . asm-mode))

;; (add-hook 'asm-mode-hook '(lambda () (local-unset-key ":")))
;; (add-hook 'asm-mode-hook '(lambda () (local-set-key ":" ":")))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "linker")

(when (fboundp 'iar-linker-config-mode)
  (add-to-list 'auto-mode-alist '("\\.icf\\'" . iar-linker-config-mode))
  )
(when (fboundp 'iar4-linker-config-mode)
  (add-to-list 'auto-mode-alist '("\\.xcl\\'" . iar4-linker-config-mode))
  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "lisp, elisp")

(setq list-command-history-max 256)

(add-hook 'emacs-lisp-mode-hook 'turn-on-eldoc-mode)

(defun my-elisp-find-tag ()
  (interactive)
  (require 'etags)
  (ring-insert find-tag-marker-ring (point-marker))
  (unless (find-variable-at-point)
    (find-function-at-point)
    ))
;; Goto elisp definition.
(define-key emacs-lisp-mode-map (kbd "M-.") 'my-elisp-find-tag)

;; http://www.emacswiki.org/emacs/PrettyLambda
(font-lock-add-keywords
 'emacs-lisp-mode
 `(
   ("(\\<\\(lambda\\)\\>"
    (1 (progn (compose-region (match-beginning 1) (match-end 1) ,(make-char 'greek-iso8859-7 107)) font-lock-keyword-face))
    )
   ))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "C, c-mode, C++, c++-mode")

;; Minor mode that highlights suspicious C and C++ constructions.
(cwarn-mode 1)

(setq c-echo-syntactic-information-p t)

(defun my-c-mode-common-hook ()
  ;; Automatically inserte newlines after special characters such as brace, comma, semi-colon, and colon.
  (c-toggle-auto-newline -1)
  ;; Delete all preceding whitespace by DEL.
  (c-toggle-hungry-state -1)
  ;; Auto indent after typing colon according to `c-hanging-colons-alist'.
  (c-toggle-electric-state 1)
  )
(add-hook 'c-mode-common-hook 'my-c-mode-common-hook)

(defconst my-c-style
  '((c-tab-always-indent . t)
    (c-comment-only-line-offset . 4)
    (c-hanging-braces-alist
     . (
        (brace-list-open)
        (substatement-open after)
        ))
    (c-hanging-colons-alist
     . (
        (access-label after)
        (case-label after)
        (inher-intro)
        (label after)
        (member-init-intro before)
        ))
    (c-cleanup-list
     . (
        defun-close-semi
        empty-defun-braces
        scope-operator
        ))
    (c-offsets-alist
     . (
        (access-label . -)
        (arglist-intro . ++)
        (arglist-cont-nonempty . ++)
        (arglist-close . ++)
        (block-open . 0)
        (case-label . 0)
        (cpp-define-intro . 0)
        (comment-intro . 0)
        (func-decl-cont . ++)
        (inexpr-class . 0)
        (inline-open . 0)
        (knr-argdecl-intro . -)
        (label . 0)
        (statement-block-intro . +)
        (statement-cont . ++)
        (substatement-open . 0)
        (inextern-lang . 0)
        ))
    (c-echo-syntactic-information-p . t))
  "My C Programming Style")

(defun my-c-mode-style-hook ()
  (c-add-style "my" my-c-style t)
  ;; If set 'c-default-style' before 'c-add-style'
  ;; "Undefined style: my" error occured from 'c-get-style-variables'.
  (setq c-default-style
        '(
          (java-mode . "my") (c-mode . "my") (csharp-mode . "my") (c++-mode . "my") (objc-mode . "my")
          (idl-mode . "my")
          (awk-mode . "awk")
          (other . "my")
          ))
  )
(add-hook 'c-mode-common-hook 'my-c-mode-style-hook)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "python")

(when (equal window-system 'w32)
  (add-to-list 'process-coding-system-alist '("python" cp1251-unix . cp1251-unix))
  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "javascript, js")

;; (if (>= emacs-major-version 23)
;;     (add-to-list 'auto-mode-alist '("\\.js$" . js-mode))
;;   (add-to-list 'auto-mode-alist '("\\.js$" . javascript-generic-mode))
;;   )

(setq auto-mode-alist (rassq-delete-all 'js-mode auto-mode-alist))
(add-to-list 'auto-mode-alist '("\\.js$" . c++-mode))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "bat file, batch")

;; loaded from 'generic-x.el'

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "nsis-mode")

(when (fboundp 'nsis-mode)
  (add-to-list 'auto-mode-alist '("\\.\\(nsi\\|nsh\\)\\'" . nsis-mode))
  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "csharp, c-sharp")

(autoload 'csharp-mode "csharp-mode" "Major mode for editing C# code." t)
(add-to-list 'auto-mode-alist '("\\.cs$" . csharp-mode))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "java")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "ECB")

(setq ecb-tip-of-the-day nil)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "html")

(defun html-charref-escape-region (start end)
  (interactive "r")
  (save-excursion
    (save-restriction
      (narrow-to-region start end)
      (goto-char (point-min))
      (replace-string "&" "&amp;")
      (goto-char (point-min))
      (replace-string "<" "&lt;")
      (goto-char (point-min))
      (replace-string ">" "&gt;")
      )))

(defun html-charref-from-char (char)
  (format "&#%d;" char)
  )

(defun html-charref-from-string (string)
  (let ((res ""))
    (mapc
     (lambda (char) (setq res (concat res (html-charref-from-char char))))
     string)
    res
    ) )

(defun html-charref-escape-region2 (begin end &optional prefix)
  (interactive "r\nP")
  (if prefix
      (save-excursion
        (goto-char begin)
        (insert (html-charref-from-string (delete-and-extract-region begin end))))
    (html-charref-from-string (buffer-substring begin end))
    ))

(defun html-charref-to-string (html)
  (let ((res "") (pos 0))
    (while (string-match "&#\\([[:digit:]]+\\);" html pos)
      (setq res (concat res (string (string-to-int (substring html (match-beginning 1) (match-end 1)) 10))))
      (setq pos (match-end 0))
     )
    res
    ) )

(defun html-charref-unescape-region (begin end &optional prefix)
  (interactive "r\nP")
  (if prefix
      (save-excursion
        (goto-char begin)
        (insert (html-charref-to-string (delete-and-extract-region begin end))))
    (html-charref-to-string (buffer-substring begin end))
    ))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "nxml")

(setq nxml-sexp-element-flag t)
(setq nxml-child-indent 2)
(setq nxml-attribute-indent 4)

(eval-after-load 'rng-loc
  '(add-to-list 'rng-schema-locating-files "~/.emacs.d/rnc/schemas.xml")
  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "psgml")

(setq my-html-template
      '("html"
        (nil
         "\n<head>" \n
         "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" (read-input "Charset: ") "\">" \n
         "<title>" (setq str (read-input "Title: ")) "</title>\n"
         "</head>\n"
         "<body>\n<h1>" str "</h1>"
         "\n<address>" \n
         "<a href=\"mailto:" user-mail-address "\">" (user-full-name) "</a>" \n
         "</address>" \n
         "</body>\n"
         ))
      )

(setq sgml-set-face t)                  ; for highlighting in sgml
(eval-after-load 'sgml-mode
  '(progn
     (unless (featurep 'psgml)
       (setq html-tag-alist
             (cons
              my-html-template
              (my-filter
               (lambda (item) (not (equal (car item) "html")))
               html-tag-alist)))
       (add-to-list 'html-tag-alist '("script" (\n) ("type" "text/javascript") ))
       (add-to-list 'html-tag-alist '("style" (\n) ("type" "text/css") ))
     )))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "sh, bash")

(add-to-list 'auto-mode-alist '("\\.cygport\\'" . shell-script-mode))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "printing")

;; Use Notepad to print plain text files to the default Windows printer
;(setq lpr-command "notepad")
;(setq lpr-headers-switches '("/p"))    ; \ mis-use these
;(setq lpr-switches nil)                ; / two variables
;(setq printer-name nil)        ; notepad takes the default
;(setq lpr-printer-switch "/P") ;; run notepad as batch printer
;;

;; Printing to file.

;(setq printer-name "~/myprint.txt")
;(setq ps-printer-name nil)
;(setq ps-print-header nil)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "SQL")

(setq sql-password "")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "backuping")

(setq
 make-backup-files t
 ;; In other case (by renaming) you loose original file creation date.
 backup-by-copying t
 backup-directory-alist '(("." . "~/.backup")) ; don't litter my fs tree
 delete-old-versions t                         ; delete excess backup versions silently
 kept-old-versions 1                           ; store first original version
 kept-new-versions 3                           ; store last 3 version
 version-control t)                            ; use versioned backups

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "auto save")

(setq auto-save-default t)
;; If nil autosave to different than original to buffer file.
(setq auto-save-visited-file-name nil)
(setq auto-save-interval 300)
;; Note: if you kill unsaved file auto save file not deleted.
(setq delete-auto-save-files t)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Save and restore my buffers every time.

(setq desktop-base-file-name ".emacs.desktop")
(setq desktop-base-lock-name ".emacs.desktop.lock")
(when (eq system-type 'cygwin)
  (setq desktop-base-file-name ".emacs.desktop-cygwin")
  (setq desktop-base-lock-name ".emacs.desktop-cygwin.lock")
  )

(when (>= emacs-major-version 22)
  (desktop-save-mode 1)
  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(message "User welcome msg")

(add-hook 'emacs-startup-hook
          (lambda ()
            (let ( (mgs-list '("Welcome to emacs, the thermonuclear editor."
                               "You enter to Out Space. Emacs on."
                               "Nice day for Emacsing!")) )
              (message (nth (random (length mgs-list)) mgs-list)))))

(switch-to-buffer "*Messages*")
(setq default-directory "~/")
(switch-to-buffer "*scratch*")
(setq default-directory "~/")

;;; End loading...

;; Local variables:
;; mode: outline-minor
;; outline-regexp: "(message \""
;; End: