;; -*- Mode: Emacs-Lisp -*-
;; -*- lisp -*-
;; $Id: .emacs-d-startup,v 1.3 2002/02/28 10:41:03 amos-cvs Exp $
;; Copyright (C) Jan Borsodi 1998-2001
;;

;; Turn off blink mode in Emacs 21+, it's turned on in the options system by the user.
(if (>= emacs-major-version 21)
    (blink-cursor-mode -1))

;; make compiler in a new frame.
(setq special-display-buffer-names
      (cons "*compilation*" special-display-buffer-names))

(defun yank-and-forward-line ()
  "Executes `yank' and moves the cursor one line down from where it initially was."
  (interactive)
  (let ((old-col (current-column)))
    (yank)
    (forward-line)
    (while (and (not (eolp)) (> old-col 0))
      (forward-char)
      (setq old-col (1- old-col)))))
(global-set-key "\C-t" 'yank-and-forward-line)

(defvar toggle-source-func nil
  "Name of function which is called when the using `toggle-source-header'")

;; Switches between source/header files
(defun c++-toggle-source-header()
  "Switches to the source buffer if currently in the header buffer and vice versa."
  (interactive)
  (let ((buf (current-buffer))
	(name (file-name-nondirectory (buffer-file-name)))
	file
	offs)
    (setq offs (string-match c++-header-ext-regexp name))
    (if offs
	(let ((lst c++-source-extension-list)
	      (ok nil)
	      ext)
	  (setq file (substring name 0 offs))
	  (while (and lst (not ok))
	    (setq ext (car lst))
	    (if (file-exists-p (concat file "." ext))
		  (setq ok t))
	    (setq lst (cdr lst)))
	  (if ok
	      (find-file (concat file "." ext))))
      (let ()
	(setq offs (string-match c++-source-ext-regexp name))
	(if offs
	    (let ((lst c++-header-extension-list)
		  (ok nil)
		  ext)
	      (setq file (substring name 0 offs))
	      (while (and lst (not ok))
		(setq ext (car lst))
		(if (file-exists-p (concat file "." ext))
		    (setq ok t))
		(setq lst (cdr lst)))
	      (if ok
		  (find-file (concat file "." ext)))))))))

;; Made by Joe Casadonte (joc)
(defun joc-bounce-sexp ()
  "Will bounce between matching parens just like % in vi"
  (interactive)
  (let ((prev-char (char-to-string (preceding-char)))
	(next-char (char-to-string (following-char))))
	(cond ((string-match "[[{(<]" next-char) (forward-sexp 1))
		  ((string-match "[\]})>]" prev-char) (backward-sexp 1))
		  (t (error "%s" "Not on a paren, brace, or bracket")))))

(global-set-key [(control =)] 'joc-bounce-sexp)

(defun make-makefile()
  "Creates the Makefile from the .pro project file"
  (interactive)
  (let ((project (project-main)))
    (shell-command (project-creation-line  (file-name-nondirectory (buffer-file-name project))))))

;; Finds all functions in a class in a given buffer
;; Creates a list which looks like this.
;; ((classname) func1 func2 ...)
;; where func1 looks like
;; (type1 type2 type3 reference name args)
(defun find-class-functions ( buf )
  (interactive)
  (save-excursion
    (set-buffer buf)
    (beginning-of-buffer)
;;    (message "searching")
    (if (search-forward-regexp (concat "^\\(template[ \t]*<[^>]+>[ \t]*\\)?class[ \t]+\\([a-zA-Z0-9_]+\\)[ \t\n]*"
				       "\\([:][ \t\n]*\\(public\\|protected\\|private\\)?[ \t\n]*\\<[a-zA-Z0-9_]+\\>\\)?"
				       "[ \t\n]*{") nil t)
	(let (start
	      stop
	      (name (match-string-no-properties 2)))
;;	  (message "found first")
	  (setq start (match-end 0))
	  (if ( search-forward "};" nil t)
	      (let ((funclist '()))
		(setq stop (match-beginning 0))
;;		(message "found second")
		(save-restriction
		  (narrow-to-region start stop)
		  (beginning-of-buffer)
		  (while (search-forward-regexp (concat
						 "\\(\\([a-zA-Z_][a-zA-Z0-9_]*\\)[ \t]+\\)?"
						 "\\(\\([a-zA-Z_][a-zA-Z0-9_]*\\)[ \t]+\\)?"
						 "\\(\\([a-zA-Z_][a-zA-Z0-9_]*\\)[ \t]+\\)?"
						 "\\([*&]?\\)[ \t]*"
						 "\\([~]?[a-zA-Z][a-zA-Z0-9_]*\\)[ \t]*"
						 "(\\([^\)]*\\))[ \t]*;")
						nil t)
		    (let (
			  (type1 (match-string-no-properties 2))
			  (type2 (match-string-no-properties 4))
			  (type3 (match-string-no-properties 6))
			  (ref (match-string-no-properties 7))
			  (name (match-string-no-properties 8))
			  (args (match-string-no-properties 9)))
		      (setq funclist (cons (list type1 type2 type3 ref name args) funclist))
		    ))
		  (setq funclist (cons (list name) funclist ))
		  funclist)))))))

;; Removes virtual and static from a type
(defun string-remove-type ( str reg )
  (interactive)
  (let (tmp)
    (if (eq str nil)
	(setq tmp "")
      (if (string-match "\\(virtual\\|static\\)" str)
	  (setq tmp "")
	(if reg
	    (setq tmp (concat str "[ \t]+"))
	  (setq tmp (concat str " ")))))
    tmp))

;; Finds all functions in this buffers class and adds the one's missing from
;; the source file.
(defun expand-class-functions ( buf )
  (interactive)
  (if (string-match c++-header-ext-regexp (buffer-name buf))
      (save-excursion
	(set-buffer buf)
	(let ((lst (find-class-functions buf))
	      item
	      classname)
	  (toggle-source-header)
	  (beginning-of-buffer)
	  (setq classname (car (car lst)))
	  (setq lst (cdr lst))
	  (let (type1 type1_reg
		      type2 type2_reg
		      type3 type3_reg
		      ref ref_reg
		      name
		      args args_reg)
	    (setq lst (nreverse lst))
	    (while lst
	      (setq item (car lst))
	      (setq type1 (car item))
	      (setq item (cdr item))
	      (setq type2 (car item))
	      (setq item (cdr item))
	      (setq type3 (car item))
	      (setq item (cdr item))
	      (setq ref (car item))
	      (setq item (cdr item))
	      (setq name (car item))
	      (setq item (cdr item))
	      (setq args (car item))
	      (setq item (cdr item))
	      (setq type1_reg (string-remove-type type1 t))
	      (setq type2_reg (string-remove-type type2 t))
	      (setq type3_reg (string-remove-type type3 t))
	      (if (eq ref nil)
		  (setq ref_reg "[ \t]*")
		(setq ref_reg (concat "[" ref "]" "[ \t]*")))
	      (setq args_reg (regexp-opt (list args)))
	      (beginning-of-buffer)
	      (if (search-forward-regexp (concat "^" type1_reg type2_reg type3_reg ref_reg
						 classname "::" name "[ \t]*" "(\\([^)]+\\))" ) nil t)
		  (let (args_org
			args_new
			(offs_org 0) (len_org 0)
			(offs_new 0) (len_new 0)
			type1 type2 type3 ref
			(all t)
			(args_reg (concat "\\(\\([a-zA-Z]+\\)[ \t]+\\)?"
					  "\\(\\([a-zA-Z]+\\)[ \t]+\\)?"
					  "\\(\\([a-zA-Z]+\\)[ \t]+\\)?"
					  "\\([&*]\\)?[ \t]*\\([a-zA-Z_][a-zA-Z_]*\\)?\\([ \t]*=[^,]+\\)?")))
		    (setq args_new (match-string 1))
		    (yes-or-no-p "match")
		    (while (and (not offs_org) (not offs_new))
		      (setq offs_org (string-match args_reg args offs_org))
		      (setq type1 (substring args (match-beginning 2) (match-end 2)))
		      (setq type2 (substring args (match-beginning 4) (match-end 4)))
		      (setq type3 (substring args (match-beginning 6) (match-end 6)))
		      (setq ref (substring args (match-beginning 7) (match-end 7)))
;;		      (setq offs_new (string-match args_reg args_new offs_new))
		      (yes-or-no-p (concat type1 ":" type2 ";" type3 ":" ref ))))
		(save-excursion
		  ;;		(message (concat "^" type1_reg type2_reg type3_reg ref_reg
		  ;;				 classname "::" name "[ \t]*" "(" args_reg ")" ))
		    (end-of-buffer)
		    (setq type1_reg (string-remove-type type1 nil))
		    (setq type2_reg (string-remove-type type2 nil))
		    (setq type3_reg (string-remove-type type3 nil))
		    (if (eq ref nil)
			(setq ref_reg "")
		      (setq ref_reg (concat ref)))
		    (if (not (bolp))
			(insert-string "\n"))
					;		(yes-or-no-p "h")
		    (insert-string (concat "\n/*!\n  \n*/\n\n"
					   type1_reg type2_reg type3_reg ref_reg
					   classname "::" name "(" args ")"
					   "\n{\n}\n"))))
	      (setq lst (cdr lst))
	      ))))))

;; Will make sure that the #ifndef and #define that should be present in all c/c++ headers
;; are corrected according their filename.
(defun correct-c-header-define( buf )
  (interactive "b")
  (save-excursion
    (set-buffer buf)
    (if (string-match c++-header-ext-regexp (buffer-name))
	(let ((bufname (buffer-name))
	      defname
	      defstring)
	  (setq defname (concat (upcase (file-name-sans-extension bufname)) "_"
				(upcase (file-name-extension bufname))))
	  (setq defstring (concat
			   "#ifndef " defname "\n"
			   "#define " defname "\n"))
	  (beginning-of-buffer)
	  (if (search-forward-regexp (concat "^#ifndef[ \t]+\\([a-zA-Z_][a-zA-Z0-9_]*\\)[ \t]*[\n]"
					     "#define[ \t]+\\([a-zA-Z_][a-zA-Z0-9_]*\\)[ \t]*[\n]")
				     nil t)
;;	      (if (string-equal (match-string 1) (match-string 2))
	      (replace-match defstring t t ))))))

;; New version, use later
; (defun correct-c-header-define( buf )
;   (interactive "b")
;   (save-excursion
;     (set-buffer buf)
;     (if (string-match "\\.\\(hpp\\|h\\|\hh\\|H\\)$" (buffer-name))
; 	(let* ((bufname (buffer-name))
; 	      (defname (concat (upcase (file-name-sans-extension bufname)) "_"
; 				(upcase (file-name-extension bufname))))
; 	      (defstring (concat
; 			   "#ifndef " defname "\n"
; 			   "#define " defname "\n"))
; 	      (endstring (concat "#endif // " defname)))
; 	  (beginning-of-buffer)
; 	  (if (search-forward-regexp (concat "^#ifndef[ \t]+\\([a-zA-Z_][a-zA-Z0-9_]*\\)[ \t]*[\n]"
; 					     "#define[ \t]+\\([a-zA-Z_][a-zA-Z0-9_]*\\)[ \t]*[\n]")
; 				     nil t)
; 	      (replace-match defstring t t)
; 	    (progn
; 	      (beginning-of-buffer)
; 	      (insert defstring)))
; 	  (if (search-forward-regexp "^#endif[ \t]*//[ \t]*[a-zA-Z_][a-zA-Z0-9_]*[ \t]*$" nil t)
; 	      (replace-match endstring t t)
; 	    (progn
; 	      (end-of-buffer)
; 	      (insert endstring)))))))


;; Tries to set the autoinsert directory, it first checks the wanted directory,
;; then the default, if all fails it sets it to nil.
(defun project-select-autoinsert (&optional dir)
  "Returns a valid directory to be used for autoinserting, if none is valid, nil is returned.

The order of directories tested goes as following:
First if a directory is passed as a param it is tested,
next the `project-auto-insert-directory' is tested
and finally the `default-auto-insert-directory'."
  (cond
   ((cond ((stringp dir) (file-exists-p dir)) (t nil)) dir)
   ((file-exists-p project-auto-insert-directory) project-auto-insert-directory)
   ((file-exists-p default-auto-insert-directory) default-auto-insert-directory)
   (t nil)))

(defun project-create-autoinsert-alist ()
  "Creates an autoinsert-alist which can be used to set the `auto-insert-alist'
it is automaticly created from the list specified in `project-autoinsert-alist'"
  (let (autoinsert-list
	(lst project-autoinsert-alist)
	item)
    (while lst
      (setq item (car lst))
      (setq autoinsert-list (append autoinsert-list (eval item)))
      (setq lst (cdr lst)))
    autoinsert-list))

;; Make sure revive resumes on init
(defun resume-try()
  "Tries to resume a buffer if the file exists and adds `save-current-configuration' if it is loaded"
  (if (file-exists-p revive:configuration-file)
      (let ()
	(resume)
	(add-hook 'kill-emacs-hook 'save-current-configuration))))

(defun auto-store-revive ()
  (if (file-exists-p revive:configuration-file)
      (save-current-configuration)))

; (run-at-time nil 30 'auto-store-revive)

;; Make sure revive don't save it's configuration on exit when wiping
(defun wipe-try()
  "Wipes the revive configuration and removes the `save-current-configuration' from the exit hook"
  (wipe)
  (if (file-exists-p revive:configuration-file)
      (delete-file revive:configuration-file))
  (remove-hook 'kill-emacs-hook 'save-current-configuration))

;; Will align c/c++ variable declarations in the selected region
;; Example:
;; int a;
;; const QString b;
;; static unsigned int c;
;;
;; will become:
;; int                 a;
;; const QString       b;
;; static unsigned int c;
(defun align-vars(beg end)
  "Aligns c/c++ variable declaration names on the same column, with beginning and end taken from selected region."
  (interactive "r")
  (save-excursion
    (let (bol eol expr-end
	  (max-col 0) col
	  poslist curpos)
      (goto-char end)
      (if (not (bolp))
	  (setq end (line-end-position)))
      (goto-char beg)
      (while (and (> end (point)) (not (eobp)))
	(setq bol (line-beginning-position))
	(setq eol (line-end-position))
	(beginning-of-line)
	(setq expr-end (point))
	(if (search-forward-regexp "^[^/][^/]\\([a-zA-Z][a-zA-Z]*\\)[ \t]+[^;]" eol t)
	    (let ()
	      (setq expr-end (match-end 1))
	      (while (search-forward-regexp "\\([a-zA-Z][a-zA-Z]*\\)[ \t]+[^;]" eol t)
		(setq expr-end (match-end 1)))
	      (goto-char expr-end)
	      (setq col (current-column))
	      (if (search-forward-regexp (concat "\\(\\*\\|&[ \t]*\\)?"
						 "\\([a-zA-Z\\_][a-zA-Z0-9\\_]*\\)\\([\[][0-9]+[\]]\\)?"
						 "\\([ \t]*,[ \t]*\\([a-zA-Z\\_][a-zA-Z0-9\\_]*\\)\\([\[][0-9]+[\]]\\)?\\)*"
						 "[ \t]*;$") eol t)
		  (let ((name-col-end 0))
		    (if (eq (match-beginning 2) (match-beginning 0))
			(setq name-col-end 1))
		    (setq poslist (cons (list expr-end col (match-beginning 0) name-col-end) poslist))
		    (if (> col max-col)
			(setq max-col col))
		    (beginning-of-next-line))
		(beginning-of-next-line)))
	  (beginning-of-next-line)))
      (setq curpos poslist)
      (while curpos
	(let* ((pos (car curpos))
	       (col (car (cdr pos)))
	       (col-end (car (cdr (cdr pos))))
	       (col-end-name (car (cdr (cdr (cdr pos)))))
	       (abs-pos (car pos)))
	  (goto-char abs-pos)
	  (delete-region abs-pos col-end)
	  (insert-string (make-string (+ (+ (- max-col col) 1) col-end-name) 32)))
	(setq curpos (cdr curpos))))))

;; Use the align package from ... instead
(if (emacs-type-is-regular)
    (require 'align nil t)
  (require 'align))

;; Aligns all variable declarations in this buffer
(defun align-vars-buffer()
  "Aligns c/c++ variable declaration names on the same column in this buffer."
  (interactive)
  (save-excursion
    (let (beg end)
      (beginning-of-buffer)
      (setq beg (point))
      (end-of-buffer)
      (setq end (point))
      (align-vars beg end))))

;; Jump to beginning of the next line if possible.
(defun beginning-of-next-line()
  "Moves cursor to the beginning of the next line, or nowhere if at end of the buffer"
  (interactive)
  (end-of-line)
  (if (not (eobp))
      (forward-char 1)))

;; Load default variables
(load-file-module "vars")

;; Load the keys file
(load-file-module "keys")

(defvar php-extension-list (list (cons project-php-source-ext 'php-toggle-from-source)
				 (cons project-php-template-ext 'php-toggle-from-template)
				 (cons project-php-language-ext 'php-toggle-from-language)))

(defun file-name-without-extension (file ext)
  (if (string-match (concat "^\\(.+\\)\\." ext "$") file)
      (substring file (match-beginning 1) (match-end 1))
    file))

(defvar project-php-template-style "standard")
(defvar project-php-language "en_GB")

(defun php-toggle-from-source()
  "Toggle from PHP source file to eZ publish template file"
  (interactive)
  (let* ((buf (current-buffer))
	 (name (file-name-nondirectory (buffer-file-name)))
	 (plain (file-name-without-extension name project-php-source-ext))
	 (dir (file-name-directory (buffer-file-name)))
	 (source (concat dir "templates/" project-php-template-style "/" plain "." project-php-template-ext)))
    (if (file-exists-p source)
	(find-file source))))

(defun php-toggle-from-template()
  "Toggle from eZ publish template file to eZ publish language file"
  (interactive)
  (let* ((buf (current-buffer))
	 (name (file-name-nondirectory (buffer-file-name)))
	 (plain (file-name-without-extension name project-php-template-ext))
	 (dir (file-name-directory (buffer-file-name)))
	 (source (concat dir "../../intl/" project-php-language "/" plain "." project-php-language-ext)))
    (if (file-exists-p source)
	(find-file source))))

(defun php-toggle-from-language()
  "Toggle from eZ publish language file to PHP source file"
  (interactive)
  (let* ((buf (current-buffer))
	 (name (file-name-nondirectory (buffer-file-name)))
	 (plain (file-name-without-extension name project-php-language-ext))
	 (dir (file-name-directory (buffer-file-name)))
	 (source (concat dir "../../" plain "." project-php-source-ext)))
    (if (file-exists-p source)
	(find-file source))))

;; Switches between source/header files
(defun php-toggle-sources()
  "Switches to between the related files in a PHP (eZ publish) session"
  (interactive)
  (let ((name (file-name-nondirectory (buffer-file-name)))
	(exts php-extension-list))
    (while (and exts
		(not (if (string-match (concat "\\." (car (car exts)) "$") name)
			 (eval (list (cdr (car exts)))))))
      (setq exts (cdr exts)))))

(defun toggle-source-header()
  (interactive)
  (let ((func (or toggle-source-func
		  'c++-toggle-source-header)))
    (eval (list func))))

(make-variable-buffer-local 'toggle-source-func)

(defun option-save-to-file (&optional file) 
  "Save all options from `option-save-alist' to `option-config-file',
each list item is evaluated and the result added to the save buffer"
  (let* ((old-buffer (current-buffer))
	(loadfile (cond
		   (file file)
		   (t option-config-file)))
        (optionbuffer (find-file-noselect loadfile t t))
	(varlst nil))
    (switch-to-buffer optionbuffer)
    (if (> (buffer-size) 0)
        (delete-region 1 (buffer-size)))
    (insert (concat ";; -*- Mode: Emacs-Lisp -*-\n;; -*- lisp -*-\n"
		    ";---------------------------------------------------------------------\n"
		    ";; This file is automaticly generated, please do not modify\n"
		    ";; Version "
		    (option-config-version) "\n"))
    (insert "(progn")
    (mapcar (lambda (x)
              (if x
		  (if (listp x)
		      (progn
			(insert "\n  ")
			(insert (eval x)))
		    (setq varlst (cons x varlst)))))
            option-save-alist)
    (insert ")\n\n")
    (if varlst
	(progn
	  (insert "(setq")
	  (mapcar (lambda (x)
		    (if x
			(if (boundp x)
			  (progn
			    (insert "\n ")
			    (prin1 x optionbuffer)
			    (insert " '")
			    (prin1 (eval x) optionbuffer)))))
		  varlst)
	  (insert ")\n")))
    (option-config-validate)
    (basic-save-buffer)
    (kill-buffer optionbuffer)
    (switch-to-buffer old-buffer)))

(defun option-save-to-file-locally ()
  "Save all options from `option-save-alist' to `option-local-config-file',
each list item is evaluated and the result added to the save buffer"
  (option-save-to-file (concat (option-local-config-dir) option-local-config-file)))

(defun option-load-from-file (&optional file)
  "Load all options from `option-config-file' and evaluate them."
  (let ((loadfile (cond
		   (file file)
		   (t option-config-file))))
    (option-config-validate)
    (if (file-exists-p loadfile)
	(progn
	  (load-file loadfile)
	  t)
      nil)))

(defun option-local-config-dir ()
  (if option-local-config-dir-func
      (eval option-local-config-dir-func)
    "./"))

(defun project-local-config-dir ()
  "./")
;   (let ((main (project-main)))
;     (file-name-directory (buffer-file-name main))))

(defun option-load-from-file-locally ()
  "Load all options from `option-local-config-file' and evaluate them."
  (option-load-from-file (concat (option-local-config-dir) option-local-config-file)))
      
(defun option-config-validate ()
  "Makes sure the `option-config-dirty' flag is cleared (nil)."
  (setq option-config-dirty nil))

(defun option-config-invalidate ()
  "Makes sure the `option-config-dirty' flag is set (t),
call this if you have changed an option which is to be saved in the `option-config-file' or `option-local-config-file'."
  (setq option-config-dirty t))

(defun option-line-smooth-scroll()
  "Returns a string, dependening on wheter `option-smooth-scroll' is enabled,
which is stored by `option-save-to-file'."
  (let (tmp)
    (if option-smooth-scroll
	(setq tmp (concat "(option-smooth-scroll-enable t)"))
      (setq tmp (concat "(option-smooth-scroll-enable nil)")))
    tmp))

(defun option-smooth-scroll-enable (enable)
  "Turns on smooth keyboard scrolling if ENABLE is non-nil and updates `option-smooth-scroll'."
  (if enable
      (setq scroll-margin '0
	    scroll-step '1)
    (setq scroll-margin '2
	  scroll-step '1))
  (option-config-invalidate)
  (setq option-smooth-scroll enable))

(defun option-smooth-scroll-toggle ()
  "Toggles smooth keyboard scrolling, see `option-smooth-scroll-enable' for information."
  (option-smooth-scroll-enable (not option-smooth-scroll)))

(defun option-load-package (pkg)
  "Tries to load a specific package and set a flag it succeeds,
PKG contains (NAME AVAIL LOADED INIT EXIT), where
NAME is the name of the package,
AVAIL is the name of the availability variable,
and LOADED is the name of the loaded variable."
  (let ((avail (eval (cadr pkg)))
	(name-var (car pkg))
	fname-var
	(load-var (caddr pkg)))
    (if (listp name-var)
	(progn
	  (setq fname-var (cadr name-var))
	  (setq name-var (car name-var)))
      (setq fname-var name-var))
    (if avail
	(if (or (not name-var) (require-if name-var))
 	    (progn
 	      (set load-var 't)
 	      (if (cadr (cdr (cdr pkg)))
		  (eval (cadr (cdr (cdr pkg)))))
	      t)
	  nil)
      nil)))

(defun option-unload-package (pkg)
  "Tries to unload a specific package and set a flag it succeeds,
PKG contains (NAME AVAIL LOADED INIT EXIT), where
NAME is the name of the package,
AVAIL is the name of the availability variable,
and LOADED is the name of the loaded variable."
  (let ((avail (eval (cadr pkg)))
	(name-var (car pkg))
	fname-var
	(load-var (caddr pkg)))
    (if (listp name-var)
	(progn
	  (setq fname-var (cadr name-var))
	  (setq name-var (car name-var)))
      (setq fname-var name-var))
    (if avail
	(progn
	  (set load-var 'nil)
	  (if (cadr (cdr (cdr (cdr pkg))))
	      (eval (cadr (cdr (cdr (cdr pkg))))))
	  t)
      nil)))


(defun option-check-packages ()
  (let ()
    (mapcar (lambda (x)
	      (option-check-package (eval x)))
	    option-package-available-alist)))

(defun option-check-package (pkg)
  (let ((dirlst load-path)
	(found nil)
	file
	(avail (cadr pkg))
	(name (car pkg))
	fname)
    (if (listp name)
	(progn
	  (setq fname (cadr name))
	  (setq name (car name)))
      (setq fname name))
    (if name
	(progn
	  (while (and dirlst (not found))
	    (setq file (concat (car dirlst) "/" (prin1-to-string fname) ".el"))
	    (if (file-exists-p file)
		(setq found t))
	    (setq dirlst (cdr dirlst)))
	  (set avail found)
	  found)
      (progn
	(set avail t)
	t))))

(defun option-package-start-rect-mark ()
  (autoload 'rm-set-mark "rect-mark"
    "Set mark for rectangle." t)
  (autoload 'rm-exchange-point-and-mark "rect-mark"
    "Exchange point and mark for rectangle." t)
  (autoload 'rm-kill-region "rect-mark"
    "Kill a rectangular region and save it in the kill ring." t)
  (autoload 'rm-kill-ring-save "rect-mark"
    "Copy a rectangular region to the kill ring." t)
  (autoload 'rm-mouse-drag-region "rect-mark"
    "Drag out a rectangular region with the mouse." t)
  (option-enable-keys 'option-keys-rect-mark-alist))

(defun option-package-end-rect-mark ()
  (option-disable-keys 'option-keys-rect-mark-alist))

(defun option-package-start-blank-mode ()
  (autoload 'blank-mode-on        "blank-mode"
    "Turn on blank visualization."   t)
  (autoload 'blank-mode-off       "blank-mode"
    "Turn off blank visualization."  t)
  (autoload 'blank-mode           "blank-mode"
    "Toggle blank visualization."    t)
  (autoload 'blank-mode-customize "blank-mode"
    "Customize blank visualization." t)
  (blank-mode-on))

(defun option-package-end-blank-mode ()
  (blank-mode-off))

(defun option-package-start-revive ()
  (autoload 'save-current-configuration "revive" "Save status" t)
  (autoload 'resume "revive" "Resume Emacs;; " t)
  (autoload 'wipe "revive" "Wipe Emacs" t)
  ;; Make sure the configuration is saved in a local directory
  (setq revive:configuration-file ".revive.el")
  ;; This is needed to avoid that the save-history buffer is revived as well
  (setq revive:ignore-buffer-pattern "^\\( \\*\\)\\|\\(\\.emacs-histories\\)")
  ;; Save on exit is optional, uncomment to always enable
  ;; (add-hook 'kill-emacs-hook 'save-current-configuration)
  (add-hook 'after-init-hook 'resume-try)
  (option-enable-keys 'option-keys-revive-alist))

(defun option-package-end-revive ()
  (remove-hook 'after-init-hook 'resume-try)
  (option-disable-keys 'option-keys-revive-alist))

(defun option-save-history-toggle ()
  "Toggles the automatic saving of history between sessions"
  (if option-save-history-flag
      (option-save-history-enable nil)
    (option-save-history-enable t)))

(defun option-save-history-enable (enable)
  (if enable
      (progn
	(add-hook 'after-init-hook 'save-history-load)
	(add-hook 'kill-emacs-hook 'save-history-save)
	(setq option-save-history-flag t)
	(option-config-invalidate))
    (progn
      (remove-hook 'after-init-hook 'save-history-load)
      (remove-hook 'kill-emacs-hook 'save-history-save)
      (setq option-save-history-flag nil)
      (option-config-invalidate))))

(defun option-enable-keys (keys)
  "Turns on all keys in the list,
the contents of KEYS is a list of MAPPINGs,
the first entry is used for storing the old keys,
each MAPPING looks like (KEYMAP KEY DEF)."
;; use (lookup-key) too find keys
  (let ((lst (eval keys)))
    (setq lst (cdr lst))
    (mapcar (lambda (x)
	      (define-key (eval (car x)) (cadr x) (caddr x)))
	    lst)))

(defun option-disable-keys (keys)
  "Turns off all keys in the list,
the contents of KEYS is a list of MAPPINGs,
the first entry is used for storing the old keys,
each MAPPING looks like \(KEYMAP KEY DEF\)."
  (mapcar (lambda (x)
	    (define-key (eval (car x)) (cadr x) nil))
	  (cdr (eval keys))))

(defun option-popup-contents ()
  "Creates the content for a popup menu,
the popup menu is used to inform the user of the first time use."
  (list (concat "          This seems to be your first time
      running version " (option-config-version) " of the emacs config.
           Most options are now turned off.
 Do you wish to save a default global configuration?
\(You can change the default options by changing items
in the Options menu and then selecting save global\)") '("OK" . t) '("Cancel" . nil)))

; Try to load the default global configuration file, if it fails ask
; the user what to do.
; The console variant must be implemented as well as NT and Mac specifics
(if (not (option-load-from-file))
    (let ((cont (option-popup-contents))
	  (type (emacs-type)))
      (if (cond
	   ((eq type 'emacs-window)
	    (x-popup-dialog t cont))
	   ((eq type 'xemacs-window)
	    (get-dialog-box-response t cont)))
	  (option-save-to-file))))

; ;; Try to load the default global configuration file, if it fails ask
; ;; the user what to do.
; (if (not (option-load-from-file))
;     (if (x-popup-dialog t (list (concat "          This seems to be your first time
;       running version " (option-config-version) " of the emacs config.
;            Most options are now turned off.
;  Do you wish to save a default global configuration?
; \(You can change the default options by changing items
; in the Options menu and then selecting save global\)") '("OK" . t) '("Cancel" . nil)))
; 	(option-save-to-file)))

;; Next try the local configuration file.
(option-load-from-file-locally)

(option-check-packages)

;; Load the customization file
(load-file-module "custom")

;; Load default project
(load-file-module "project")

;; Load default classes
(load-file-module "classes")

;; Count words in buffer
(defun count-words-buffer ()
  "Count the number of words in current the buffer
print a message in the minibuffer with the result."
  (interactive)
  (save-excursion
    (let ((count 0))
      (goto-char (point-min))
      (while (< (point) (point-max))
	(forward-word 1)
	(setq count (1+ count)))
      (message "buffer contains %d words." count))))


(defun config-menu (modestr)
  (let ((m
	 '(
	   ("Project"
	    ["Automatic Insert Include"
	     (progn (setq c++-auto-include-add (not c++-auto-include-add)) (option-config-invalidate))
	     :style toggle
	     :selected c++-auto-include-add]
	    ["Automatic Remove Include"
	     (progn (setq c++-auto-include-remove (not c++-auto-include-remove)) (option-config-invalidate))
	     :style toggle
	     :selected c++-auto-include-remove]
	    ["Ask Before Loading Project"
	     (progn (setq project-ask-load (not project-ask-load)) (option-config-invalidate))
	     :style toggle
	     :selected project-ask-load]
	    ["Use Project Auto Insertion"
	     (progn (setq project-use-auto-insert (not project-use-auto-insert)) (option-config-invalidate))
	     :style toggle
	     :selected project-use-auto-insert]
	    "---"
	    ["Delete Removed Classes"
	     (progn (setq project-delete-redundant (not project-delete-redundant)) (option-config-invalidate))
	     :style toggle
	     :selected project-delete-redundant]
	    ["Confirm Deletion of Removed Classes"
	     (progn (setq project-delete-confirm (not project-delete-confirm)) (option-config-invalidate))
	     :style toggle
	     :active project-delete-redundant
	     :selected project-delete-confirm]
	    )
	   ("General"
	    ["Smooth scrolling"
	     (option-smooth-scroll-toggle)
	     :style toggle
	     :selected option-smooth-scroll]
	    )
	   ("Packages"
	    ["ibuffer"
	     (if option-package-load-ibuffer
		 (option-unload-package option-package-ibuffer)
	       (option-load-package option-package-ibuffer))
	     :style toggle
	     :active option-package-available-ibuffer
	     :selected option-package-load-ibuffer]
	    ["CUA (Cut/Copy/Paste/Undo)"
	     (if option-package-load-CUA
		 (option-unload-package option-package-CUA)
	       (option-load-package option-package-CUA))
	     :style toggle
	     :active option-package-available-CUA
	     :selected option-package-load-CUA]
	    ["IDO Buffer/File switching"
	     (if option-package-load-ido
		 (option-unload-package option-package-ido)
	       (option-load-package option-package-ido))
	     :style toggle
	     :active option-package-available-ido
	     :selected option-package-load-ido]
	    ["Blank"
	     (if option-package-load-blank-mode
		 (option-unload-package option-package-blank-mode)
	       (option-load-package option-package-blank-mode))
	     :style toggle
	     :active option-package-available-blank-mode
	     :selected option-package-load-blank-mode]
	    ["BBDB"
	     (if option-package-load-bbdb
		 (option-unload-package option-package-bbdb)
	       (option-load-package option-package-bbdb))
	     :style toggle
	     :active option-package-available-bbdb
	     :selected option-package-load-bbdb]
	    ["Clipper"
	     (if option-package-load-clipper
		 (option-unload-package option-package-clipper)
	       (option-load-package option-package-clipper))
	     :style toggle
	     :active option-package-available-clipper
	     :selected option-package-load-clipper]
	    ["Mouse Wheel Support"
	     (if option-package-load-mwheel
		 (option-unload-package option-package-mwheel)
	       (option-load-package option-package-mwheel))
	     :style toggle
	     :active option-package-available-mwheel
	     :selected option-package-load-mwheel]
	    ["Blinking Cursor"
	     (if option-package-load-blinking-cursor
		 (option-unload-package option-package-blinking-cursor)
	       (option-load-package option-package-blinking-cursor))
	     :style toggle
	     :active option-package-available-blinking-cursor
	     :selected option-package-load-blinking-cursor]
	    ["Recent Files"
	     (if option-package-load-recentf
		 (option-unload-package option-package-recentf)
	       (option-load-package option-package-recentf))
	     :style toggle
	     :active option-package-available-recentf
	     :selected option-package-load-recentf]
	    ["Rectangle Mark"
	     (if option-package-load-rect-mark
		 (option-unload-package option-package-rect-mark)
	       (option-load-package option-package-rect-mark))
	     :style toggle
	     :active option-package-available-rect-mark
	     :selected option-package-load-rect-mark]
	    ["Revive"
	     (if option-package-load-revive
		 (option-unload-package option-package-revive)
	       (option-load-package option-package-revive))
	     :style toggle
	     :active option-package-available-revive
	     :selected option-package-load-revive]
	    ["Java Development Enviroment"
	     (if option-package-load-jde
		 (option-unload-package option-package-jde)
	       (option-load-package option-package-jde))
	     :style toggle
	     :active option-package-available-jde
	     :selected option-package-load-jde]
	    ["Save History"
	     (if option-package-load-save-history
		 (option-unload-package option-package-save-history)
	       (option-load-package option-package-save-history))
	     :style toggle
	     :active option-package-available-save-history
	     :selected option-package-load-save-history]
	    ["Speedbar"
	     (if option-package-load-speedbar
		 (option-unload-package option-package-speedbar)
	       (option-load-package option-package-speedbar))
	     :style toggle
	     :active option-package-available-speedbar
	     :selected option-package-load-speedbar]
	    ["Completion"
	     (if option-package-load-completion
		 (option-unload-package option-package-completion)
	       (option-load-package option-package-completion))
	     :style toggle
	     :active option-package-available-completion
	     :selected option-package-load-completion]
	    ["Auto Revert"
	     (if option-package-load-autorevert
		 (option-unload-package option-package-autorevert)
	       (option-load-package option-package-autorevert))
	     :style toggle
	     :active option-package-available-autorevert
	     :selected option-package-load-autorevert]
	    ["Highlight Line"
	     (if option-package-load-line-highlight
		 (option-unload-package option-package-line-highlight)
	       (option-load-package option-package-line-highlight))
	     :style toggle
	     :active option-package-available-line-highlight
	     :selected option-package-load-line-highlight]
	    )
; 	   ("Package options"
; 	    ["CUA (Cut/Copy/Paste/Undo)"
; 	     (option-smooth-scroll-toggle)
; 	     :style toggle
; 	     :active option-package-available-CUA
; 	     :selected option-smooth-scroll]
; 	    ["Mouse Wheel Support"
; 	     (progn (setq do-require-mwheel (not do-require-mwheel)) (option-config-invalidate))
; 	     :style toggle
; 	     :active option-package-available-mwheel
; 	     :selected do-require-mwheel]
; 	    ["Blinking Cursor"
; 	     (progn (if blinking-cursor-mode (blinking-cursor-mode -1) (blinking-cursor-mode 1)) (option-config-invalidate))
; 	     :style toggle
; 	     :active (require 'blinking-cursor nil t)
; 	     :selected blinking-cursor-mode]
; 	    ["Recent Files"
; 	     (progn (if recentf-mode (recentf-mode -1) (recentf-mode 1)) (option-config-invalidate))
; 	     :style toggle
; 	     :active (require 'recentf nil t)
; 	     :selected recentf-mode]
; 	    ["Save History"
; 	     (option-save-history-toggle)
; 	     :style toggle
; 	     :active (require 'save-history nil t)
; 	     :selected option-save-history-flag]
; 	    )
	   "---"
	   ("Session"
	    ["Save"
	     (save-current-configuration)
	     :active option-package-load-revive]
	    ["Restore"
	     (resume-try)
	     :active option-package-load-revive]
	    ["Wipe"
	     (wipe-try)
	     :active option-package-load-revive])
	   ["ibuffer"
	    (ibuffer)
	    :active option-package-load-ibuffer]
	   ["Start gnuserv"
	    (gnuserv-start)]
	   "---"
	   ["Save global"   (option-save-to-file) t]
	   ["Save"          (option-save-to-file-locally) t]
	   ["Revert global" (option-load-from-file) t]
	   ["Revert"        (option-load-from-file-locally) t]
	   )))
    (cons modestr m)))

(let ((option-name (cond ((emacs-type-is-regular) "Options")
			 (t "EOptions"))))
  (easy-menu-define config-symbol-menu lisp-interaction-mode-map "General options"
		    (config-menu option-name))
  (easy-menu-add (config-menu option-name))

  (easy-menu-define config-symbol-menu emacs-lisp-mode-map "General options"
		    (config-menu option-name))
  (easy-menu-add (config-menu option-name)))


; Reads in an abbrev file if it exists
; C-x a i g to create an abbrev
(if (file-exists-p abbrev-file-name)
    (read-abbrev-file))

;; Jumps to next buffer in the bufferlist, consecutive uses will browse trough all your buffers
(defun switch-to-next-buffer()
  "Jumps to next buffer in the buffer list, or the beginning of the list if at the end"
  (interactive)
  (let ((cur (current-buffer))
	(ok t))
    ;; Find current buffer in list
    (while (and cur ok)
      (setq cur (next-buffer cur (current-buffer)))
      (if cur
	  (if (buffer-allowed cur)
	      (setq ok nil))))
    (if (and cur (not ok))
	(switch-to-buffer cur t))))

;; Jumps to next buffer in the bufferlist, consecutive uses will browse trough all your buffers
(defun next-buffer(buf orig)
  "Jumps to next buffer in the buffer list, or the beginning of the list if at the end"
  (interactive)
  (let ((lst (buffer-list))
	nxt
	cur)
    ;; Find current buffer in list
    (while (and lst (not (eq buf (car lst))))
      (setq cur (car lst))
      (setq lst (cdr lst)))
    ;; Get next
    (setq nxt (car (cdr lst)))
    (if (eq nxt orig)
	nil)
    ;; If zero get first.
    (if nxt
	()
      (setq nxt (car (buffer-list))))
    nxt))

(defun buffer-allowed( buf )
  (interactive)
  (let ((incs buffer-include-regexp)
	inc
	(bname (buffer-name buf))
	(allow nil))
    (while (and incs (not allow))
      (setq inc (car incs))
      (if (string-match inc bname)
	  (setq allow t))
      (setq incs (cdr incs)))
    (if allow
	(let ((exs buffer-exclude-regexp)
	      ex)
	  (while (and exs allow)
	    (setq ex (car exs))
	    (if (string-match ex bname)
		(setq allow nil))
	    (setq exs (cdr exs)))
	  allow)
      allow)))

;; make backup files in ~/.backups/ rather than scattered around all
;; over the filesystem.
(if (>= emacs-major-version 21)
    (progn
;      (setq make-backup-file-name-function 'make-backup-file-name)
;      (setq backup-directory-alist '((".*" . "/home/amos/src/")))
      )
  (progn
    (defun make-backup-file-name (file-name)
      "Create the non-numeric backup file name for `file-name'."
      (require 'dired)
      (if (file-exists-p "~/.backups")
	  (concat (expand-file-name "~/.backups/")
		  (dired-replace-in-string "/" "|" file-name))
	(concat file-name "~")))))

;; disable backups for files in /tmp or in my Mail or News directories.     
(defun ecm-backup-enable-predicate (filename)
  (and (not (string= "/tmp/" (substring filename 0 5)))           
       (not (string-match "/Mail/" filename))           
       (not (string-match "/News/" filename))))        

(setq backup-enable-predicate 'ecm-backup-enable-predicate)


; This doesn't seem to work:
(setq auto-save-directory (expand-file-name "~/.autosaves/"))

; This gives error when trying ispell
;(setq ispell-dictionary "/usr/lib/ispell/norsk.hash")

;---------------------------------------------------------------------
; C++ mode modifications
;

;; Add project menu to the mode first started in emacs
(easy-menu-define project-menu lisp-interaction-mode-map "C++ Project Commands"
		  (c-project-menu "Project"))
(easy-menu-add (c-project-menu "Project"))


;; Define a new regexp for font-lock-mode
;; DONT'T MESS WITH IT
(if (emacs-type-is-regular)
    (progn
      (defconst c++-new-font-lock-keywords
	'(
	  ("\\<[0-9]+\\.[0-9]+\\>" (0 font-lock-floatnumber-face))
	  ("^#[ 	]*error[ 	]+\\(.+\\)"
	   (1 font-lock-warning-face prepend))
	  ("^#[ 	]*\\(import\\|include\\)[ 	]*\\(<[^>\"\n]*>?\\)"
	   (2 font-lock-string-face))
	  ("^#[ 	]*define[ 	]+\\(\\sw+\\)("
	   (1 font-lock-function-name-face))
	  ("^#[ 	]*\\(elif\\|if\\)\\>"
	   ("\\<\\(defined\\)\\>[ 	]*(?\\(\\sw+\\)?" nil nil
	    (1 font-lock-builtin-face)
	    (2 font-lock-variable-name-face nil t)))
	  ("^#[ 	]*\\(\\sw+\\)\\>[ 	!]*\\(\\sw+\\)?"
	   (1 font-lock-builtin-face)
	   (2 font-lock-variable-name-face nil t))
	  ("\\<\\(public\\|private\\|protected\\)\\>[ \t]+\\(\\<\\(signals\\|slots\\)\\>\\)[ \t]*:"
	   (1 font-lock-type-face)
	   (2 font-lock-type-face)
	   )
	  ("\\<\\(class\\|public\\|private\\|protected\\|typename\\|signals\\|slots\\)\\>[ 	]*\\(\\(\\sw+\\)\\>\\([ 	]*<\\([^>\n]+\\)[ 	*&]*>\\)?\\([ 	]*::[ 	*~]*\\(\\sw+\\)\\)*\\)?"
	   (1 font-lock-type-face)
	   (3
	    (if
		(match-beginning 6)
		font-lock-type-face font-lock-function-name-face)
	    nil t)
	   (5 font-lock-function-name-face nil t)
	   (7 font-lock-function-name-face nil t))
	  ("^\\(\\sw+\\)\\>\\([ 	]*<\\([^>\n]+\\)[ 	*&]*>\\)?\\([ 	]*::[ 	*~]*\\(\\sw+\\)\\)*[ 	]*("
	   (1
	    (if
		(or
		 (match-beginning 2)
		 (match-beginning 4))
		font-lock-type-face font-lock-function-name-face))
	   (3 font-lock-function-name-face nil t)
	   (5 font-lock-function-name-face nil t))
	  ("\\<\\(auto\\|bool\\|c\\(har\\|o\\(mplex\\|nst\\)\\)\\|double\\|e\\(num\\|x\\(p\\(licit\\|ort\\)\\|tern\\)\\)\\|f\\(loat\\|riend\\)\\|in\\(line\\|t\\)\\|long\\|mutable\\|namespace\\|register\\|s\\(hort\\|igned\\|t\\(atic\\|ruct\\)\\)\\|t\\(emplate\\|ypedef\\)\\|u\\(n\\(ion\\|signed\\)\\|sing\\)\\|v\\(irtual\\|o\\(id\\|latile\\)\\)\\|JBF[a-zA-Z0-9]+\\|eZ[a-zA-Z0-9_]+\\|Q[A-Z][a-zA-Z_]*\\|Q[a-z][A-Z][a-zA-Z_]*\\|uint\\|ulong\\|string\\)\\>"
	   (0 font-lock-type-face))
	  ("\\<\\(operator\\)\\>[ 	]*\\(!=\\|%=\\|&[&=]\\|()\\|\\*=\\|\\+[+=]\\|-\\(>\\*\\|[=>-]\\)\\|/=\\|<\\(<=\\|[<=]\\)\\|==\\|>\\(>=\\|[=>]\\)\\|\\[\\]\\|\\^=\\||[=|]\\|[!%&*+,/<=>|~^-]\\)?"
	   (1 font-lock-keyword-face)
	   (2 font-lock-builtin-face nil t))
	  ("\\<\\(case\\|goto\\)\\>[ 	]*\\(-?\\sw+\\)?"
	   (1 font-lock-keyword-face)
	   (2 font-lock-constant-face nil t))
	  (":"
	   ("^[ 	]*\\(\\sw+\\)[ 	]*:\\($\\|[^:]\\)"
	    (beginning-of-line)
	    (end-of-line)
	    (1 font-lock-constant-face)))
	  ("\\<\\(asm\\|break\\|c\\(atch\\|on\\(st_cast\\|tinue\\)\\)\\|d\\(elete\\|o\\|ynamic_cast\\)\\|else\\|for\\|if\\|new\\|re\\(interpret_cast\\|turn\\)\\|s\\(izeof\\|tatic_cast\\|witch\\)\\|t\\(h\\(is\\|row\\)\\|ry\\)\\|while\\)\\>"
	   (0 font-lock-keyword-face))
	  ("\\<\\(false\\|true\\)\\>"
	   (0 font-lock-constant-face))
	  ("\\<\\(auto\\|bool\\|c\\(har\\|o\\(mplex\\|nst\\)\\)\\|double\\|e\\(num\\|x\\(p\\(licit\\|ort\\)\\|tern\\)\\)\\|f\\(loat\\|riend\\)\\|in\\(line\\|t\\)\\|long\\|mutable\\|namespace\\|register\\|s\\(hort\\|igned\\|t\\(atic\\|ruct\\)\\)\\|t\\(emplate\\|ypedef\\)\\|u\\(n\\(ion\\|signed\\)\\|sing\\)\\|v\\(irtual\\|o\\(id\\|latile\\)\\)\\|JBF[a-zA-Z0-9_]*\\|eZ[a-zA-Z0-9_]*\\|Q[a-zA-Z_]*\\|uint\\|ulong\\|string\\)\\>\\([ 	]*<\\([^>\n]+\\)[ 	*&]*>\\)?\\([ 	]*::[ 	*~]*\\(\\sw+\\)\\)*\\([ 	*&]+\\(\\sw+\\)\\>\\([ 	]*<\\([^>\n]+\\)[ 	*&]*>\\)?\\([ 	]*::[ 	*~]*\\(\\sw+\\)\\)*\\)*"
	   (font-lock-match-c++-style-declaration-item-and-skip-to-next
	    (goto-char
	     (or
	      (match-beginning 20)
	      (match-end 1)))
	    (goto-char
	     (match-end 1))
	    (1
	     (cond
	      ((or
		(match-beginning 2)
		(match-beginning 4))
	       font-lock-type-face)
	      ((match-beginning 6)
	       font-lock-function-name-face)
	      (t font-lock-variable-name-face)))
	    (3 font-lock-function-name-face nil t)
	    (5
	     (if
		 (match-beginning 6)
		 font-lock-function-name-face font-lock-variable-name-face)
	     nil t)))
	  ("\\(}\\)[ 	*]*\\sw"
	   (font-lock-match-c++-style-declaration-item-and-skip-to-next
	    (goto-char
	     (match-end 1))
	    nil
	    (1
	     (if
		 (match-beginning 6)
		 font-lock-function-name-face font-lock-variable-name-face))))
	  ("^\\(\\(\\sw+\\)\\>\\([ 	]*<\\([^>\n]+\\)[ 	*&]*>\\)?\\([ 	]*::[ 	*~]*\\(\\sw+\\)\\)*[ 	*&]*\\)+"
	   (font-lock-match-c++-style-declaration-item-and-skip-to-next
	    (goto-char
	     (match-beginning 1))
	    (goto-char
	     (match-end 1))
	    (1
	     (cond
	      ((or
		(match-beginning 2)
		(match-beginning 4))
	       font-lock-type-face)
	      ((match-beginning 6)
	       font-lock-function-name-face)
	      (t font-lock-variable-name-face)))
	    (3 font-lock-function-name-face nil t)
	    (5
	     (if
		 (match-beginning 6)
		 font-lock-function-name-face font-lock-variable-name-face)
	     nil t)))
	  ("[{}()<>=;:+\\*\\/\\[]\\|\\]\\|\\-" (0 font-lock-keys-face))
	  ("\\<[0-9]+\\>" (0 font-lock-number-face))
	  ("\\<0x[0-9a-fA-F]+\\>" (0 font-lock-hexnumber-face))
					;     ((concat "\\<"
; 	     (regexp-opt '("Q_OBJECT" "emit" "connect" "disconnect" "SIGNAL" "SLOT" "Q_EXPORT"))
					; 	     "\\>" )
					;      (0 font-lock-qt-face))
	  ("\\<\\(Q_\\(EXPORT\\|OBJECT\\|PROPERTY\\)\\|S\\(IGNAL\\|LOT\\)\\|connect\\|disconnect\\|emit\\)\\>"
	   (0 font-lock-qt-face))
	  ))
      (defconst my-c++-font-lock
	'(
	  ("\\<[0-9]+\\.[0-9]+\\>" (0 font-lock-floatnumber-face))
;; 	  ("eZ[a-zA-Z0-9_]*\\|Q[a-zA-Z_]*" (0 font-lock-variable-name-face t))
;;   	  ("[{}()<>=;:+&\\*\\/\\[]\\|\\]\\|\\-" (0 font-lock-keys-face t))
  	  ("[{}()=;:+&\\[]\\|\\]\\|\\-" (0 font-lock-keys-face t))
	  ("\\<[0-9]+\\>" (0 font-lock-number-face))
	  ("\\<0x[0-9a-fA-F]+\\>" (0 font-lock-hexnumber-face))
;; 	  ("\\<\\(Q_\\(EXPORT\\|OBJECT\\|PROPERTY\\)\\|S\\(IGNAL\\|LOT\\)\\|connect\\|disconnect\\|emit\\)\\>"
;; 	   (0 font-lock-qt-face))
	  ))
      (defconst my-php-font-lock
	'(
	  ("\\<[0-9]+\\.[0-9]+\\>" (0 font-lock-floatnumber-face))
 	  ("eZ[a-zA-Z0-9_]*\\|Q[a-zA-Z_]*" (0 font-lock-variable-name-face t))
  	  ("[{}()<>=;:+&\\*\\/\\[]\\|\\]\\|\\-" (0 font-lock-keys-face t))
	  ("\\<[0-9]+\\>" (0 font-lock-number-face))
	  ("\\<0x[0-9a-fA-F]+\\>" (0 font-lock-hexnumber-face))
;; 	  ("\\<\\(Q_\\(EXPORT\\|OBJECT\\|PROPERTY\\)\\|S\\(IGNAL\\|LOT\\)\\|connect\\|disconnect\\|emit\\)\\>"
;; 	   (0 font-lock-qt-face))
	  ))))


;; Load default autoinsert
(load-file-module "autoinsert")

;; Automaticly rescan the index
;(setq imenu-auto-rescan t)


;; Add Time-stamp <> or Time-stamp " " anywhere in the top 8 lines of a
;; file to insert save date and time and user:

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

;---------------------------------------------------------------------
;I'd like to enable ispell check for text-mode too...

(setq default-major-mode 'indented-text-mode)
(add-hook 'indented-text-mode-hook 'turn-on-auto-fill)


(add-hook 'server-switch-hook 'make-frame-command)

;Faces
; (set-face-foreground 'region "black")
; (set-face-background 'highlight "CadetBlue")
; (set-face-background 'secondary-selection "MediumSeaGreen")


;; New faces
(defvar font-lock-number-face 'font-lock-number-face)
(defvar font-lock-hexnumber-face 'font-lock-hexnumber-face)
(defvar font-lock-floatnumber-face 'font-lock-floatnumber-face)
(defvar font-lock-keys-face 'font-lock-keys-face)
(defvar font-lock-qt-face 'font-lock-qt-face)

(defface font-lock-number-face
  '(
    (((class grayscale) (background light)) (:foreground "LightGray" :bold t))
    (((class grayscale) (background dark)) (:foreground "DimGray" :bold t))
    (((class color) (background light)) (:background "hotpink"))
    (((class color) (background dark)) (:foreground "black" :background "hotpink"))
    (t (:italic t)))
  "blah"
  :group 'font-lock-highlighting-faces)

(defface font-lock-hexnumber-face
  '(
    (((class grayscale) (background light)) (:foreground "LightGray" :bold t))
    (((class grayscale) (background dark)) (:foreground "DimGray" :bold t))
    (((class color) (background light)) (:background "darkblue"))
    (((class color) (background dark)) (:foreground "black" :background "darkblue"))
    (t (:italic t)))
  "blah"
  :group 'font-lock-highlighting-faces)

(defface font-lock-floatnumber-face
  '(
    (((class grayscale) (background light)) (:foreground "LightGray" :bold t))
    (((class grayscale) (background dark)) (:foreground "DimGray" :bold t))
    (((class color) (background light)) (:background "darkgreen"))
    (((class color) (background dark)) (:foreground "black" :background "darkgreen"))
    (t (:italic t)))
  "blah"
  :group 'font-lock-highlighting-faces)

(defface font-lock-keys-face
  '(
    (((class grayscale) (background light)) (:foreground "LightGray" :bold t))
    (((class grayscale) (background dark)) (:foreground "DimGray" :bold t))
    (((class color) (background light)) (:background "yellow"))
    (((class color) (background dark)) (:foreground "black" :background "yellow"))
    (t (:italic t)))
  "blah"
  :group 'font-lock-highlighting-faces)

(defface font-lock-qt-face
  '(
    (((class grayscale) (background light)) (:foreground "LightGray" :bold t))
    (((class grayscale) (background dark)) (:foreground "DimGray" :bold t))
    (((class color) (background light)) (:background "brown"))
    (((class color) (background dark)) (:foreground "green" :background "brown"))
    (t (:italic t)))
  "blah"
  :group 'font-lock-highlighting-faces)

;; First try to load default colors
(load-file-module "colors")

;; Set the new size
;(set-frame-width (car (car (cdr (current-frame-configuration)))) default-frame-width)
;(set-frame-height (car (car (cdr (current-frame-configuration)))) default-frame-height)

; Start with the same buffers, major modes and buffer positions:
; You must do a M-x desktop-save the first time it's used. Emacs
; must be started in the same current directory.

(load "desktop")
(desktop-load-default)
(desktop-read)

;; Options Menu Settings
;; =====================
(cond
 ((and (string-match "XEmacs" emacs-version)
       (boundp 'emacs-major-version)
       (or (and
            (= emacs-major-version 19)
            (>= emacs-minor-version 14))
           (= emacs-major-version 20))
       (fboundp 'load-options-file))
  (load-options-file "/root/.xemacs-options")))
;; ============================
;; End of Options Menu Settings

;; Load the extras file
(load-local-file-module "extras")

;; returns t if the current buffer is an emacs-client file
;; (defun is-buffer-a-client ()
;;   (interactive)
;;   (let ((cls server-clients)
;; 	cl
;; 	bufs
;; 	buf
;; 	(ok nil))
;;     (while cls
;;       (setq cl (car cls))
;;       (setq bufs (cdr cl))
;;       (while bufs
;; 	(setq buf (car bufs))
;; 	(if (eq buf (current-buffer))
;; 	    (setq ok t))
;; 	(setq bufs (cdr bufs)))
;;       (setq cls (cdr cls)))
;;     ok))

;; This starts emacs as a server.
;;(server-start)

;; Use gnu serv instead if available
;; Gnuserv is disabled for the moment

; (if (emacs-type-is-regular)
;     (require 'gnuserv nil t)
;   (require 'gnuserv))
;     (gnuserv-start)
;   (server-start))

;;
;; Rebind mouse-2 events to mouse-1 in various places:
;; Completion list
(add-hook 'completion-list-mode-hook
  '(lambda() (define-key completion-list-mode-map [down-mouse-1] 
	       'mouse-choose-completion)))
;; TexInfo
(add-hook 'Info-mode-hook
  '(lambda() (define-key Info-mode-map [down-mouse-1] 
	       'Info-mouse-follow-nearest-node)))
;; Buffer Menu
(add-hook 'buffer-menu-mode-hook
  '(lambda() (define-key Buffer-menu-mode-map [down-mouse-1] 
	       'Buffer-menu-mouse-select)))

;; Add a new menu element
;;(define-key-after (lookup-key global-map [menu-bar edit])
;;  [startup] '("Toggle Truncate Lines" . (lambda () (interactive)
;;					(setq-default truncate-lines (not truncate-lines)))) [calendar])

;; If non-nil each line of text is exactly one screen line, else wrap text.
(setq-default truncate-lines nil)

;;(require 'speedbar)

;;(define-key-after (lookup-key global-map [menu-bar tools])
;;  [speedbar] '("Speedbar" . speedbar-frame-mode) [calendar])

(setq imenu-always-use-completion-buffer-p t)


(defun change-var-in-file( var file val )
  "Changes the variable named var in the given file with the given val and saves it"
  (let (buf)
    (save-excursion
      (setq buf (find-file-noselect file))
      (set-buffer buf)
      (beginning-of-buffer)
      (if (search-forward-regexp (concat "^(defvar[ \t]+"
					 var
					 "[ \t]+\\(t\\|nil\\))")
				 nil t)
	  (save-restriction
	    (narrow-to-region (match-beginning 1) (match-end 1))
	    (replace-match val t nil nil 1)
	    (save-buffer))))))

;; Set the wanted color style
(change-color-style default-color-style)

(c-set-style "ezsystems")

(project-update-project-menu)

;; HTML/SGML related stuff

;; DocBook IDE mode
(autoload 'docbook-mode "docbookide" "Major mode for DocBook documents." t)

;; Turn on font lock when in DocBook mode
(add-hook 'docbook-mode-hook
	  'turn-on-font-lock)

;; You might want to make this the default for .sgml or .xml documents,
;; or you might want to rely on -*- DocBook -*- on the first line,
;; or perhaps buffer variables. It's up to you...
(setq auto-mode-alist
      (append
       (list
	'("\\.sgm" . docbook-mode)
	'("\\.sgml" . docbook-mode)
	'("\\.xml" . docbook-mode)
	'("\\.html" . html-mode)
	'("\\.ptl" . html-mode))
       auto-mode-alist))

(defun delete-word (arg)
  "Delete characters forward until encountering the end of a word.
With argument, do this that many times.
Does not copy the text to the clipboard as `kill-word' does."
  (interactive "p")
  (delete-region (point) (progn (forward-word arg) (point))))

(defun backward-delete-word (arg)
  "Delete characters backward until encountering the end of a word.
With argument, do this that many times.
Does not copy the text to the clipboard as `backward-kill-word' does."
  (interactive "p")
  (delete-word (- arg)))

(global-set-key [C-backspace] 'backward-delete-word)
;; Turn on end of line tracking
(setq track-eol t)

;; Make sure diary mailing only mails one day
(setq diary-mail-days 1)

;; Load the bbdb file
;; (load-file-module "bbdb")

(if (require-if 'dired-efap)
    (define-key dired-mode-map [f2] 'dired-efap))
