;;
;; .emacs pour  dans 
;; 
;; Crée par Guillaume CONNAN
;; Login   <gconnan@free.fr>
;; 
;; 
;;
(add-to-list 'load-path "/home/moi/emacs/")
(add-to-list 'load-path "/home/moi/emacs/tuareg-mode-1.45.6/")
;;(add-to-list 'load-path "/home/moi/emacs-23.1/")
(add-to-list 'load-path "/home/moi/emacs.d/")
(add-to-list 'load-path "/usr/local/share/emacs/22.2/")
(add-to-list 'load-path "/usr/local/share/emacs/22.2/lisp")
(add-to-list 'load-path "/home/moi/emacs/emacs/site-lisp")
(add-to-list 'load-path "/usr/local/share/emacs/22.2/lisp/")
(add-to-list 'load-path "/usr/share/emacs22/site-lisp/")
(add-to-list 'load-path "/home/moi/emacs/mupacs-3.2.3/")
(add-to-list 'load-path "/usr/share/emacs/22.2/lisp/")
(add-to-list 'load-path "/usr/share/emacs22/site-lisp/")
(add-to-list 'load-path "/usr/share/emacs/22.2/lisp/")
(add-to-list 'load-path "/usr/local/share/emacs/23.1/")
(add-to-list 'load-path "/usr/local/share/emacs/23.1/lisp")
(add-to-list 'load-path "/home/moi/emacs/emacs/site-lisp")
(add-to-list 'load-path "/usr/local/share/emacs/23.1/lisp/")
(add-to-list 'load-path "/usr/share/emacs22/site-lisp/")
(add-to-list 'load-path "/home/moi/emacs/mupacs-3.2.3/")
(add-to-list 'load-path "/usr/share/emacs/23.1/lisp/")
(add-to-list 'load-path "/usr/share/emacs22/site-lisp/")
(add-to-list 'load-path "/usr/share/emacs/23.1/lisp/")
(add-to-list 'load-path "/usr/share/emacs/")
(add-to-list 'load-path "/usr/share/emacs/site-lisp/")
;(add-to-list 'load-path "/usr/share/emacs/21.4/lisp/")
;(add-to-list 'load-path "/usr/share/emacs21/site-lisp/")
;(add-to-list 'load-path "/usr/share/emacs21/")
(add-to-list 'load-path "/usr/share/emacs22/")
 (add-to-list 'load-path "/emacs-23.1/lisp/")
    (add-to-list 'load-path "/usr/share/emacs22/site-lisp/bbdb/")
    (add-to-list 'load-path "/usr/share/emacs21/site-lisp/")
    (add-to-list 'load-path "/usr/share/emacs21/site-lisp/bbdb/")
    (add-to-list 'load-path "/home/moi/emacs/")
(add-to-list 'load-path "/usr/local/share/emacs/23.1/lisp/gnus/")

(require 'iso-cvt)
(add-hook 'TeX-mode-hook '(lambda () (iso-cvt-define-menu)))



;;; GNUS
(setq load-path (cons (expand-file-name "~/gnus/lisp") load-path))
   (require 'gnus-load)


(require 'zone)

(load-file "~/emacs/std_comment.el")







 (autoload 'trivial-cite "tc" t t)
 ;(require 'asy-mode)
; (require 'asy-keywords)       
;(require 'asy-init)

;;Inhiber l'affichage du message d'accueil
;(setq inhibit-startup-message t       ;Emacs
;          gnus-inhibit-startup-message t) ;Gnus

;; beep visuel
;(setq visible-bell t)

;; curseur en barre et non clignotant
;;(setq cursor-type 'bar) -> default-frame-alist
;(blink-cursor-mode 0)
;;(set-cursor-color "black")

;; Ne pas utiliser de boîte de dialogue mais le minibuffer pour poser une question
;; (les dialogues marchent mal sous OSX pour choisir un fichier inexistant)
(setq use-dialog-box nil)
                                        ;     use-file-dialog nil)


;; Laisser le curseur en place lors d'un défilement par pages.
;; Par défaut, Emacs place le curseur en début ou fin d'écran
;; selon le sens du défilement.
(setq scroll-preserve-screen-position t)

;; Faire apparaître la position du curseur dans la ligne modale
(setq column-number-mode t)
(setq line-number-mode t)




;;; * Active le serveur Emacs pour utiliser emacsclient *
(when (string= system-type "gnu/linux")
  (require 'server)
  (unless server-process (server-start)))


;; Colorisation syntaxique maximale dans tous les modes
;; Avec emacs 21, la colorisation est disponible en mode texte. Cool !
(global-font-lock-mode t)
(setq font-lock-maximum-decoration t)


;; pour sage et python
;;

(load "pyrex-mode")
(load "python-mode")
;(setq ipython-command "sage")  ;; depends on where your sage is.
;(load "sage") 
;(require 'ipython)

(fset 'py-shell-fullscreen
   [?\M-x ?p ?y ?- ?s ?h ?e ?l ?l return ?\C-x ?1])
(define-key esc-map "i" 'py-shell-fullscreen)

(setq auto-mode-alist (cons '("\\.pyx\\'" . pyrex-mode) auto-mode-alist)) 
(setq auto-mode-alist (cons '("\\.pxd\\'" . pyrex-mode) auto-mode-alist)) 
(setq auto-mode-alist (cons '("\\.pxi\\'" . python-mode) auto-mode-alist)) 




;; Montrer la correspondance des parenthèses
;; (systématiquement et non seulement après la frappe)
(when (require 'paren)
  (show-paren-mode t)
  (setq blink-matching-paren t)
  (setq blink-matching-paren-on-screen t)
  (setq show-paren-style 'parenthesis)
  ;;(setq show-paren-style 'expression)
  (setq blink-matching-paren-dont-ignore-comments t))

;; (dé)compression automatique des fichiers lus et écrits
(auto-compression-mode t); nil (jka-compr))



;;lilypond
(autoload 'lilypond-init "lilypond-init" t)




(global-font-lock-mode t) ;pour avoir les couleurs sans avoir a taper font-lock-mode

   (setq font-lock-maximum-decoration t) ;maximum de couleurs

   (setq font-lock-maximum-size nil)

   (transient-mark-mode t) ;pour que la region selectionnee soit mise en surbrillance

   (setq compilation-window-height 5) ;pour que la fenetre de compilation ne soit pas trop grande



   (setq ispell-dictionary "francais") ;dictionnaire francais par defaut




 
;;; fichier de conf. emacs21
(fset 'yes-or-no-p 'y-or-n-p)
(tool-bar-mode -1)
;(menu-bar-mode -1)
(column-number-mode t)
(recentf-mode t)
(global-font-lock-mode t)



(setq default-frame-alist
      '((foreground-color."yellow"))
      )


(setq-default
 inhibit-startup-message t
 frame-background-mode 'dark
 default-major-mode 'text-mode          ; mode standard
 visible-bell t
 display-time-24hr-format t
 display-time-format "%R %a %e/%m/%Y")

(display-time)                          ; montre l'heure dans la barre d'état

;; (require 'uniquify)                  ; changements de buffer C-x b améliorés
;; (setq-default uniquify-buffer-name-style 'post-forward-angle-brackets)
;; (setq uniquify-after-kill-buffer-p t)
;; (uniquify-rationalize-file-buffer-names)
;; (iswitchb-default-keybindings)




;;; Apropos
(global-set-key [f3]
                (lambda ()
                  (interactive)
                  (apropos (current-word))))
;;; Manuel
;; (autoload 'manual-entry "man" "appelle une page de manuel")
;; (autoload 'Man-default-man-entry "man" "choisit une page de manuel")
;; (global-set-key (kbd "<f4> <f4>")
;;              (lambda ()
;;                (interactive)
;;                (manual-entry (Man-default-man-entry))))






;;;php
(autoload 'html-helper-mode "html-helper-mode" "Yay HTML" t)









(setq auto-mode-alist (cons '("\\.html$" . html-helper-mode) auto-mode-alist))
(setq auto-mode-alist (cons '("\\.php$" . html-helper-mode) auto-mode-alist))





;;;
;;; X-window|console ?
;;;
(if window-system
    (progn
      ;; options d'emacs sous X-window
      (setq-default
       wheel-scroll-interval 6          ; nombre de lignes déplacées par la roulette
       hauteur-normale 62               ; petite hauteur du frame emacs
       largeur-normale 118
      ;; gestions des fenêtres -- fonte 9x15, X 1024*768
       largeur-ecran 183
       hauteur-ecran 83
       )

;;; fonctions d'emacs sous X-window
      ;; mulot à roulette
      (defun wheel-scroll-down-some-lines ()
        (interactive)
        (scroll-down wheel-scroll-interval))
      (defun wheel-scroll-up-some-lines ()
        (interactive)
        (scroll-up wheel-scroll-interval))

      (defun wheel-scroll-down-page ()
        (interactive)
        (scroll-down))
      (defun wheel-scroll-up-page ()
        (interactive)
        (scroll-up))

      (defun wheel-scroll-down-other-page ()
        (interactive)
        (scroll-other-window-down wheel-scroll-interval))
      (defun wheel-scroll-up-other-page ()
        (interactive)
        (scroll-other-window wheel-scroll-interval))

      (global-set-key [mouse-5] 'wheel-scroll-up-some-lines)
      (global-set-key [mouse-4] 'wheel-scroll-down-some-lines)

      (global-set-key [S-mouse-5] 'wheel-scroll-up-page)
      (global-set-key [S-mouse-4] 'wheel-scroll-down-page)

      (global-set-key [C-mouse-5] 'wheel-scroll-up-other-page)
      (global-set-key [C-mouse-4] 'wheel-scroll-down-other-page)
      ;; end mulot

      (defun lhh-grande-fenetre ()
        "place et dimensionne la fenêtre active"
        (interactive)
        (set-frame-size (selected-frame) largeur-ecran hauteur-ecran)
        (set-frame-position (selected-frame) 0 0))

      (defun lhh-large-fenetre ()
        "redimensionne la fenêtre active"
        (interactive)
        (set-frame-size (selected-frame) largeur-ecran hauteur-normale))

      (defun lhh-petite-fenetre ()
        "redimensionne la fenêtre active"
        (interactive)
        (set-frame-size (selected-frame) largeur-normale hauteur-normale))

      (defun lhh-haute-fenetre ()
        "redimensionne la fenêtre active"
        (interactive)
        (set-frame-size (selected-frame) largeur-normale hauteur-ecran))

      (defun lhh-fenetre-utile ()
        "la fenêtre active prend la largeur utile"
        (interactive)
        (set-frame-width (selected-frame) (+ fill-column 1)))

      (defun lhh-bascule ()
        "bascule la taille de la fenêtre"
        (interactive)
        (cond
         ((= taille-fenetre 0)
          (progn (lhh-large-fenetre)
                 (setq taille-fenetre 1)))
         ((= taille-fenetre 1)
          (progn (lhh-petite-fenetre)
                 (setq taille-fenetre 2)))
         ((= taille-fenetre 2)
          (progn (lhh-haute-fenetre)
                 (setq taille-fenetre 3)))
         (t
          (progn (lhh-grande-fenetre)
                 (setq taille-fenetre 0)))))

      (defvar taille-fenetre 0)

      (defun intelligent-kill ()
        "ferme la fenêtre active"
        (interactive)
        (if multiple-frames
            (delete-frame)
          (save-buffers-kill-emacs)))
      (global-set-key "\C-x\C-c" 'intelligent-kill)

      ;; www

      ; Utilisation de w3m-emacs
      ; il faut que le programme w3m soit installé
      (autoload 'w3m "w3m" "Interface for w3m on Emacs." t)

   
   ;;  (require 'w3-auto "w3-auto")

;;     (autoload 'w3-preview-this-buffer "w3" "WWW Previewer" 't)
;;     (autoload 'w3 "w3" "WWW Browser" 't)
;;     (autoload 'w3-open-local "w3" "Open local file for WWW browsing" 't)
;;     (autoload 'w3-fetch "w3" "Open remote file for WWW browsing" 't)
;;     (autoload 'w3-use-hotlist "w3" "Use shortcuts to view WWW docs" 't)
;;    ; (autoload 'w3-
;;     (setq-default w3-do-incremental-display t
;;                   url-be-asynchronous t)
;; ;; (setq w3-use-netscape-configuration-file t
;; ;; w3-netscape-configuration-file
;; ;; "/where/the/file/is/.netscape-preferences")
;;     (setq url-using-proxy t
;; ;          w3-hotlist-file (expand-file-name "~/.netscape/bookmarks.html")
;;          ; browse-url-browser-function 'browse-url-netscape
;;          ; url-proxy-services
;;           ;'(("ftp" . "localhost:8080")
;;            ; ("http" . "localhost:8080")
;;             ;("gopher" . "localhost:8080")
;;            ; ("no_proxy" . "localhost"))
;;           url-confirmation-func 'y-or-n-p
;;           w3-default-homepage "http://gconnan.free.fr/"
;;           ;w3-default-homepage "une-URL"                       MODIFIER CECI
;;           ;url-pgp/pem-entity "mon-adresse@mon-domaine"        MODIFIER CECI
;;           url-personal-mail-address "gconnan@free.fr" ;MODIFIER CECI
;;           url-xterm-command "nxterm -title %s -ut -e %s %s %s"
;;           w3-delimit-links t
;;           url-confirmation-func 'y-or-n-p
;;           w3-show-status t
;; ;         w3-debug-html t
;;           url-show-status t
;;        url-keep-history t
;;           )
;; (global-set-key [(super w)] 'w3-follow-url-at-point)

      ;(setq-default
       ;; browse-url-browser-function 'browse-url-lynx-xterm
      ; browse-url-xterm-program "lxterm"
      ; browse-url-browser-function 'browse-url-generic
      ; browse-url-generic-program "lxterm"
      ; browse-url-generic-args '("-e" "w3m")
       ;;browse-url-browser-function 'w3m-browse-url
      ; w3-default-homepage "http://localhost"
      ; url-keep-history "~/.emacs-w3-history"
      ; url-global-history-file "~/.mosaic-global-history"
      ; )

      (setq
       default-mode-line-format
       '("" mode-line-mule-info
         mode-line-modified
         (line-number-mode " L%l") (column-number-mode " C%c") " %p"
          mode-line-frame-identification "%b"
         " %[(" mode-name mode-line-process minor-mode-alist "%n" ")%] "
         global-mode-string
         (which-func-mode ("" which-func-format " ")))

       frame-title-format
       '((multiple-frames "%F " "Emacs ")
         user-real-login-name "@" system-name " " display-time-string " " default-directory
         " %[(" mode-name mode-line-process minor-mode-alist "%n" ")%] "
         "%b")

       icon-title-format
       '((multiple-frames "emacs " "Emacs ")
         user-real-login-name " %b")

       ;; default-frame-alist
       ;; ' ( (foreground-color . "beige")(background-color . "grey14")
       ;;        (scroll-bar-width . 9)
       ;;        (font . "-misc-fixed-medium-r-normal-*-15-140-75-75-c-90-iso8859-1")
       ;;        (top . 0)(left . 0)
       ;;        (width . 88)
       ;;        (height . 49) )

       ;; initial-frame-alist
       ;; '((foreground-color . "ivory")(background-color . "black")
       ;;        (width . 103)
       ;;        )

       ;; Man-notify-method 'newframe
       ;; Man-frame-parameters
       ;; '((background-color . "grey15")
       ;;        (cursor-color . "deepskyblue2")
       ;;        (mouse-color . "gold")
       ;;        (width . 80)
       ;;        (tool-bar-lines . 0))
       )

      ;; (defun lhh-quitte-gnus ()
      ;;        "quitte les niouzes et ferme le frame"
      ;;        (interactive)
      ;;        (gnus-group-exit)
      ;;        (delete-frame))

      ;; (defun lhh-suspend-gnus ()
      ;;        "suspend les niouzes et ferme le frame"
      ;;        (interactive)
      ;;        (gnus-group-suspend)
      ;;        (delete-frame))

;;       (defun niouzes ()
;;      "les niouzes"
;;      (interactive)
;;      (if (equal (buffer-name) "*Group*")
;;                 (progn
;;                   (make-frame-command)
;;                   (switch-to-buffer "*Group*"))
;;                 (gnus-other-frame))
;;      (modify-frame-parameters
;;       nil '(;;(font . "-etl-fixed-medium-r-normal--14-135-75-75-c-0-iso8859-1")
;;             (foreground-color . "orange")
;;             (height . 49)
;;             (width . 100)))
;;      (gnus-topic-mode t t)
;;      (tool-bar-mode -1)
;; ;;   (define-key gnus-group-mode-map "q" 'lhh-quitte-gnus)
;;      (define-key gnus-group-mode-map "z" 'lhh-suspend-gnus))

      ;; touches X
      (global-set-key [f12] 'lhh-bascule)
      (global-set-key "\C-x5+" 'lhh-grande-fenetre)
      (global-set-key "\C-x5-" 'lhh-petite-fenetre)

      (global-set-key [menu] 'tmm-menubar)
      (global-set-key [C-tab] 'other-window)

      ;; curseur variable selon insert/overwrite/read-only
      (defvar cursor-color nil "Last cursor color used (string)")
      (defun ins-cursor-set () "set cursor color according to ins mode"
        (let ((sv-crs-str cursor-color))
          (cond (overwrite-mode
                 (modify-frame-parameters (selected-frame) '((cursor-type . box)))
                 (setq cursor-color "orchid")) ;overwrite cursor color
                (buffer-read-only
                 (modify-frame-parameters (selected-frame) '((cursor-type . box)))
                 (setq cursor-color "limegreen")) ;insertbuffer read only
                (t
                 (modify-frame-parameters (selected-frame) '((cursor-type . (bar . 4))))
                 (setq cursor-color "orangered"))) ;insert mode
          (or (string= sv-crs-str cursor-color)
              (set-cursor-color cursor-color)))) ;X terminal cursor color
      (add-hook 'post-command-hook 'ins-cursor-set))
  ;; fin du cas X

  ;; emacs-console : initialisation d'emacs en mode texte
  (progn
    (menu-bar-mode -1)                  ; pas de menus
    )
  ;; c'est tout pour l'instant
  )
;;; fin de (X | console)

;;; blancs & tabs
;;; whitespace
(autoload 'nuke-trailing-white-space "white-space" nil t)
(global-set-key [f16] 'nuke-trailing-white-space)

;;; blank-mode
(autoload 'blank-mode           "blank-mode"
  "Toggle blank visualization."    t)
(autoload 'blank-mode-customize "blank-mode"
  "Customize blank visualization." t)
(global-set-key [f6] 'blank-mode)

(add-hook 'text-mode-hook
          (lambda ()
            (setq show-trailing-whitespace t)))

;;; Tools

(defvar scissors "8<------"
  "string to insert in \\[scissors]")

(defun scissors ()
  "Insert a line of SCISSORS in the buffer"
  (interactive)
  (or (bolp) (beginning-of-line 2))
  (while (<= (current-column) (- (or fill-column 79) (length scissors)))
    (insert scissors))
  (newline))


 (global-set-key [(super s) (super s)] 'scissors)



(defvar pourcent "%"
  "string to insert in \\[pourcent]")

(defun pourcent ()
  "Insert a line of % in the buffer"
  (interactive)
  (or (bolp) (beginning-of-line 2))
  (while (<= (current-column) (- (or fill-column 79) (length pourcent)))
    (insert pourcent))
  (newline))

(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super p) (super p)] 'pourcent)))


 





;(require 'lilypond-mode)


;(require 'scrmable)

 


;;(require 'scroll-in-place)

;; ;; hll - B. rutt
;; ;;(require 'hll)
;; (autoload 'hll-toggle-line "hll" "Highline lines and jumps" t)
;; (global-set-key (kbd "C-c h h") 'hll-toggle-line)
;; (global-set-key (kbd "C-c h p") 'hll-prev-highlight)
;; (global-set-key (kbd "C-c h n") 'hll-next-highlight)
;; (global-set-key (kbd "C-c h u") 'hll-unhighlight-buffer)

;; ;;; ibuffer
 (require 'ibuffer)
 (setq ibuffer-line-format
       "%o%m%r %(%-16,999n%) %s \t%-13,999M %{%p%} %f")
 (global-set-key [f10] 'ibuffer)
 (setq ibuffer-formats '((mark modified read-only " " (name 20 20) " "
                              (size 8 -1 :right) " " (mode 20 20)
                              " " (process 8 -1) " " filename)
                        (mark " " (name 25 -1) " " filename))
       ;ibuffer-elide-long-columns t
       )

;; ;;;
;; ;;; Hooks
;; ;;;

;; (setq skeleton-pair t)
;; (defun my-skeleton-keys ()
;;          (local-set-key "{" 'skeleton-pair-insert-maybe)
;;          (local-set-key "(" 'skeleton-pair-insert-maybe)
;;          (local-set-key "[" 'skeleton-pair-insert-maybe))

;; (add-hook 'text-mode-hook 'my-skeleton-keys)
;; (add-hook 'emacs-lisp-mode-hook 'my-skeleton-keys)

;; (add-hook 'Info-mode-hook
;;        (lambda ()
;;            ;; mode Info à la Lynx
;;            (local-set-key [home]  'Info-up)
;;            (local-set-key [right] 'Info-follow-nearest-node)
;;            (local-set-key [left]  'Info-last)
;;            (local-set-key [up]    'Info-prev-reference)
;;            (local-set-key [down]  'Info-next-reference)))




;;mupacs



(autoload 'mupad-run      "/home/moi/emacs/mupacs-3.2.3/mupad-run.el" "To start a MuPAD session" t)
;;y(add-hook 'mupad-run-mode-hook 'mupad-bus-adapt-textwidth)

;; Pari
;; (defvar hilit-mode-enable-list nil)
;; (add-to-list 'hilit-mode-enable-list 'gp-mode)
;; (add-to-list 'hilit-mode-enable-list 'gp-script-mode)
;; (setq pari-colors "~/.gpdir/pari-colors.el")

;; (autoload 'gp-mode "pari" nil t)
;; (autoload 'gp-script-mode "pari" nil t)
;; (autoload 'gp "pari" nil t)
;; (autoload 'gpman "pari" nil t)
;; (add-to-list 'auto-mode-alist '("\\.gp$" . gp-script-mode))

;; (setq-default gp-window-height 15)
;; (defvar gp-process nil)
;; (defun gp-sub-window ()
;;   "ouvre/masque une fenêtre *PARI*"
;;   (interactive)
;;   (if (equal (buffer-name) "*PARI*")
;;       (delete-windows-on "*PARI*" t)
;;     (progn
;;       (split-window nil (max (- (window-height) gp-window-height) gp-window-height))
;;       (if gp-process
;;        (progn
;;          (other-window 1)
;;          (switch-to-buffer "*PARI*"))
;;      (gp)
;;      (shrink-window (max 0 (- (window-height) gp-window-height)))))))
;; (global-set-key (kbd "<f5>") 'gp-sub-window)
;; ;; fin de pari

;;;
;;; fonctions globales
;;;
(defun insert-date ()
  (interactive)
  (insert (format-time-string "%d/%m/%Y")))

(defun insert-long-date ()
  (interactive)
  (insert (format-time-string "date '+%A %e %B %Y, à %H:%M'")))

(defun recenter-arg-zero ()
  "ram�ne la ligne courante en haut de l'écran"
  (interactive)
  (recenter 0))

(defun dos-unix ()
  "efface les retours-chariot"
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (while (search-forward "\r\n" nil t) (replace-match "\n"))))

(defun unix-dos ()
  "crée les retours-chariot"
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (while (search-forward "\n" nil t) (replace-match "\r\n"))))

;; (defun reformat-line ()
;;   "Indente la ligne, supprime les espaces finaux et passe à la ligne."
;;   (interactive)
;;   (indent-according-to-mode)
;;   (end-of-line)
;;   (delete-region (point) (progn (skip-chars-backward " \t") (point)))
;;   (next-line 1))

(defun my-text-wash ()
  "nettoie début et fin de lignes des espaces inutiles"
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (while
        (search-forward-regexp "\\(^[ \t]+\\|[ \t]+$\\)" nil t)
      (replace-match ""))))

;; Dired
;; (defun dired-first-file ()
;;   "remonte au premier fichier"
;;   (interactive)
;;   (beginning-of-buffer)
;;   (dired-next-line 2))

;; (defun dired-last-file ()
;;   "descend au dernier fichier"
;;   (interactive)
;;   (end-of-buffer)
;;   (dired-previous-line 1))

;; (setq-default dired-trivial-filenames "^\\.\\.?$\\|^#") ; fichiers cachés

;; (add-hook 'dired-load-hook
;;        (lambda ()
;;          (load "dired-x")
;;          (setq dired-recursive-deletes 'top
;;                dired-x-hands-off-my-keys nil
;;                ;; cache les fichiers .*
;;                dired-omit-files
;;                (concat dired-omit-files "\\|^\\..+$\\|\\.bak$\\|\\.index\\|\\.old$"))
;;          ;; touches dired
;;          (define-key dired-mode-map [left] 'dired-up-directory)
;;          (define-key dired-mode-map [right] 'dired-view-file)
;;          (define-key dired-mode-map [home] 'dired-first-file)
;;          (define-key dired-mode-map [end] 'dired-last-file)))

;; (add-hook 'dired-mode-hook
;;        (function (lambda ()
;;                    (setq dired-omit-files-p t)
;;                    )))

;; (defun backward-char-or-view-quit ()
;;   "recule ou quitte"
;;   (interactive)
;;   (if (equal (point) 1)
;;       (View-quit)
;;     (backward-char)))

;; (eval-after-load "view"
;;   '(define-key view-mode-map [left] 'backward-char-or-view-quit))


;;; shell
(require 'shell)

;;; ssh
(autoload 'ssh "ssh" "Ssh shell" t)

;;; options de clavier emacs
;; Remaps universels
(global-set-key (kbd "\C-c <delete>") 'delete-region)
(global-set-key "\C-cg" 'goto-line)
(global-set-key "\C-cG" 'goto-char)
;(global-set-key "\e*"   'ispell-complete-word)
(global-set-key [insertchar] 'overwrite-mode)

;; ;; mise en boîte des citations
;; (require 'boxquote)
;; (global-set-key "\C-cbB" 'boxquote-boxquote)
;; (global-set-key "\C-cbR" 'boxquote-unbox-region)
;; (global-set-key "\C-cbb" 'boxquote-buffer)
;; (global-set-key "\C-cbf" 'boxquote-defun)
;; (global-set-key "\C-cbi" 'boxquote-insert-file)
;; (global-set-key "\C-cbk" 'boxquote-kill)
;; (global-set-key "\C-cbK" 'boxquote-describe-key)
;; (global-set-key "\C-cbn" 'boxquote-narrow-to-boxquote)
;; (global-set-key "\C-cbp" 'boxquote-paragraph)
;; (global-set-key "\C-cbr" 'boxquote-region)
;; (global-set-key "\C-cbt" 'boxquote-title)
;; (global-set-key "\C-cbu" 'boxquote-unbox)
;; (global-set-key "\C-cbv" 'boxquote-describe-variable)
;; (global-set-key "\C-cby" 'boxquote-yank)
;; ;; fin de boxquote

;; mouvements du curseur
(global-set-key [home] 'my-home)
(global-set-key [end]  'my-end)

;; ;;;;; filladapt-mode ;;;;;
;; ;; (filladapt.el) Augment the standard fill-mode
;; ;; with more smarts - handles multiply quoted mail text, for example.
 (require 'filladapt)
 (setq-default default-justification 'full)
;; ;; always use filladapt in several modes
 (add-hook 'text-mode-hook 'turn-on-filladapt-mode)
;; ;;(add-hook 'emacs-lisp-mode 'turn-on-filladapt-mode)

 (global-set-key [f9] 'auto-fill-mode)
(require 'filladapt)
(add-hook 'text-mode-hook 
          '(lambda () (auto-fill-mode 1) ))


(require 'filladapt)
(defun sk-text-hook ()
  (set-fill-column 72)
  (turn-on-auto-fill)
  (filladapt-mode)
;;  (flyspell-mode)
  (setq default-justification 'full)
  (setq footnote-spaced-footnotes nil
        footnote-section-tag "")
  (footnote-mode)
  )
(add-hook 'text-mode-hook 'sk-text-hook)





;;; ido
;; (require 'ido)
;; (ido-mode t)

;;; ffap
;;(ffap-bindings)

;;(require 'ff-paths)
;;
;;  You may alter the value of the variables:
;;
;;   ff-paths-list
;;   ff-paths-use-locate
;;   ff-paths-locate-max-matches
;;   ff-paths-using-ms-windows
;;   ff-paths-display-non-existent-filename
;;   ff-paths-prompt-for-only-one-match
;;   ff-paths-require-match
;;   ff-paths-gzipped



;;; local
(defvar french-holidays
  '((holiday-fixed 1 1 "Nouvel an")
    (holiday-float 4 1 1 "Lundi de Pâques")
    (holiday-fixed 5 1 "Fête du travail")
    (holiday-fixed 5 8 "Victoire 1945")
    (holiday-float 5 4 3 "Ascension")
    (holiday-float 5 1 -1 "Lundi de Pentecôte")
    ;; (holiday-float 6 0 1 "Fête des m�res") ; merde à pétain
    ;; (holiday-float 6 0 3 "Fête des p�res")
    (holiday-fixed 7 14 "Fête Nationale")
    (holiday-fixed 8 15 "Assomption")
    (holiday-fixed 11 1 "Toussaint")
    (holiday-fixed 11 11 "Armistice 1918")
    (holiday-fixed 12 25 "Noël")
    (holiday-fixed 10 27 "Début vacances toussaint 2007")
    (holiday-fixed 11 07 "Fin vacances toussaint 2007")
    (holiday-fixed 12 22 "Début vacances noël 2007")
    (holiday-fixed 01 06 "Fin vacances noël 2008")
    (holiday-fixed 02 16 "Début vacances hiver 2008")
    (holiday-fixed 03 02 "Fin vacances hiver 2008")
    (holiday-fixed 04 12 "Début vacances printemps 2008")
    (holiday-fixed 04 27 "Fin vacances printemps 2008")
    )
  "French holidays")

(setq-default
 calendar-holidays french-holidays
 calendar-latitude 47.3                 ; Hey, emacs, I'm here !
 calendar-location-name "Nantes, fr"
 calendar-longitude -1.5
 calendar-week-start-day 1              ; démarre la semaine le lundi
 diary-file "~/.memento"
 european-calendar-style t              ; date normale jour/mois/année
 mark-diary-entries-in-calendar t
 mark-holidays-in-calendar t
 view-calendar-holidays-initially t
 view-diary-entries-initially   t
 calendar-day-name-array
 ["Dimanche" "Lundi" "Mardi" "Mercredi" "Jeudi" "Vendredi" "Samedi"]
 calendar-month-name-array
  ["Janvier" "Février" "Mars" "Avril" "Mai" "Juin" "Juillet"
   "Août"   "Septembre" "Octobre" "Novembre" "Décembre"])

;;; Flyspell
(ispell-change-dictionary "francais" t) ; mon dico...
(autoload 'flyspell-mode "flyspell" "On-the-fly spelling checking" t)
(setq
 flyspell-global-modes
 '(LaTeX-mode TeX-mode latex-mode tex-mode gnus-article-edit-mode message-mode post-mode)
 flyspell-default-dictionary "francais")

;;; Devine la langue pour flyspell
;;; Langue(s)
;;(require 'guess-lang)
;(;;defun my-lang ()
 ;; "Le premier appel devine la langue,
;;le second bascule sur une langue usuelle"
 ;; (interactive nil)
  ;;(cond
  ;; ((eq last-command 'my-lang)
   ;; (lang-toggle))
   ;;(t
   ;; (guess-dictionary))))

(setq
 ispell-dictionary "francais"
 ispell-other-dictionary "british"
 flyspell-default-dictionary ispell-dictionary)
;;; devine le dictionnaire/bascule entre français et anglais
;(global-set-key (kbd "<f7>") 'my-lang)
;;; (dés)active flyspell
;(global-set-key (kbd "C-<f7>") 'flyspell-mode)

;;; Ocaml
(setq load-path (cons "~/emacs/tuareg-mode-1.45.6/" load-path))

(add-to-list 'load-path "~/emacs/tuareg-mode-1.45.6/tuareg-mode")
    (autoload 'tuareg-mode "tuareg" "Major mode for editing Caml code" t)
    (autoload 'camldebug "camldebug" "Run the Caml debugger" t)
    (autoload 'tuareg-imenu-set-imenu "tuareg-imenu" 
      "Configuration of imenu for tuareg" t) 

    (add-hook 'tuareg-mode-hook 'tuareg-imenu-set-imenu)

    (setq auto-mode-alist 
        (append '(("\\.ml[ily]?$" . tuareg-mode)
                  ("\\.topml$" . tuareg-mode))
                  auto-mode-alist))



;; (require 'tuareg)
;; (add-to-list 'auto-mode-alist '("\\.ml[iylp]?$" . tuareg-mode))
;(autoload 'tuareg-mode "caml" "Major mode for editing Caml code." t)
;(autoload 'run-caml "inf-caml" "Run an inferior Caml process." t)

;;; Scilab
;;(add-to-list 'auto-mode-alist '("\\(\\.sci$\\|\\.sce$\\)" . scilab-mode))
;;(autoload 'scilab-mode "scilab" "Major mode for editing Scilab code" t)

;;; Mutt
(defun my-post-settings ()
  (setq fill-column 72)
  (turn-on-auto-fill)
  (flyspell-mode 1))

(add-hook 'post-mode-hook 'my-post-settings)
;;(add-to-list 'auto-mode-alist '("^/tmp/mutt-" . post-mode))

;; TeX & LaTeX & AucTeX
;;(require 'tex-site)
(load "auctex.el" nil t t)
(setq-default
 tex-dvi-view-command "/usr/bin/evince"
 tex-dvi-print-command "lpr"
 TeX-auto-save t
 TeX-parse-self t
 TeX-master nil
 ;; Postscript
 ps-paper-type 'a4)
 ;; LaTeX
 ;;LaTeX-command-style '(("^french$" "frlatex") ; ligne à ajouter
;;                     ("." "latex")))

 ;; Auctex - math-abbrev-prefix = ² (kbd "²")
 ;; (setq LaTex-math-abbrev-prefix [2226])
 ;;LaTeX-math-abbrev-prefix [?\262])

;; (defun my-LaTeX-setup ()
;;   "Configuration LaTeX"
;;   (interactive)
;;   ;(auto-fill-mode t)
;;   (setq ;fill-column 100                     ; <-texte->
;;      ispell-parser 'tex
;;      TeX-insert-braces nil)
;;   (LaTeX-math-mode t)
;;   (when window-system
;;     (flyspell-mode 1)))

;; (add-hook 'LaTeX-mode-hook 'my-LaTeX-setup)

(defun my-french-guill ()
  "Insère une paire de guillemets"
  (interactive)
  (insert "\\og \\fg{}")
  (backward-char 5))

;; (defun my-displaymaths ()
;;   "Ouvre un « displaymath »"
;;   (interactive)
;;   (newline-and-indent)
;;   (indent-for-tab-command)
;;   (insert "\\begin{displaymath}")
;;   (newline-and-indent)
;;   (newline-and-indent)
;;   (insert "\\end{displaymath}")
;;   (indent-for-tab-command)
;;   (previous-line 1)
;;   (indent-for-tab-command))

;; (defun my-display-maths ()
;;   "Ouvre un « displaymaths »"
;;   (interactive)
;;   (newline-and-indent)
;;   (indent-for-tab-command)
;;   (insert "\\[")
;;   (newline-and-indent)
;;   (newline-and-indent)
;;   (insert "\\]")
;;   (indent-for-tab-command)
;;   (previous-line 1)
;;   (indent-for-tab-command))

(defun my-footnote ()
  "Ouvre une footnote"
  (interactive)
  (search-backward-regexp "[])>».,[:alnum:]]")
  (forward-char)
  (insert "\\footnote{%\n  .}")
  (newline-and-indent)
  (beginning-of-line)
  (backward-char 4))

(defun my-fraction ()
  "InsÃ?re une fraction"
  (interactive)
  (insert "\\frac{}{}")
  (backward-char 3))

(defun my-display-fraction ()
  "InsÃ?re une grande fraction"
  (interactive)
  (insert "\\dfrac{}{}")
  (backward-char 3))

(defun my-frac-or-foot ()
  "InsÃ?re une fraction ou une footnote selon le contexte"
  (interactive)
  (if (texmathp)
          (my-fraction)
        (my-footnote)))

(defun my-nombre ()
  "Insèère \"\\nombre{}\""
  (interactive)
  (insert "\\nombre{}")
  (backward-char 1))

(defun index-current-word ()
  "Indexe le mot sous ou précédant le curseur"
  (interactive)
  (forward-char)
  (backward-word 1)
  (forward-word 1)
  (insert (concat "\\index{" (current-word) "}")))

(defun my-label ()
  "Ouvre un label"
  (interactive)
  (forward-char)
  (backward-word 1)
  (insert "\\label{}")
  (backward-char 1))

;; (defun my-latex-keys ()
;;   "Touches LaTeX"
;;   (interactive)
;;   (setq skeleton-pair t)
;;   (define-key LaTeX-mode-map "$" 'skeleton-pair-insert-maybe)
;;   (define-key LaTeX-mode-map "{" 'skeleton-pair-insert-maybe)
;;   (define-key LaTeX-mode-map "(" 'skeleton-pair-insert-maybe)
;;   (define-key LaTeX-mode-map "[" 'skeleton-pair-insert-maybe)
;;   (define-key LaTeX-mode-map (kbd "C-c f") 'my-frac-or-foot)
;;   (define-key LaTeX-mode-map (kbd "C-c F") 'my-display-fraction)
;;   (define-key LaTeX-mode-map (kbd "C-c n") 'my-nombre)
;;   (define-key LaTeX-mode-map [S-f12] 'wysiwyg-latex-tabular)
;;   (define-key LaTeX-mode-map (kbd "C-c !") 'TeX-next-error)
;;   (define-key LaTeX-mode-map (kbd "C-c i") 'index-current-word)
;;   (define-key LaTeX-mode-map (kbd "C-c l") 'my-label)
;;   (define-key LaTeX-mode-map [?\253] 'my-french-guill)
;;   ;(define-key LaTeX-mode-map "\"" 'my-french-guill)
;;   (define-key LaTeX-mode-map (kbd "C-c m") 'my-display-maths)
;;   (setq LaTex-math-abbrev-prefix (kbd "<pause>")))

;; (add-hook 'LaTeX-mode-hook 'my-latex-keys)
(require 'font-latex)

;; reftex -- D. Kastrup
(require 'reftex)
(add-hook 'LaTeX-mode-hook 'turn-on-reftex)
(setq reftex-plug-into-AUCTeX t)

;;; ... et c'est en couleurs !
(set-face-foreground 'font-lock-comment-face "gold")
(set-face-background 'font-lock-comment-face "grey32")
(set-face-background 'fringe "gray25")

(defun my-message-colors ()
  (interactive)
  (set-face-foreground 'message-cited-text-face "gold")
  (set-face-background 'message-cited-text-face "grey32"))
(eval-after-load "message-mode" 'my-message-colors)

;;; w3m
;;(setq w3m-icon-directory "/usr/src/ftp/cvs/emacs-w3m/icons")
;;(autoload 'w3m "w3m" "Interface for w3m on Emacs." t)

;;; mail
(add-hook 'mail-setup-hook 'mail-abbrevs-setup)

;(setq gnus-auto-select-next 'quietly)

;;; essai d'unification...
;(set-language-environment "Latin-1") 
(set-language-environment "utf-8")
                                        ;(setq gnus-group-posting-charset-alist
;      '((message-this-is-mail iso-8859-1 (iso-8859-1))
;       (message-this-is-news iso-8859-1 (iso-8859-1))))

;;; aussi dans ~/.gnus
;(setq mm-body-charset-encoding-alist
;      '((iso-8859-1 . 8bit)
;       (iso-8859-15 . 8bit)))

;(require 'ucs-tables)
;(unify-8859-on-encoding-mode 1)
;(unify-8859-on-decoding-mode 1)
;(standard-display-8bit 128 255)


;;;
(defun adieu ()
  (unless (y-or-n-p "Fermer cette instance d'Emacs ?")
    (keyboard-quit)))

(add-hook 'kill-emacs-hook
          'adieu)

(if (equal user-real-login-name "lhh")
    (require 'trucs))
;;; The End ;;;
 


;2/ Le fichier ~/.elisp21/trucs.el contient des trucs à l'essai

 
;;; trucs et bidules à l'essai
(message "les trucs...")

;;; Linus
;; (defun linux-c-mode ()
;;   "C mode with adjusted defaults for use with the Linux kernel."
;;   (interactive)
;;   (c-mode)
;;   (c-set-style "K&R")
;;   (setq c-basic-offset 8))

;;; Jay Belanger(defvar zoomconf nil)

;; (defun zoom-in ()
;;   "Maximize the current window, saving the current window configuration"
;;   (interactive)
;;   (setq zoomconf (current-window-configuration))
;;   (delete-other-windows))

;; (defun zoom-out ()
;;   "Restore the window configuration"
;;   (interactive)
;;   (set-window-configuration zoomconf))

;;; euro
(setq euro-rate 6.55957)
(defun cvef (&optional arg)
"Converts ARG euros to francs. If ARG is nil,
returns the exchange rate contained in euro-rate variable."
(interactive "p")
(if arg
    (/ (float (floor (+ 0.5 (* 100 (* euro-rate
                                      (if (numberp arg) arg
                                        (prefix-numeric-value arg))))))) 100)
  euro-rate))

(defun cvfe (&optional arg)
"Converts ARG francs to euros. If ARG is nil,
returns the exchange rate contained in euro-rate variable."
(interactive "p")
(if arg
    (/ (float (floor (+ 0.5 (* 100 (/ (if (numberp arg) arg
                                        (prefix-numeric-value arg))  euro-rate))))) 100)
  (/ 1 euro-rate)))

(defun conv-euro (&optional arg)
"Converts ARG euros to locale currency.
If ARG is nil, converts the number before point."
(interactive)
(if arg
    (cvef arg)
  (let ((pos (point))
        (value nil))
    (save-excursion
      (if (re-search-backward "^\\|[ \t\n]" 0 t 1)
          (if (re-search-forward "[0-9]*\\(.?[0-9]+\\)"
                                 pos t 1)
              (setq value (cvef (float
                                 (string-to-number
                                  (match-string 0)))))
            (setq value (cvef))))
      (if value
          (message "%s" value))))))

;;; calendrier
(require 'calendar)


(global-set-key [f11] (lambda ()
                        (interactive)
                        (require 'calendar)
                        (insert (calendar-french-date-string (calendar-current-date)))))


(global-set-key (kbd "C-c <deletechar>") 'delete-region)
(global-set-key (kbd "M-\"") 'my-french-guill)

;;; no-word
(autoload 'no-word "no-word" "word to txt")
(add-to-list 'auto-mode-alist '("\\.doc\\'" . no-word))
;;; ePiX
(setq auto-mode-alist (cons '("\\.xp" . epix-mode) auto-mode-alist))
(autoload 'epix-mode "epix" "ePiX editing mode" t)
(setq epix-mark-files-as-epix t)
(setq epix-insert-template-in-empty-buffer t)

(autoload 'flix-mode "epix" "ePiX editing mode" t)
(setq auto-mode-alist (cons '("\\.flx" . flix-mode) auto-mode-alist))

;;; Post
;;(require 'post)

;;; parenthÃ?ses
;;(global-set-key "%" 'goto-match-paren)
;; (defun goto-match-paren (arg)
;;   "Go to the matching parenthesis if on parenthesis, otherwise insert %."
;;   (interactive "p")
;;   (cond ((looking-at "\\s\(") (forward-list 1) (backward-char 1))
;;         ((looking-at "\\s\)") (forward-char 1) (backward-list 1))
;;         (t (self-insert-command (or arg 1)))))

;; This will match the corresponding ( even when the cursor
;; is on or following the ) char

;; (defun goto-match-paren (arg)
;;   "Move to the parenthesis matching the one under or before the
;; cursor, otherwise insert %"
;;   (interactive "p")
;;   (cond ((looking-at "\\s\(") (forward-list 1) t)
;;      ((eq (char-syntax (preceding-char)) ?\)) (backward-list 1) t)
;;      ((looking-at "\\s\)") (forward-char 1) (backward-list 1) t)
;;         (t (self-insert-command (or arg 1)))))

;;; indentation auto
(global-set-key (kbd "RET") 'newline-and-indent)
(define-key text-mode-map (kbd "RET") 'newline)

;;; voir les images
(auto-image-file-mode t)

;;; jit-lock
(setq-default
 jit-lock-stealth-time 16
 jit-lock-stealth-nice 0.5
 jit-lock-defer-contextually t
 font-lock-multiline t)

;; B. Rutt
(setq gc-cons-threshold 4000000)


;(define-key global-map [menu-bar]
;  (remove '(buffer) (lookup-key global-map [menu-bar])))
;(define-key global-map [menu-bar buffer]
;  (cons "Buffers" (make-sparse-keymap "Buffers")))

;;(menu-bar-mode -1) ; pas de menu apparent par défaut

;(require 'wysiwyg-latex-tabular)


;;(define-key LaTeX-mode-map (kbd "C-<f6>") 'nuke-trailing-white-space)
(global-set-key (kbd "C-<f6>") 'nuke-trailing-white-space)

(set-face-font 'modeline "8x13")

;;; Aspell
(setq-default ispell-program-name "aspell")

;;; Fin ;;;
(provide 'trucs)
(message "OK pour les trucs")

;;; 1 Germinal an 213 de la Révolution
 

 
;;; This code determines the buffer language by counting several small and
;;; often used words characteristic each language and ranks them.  The
;;; original version was posted by Jean-Philippe Theberge.
;;;    From: Jean-Philippe Theberge <mailto:jphil@godzilla.act.oda.fr> 
;;;    Subject: Re: Guessing a language.
;;;    Newsgroups: gnu.emacs.help
;;;    Date: 03 Mar 2000 16:46:41 +0100"
;;; Adapted by Alex Schroeder <alex@gnu.org>

;;; modified by Jacques L'helgoualc'h <lhh@free.fr> 17:28:49, dimanche 20 mai 2001

;;; Installation: put this file somewhere in your load-path,
;;;
;;;             (require 'guess-lang)
;;;
;;; in your ~/.emacs, set initial values like:
;;;
;;;  (setq
;;;   flyspell-default-dictionary "francais"
;;;   ispell-other-dictionary "british")
;;;
;;; and set keys as you want:
;;;
;;;(global-set-key (kbd "<f7>") 'guess-dictionary)

;; (require 'cl)

;; (defvar guess-language-rules
;;   '(("en" . "\\<\\(of\\|the\\|and\\|or\\|how\\)\\>")
;;     ("de" . "\\<\\(und\\|oder\\|der\\|die\\|das\\|wie\\)\\>") 
;;     ("fr" . "\\<\\(et\\|ou\\|[ld]es\\|que\\)\\>"))
;;   "Alist of rules to determine the language of some text.
;;     Each rule has the form (CODE . REGEXP) where CODE is a string to
;;     identify the language (probably according to ISO 639), and REGEXP is a
;;     regexp that matches some very common words particular to that language.
;;     The default language should be listed first.  That will be the language
;;     returned when no REGEXP matches, as would happen for an empty
;;     document.")

;; (defvar lang-dictionary-alist
;;   '(("en" . "british")
;;     ("de" . "deutsch")
;;     ("fr" . "francais"))
;;   "Alist of rules (LANG . ISPELL-DICTIONARY)")

;; (defun guess-buffer-language ()
;;   "Guess language in the current buffer"
;;   (save-excursion 
;;     (goto-char (point-min))
;;     (let ((count (map 'list (lambda (x)
;;                            (cons (string-to-number
;;                                   (count-matches (cdr x))) (car x)))
;;                    guess-language-rules)))
;;       (cdr (assoc (car (sort (map 'list 'car count) '>)) 
;;                count)))))

;; (defun guess-lang ()
;;   "Guess language in the current buffer."
;;   (interactive)
;;   (message (guess-buffer-language)))

;; (defun guess-dictionary ()
;;   "Set ispell-local-dictionary according to guessed language"
;;   (interactive)
;;   (ispell-change-dictionary 
;;    (setq ispell-local-dictionary (cdr (assoc (setq lang (guess-buffer-language)) lang-dictionary-alist))))
;;   (set-face-inverse-video-p 'modeline (not (equal ispell-local-dictionary flyspell-default-dictionary)))
;;   (message (concat "Ispell will use dictionary: " ispell-local-dictionary)))

;; ;;; 
;; (defun lang-toggle ()
;;   "Toggles between two languages - Alterne entre deux langues"
;;   (interactive)
;;   (ispell-change-dictionary
;;    (setq ispell-local-dictionary
;;       (if (set-face-inverse-video-p
;;            'modeline
;;            (equal ispell-local-dictionary flyspell-default-dictionary))
;;           ispell-other-dictionary
;;         flyspell-default-dictionary))))

;; (provide 'guess-lang)
 

 
;;; wysiwyg-latex-tabular.el - Adjust spacing in LaTeX tabular constructs
;;;
;;; Copyright © 1992-2003 Dag Asheim, Linpro AS
;;;
;;; Author: Dag Asheim <dash@linpro.no>
;;;
;;; $Id: wysiwyg-latex-tabular.el,v 1.41 2003/01/16 20:27:25 dash Exp $

;;; This file is not (yet) part of GNU Emacs.
;;;
;;; This is free software; you can redistribute it and/or modify it
;,; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 2, or (at your option)
;,; any later version.

;;; LaTeX and WYSIWYG (What You See Is What You Get) are two very
;;; different concepts, each with their own pros and cons. The ideas
;;; behind LaTeX and structured mark-up are excellent, but even the
;;; most avid LaTeX proponent can have a hard time justifying (pun
;;; intended) layout of complex \multicolumn-ridden LaTeX tables.
;;;
;;; This code attempts to aid in that process by bringing just a touch
;;; of WYSIWYG to the table.  Wouldn't it be nice if there was some
;;; Emacs Lisp function that could transform the following LaTeX code:
;;;
;;; \begin{tabular}{lcr}\hline
;;; left justified&centred&right justified\\
;;; l&c&r\\
;;; \& and \%&\multicolumn{2}{|c|}{centred over 2 columns}\\
;;; \multicolumn{2}{|l|}{left justified over 2 columns}&r\\
;;; \end{tabular}
;;;
;;; ... to something more readable?  Let's say, something like this:
;;;
;;; \begin{tabular}{lcr}\hline
;;; left justified &              centred               & right justified \\
;;; l              &                 c                  &               r \\
;;; \& and \%      &     \multicolumn{2}{|c|}{centred over 2 columns}     \\
;;; \multicolumn{2}{|l|}{left justified over 2 columns} &               r \\
;;; \end{tabular}
;;;
;;; If you agree, then this code might be for you.  Features:
;;;
;;;  o Supports most of LaTeX's table making environments (check out
;;;    the ones you don't have from www.ctan.org):
;;;
;;;    Environment                     Description
;;;    \begin{tabular}{FMT}            Standard table, format FMT
;;;    \begin{tabular*}{W}{FMT}        Table of width W and format FMT
;;;    \begin{array}{FMT}              Typeset table in math mode
;;;    \begin{supertabular}{FMT}¹      Table can span more than 1 page
;;;    \begin{supertabular*}{W}{FMT}¹  Width = W, more than 1 page
;;;    \begin{longtable}{FMT}²        Table can span more than 1 page
;;;    \begin{tabularx}{W}{FMT}²       Width = W, supports format X
;;;    \begin{ltxtable}{W}{FMT}²       Combines longtable and tabularx
;;;    \begin{array}DELIM{FMT}DELIM³   As array, but with delimiters
;;;
;;;    ¹ \usepackage{supertab} is needed to provide these to LaTeX.
;;;
;;;    ² These environments must be imported to LaTeX with
;;;      \usepackage{name-of-environment} before use.
;;;
;;;    ³ After an \usepackage{delarray} declaration, it it possible to
;;;      include delimiters around the format string of an array
;;;      environment to get huge delimiters around the table in the
;;;      output.  The delimiters can be: \{, \}, (, ), |, or . (for no
;;;      delimiter).
;;;
;;;    (Btw, all this has nothing to do with the environment named
;;;    'table', which (confusingly) is inessential for making tables.)
;;;
;;;  o Supports the following column format codes:
;;;
;;;    Format code       Effect on LaTeX tables
;;;    l                 Left justify
;;;    c                 Center
;;;    r                 Right justify
;;;    p{WIDTH}          Paragraph, can be multiline (aligned as 'l')
;;;    @{CODE}           Suppress spacing and insert CODE at each row
;;;    |                 Vertical line - does not create a column
;;;    *{COUNT}{FORMAT}  COUNT repetitions of FORMAT
;;;    X¹               As p, but width is calculated automatically
;;;    m{WIDTH}²        As p, but vertically aligned in the middle
;;;    b{WIDTH}²        As p, but vertically aligned to the bottom
;;;    >{CODE}²                 Insert CODE before next column
;;;    <{CODE}²                 Insert CODE after previous column
;;;    !{CODE}²                 Insert CODE at each row (but keep spacing)
;;;    P{SPEC}³                 Format numbers (supported as an 'r'-column)
;;;    D{TEX}{DVI}{NR}³         Format numbers (supported as an 'r'-column)
;;;
;;;    ¹ \usepackage{tabularx} or \usepackage{ltxtable} is needed to
;;;      provide the format code X to LaTeX, and it is then only
;;;      recognised within the respective environments.
;;;
;;;    ² \usepackage{array} is needed to provide these 5 format codes
;;;      to LaTeX, but then they are available to the regular tabular
;;;      environments.
;;;
;;;    ³ These environments align numbers on decimal point:
;;;      \usepackage{warpcol} is needed for P (e.g P{3.1}) and
;;;      \usepackage{dcolumn} is needed for D (e.g D{.}{\cdot}{2}).
;;;
;;;  o Supports \multicolumn, and (for brevity) the abbreviation \mc
;;;    (for \mc to work in LaTeX, an declaration such as the following
;;;    is needed: \def\mc{\multicolumn})
;;;
;;;  o Points out some common mistakes in the table formating:
;;;
;;;    These are marked as errors (no processing is done):
;;;
;;;    - Not in LaTeX tabular(*{})/array/supertabular(*{})/-
;;;      longtable/tabularx/ltxtable{} format
;;;    - Empty format string - no use of l, c, r, X, p{}, m{}, b{},
;;;      @{}, !{}, <{}, >{}, or *{}{}
;;;    - Error in format string, unrecognised character: '...'
;;;    - Format string requires ... columns, but more are
;;;      present in row ...
;;;    - Format string requires ... columns, but only ... are
;;;      present in row ...
;;;    - Mismatched environment: \begin{E1} ... \end{E2}
;;;
;;;    This is just a warning (i.e. the processing is done):
;;;
;;;    - Warning: Format code 'X' used in ... environment, not
;;;      tabularx or ltxtable
;;;
;;; Basic assumptions:
;;;
;;; This code is meant for tables where each row in the table are on a
;;; single line in the input.  This may lead to very long lines on
;;; some tables.  LaTeX does not require \\ at the end of the last
;;; row, but this code does.  Text after \\ is ignored for formating
;;; purposes, so don't put &-signs there.

;; (defun wysiwyg-latex-tabular ()
;;   "Align columns in LaTeX tabular constructs, giving a quasi-WYSIWYG effect.
;; The alignment is based on the format string (e.g. {lcr}) to make the
;; spacing in the mark-up similar to the printed output.

;; Before:

;; \\begin{tabular}{lcr}\\hline
;; left justified&centred&right justified\\\\
;; l&c&r\\\\
;; \\& and \\%&\\multicolumn{2}{|c|}{centred over 2 columns}\\\\
;; \\multicolumn{2}{|l|}{left justified over 2 columns}&r\\\\
;; \\end{tabular}

;; After:

;; \\begin{tabular}{lcr}\\hline
;; left justified &              centred               & right justified \\\\
;; l              &                 c                  &               r \\\\
;; \\& and \\%      &     \\multicolumn{2}{|c|}{centred over 2 columns}     \\\\
;; \\multicolumn{2}{|l|}{left justified over 2 columns} &               r \\\\
;; \\end{tabular}"
;;   (interactive "*")

;;   (defun unique-string-in-buffer (&optional init start end limit)
;;     "Return a string which don't (yet) exist in current buffer."

;;     (defun a+ (str limit)
;;       "Increase value of string STR destructivly, as a base LIMIT number."
;;       (cond ((string= str "")
;;           (string 0))
;;          ((< (aref str (1- (length str))) (1- limit))
;;           (progn (aset str (1- (length str))
;;                        (1+ (aref str (1- (length str)))))
;;                  str))
;;          ((concat (a+ (substring str 0 -1) limit) (string 0)))))

;;     (let* ((limit (if (null limit) 32 limit))
;;         (str (cond ((stringp init) (a+ (copy-sequence init) limit))
;;                    ((integerp init) (make-string init 0))
;;                    (make-string 0)))
;;         (start (if (null start) (point-min) start)))
;;       (save-excursion
;;      (goto-char start)
;;      (while (re-search-forward str end t)
;;        (goto-char start)
;;        (setq str (a+ str limit))))
;;       str))


;;   (defun width-from-to (c1 c2)
;;     "Calculate the width from column C1 to C2, based on the widths array."
;;     (let ((sum 0))
;;       (while (< c1 c2)
;;      (setq sum (+ sum (aref widths c1) 3) ; 3 == (length " & ")
;;            c1 (1+ c1)))
;;       (+ sum (aref widths c1))))


;;   (defun re-paren (&optional n)
;;     "Return the string matched by the last search in the current buffer.
;; Argument N is number of the parenthesis which matched, 1 by default."
;;     (if (null n)
;;      (setq n 1))
;;     (buffer-substring (match-beginning n) (match-end n)))


;;   (defun match-int (n)
;;     "Return the integer matched by the last search in the current buffer.
;; Argument N is number of the parenthesis which matched."
;;     (string-to-int (re-paren n)))


;;   (defun insert-3 (c2 c1 w ll)
;;     "Insert '(C2 C1 W) into the list LL.
;; LL has the form ((ac2 ac1 aw) (bc2 bc1 bw) ...), with ac2 < bc2."
;;     (if (or (null ll) (< c2 (car (car ll))))
;;      (cons (list c2 c1 w) ll)
;;       (cons (car ll) (insert-3 c2 c1 w (cdr ll)))))


;;   (defun parse-format ()
;;     "Parse the format string from a LaTeX array/tabular construct.
;; The function does not take any arguments, but it communicates with
;; the caller by reading (match-end 0)"

;;     (defun parse-format-internal (pt fmt rep)
;;       "The internal parsing function for tabular format strings.
;; Start at position PT.  Append result to FMT.  Do REP repetitions.  Return FMT."
;;       (while (<= 0 (setq rep (1- rep)))
;;      (goto-char pt)
;;      (while (looking-at re-fmt)
;;        (goto-char (match-end 0))
;;        (cond ((memq (char-after (match-beginning 0))
;;                     '(?l ?c ?r ?p ?m ?b ?X ?P ?D))
;;               (setq fmt (cons (char-after (match-beginning 0)) fmt)))
;;              ((eq (char-after (match-beginning 0)) ?*)
;;               (setq fmt
;;                     (parse-format-internal (point) fmt (match-int 1)))))))
;;       (if (eq (char-after) ?\})
;;        (forward-char)
;;      (error "Error in format string, unrecognised character: '%c'"
;;             (char-after)))
;;       fmt)

;;     (or (nreverse (parse-format-internal (match-end 0) '() 1))
;;      (error "Empty format string - no use of l, c, r, X, p{}, m{}, b{}, @{}, !{}, <{}, >{}, *{}{}, P{}, or D{}{}{}")))


;;   (let ((fmt '())                    ; List of format codes for each column
;;      (widths '())                    ; Used as a vector (aset/aref)
;;      (multi  '())                    ; \multicolumn data: '((C2 C1 W) ...)
;;      (colnum 0)                      ; Number of current column
;;      (maxcol 0)                      ; Max number of columns/length of fmt
;;      (maxw   0)                      ; Max width in characters
;;      (w      0)                      ; Width of current cell
;;      (tmp    0)
;;      (unique1 "")
;;      (unique2 "")
;;      (unique3 "")
;;      (newtable "")
;;      (marker '())
;;      (origpos (point))
;;      (delta  0)
;;      (type   0)                      ; Format type
;;      (envir '())                     ; Environment (following \begin)
;;      (re-beg "\\\\begin{\\(\\(tabular\\*\\|supertabular\\*\\|tabularx\\|ltxtable\\)}{[^}]*\\|tabular\\|supertabular\\|array\\|longtable\\)}\\(\\[[tb]\\]\\)?\\(%[^\n]*\n\\)*\\(\\\\[{}]\\|[(|).]\\)?{")
;;      (re-end "\\\\end{\\(\\(super\\)?tabular\\*?\\|array\\|longtable\\|tabularx\\|ltxtable\\)}")
;;      (re-fs "%\\|\n\\|&\\|\\\\\\\\") ; Field (+ line) separator
;;      (re-fmt "[lcrX|]\\|[pmb@!><P]{[^}]*}\\|D{[^}]*}{[^}]*}{[^}]*}\\|\\*{\\([0-9]+\\)}{")
;;      (re-mc  "[ \t]*\\\\\\(multicolumn\\|mc\\){\\([1-9][0-9]*\\)}{"))
;;     (save-excursion
;;       (end-of-line)
;;       (condition-case err (re-search-backward re-beg)
;;      (search-failed (error "Not in LaTeX tabular(*{})/array/supertabular(*{})/longtable/tabularx/ltxtable{} format")))

;;       (setq envir (buffer-substring (match-beginning 1) (match-end 1))
;;          fmt (parse-format))

;;       (if (string-match "}{.*" envir)        ; Search for and ...
;;        (setq envir (replace-match "" t t envir))) ; ... remove '}{width'

;;       (if (and (memq ?X fmt) (not (member envir '("tabularx" "ltxtable"))))
;;        (message "%s%s%s"
;;                 "Warning: Format code 'X' used in "
;;                 envir
;;                 " environment, not tabularx or ltxtable"))

;;       (setq maxcol (length fmt)              ; Init maxcol
;;          widths (make-vector maxcol 0)) ; Set all widths to 0

;;       (forward-line)

;;       (setq delta (- origpos (point)))

;;       (setq buf (current-buffer)
;;          start (point)
;;          end
;;          (save-excursion
;;            (re-search-forward re-end nil 'move)
;;            (if (not (string= envir (re-paren)))
;;                (error "Mismatched environment: \\begin{%s} ... \\end{%s}"
;;                       envir
;;                       (re-paren)))
;;            (1- (match-beginning 0))))

;;       (setq
;;        newtable
;;        (with-temp-buffer             ; Copy table to scratch buffer
;;       (insert-buffer-substring buf start end)

;;       (setq marker (make-marker))
;;       (set-marker marker delta)

;;       (setq unique1 (unique-string-in-buffer 2))

;;       (goto-char (point-min))
;;       (while (re-search-forward "\\\\&" nil t)
;;         (replace-match unique1 t t)) ; Hide \&

;;       (setq unique2 (unique-string-in-buffer unique1))

;;       (goto-char (point-min))
;;       (while (re-search-forward "\\\\%" nil t)
;;         (replace-match unique2 t t)) ; Hide \%

;;       (setq unique3 (unique-string-in-buffer unique2))

;;       (goto-char (point-min))
;;       (while (re-search-forward "%[^\n&]*\\(&\\)" nil t)
;;         (replace-match unique3 t t nil 1) ; Hide & after %
;;         (goto-char (point-min)))

;;       (goto-char (point-min))
;;       (while (re-search-forward "[ \t]*&[ \t]*" nil t) ; Kill whitespace
;;         (replace-match "&" t t))

;;       (goto-char (point-min))
;;       (while (re-search-forward "^[ \t]+\\|[ \t]+$" nil t)
;;         (replace-match "" t t))

;;       (goto-char (point-min))
;;       (while (re-search-forward "[ \t]+\\\\\\\\" nil t)
;;         (replace-match "\\\\" t t))

;;       (goto-char (point-min))

;;       (while (not (eobp))            ; Find the width of the rows
;;         (setq w (- (save-excursion (re-search-forward re-fs nil t)
;;                                    (match-beginning 0))
;;                    (point)))         ; w == width of current cell
;;         (cond ((looking-at re-mc)
;;                (setq multi (insert-3 (+ colnum (match-int 2) -1)
;;                                      colnum w multi)
;;                      colnum (+ colnum (match-int 2) -1)))
;;               ((< (aref widths colnum) w)
;;                (aset widths colnum w))) ; width = max width
;;         (forward-char w)
;;         (cond ((looking-at "\\\\\\\\")
;;                (if (< (1+ colnum) maxcol)
;;                    (error "Format string requires %d columns, but only %d are present in row %d"
;;                           maxcol
;;                           (1+ colnum)
;;                           (count-lines (point-min) (point))))
;;                (setq colnum 0)
;;                (forward-line))
;;               ((looking-at "\n")
;;                (forward-line))
;;               ((looking-at "%")
;;                (forward-line))
;;               ((looking-at "&")
;;                (setq colnum (1+ colnum))
;;                (forward-char)))
;;         (if (<= maxcol colnum)
;;             (error "Format string requires %d columns, but more are present in row %d"
;;                    maxcol
;;                    (count-lines (point-min) (point)))))
;;       (goto-char (point-min))

;;       ;; (aref widths N) == max width of row N, excluding \multicolumn

;;       (while multi           ; Adjust field widths for \multicolumn
;;         (let* ((c2 (car (car multi))) ; Ending column
;;                (w (car (cdr (cdr (car multi))))) ; Width from \multicolumn
;;                (cw (width-from-to (car (cdr (car multi))) c2)))
;;           (if (< cw w)
;;               (aset widths c2 (+ (aref widths c2) (- w cw))))
;;           (setq multi (cdr multi))))

;;       ;; (aref widths N) == max width of row N, including \multicolumn

;;       (while (not (eobp))            ; Insert correct spacing
;;         (setq colnum 0)
;;         (while (< colnum maxcol)
;;           (if (looking-at re-mc)
;;               (setq type (let ((data (match-data)))
;;                            (prog1 (save-excursion
;;                                     (car (parse-format)))
;;                              (store-match-data data)))
;;                     maxw (width-from-to colnum
;;                                         (+ colnum -1 (match-int 2)))
;;                     colnum (+ colnum (match-int 2)))
;;             (setq type (nth colnum fmt)
;;                   maxw  (aref widths colnum)
;;                   colnum (1+ colnum)))
;;           (setq w (- (save-excursion (re-search-forward re-fs nil t)
;;                                      (match-beginning 0))
;;                      (point))
;;                 tmp (- maxw w))
;;           (cond ((memq type '(?l ?p ?m ?b ?X))
;;                  (forward-char w)    ; Align left,
;;                  (insert-char 32 tmp)) ; spaces after
;;                 ((memq type '(?c))   ; Align centre,
;;                  (insert-char 32 (/ tmp 2)) ; space before...
;;                  (forward-char w)
;;                  (insert-char 32 (/ (1+ tmp) 2))) ; ... and after
;;                 ((memq type '(?r ?P ?D)) ; Align right,
;;                  (insert-char 32 tmp) ; space before
;;                  (forward-char w)))
;;           (if (looking-at "\n\\|%")
;;               (progn
;;                 (setq colnum (1- colnum))
;;                 (forward-line)
;;                 (if (< 0 colnum)
;;                     (insert-char 32 (+ 3 (width-from-to 0 (1- colnum)))))
;;                 (backward-char)))
;;           (forward-char))
;;         (forward-line))

;;       (goto-char (point-min))        ; Insert space around &
;;       (while (re-search-forward "&" nil t)
;;         (replace-match " & " t t))

;;       (goto-char (point-min))        ; Insert space before \\
;;       (while (re-search-forward "\\\\\\\\" nil t)
;;         (replace-match " \\\\" t t))

;;       (goto-char (point-min))        ; Restore & after %
;;       (while (re-search-forward unique3 nil t)
;;         (replace-match "&" t t))

;;       (goto-char (point-min))        ; Restore \%
;;       (while (re-search-forward unique2 nil t)
;;         (replace-match "\\%" t t))

;;       (goto-char (point-min))        ; Restore \&
;;       (while (re-search-forward unique1 nil t)
;;         (replace-match "\\&" t t))

;;       (goto-char (point-min))        ; Remove indention on comments
;;       (while (re-search-forward "\n *%" nil t)
;;         (replace-match "\n%" t t))

;;       (list (marker-position marker) (buffer-string))))

;;       (setq delta (car newtable))
;;       (if (or (<= origpos start) (< end origpos))
;;        (setq delta 0))
;;       (delete-region start end)
;;       (insert (car (cdr newtable))))
;;     (forward-char delta)))

;; ;;;
;; (provide 'wysiwyg-latex-tabular)



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


;; LATEX PERSO

(require 'asy-mode)
 (eval-after-load "latex"
   '(progn
      (define-key LaTeX-mode-map (kbd "<C-return>") 'lasy-view-ps)
      (define-key LaTeX-mode-map (kbd "<C-S-return>") 'asy-master-tex-view-ps-f)
      (define-key LaTeX-mode-map (kbd "<M-return>") 'lasy-view-pdf-via-pdflatex)
      (define-key LaTeX-mode-map (kbd "<M-S-return>") 'asy-master-tex-view-pdflatex-f)
      (define-key LaTeX-mode-map (kbd "<C-M-return>") 'lasy-view-pdf-via-ps2pdf)
      (define-key LaTeX-mode-map (kbd "<C-M-S-return>") 'asy-master-tex-view-ps2pdf-f)))


(defvar guillaume-latexbis-command " latex -interaction=nonstopmode %s.tex  && dvips -o %s.ps  %s.dvi && ps2pdf %s.ps %s.pdf && rm %s.ps ")

(defun guillaume-latexbis () (interactive)
   (save-buffer)
 (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-latexbis-command
                fnse  fnse  fnse fnse fnse fnse fnse))))
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super l) (super l)] 'guillaume-latexbis)))





(defvar guillaume-pdfbis-command "pdflatex  -interaction=nonstopmode %s.tex")

(defun guillaume-pdfbis () (interactive)
   (save-buffer)
 (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-pdfbis-command
                    fnse fnse))))
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super d) (super d)] 'guillaume-pdfbis)))



(defvar guillaume-asy-command "latex %s.tex && asy %s && latex %s.tex && latex %s.tex  && dvips -o %s.ps  %s.dvi && ps2pdf %s.ps %s.pdf && rm %s.ps")

(defun guillaume-asy () (interactive)
   (save-buffer)
    (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-asy-command
                fnse fnse fnse fnse fnse fnse fnse fnse fnse))))
(add-hook 'LaTeX-mode-hook
          '(lambda nil
             (define-key LaTeX-mode-map [(super c) (super a)] 'guillaume-asy)))



(defvar guillaume-asyr-command "rm %s.asy && rm *.pdf && rm *.thm")

(defun guillaume-asyr () (interactive)
   (save-buffer)
    (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-asyr-command
                fnse fnse fnse fnse ))))
(add-hook 'LaTeX-mode-hook
          '(lambda nil
             (define-key LaTeX-mode-map [(super c) (super A)] 'guillaume-asyr)))





;; (defvar guillaume-asyp-compile "asy -f pdf -wait %s && acroread %s.pdf")

;; (defun guillaume-asyp () (interactive)
;;    (save-buffer)
;;     (let ((fnse (file-name-sans-extension (buffer-file-name))))
;;     (shell-command (format
;;                     guillaume-asyp-compile
;;                 fnse fnse ))))
;; (add-hook 'asy-mode-hook
;;        '(lambda nil
;;           (define-key asy-mode-map [(super a) (super a)] 'guillaume-asyp)))




;; (defvar guillaume-asye-compile "asy -wait %s && okular %s.eps")

;; (defun guillaume-asye () (interactive)
;;    (save-buffer)
;;     (let ((fnse (file-name-sans-extension (buffer-file-name))))
;;     (shell-command (format
;;                     guillaume-asye-compile
;;                 fnse fnse ))))
;; (add-hook 'asy-mode-hook
;;        '(lambda nil
;;           (define-key asy-mode-map [(super a) (super e)] 'guillaume-asye)))





(defvar guillaume-compile-command "rubber -pd %s.tex && rm %s.ps")

(defun guillaume-compile () (interactive)
   (save-buffer)
    (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-compile-command
                fnse fnse ))))
(add-hook 'LaTeX-mode-hook
          '(lambda nil
             (define-key LaTeX-mode-map [(super c) (super l)] 'guillaume-compile)))





;; (defvar asyguillaume-compile-command "rubber -pd %s.tex && rm %s.ps")

;; (defun asyguillaume-compile () (interactive)
;;    (save-buffer)
;;     (let ((fnse (file-name-sans-extension (buffer-file-name))))
;;     (shell-command (format
;;                     asyguillaume-compile-command
;;                 fnse fnse ))))
;; (add-hook 'lasy-mode-hook
;;        '(lambda nil
;;           (define-key lasy-mode-map [(super c) (super l)] 'asyguillaume-compile)))








(defvar guillaume-compilepdf-command "rubber -dsv %s")

(defun guillaume-compilepdf () (interactive)
   (save-buffer)
   (shell-command (format guillaume-compilepdf-command buffer-file-name))
   )
(add-hook 'LaTeX-mode-hook
          '(lambda nil
             (define-key LaTeX-mode-map [(super c) (super p)] 'guillaume-compilepdf)))




(defvar guillaume-shellesc-command " latex -shell-escape -interaction=nonstopmode %s.tex  && dvips -o %s.ps  %s.dvi && ps2pdf %s.ps %s.pdf && rm %s.ps")

(defun guillaume-shellesc () (interactive)
   (save-buffer)
 (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-shellesc-command
                fnse  fnse  fnse fnse fnse fnse fnse))))
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super w) (super l)] 'guillaume-shellesc)))





(defvar guillaume-shellescp-command "pdflatex   -shell-escape -interaction=nonstopmode %s.tex ")

(defun guillaume-shellescp () (interactive)
   (save-buffer)
 (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-shellescp-command
                    fnse ))))
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super w) (super p)] 'guillaume-shellescp)))


(defvar guillaume-shellescpd-command "pdflatex   -shell-escape -interaction=nonstopmode %s.tex &&  okular %s.pdf &")

(defun guillaume-shellescpd () (interactive)
   (save-buffer)
 (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-shellescpd-command
                    fnse fnse))))
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super w) (super d)] 'guillaume-shellescpd)))


(defvar guillaume-shellescx-command "xelatex   -shell-escape -interaction=nonstopmode %s.tex &&  okular %s.pdf &")

(defun guillaume-shellescx () (interactive)
   (save-buffer)
 (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-shellescx-command
                    fnse fnse))))
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super x) (super e)] 'guillaume-shellescx)))







(defvar guillaume-view-command "kghostview %s.ps & " "&")

(defun guillaume-view () (interactive)
   (save-buffer)
   (shell-command (format guillaume-view-command
(file-name-sans-extension(buffer-file-name))))
   )
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super c) (super v)] 'guillaume-view)))


(defvar guillaume-rubber-command "rubber --ps --clean %s")

(defun guillaume-rubber () (interactive)
   (save-buffer)
   (shell-command (format guillaume-rubber-command
buffer-file-name))
   )
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super c) (super r)] 'guillaume-rubber)))



(defvar guillaume-pdf-command "okular %s.pdf & ")

(defun guillaume-pdf () (interactive)
   (save-buffer)
   (shell-command (format guillaume-pdf-command
(file-name-sans-extension(buffer-file-name))))
   )
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super c) (super o)] 'guillaume-pdf)))




(defvar guillaume-pdfa-command "acroread %s.pdf & ")

(defun guillaume-pdfa () (interactive)
   (save-buffer)
   (shell-command (format guillaume-pdfa-command
(file-name-sans-extension(buffer-file-name))))
   )
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super c) (super d)] 'guillaume-pdfa)))




;;Livret a5
(defvar guillaume-livreta5-command
  "psbook  %s.ps | psnup -2 | pstops -pa4 2:0,1U\\(1w,1h\\) > %s_livret_a5.ps | ps2pdf %s_livret_a5.ps")

(defun guillaume-livreta5 ()
  (interactive)
  (save-buffer)
  (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-livreta5-command
                    fnse fnse fnse))))
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super c) (super s)] 'guillaume-livreta5)))



;; Livret a4
(defvar guillaume-livreta4-command "psbook  %s.ps | psnup -pa3 -Pa4 -2 | pstops -pa4 2:0,1U\\(1w,1h\\) >  %s_livret_a4.ps| ps2pdf %s_livret_a4.ps")

(defun guillaume-livreta4 () (interactive)
   (save-buffer)
 (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-livreta4-command
                    fnse fnse))))
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super c) (super S)] 'guillaume-livreta4)))







;(setq auto-mode-alist (cons '("\\.tex\\" . LaTeX-mode) auto-mode-alist))
;(setq auto-mode-alist (cons '("\\.sty\\" . LaTeX-mode) auto-mode-alist))

;; pgiac
(setq auto-mode-alist
(append '(("\\.w\\' " . LaTeX-mode) ) auto-mode-alist) )


(defvar guillaume-pgiac-command "pgiac -f eps  %s.w && latex -interaction=nonstopmode %s.tex && latex -interaction=nonstopmode %s.tex && dvips -o %s.ps  %s.dvi && ps2pdf %s.ps %s.pdf && rm %s.ps ")

(defun guillaume-pgiac () (interactive)
   (save-buffer)
 (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-pgiac-command
                fnse  fnse  fnse fnse fnse fnse fnse fnse fnse))))
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super c) (super g)] 'guillaume-pgiac)))



(defvar guillaume-pgiacse-command "pgiac -f eps  %s.w && latex -shell-escape -interaction=nonstopmode %s.tex && latex -shell-escape -interaction=nonstopmode %s.tex && dvips -o %s.ps  %s.dvi && ps2pdf %s.ps %s.pdf && rm %s.ps ")

(defun guillaume-pgiacse () (interactive)
   (save-buffer)
 (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-pgiacse-command
                fnse  fnse  fnse fnse fnse fnse fnse fnse fnse))))
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super w) (super g)] 'guillaume-pgiacse)))


(defvar guillaume-pgiacf-command "pgiac -f pdf %s.w && pdflatex -interaction=nonstopmode %s.tex && pdflatex -interaction=nonstopmode %s.tex &&  okular %s.pdf &")

(defun guillaume-pgiacf () (interactive)
   (save-buffer)
 (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-pgiacf-command
                    fnse fnse fnse fnse fnse fnse fnse))))
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super c) (super f)] 'guillaume-pgiacf)))


;;pscilab



(defvar guillaume-psci-command " pscilab %s.w  &")

(defun guillaume-psci () (interactive)
   (save-buffer)
 (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-psci-command
                fnse   fnse fnse ))))
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super s) (super s)] 'guillaume-psci)))




(defvar guillaume-pscilab-command "pscilab  %s.w && pdflatex -interaction=nonstopmode %s.tex && pdflatex -interaction=nonstopmode %s.tex &&  okular %s.pdf &")

(defun guillaume-pscilab () (interactive)
   (save-buffer)
 (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-pscilab-command
                    fnse fnse fnse fnse fnse fnse fnse))))
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super s) (super p)] 'guillaume-pscilab)))




(defvar guillaume-pscilabe-command "pscilab %s.w && latex -interaction=nonstopmode %s.tex && dvips -o %s.ps  %s.dvi && ps2pdf %s.ps %s.pdf && rm %s.ps && okular %s.pdf &")

(defun guillaume-pscilabe () (interactive)
   (save-buffer)
 (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-pscilabe-command
                fnse  fnse  fnse fnse fnse fnse fnse fnse ))))
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super s) (super l)] 'guillaume-pscilabe)))




(add-hook 'LaTeX-mode-hook
'(lambda ()
(load "std_comment")))

(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super h)] 'std-file-header)))



;; (require 'filladapt)
;; (defun sk-text-hook ()
;;   (set-fill-column 70)
;;   (turn-on-auto-fill)
;;   (filladapt-mode)
;;   (flyspell-mode)
;;   (setq default-justification 'full)
;;   (setq footnote-spaced-footnotes nil
;;      footnote-section-tag "")
;;   (footnote-mode)
;;   )
;; (add-hook 'LaTeX-mode-hook 'sk-text-hook)







;;index multiple secondaire nommé cdx
(defvar guillaume-indexmul-command
  "makeindex -o %s.cnd -t %s.clg %s.cdx")

(defun guillaume-indexmul ()
  (interactive)
  (save-buffer)
  (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-indexmul-command
                    fnse fnse fnse))))
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super c) (super i)] 'guillaume-indexmul)))




;;index multiple par défaut nommé idx
(defvar guillaume-indexmuld-command
  "makeindex -o %s.ind -t %s.ilg %s.idx")

(defun guillaume-indexmuld ()
  (interactive)
  (save-buffer)
  (let ((fnse (file-name-sans-extension (buffer-file-name))))
    (shell-command (format
                    guillaume-indexmuld-command
                    fnse fnse fnse))))
(eval-after-load "latex"
  '(progn
             (define-key LaTeX-mode-map [(super c) (super x)] 'guillaume-indexmuld)))




;; * Metapost *
;;(load "meta")



  (autoload 'metafont-mode "meta-mode" "Metafont editing mode." t)
  (autoload 'metapost-mode "meta-mode" "MetaPost editing mode." t)

  (setq auto-mode-alist
        (append '(("\\.mf\\'" . metafont-mode)
                  ("\\.mp\\'" . metapost-mode)) auto-mode-alist))
 


;; tempo
 (require 'pi-tempo-abbrev)

(add-hook 'LaTeX-mode-hook
'(lambda ()
(load "~/emacs/latex-tempo")))

(load "latex-tempo")

(add-hook 'metapost-mode-hook
'(lambda ()
(load "~/emacs/meta-tempo")))


(add-hook 'metapost-mode-hook
'(lambda ()
(load "~/emacs/pi-meta")))


(setq-default abbrev-mode t) ;; enable abbreviations
;; save abbreviations upon exiting emacs whithout confirmation



(global-set-key (kbd "M-SPC") 'expand-abbrev)

(global-set-key (kbd "<f3>") 'expand-abbrev)
(global-set-key (kbd "<f3>") 'tempo-complete-tag)

 (add-hook 'LaTeX-mode-hook
   (function
    (lambda ()
     (define-key LaTeX-mode-map [(super right)] 'tempo-forward-mark)
     (define-key LaTeX-mode-map [(super left)]  'tempo-backward-mark)
     (define-key LaTeX-mode-map [f3] 'tempo-complete-tag))))










(setq save-abbrevs 'silently)
 (setq abbrev-file-name (expand-file-name "pi-tempo-abbrev"))
 (if (file-readable-p abbrev-file-name) ;; read the abbreviations every
     (read-abbrev-file abbrev-file-name)) ;; time emacs is started
;; ;; Combine tempo et abbrev
;; save abbreviations upon exiting emacs whithout confirmation







;; ;; Ajouter/modifier des tag dans les fichiers pi-tempo-abbrev-UN_NOM.el
;; ;; Voir le manuel de tempo: http://www.lysator.liu.se/~davidk/elisp/tempo.texi
;; ;; La valeur par défaut de `tempo-insert-region' pose des pb chez moi
 (setq-default tempo-insert-region nil)
;; (load "pi-tempo-abbrev-latex");; Essayer dans un buffer LaTeX-mode enu<SPACE>.
; (load "pi-tempo-abbrev-meta");; en metapost-mode, pre<space>
;; ;(load "pi-tempo-abbrev-lisp");; defun <space>...
;; ;(load "pi-tempo-abbrev-asy") 




;; pour selectionner copier coller

(load-library "pc-mode")
(pc-selection-mode)


(define-key global-map [(meta w)] 'kill-ring-save)
(define-key global-map [(control w)] 'kill-region)
(define-key global-map [(control y)] 'yank)


 ;;; home/end
 ;; (defun my-home ()
 ;;   "Le premier Home envoie en début de ligne,
 ;; le deuxième en début de page,
 ;; et le troisième au début du tampon."
 ;;   (interactive nil)
 ;;   (cond
 ;;    ((and (eq last-command 'my-home)
 ;;      (eq my-last-last-command 'my-home))
 ;;     (goto-char (point-min)))
 ;;    ((eq last-command 'my-home)
 ;;     (move-to-window-line 0))
 ;;    (t
 ;;     (beginning-of-line)))
 ;;   (setq my-last-last-command last-command))
 ;; (defun my-end ()
 ;;   "Le premier End envoie en fin de ligne,
 ;; le deuxième en fin de page,
 ;; et le troisième à la fin du tampon."
 ;;   (interactive nil)
 ;;   (cond
 ;;    ((and (eq last-command 'my-end)
 ;;      (eq my-last-last-command 'my-end))
 ;;     (goto-char (point-max)))
 ;;    ((eq last-command 'my-end)
 ;;     (move-to-window-line -1)
 ;;     (end-of-line))
 ;;    (t
 ;;     (end-of-line)))
 ;;   (setq my-last-last-command last-command))







;;(setq gnus-select-method '(nntp "news.free.fr"))



;; Definit Gnus comme lecteur courriel
 
 ;; Definit Gnus comme lecteur courriel
 
 ;; Definit Galeon comme brouteur web, pour suivre les liens
 (setq browse-url-browser-function 'browse-url-generic
       browse-url-generic-program "/home/moi/seamonkey2/seamonkey/seamonkey")



(setq
 mail-header-separator "=== le texte du message suit cette ligne ==="
 mail-self-blind t
 mail-signature t
 mail-yank-prefix "> ")



(setq gnus-posting-styles
              '((".*"
                 (signature-file "~/.signature")
                 (name "Guillaume Connan")
                 ("X-Home-Page" (getenv "WWW_HOME")))))
;;;              (organization "People's Front Against MWM"))
;;;             ("^rec.humor"
;;;              (signature my-funny-signature-randomizer))
;;;             ((equal (system-name) "gnarly")
;;;              (signature my-quote-randomizer))
;;;             ((message-news-p)
;;;              (signature my-news-signature))
;;;             (header "From\\|To" "larsi.*org"
;;;                     (Organization "Somewhere, Inc."))
;;;             ((posting-from-work-p)
;;;              (signature-file "~/.work-signature")
;;;              (address "user@bar.foo")
;;;              (body "You are fired.\n\nSincerely, your boss.")
;;;              (organization "Important Work, Inc"))
;;;             ("nnml:.*"
;;;              (From (save-excursion
;;;                      (set-buffer gnus-article-buffer)
;;;                      (message-fetch-field "to"))))
;;;             ("^nn.+:"
;;;              (signature-file "~/.mail-signature"))))



;;;;;;;;;;;;
;;gravure


;; (defun guillaume-gravure (fichiers)
;;   "Gravure de cd"
;;   (interactive "ffichiers à graver : ")
;;     (shell-command (concat "sudo cdrecord -v -dev=1,0,0 -speed=2 -fs=31m -dao -useinfo -pad"
;;                            fichiers
;;                     ))
;;      (set-window-text-height nil (ceiling (* (frame-height) .7))))

;;              (define-key global-map [(super c) (super g)] 'guillaume-gravure)



;; (add-hook 'comint-output-filter-functions

;; 'comint-watch-for-password-prompt)










(custom-set-faces
  ;; custom-set-faces was added by Custom.
  ;; If you edit it by hand, you could mess it up, so be careful.
  ;; Your init file should contain only one such instance.
  ;; If there is more than one, they won't work right.
 '(default ((t (:stipple nil :background "gray5" :foreground "wheat3" :inverse-video nil :box nil :strike-through nil :overline nil :underline nil :slant normal :weight bold :height 150 :width normal :foundry "xos4" :family "Terminus"))))
 '(background "blue")
 '(fixed-pitch ((t (:family "terminus"))))
 '(font-latex-math-face ((((class color) (background dark)) (:foreground "RoyalBlue2"))))
 '(font-latex-sectioning-0-face ((t (:inherit font-latex-sectioning-1-face :height 400 :width expanded :family "terminus"))))
 '(font-latex-sectioning-1-face ((t (:inherit font-latex-sectioning-2-face :weight extra-bold :height 300 :family "terminus"))))
 '(font-latex-sectioning-2-face ((t (:inherit font-latex-sectioning-3-face :height 240 :family "terminus"))))
 '(font-latex-sectioning-3-face ((t (:inherit font-latex-sectioning-4-face :height 220 :family "terminus"))))
 '(font-latex-sectioning-4-face ((t (:inherit font-latex-sectioning-5-face :height 210 :family "terminus"))))
 '(font-latex-sectioning-5-face ((((class color) (background dark)) (:inherit variable-pitch :foreground "yellow" :weight bold :height 200 :family "terminus"))))
 '(font-latex-verbatim-face ((((class color) (background dark)) (:foreground "tomato3"))))
 '(font-latex-warning-face ((((class color) (background dark)) (:inherit bold :foreground "red"))))
 '(font-lock-builtin-face ((((class color) (background dark)) (:foreground "Turquoise"))))
 '(font-lock-constant-face ((((class color) (background dark)) (:bold t :foreground "DarkOrchid"))))
 '(font-lock-doc-string-face ((t (:foreground "green2"))))
 '(font-lock-function-name-face ((t (:foreground "SkyBlue"))))
 '(font-lock-keyword-face ((t (:bold t :foreground "CornflowerBlue"))))
 '(font-lock-preprocessor-face ((t (:italic nil :foreground "CornFlowerBlue"))))
 '(font-lock-reference-face ((t (:foreground "DodgerBlue"))))
 '(font-lock-string-face ((t (:foreground "LimeGreen"))))
 '(font-lock-type-face ((t (:foreground "#9290ff"))))
 '(font-lock-variable-name-face ((t (:foreground "PaleGreen"))))
 '(font-lock-warning-face ((((class color) (background dark)) (:foreground "yellow" :background "red"))))
 '(header-line ((((class color grayscale) (background dark)) (:inherit mode-line :background "grey20" :foreground "grey90" :box nil :family "terminus"))))
 '(highlight ((t (:inverse-video t))))
 '(link ((((class color) (min-colors 88) (background dark)) (:foreground "red" :underline t))))
 '(list-mode-item-selected ((t (:background "gold"))))
 '(makefile-space-face ((t (:background "wheat"))))
 '(minibuffer-prompt ((((background dark)) (:foreground "cyan4"))))
 '(mode-line ((t (:background "grey10" :foreground "grey70" :box nil :slant normal :weight normal :height 125 :width normal :foundry "misc" :family "terminus"))))
 '(mouse ((t (:background "grey35"))))
 '(paren-match ((t (:background "darkseagreen4"))))
 '(pi-big-font pi-small-font)
 '(pi-toggle-font pi-toggle-font)
 '(region ((t (:background "DarkSlateBlue"))))
 '(scroll-bar ((t (:background "grey45" :foreground "#00ffbf"))))
 '(show-paren-match ((t (:foreground "black" :background "wheat"))))
 '(show-paren-mismatch ((((class color)) (:foreground "white" :background "red"))))
 '(speedbar-button-face ((((class color) (background dark)) (:foreground "green4"))))
 '(speedbar-directory-face ((((class color) (background dark)) (:foreground "khaki"))))
 '(speedbar-file-face ((((class color) (background dark)) (:foreground "cyan"))))
 '(speedbar-tag-face ((((class color) (background dark)) (:foreground "Springgreen"))))
 '(textomail-region textomail-region)
 '(vhdl-speedbar-architecture-selected-face ((((class color) (background dark)) (:underline t :foreground "Blue"))))
 '(vhdl-speedbar-entity-face ((((class color) (background dark)) (:foreground "darkGreen"))))
 '(vhdl-speedbar-entity-selected-face ((((class color) (background dark)) (:underline t :foreground "darkGreen"))))
 '(vhdl-speedbar-package-face ((((class color) (background dark)) (:foreground "black"))))
 '(vhdl-speedbar-package-selected-face ((((class color) (background dark)) (:underline t :foreground "black"))))
 '(widget-field ((((class grayscale color) (background light)) (:background "DarkBlue")))))





(custom-set-variables
  ;; custom-set-variables was added by Custom.
  ;; If you edit it by hand, you could mess it up, so be careful.
  ;; Your init file should contain only one such instance.
  ;; If there is more than one, they won't work right.
 '(LaTeX-verbatim-environments (quote ("verbatim" "verbatim*" "lstlisting" "boxedverbatim" "Verbatim")))
 '(TeX-show-compilation t)
 '(auto-compression-mode t nil (jka-compr))
 '(backup-by-copying t)
 '(canlock-password "133aadb960dace95c22833969aae1d7433b437f2")
 '(case-fold-search t)
 '(column-number-mode t)
 '(current-language-environment "UTF-8")
 '(default-input-method "utf-8-prefix")
 '(delete-old-versions nil)
 '(display-time-24hr-format t)
 '(display-time-mode t)
 '(ecb-options-version "2.32")
 '(ecb-windows-width 0.15)
 '(face-font-family-alternatives (quote (("terminus" "fixed") ("terminus" "helvetica" "arial" "fixed"))))
 '(font-latex-verbatim-environments (quote ("verbatim" "verbatim*" "lstlisting" "boxedverbatim" "Verbatim")))
 '(global-font-lock-mode t nil (font-lock))
 '(kept-new-versions 1)
 '(mail-yank-prefix "> ")
 '(maplev-default-release "4")
 '(maplev-executable-alist (quote (("9" "maple" nil "mint") ("8" "maple" nil "mint") ("7" "maple" nil "mint") ("6" "maple" nil "mint") ("5.1" "maple" nil "mint") ("5" "maple" nil "mint") ("4" "maplev" nil "mint"))))
 '(message-directory "~/.Mail/")
 '(mm-discouraged-alternatives (quote ("(\"text/html\" \"text/richtext\")")))
 '(pdf-view-command "okular")
 '(ps-view-command "okular")
 '(read-mail-command (quote gnus))
 '(safe-local-variable-values (quote ((asy-TeX-master-file . "parabolide"))))
 '(show-paren-mode t nil (paren))
 '(speedbar-frame-parameters (quote ((minibuffer) (width . 20) (border-width . 0) (menu-bar-lines . 0) (tool-bar-lines . 0) (unsplittable . t) (set-background-color "black"))))
 '(transient-mark-mode t)
 '(uniquify-buffer-name-style (quote post-forward-angle-brackets) nil (uniquify)))


;;
;;(set-frame-font "-xos4-terminus-bold-r-normal--20-*-*-*-*-*-*-*")
;;(set-frame-font "terminus-20:bold")

;;(set-default-font "-*-terminus-bold-*-*-*-20-*-*-*-*-*-*-*")

;;(set-default-font "-*-terminal-medium-*-*-*-*-140-*-*-*-*-*-*")




;;;;;;;;;;;;;
;; Les trucs à PhiPhi


(defvar user-set-coding-system-latin nil
  "* Remplacer t par nil pour ne pas utiliser
latin-1 et latin-9 comme encodage par défaut.")

;;save everything before compiling
      compilation-ask-about-save nil
      ;; Taille de la fenêtre de compilation.
      compilation-window-height 12
      ;; Non-nil to scroll the *compilation* buffer window as output appears.
      ;;compilation-scroll-output t
      ;; Autorise les variable locales
      enable-local-variables t
      ;; Controls if scroll commands move point to keep its screen line unchanged.
      scroll-preserve-screen-position t
      ;; Number of lines of margin at the top and bottom of a window.
      scroll-margin 4
      ;; Maximum number of lines to keep in the message log buffer.
      message-log-max 1000
      ;; `apropos' cherche tout:
      ;;apropos-do-all t ;; raccourcis "C-h a" plus loin.
      ;; ignorer DE PLUS les fichiers dont le nom se termine par ces suffixes.
      ;; completion-ignored-extensions (append
      ;;                                '(".mpx" ".toc" ".nav")
      ;;                                completion-ignored-extensions)

;; Voir les espaces inutiles
(setq-default show-trailing-whitespace t)
(setq-default show-leading-whitespace t)




;; Afficher numéro ligne/colonne dans la ligne de mode
(line-number-mode t)
(column-number-mode t)
;; Pour lire automatiquement les .gz et les zip
(auto-compression-mode 1)
;; Pour lire des images directement
(auto-image-file-mode t)

;; -----------------------
;; * La date en français *
(setq calendar-style 't
      display-time-day-and-date t
      display-time-24hr-format t
      calendar-week-start-day 1)
;; Affiche l'heure dans la ligne de mode.
(display-time)
;; Nom en clair des jours et mois apparaissant dans le calendrier
(setq calendar-day-abbrev-array
      ["dim" "lun" "mar" "mer" "jeu" "ven" "sam"])
(setq calendar-day-name-array
      ["dimanche" "lundi" "mardi" "mercredi" "jeudi" "vendredi" "samedi"])
(setq calendar-month-abbrev-array
      ["jan" "fév" "mar" "avr" "mai" "jun"
       "jul" "aoû" "sep" "oct" "nov" "déc"])
(setq calendar-month-name-array
      ["janvier" "février" "mars" "avril" "mai" "juin"
       "juillet" "août" "septembre" "octobre" "novembre" "décembre"])

;; ------------
;; * Spliting *
;; Ne fonctionne que si on ne fait pas de split horizontal
(setq truncate-lines nil)
;; Fonctionne avec le split horizontal
(setq truncate-partial-width-windows nil)

;; -------------------------
;; * Coloration syntaxique *
;;; Coloration maximum
(setq-default font-lock-maximum-decoration t)
;; Active la coloration dans tous les modes
(if (fboundp 'global-font-lock-mode)
    (global-font-lock-mode 1))

;; ---------------
;; * Les accents *
(when user-set-coding-system-latin
  (set-language-environment "French"))   ;met à dispo latin-1 et latin-9
  (prefer-coding-system 'utf-8)       ;mais on préfère latin-1
  (set-terminal-coding-system 'utf-8)
  (set-keyboard-coding-system 'utf-8)
  ;; When emacs is running in a text terminal...
  (when (not window-system)
    (set-keyboard-coding-system locale-coding-system)
    (set-terminal-coding-system locale-coding-system))
  ;; Les caractères encodables en latin-9 le seront directement:
  ;;(require 'ucs-tables) ;;Inutile dans Emacs22
  ;(unify-8859-on-encoding-mode 1)
  ;(unify-8859-on-decoding-mode 1))




(setq desktop-save t)
(when (> emacs-major-version 21)
  ;; Activation
  (desktop-save-mode 1))
;; Ne pas rouvrir les fichiers suivants:
(setq desktop-buffers-not-to-save
      (concat "\\(" "^nn\\.a[0-9]+\\|\\.log\\|(ftp)\\|^tags\\|^TAGS"
              "\\|\\.el\\.gz\\|\\.diary\\|\\.newsrc-dribble\\|\\.bbdb"
              "\\)$"))
;; Ne pas rouvrir les modes suivants:
(add-to-list 'desktop-modes-not-to-save 'dired-mode)
(add-to-list 'desktop-modes-not-to-save 'Info-mode)
(add-to-list 'desktop-modes-not-to-save 'info-lookup-mode)
(add-to-list 'desktop-modes-not-to-save 'fundamental-mode)

;; -----------------------------------------
;; * Sauvegarder l'historique des actions. *
(when (require 'savehist "savehist.elc" t) ;;Part of emacs22
  ;;(setq savehist-file (concat (cuid ".history-") (user-real-login-name)))
  ;; activation
  (setq savehist-mode t))

;; ----------------------------------------------------
;; * Auto-fill: coupure automatique de lignes longues *
;; Pour ne pas que le mode auto-fill coupe à l'endroit d'un ":" ou ";" etc..
;; Auteur: Matieux Moy http://www-verimag.imag.fr/~moy/emacs/
(defun pi-fill-nobreak-predicate ()
  (save-match-data
    (or (looking-at "[ \t]*[])}»!?;:]")
        (looking-at "[ \t]*\\.\\.\\.")
        (save-excursion
          (skip-chars-backward " \t")
          (backward-char 1)
          (looking-at "[([{«]")))))
(setq fill-nobreak-predicate 'pi-fill-nobreak-predicate)
;; Pas en mode auto-fill en lisp
(add-hook 'lisp-mode-hook 'turn-off-auto-fill)

;; -------------------------------------------------------
;; * Rendre exécutable certains fichiers à la sauvegarde *
;; From http://kanis.cc/viewcvs/trunk/ivan/conf/emacs
(add-hook 'after-save-hook 'pi-make-executable)
(defun pi-make-executable ()
  "Make perl, python and shell file executable."
  (if buffer-file-name
      (if (or (string-match "\\.\\(pl\\|py\\|sh\\)$" buffer-file-name)
              (string= "sh-mode" (symbol-name major-mode)))
          (set-file-modes buffer-file-name ?\755))))

;; -----------------------------------------------------
;; * Active le serveur Emacs pour utiliser emacsclient *
(if (string= system-type "gnu/linux")
    (require 'server)
  (unless server-process (server-start)))


(scroll-bar-mode t)          ;; avoir la bar de scroll
(set-scroll-bar-mode 'left);; à droite


; (require 'linum) ;; numérotation des lignes






;;; ----------------------
;;; * browse-apropos-url *
;; Most  of modern  browsers  allow  you to  write  keywords in  the
;; location bar  for doing easy  and fast searching. For  example in
;; opera "g emacswiki" googles for "emacswiki".
;; browse-apropos-url  provide this functionality and more
;; to elisp coders independently of which browser does browse-url
;; start.
;; From http://www.emacswiki.org/cgi-bin/wiki/BrowseAproposURL
(setq apropos-url-alist
      '(("^gw?:? +\\(.*\\)" . ;; Google Web
         "http://www.google.fr/search?q=\\1")

        ("^gl:? +\\(.*\\)" . ;; Google Linux
         "http://www.google.fr/linux?q=\\1")

        ("^gi:? +\\(.*\\)" . ;; Google Images
         "http://images.google.com/images?sa=N&tab=wi&q=\\1")

        ("^gg:? +\\(.*\\)" . ;; Google Groups
         "http://groups.google.com/groups?q=\\1")

        ("^ctt:? +\\(.*\\)" . ;; Google Groups comp.text.tex
         "http://groups.google.fr/group/comp.text.tex/search?group=comp.text.tex&q=\\1")

        ("^fctt:? +\\(.*\\)" . ;; Google Groups fr.comp.text.tex
         "http://groups.google.fr/group/fr.comp.text.tex/search?group=comp.text.tex&q=\\1")

        ("^fcae:? +\\(.*\\)" . ;; Google Groups fr.comp.application.emacs
         "http://groups.google.fr/group/fr.comp.applications.emacs/search?group=fr.comp.applications.emacs&q=\\1")

        ("^geh:? +\\(.*\\)" . ;; Google Groups gnu.emacs.help
         "http://groups.google.fr/group/gnu.emacs.help/search?group=gnu.emacs.help&q=\\1")

        ("^fcolc:? +\\(.*\\)" . ;; Google Groups fr.comp.os.linux.configuration
         "http://groups.google.fr/group/fr.comp.os.linux.configuration/search?group=fr.comp.os.linux.configuration&q=\\1")

        ("^colc:? +\\(.*\\)" . ;; Google Groups comp.os.linux.configuration
         "http://groups.google.fr/group/comp.os.linux.configuration/search?group=fr.comp.os.linux.configuration&q=\\1")

        ("^gt:? +\\(\\w+\\)|? *\\(\\w+\\) +\\(\\w+://.*\\)" . ;; Google Translate URL
         "http://translate.google.com/translate?langpair=\\1|\\2&u=\\3")

        ("^gt:? +\\(\\w+\\)|? *\\(\\w+\\) +\\(.*\\)" . ;; Google Translate Text
         "http://translate.google.com/translate_t?langpair=\\1|\\2&text=\\3")

        ("^ewk:? +\\(.*\\)" . ;; Emacs Wiki Search
         "http://www.emacswiki.org/cgi-bin/wiki?search=\\1")

        ("^ewk$" . ;; Emacs Wiki
         "http://www.emacswiki.org")

        ("^dic:? +\\(\\w+\\)" . ;; Trésor de la Langue Française informatisé
         "http://atilf.atilf.fr/dendien/scripts/fast.exe?mot=\\1")

        ("^pf:? +\\(\\w+\\)" . ;; Patrimoine de france.
         "http://www.patrimoine-de-france.org/search.html?q=\\1")

        ("^conj:? +\\(\\w+\\)" . ;; Conjugaison avec le bescherelle.
         "http://bescherelle.leconjugueur.com/frconjugue.php?verbe=\\1")
        ))

(defun browse-apropos-url (text &optional new-window)
  ;; (defun browse-apropos-url (text &optional new-window)
  ;;   (interactive (browse-url-interactive-arg "Location: "))
  (interactive "sLocation: ")
  (let ((text (replace-regexp-in-string
               "^ *\\| *$" ""
               (replace-regexp-in-string "[ \t\n]+" " " text))))
    (let ((url (assoc-default
                text apropos-url-alist
                '(lambda (a b) (let () (setq __braplast a) (string-match a b)))
                text)))
      (browse-url (replace-regexp-in-string __braplast url text) new-window))))

(defun browse-apropos-url-on-region (min max text &optional new-window)
  (interactive "r \nsAppend region to location: \nP")
  (browse-apropos-url (concat text " " (buffer-substring min max)) new-window))

(global-set-key (kbd "C-b") 'browse-apropos-url)
(global-set-key (kbd "C-S-b") 'browse-apropos-url-on-region)
;; Exemple sélectionner le mot "myriade" C-S-b dic <RET> et aller voir votre navigateur...








;; ------------------------------------------
;; * antiword pour lire les .doc avec Emacs *
(autoload 'no-word "no-word" "word to txt")
(add-to-list 'auto-mode-alist '("\\.doc\\'" . no-word))


;; -------------------------------------
;; * Rendu HTML de buffers et fichiers *
;; Just call `htmlize-view-buffer' to show the current buffer in
;; your web browser.
(load "htmlize")
(require 'htmlize-view)
(htmlize-view-add-to-files-menu)




;; -------------------------------------
;; * Incremental minibuffer completion *
;; (require 'icomplete)
;; (icomplete-mode 1)
;; (require 'icomplete+)
;; (setq icompletep-prospects-length 1000)
(require 'minibuffer-complete-cycle)


; -----------------------
;; * Calculs avec Scilab *
(load "scilab")
(setq auto-mode-alist (cons '("\\(\\.sci$\\|\\.sce$\\)" . scilab-mode) auto-mode-alist))
(setq scilab-mode-hook '(lambda () (setq fill-column 74)))


;; -----------------------
;; * WebBrowser in emacs *
;; (when (require 'w3m-load "w3m-load.elc" t)
;;   ;;  Où se trouve les icons pour w3m
;;   ;;(setq w3m-icon-directory (cuid "etc/icons"))
;;   ;; Definit Mozilla-seamonkey comme brouteur web, pour suivre les liens
;;   (setq browse-url-browser-function 'browse-url-generic
;;         browse-url-generic-program "/usr/local/seamonkey/seamonkey")
;;   (add-hook 'w3m-mode-hook
;;             (lambda ()
;;               ;; Use "M" (default) in w3m-mode to view url with external browser
;;               ;; (local-set-key [f4] 'w3m-view-url-with-external-browser)
;;               (define-key w3m-mode-map (kbd "<down>") 'next-line)
;;               (define-key w3m-mode-map (kbd "<up>") 'previous-line)
;;               (define-key w3m-mode-map (kbd "<right>") 'forward-char-nomark)
;;               (define-key w3m-mode-map (kbd "<left>") 'backward-char-nomark)))
;;   )







; ---------------------------------
;; * Surligne la colonne courrante *
(when (locate-library "column-marker")
  (autoload 'column-marker-1 "column-marker" "Highlight a column." t)
  ;; http://www.emacswiki.org/cgi-bin/wiki/col-highlight.el
  (require 'col-highlight)
  ;; Raccourci sur [f10]
  (global-set-key (kbd "<f10>") 'column-highlight-mode))

;; ----------------------------------------
;; * Correction orthographique à la volée *
;; Flyspell http://kaolin.unice.fr/~serrano
;(when (locate-library "flyspell")
;  (autoload 'flyspell-mode "flyspell" "On-the-fly spelling checker." t)
;  (autoload 'flyspell-delay-command "flyspell" "Delay on command." t)
;  (setq ispell-program-name "flyspell")
;  (ispell-change-dictionary "francais" 1)
;  ;; dictionnaire par défaut: francais
;  (setq flyspell-default-dictionary "francais")
;  ;; Active `flyspell-mode' pour les commentaires et
;  ;;   les chaînes dans ces modes de programmation
;  (dolist (hook '(emacs-lisp-mode-hook c-mode-hook asy-mode-hook))
;    (add-hook hook
;              (lambda ()
;                (flyspell-prog-mode)))))






;; ;; -------
;; ;; * ido *
;; ;; Pour changer de buffer ou ouvrir un fichier en donnant
;; ;; une sous chaine (clavier C-Tab defini dans pi-global-keys.el; C-x b par defaut)
;; ;; Utiliser C-s C-r pour faire défiler le menu.
;; ;; Un paquet indispensable!
;; (when (require 'ido "ido.elc" t) ;;Part of emacs22
;;   ;; C-tab ou C-x b pour changer de buffer
;;   (global-set-key (kbd "<C-tab>") 'ido-switch-buffer)
;;   (setq ido-case-fold t ;; Insensible à la casse
;;         ;; File in which the ido state is saved between invocations.
;;         ido-save-directory-list-file (cuid ".ido.last"))
;;   (ido-mode t)
;;   (setq ido-ignore-files
;;         (append ido-ignore-files
;;                 (list
;;                  ".*\\.aux$"
;;                  ".*\\.dvi$"
;;                  ".*\\.ps$"
;;                  ".*\\.eps$"
;;                  ".*\\.toc$"
;;                  ".*\\.nav$"
;;                  ".*\\.pdf$"
;;                  ".*~$")))

;;   (setq ido-ignore-buffers
;;         (append ido-ignore-buffers
;;                 (list
;;                  "\\*BBDB\\*"))))







;; ;; --------------------------
;; ;; * Lecture des mails/news *
;; (global-set-key (kbd "<f5>") 'pi-gnus-demon-handler)
;; (global-set-key (kbd "<C-f5>") 'gnus-group-get-new-news)





;; ;; -------------------------------------------
;; ;; * Filename completion anywhere with S-Tab *
;; (autoload 'comint-dynamic-complete-filename "comint" "" t)
;; ;; Liste des suffixes à négliger pendant le complètement:
;; (setq comint-completion-fignore (quote ("{" "}" "(" ")" "$" "=" "\"" "`" "'" "[" "]" "%" "<" ">")))
;; (global-set-key (kbd "<S-tab>") 'comint-dynamic-complete-filename)
;; (global-set-key (kbd "<S-iso-lefttab>") 'comint-dynamic-complete-filename)


;; ;; * Supprime le buffer et la fenêtre courrante *
;; (defun pi-kill-window-and-buffer()
;;   "* Delete current window and buffer."
;;   (interactive)
;;   (kill-buffer (current-buffer))
;;   (if (not (one-window-p nil))(delete-window)))
;; (global-set-key [(super k)] 'pi-kill-window-and-buffer)











;; ;; --------------------------------
;; ;; * Déplacer un ligne facilement *
;; (defun move-line-up (&optional n)
;;   "Moves current line up leaving point in place.  With a prefix
;; argument, moves up N lines."
;;   (interactive "p")
;;   (if (null n) (setq n 1))
;;   (let ((col (current-column)))
;;     (beginning-of-line)
;;     (next-line 1)
;;     (transpose-lines (- n))
;;     (previous-line 1)
;;     (forward-char col)))
;; (global-set-key [(meta up)] 'move-line-up)

;; (defun move-line-down (&optional n)
;;   "Moves current line down leaving point in place.  With a prefix
;; argument, moves down N lines."
;;   (interactive "p")
;;   (if (null n) (setq n 1))
;;   (let ((col (current-column)))
;;     (beginning-of-line)
;;     (next-line 1)
;;     (transpose-lines  n)
;;     (previous-line 1)
;;     (forward-char col)
;;     ))
;; (global-set-key [(meta down)] 'move-line-down)

;; ;; ---------------------
;; ;; * Find file as root *
;; (defun find-file-root ()
;;   "* Find file as root."
;;   (interactive)
;;   (let ((file (read-file-name "Find file AS ROOT: ")))
;;     (find-file (concat "/su::" file))))
;; (global-set-key [(control x) (control r)] 'find-file-root)

;; ;; ----------------------------
;; ;; * Retour en début de ligne *
;; (defun pi-home()
;;   "* Move cursor at beginning of line or first non blank character
;; depending where the cursor is."
;;   (interactive)
;;   (let ((pt_indent (point)))
;;     (back-to-indentation)
;;     (if (eq pt_indent (point))
;;      (beginning-of-line-nomark))
;;     ))
;; (global-set-key [(home)] 'pi-home)
;; ;; M'évite de lever la main pour aller en début/fin de ligne:
;; (global-set-key [(control meta prior)] 'pi-home)
;; (global-set-key [(control meta next)] 'end-of-line-nomark)













;; --------------------------------
;; * Filling région ou paragraphe *
;; By Giorgos Keramidas
(defun fill-region-or-paragraph (&optional justify)
  "Fill the current region or paragraph (depending on `mark-active')

 Fill paragraph at or after point when the mark is inactive or if
 the mark and the point are the same.  Fill each of the paragraphs
 in the region when the mark is active and is not equal to the
 current point.

 The optional JUSTIFY argument specifies the paragraph
 justification that should be used.  Valid values are all those
 described in the help of the `fill-region' function."

  (interactive "p")
  (let ((point (point))
        (mark (and mark-active (mark))))
    (message (format "justify is %s" justify))
    (if (and mark (not (equal point mark)))
        (fill-region (min point mark) (max point mark)
                     (if (= justify 1)
                         nil
                       'full))
      (fill-paragraph justify))))
;;; Bind our own `fill-region-or-paragraph' to M-q.
(global-set-key (kbd "M-q") 'fill-region-or-paragraph)

(defun pi-?comment ()
  (interactive)
  (save-excursion
    (if mark-active
        (let ((br (region-beginning))
              (be (region-end)))
          (comment-or-uncomment-region br be)
          (indent-region br be))
      (let ((br (progn  (back-to-indentation) (point)))
            (be (progn (end-of-line) (point))))
        (comment-or-uncomment-region br be)
        (indent-region br be))
      )))
(global-set-key (kbd "C-%") 'pi-?comment)
(global-set-key (kbd "C-ù") 'comment-region)

;; -------------------------
;; ;; * Entête de commentaire *
;; (defface pi-comment-section-face
;;   `((t
;;      ( :foreground "yellow")))
;;   "Face used to highlighting header of comment section."
;;   :group 'pi-comment)
;; (defface pi-comment-sub-section-face
;;   `((t
;;      ( :foreground "white")))
;;   "Face used to highlighting header of comment section."
;;   :group 'pi-comment)

;; (add-hook 'emacs-lisp-mode-hook
;;           (lambda ()
;;             (font-lock-add-keywords
;;              'nil
;;              '(("\\(;; \\*=*\\*$\\)" 1 'pi-comment-section-face t)
;;                ("\\(;; \\*\\..*\\.\\*$\\)" 1 'pi-comment-section-face t)
;;                ("\\(;; -*\n;; \\*.*\\*$\\)" 1 'pi-comment-sub-section-face t)))))
;; (font-lock-add-keywords
;;  'emacs-lisp-mode-hook
;;  '(("\\(;; -*\n;; \\*.*\\*$\\)" 1 'pi-comment-sub-section-face t)))

;; (defun pi-insert-comment-section ()
;;   "* To insert a section comments."
;;   (interactive)
;;   (let* ((str (if (and mark-active transient-mark-mode)
;;                   (prog1
;;                       (buffer-substring (region-beginning) (region-end))
;;                     (delete-region (region-beginning) (region-end)))
;;                 (read-string "Section comment: ")))
;;          (str_ (if (string= str "") " - " str))
;;          (v1 (make-string (- fill-column 15) ?=))
;;          (v2 (- fill-column 15 (length str_)))
;;          (spce (make-string (floor v2 2) ?.))
;;          (pt (progn (beginning-of-line) (point))))
;;     (insert (concat "*" v1 "*\n*" spce str_ spce
;;                     (unless (= (ceiling v2 2) (/ v2 2)) ".")
;;                     "*\n*" v1 "*"))
;;     (comment-region pt (point))
;;     (next-line)
;;     (beginning-of-line)))
;; (global-set-key (kbd "C-µ") 'pi-insert-comment-section)




;; (defun pi-insert-comment-sub-section ()
;;   "* To insert a section sub comments"
;;   (interactive)
;;   (let* ((str (if (and mark-active transient-mark-mode)
;;                   (prog1
;;                       (buffer-substring (region-beginning) (region-end))
;;                     (delete-region (region-beginning) (region-end)))
;;                 (read-string "Sub section comment: ")))
;;          (str_ (if (string= str "") " - " str))
;;          (v1 (make-string (+ (length str_) 4) ?-))
;;          (pt (progn (beginning-of-line) (point))))
;;     (insert (concat  v1 "\n* " str_ " *"))
;;     (comment-region pt (point))
;;     (next-line)
;;     (beginning-of-line)))
;; (global-set-key (kbd "C-*") 'pi-insert-comment-sub-section)



;;  (add-hook 'text-mode-hook
;;       (lambda ()
;;       (auto-fill-mode 1)
;;       (setq default-justification 'full))
;;       )

;; (setq default-justification 'full)



;; ------------------------
;; * LaTeX vers ascii-art *
;;;###autoload
(defun textomail-region (beginr endr)
;;Convertir la région de LaTeX en ascii-art
(interactive "r")
(write-region beginr endr "~/textomail" nil nil)
(kill-region beginr endr)
(insert (shell-command-to-string "perl /home/moi/bin/tex2mail ~/textomail")))













;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
;                lilypond
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;


(defvar guillaume-midi2wav-command "midi2wav %s")

(defun guillaume-midi2wav () (interactive)
   (save-buffer)
   (shell-command (format guillaume-midi2wav-command
                         (file-name-sans-extension(buffer-file-name))))
   )
(add-hook 'LilyPond-mode-hook
          '(lambda nil
             (define-key LilyPond-mode-map [(super c) (super w)] 'guillaume-midi2wav)))


;;


;; D'autres trucs

;;


(require 'zone)

;;(load-file "~/emacs/std_comment.el")



;;(load "std.el")
(load "std_comment.el")
;;changement de buffer ac ctrl+tab
(global-set-key [(control tab)] 'other-window)

;;goto line= alt+l
(global-set-key "\C-l" 'goto-line)


;;;;A fun startup message, somewhat reminiscent of "The Matrix: Reloaded"
(defun emacs-reloaded ()
  (animate-string (concat ";; Initialization successful. Welcome to "
                          (substring (emacs-version) 0 16)
                          ".")
                  0 1)
  (newline-and-indent)  (newline-and-indent))
(add-hook 'after-init-hook 'emacs-reloaded) 

;;;;I've seen this in a few other .emacs, and it doesn't seem to do
;;;;anything *bad*...
(random t) 


;;;;Do without those obnoxious startup messages- the whole GNU Emacs logo
;;;;thing, that is.
(setq inhibit-splash-screen t) 

;;;;Modify the mode-line as well. This is a cleaner setup than the 
;;;;default settings for the mode-line.
(setq default-mode-line-format
      '("-"
       mode-line-mule-info
       mode-line-modified
       mode-line-frame-identification
       mode-line-buffer-identification
       "  "
       global-mode-string
       "   %[(" mode-name mode-line-process minor-mode-alist "%n"
")%]--"
       (line-number-mode "L%l--")
       (column-number-mode "C%c--")
       (-3 . "%p")
       "-%-"))



;;;;Require C-x C-q prompt. I've closed too often by accident.
;;;;http://www.dotemacs.de/dotfiles/KilianAFoth.emacs.html
(global-set-key [(control x) (control q)] 
  (function 
   (lambda () (interactive) 
     (cond ((y-or-n-p "Quit? ")
            (save-buffers-kill-emacs))))))

;;;;C-x k is a command I use often, but C-x C-k (an easy mistake) is
;;;;bound to nothing!
;;;;Set C-x C-k to same thing as C-x k.
(global-set-key "\C-x\C-k" 'kill-this-buffer)


;;;;Use ANSI colors within shell-mode
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)


;;;;Change pasting behavior. Normally, it pastes where the mouse 
;;;;is at, which is not necessarily where the cursor is. This changes 
;;;;things so all pastes, whether they be middle-click or C-y or menu, 
;;;;all paste at the cursor.
(setq mouse-yank-at-point t)


;;;;The autosave is typically done by keystrokes, but I'd like to save
;;;;after a certain amount of time as well.
(setq auto-save-timeout 1800)


;;;;Change backup behavior to save in a directory, not in a miscellany
;;;;of files all over the place.
(setq
 backup-by-copying t      ; don't clobber symlinks
 backup-directory-alist
 '(("." . "~/.sauvegardes"))    ; don't litter my fs tree
 delete-old-versions t
 kept-new-versions 6
 kept-old-versions 2
 version-control t)       ; use versioned backups



;;;;This starts up a server automatically, so it will be running to 
;;;;accept things like wikipedia articles.
(server-start)

;;;;Call a function which will have the time displayed in the modeline
(display-time)


;;;;What it says. Keeps the cursor in the same relative row during
;;;;pgups and dwns.
(setq scroll-preserve-screen-position t)

 ;;;;;Accelerate the cursor when scrolling.
(load "accel" t t)

;;;;;Push the mouse out of the way when the cursor approaches.
(mouse-avoidance-mode 'jump)

;;;SavePlace- this puts the cursor in the last place you editted
;;;a particular file. This is very useful for large files.
(require 'saveplace)
(setq-default save-place t)


;;;;Set so when moving by page, last visible line is highlighted.
;;(load "highlight-context-line.el")


;;;;We can also get completion in the mini-buffer as well.
;(icomplete-mode t)

;;;;"I always compile my .emacs, saves me about two seconds
;;;;startuptime. But that only helps if the .emacs.elc is newer
;;;;than the .emacs. So compile .emacs if it's not."
(defun autocompile nil
  "compile itself if ~/.emacs"
  (interactive)
  (require 'bytecomp)
  (if (string= (buffer-file-name) (expand-file-name (concat
default-directory ".emacs")))
      (byte-compile-file (buffer-file-name))))

(add-hook 'after-save-hook 'autocompile)


;;;More display goodness- highlight-tail mode, which
;;;;colorizes recently added text, but the color diminishes
;;;;over time, so you can see what you most recently typed.
;;;;http://groups.google.com/group/gnu.emacs.sources/msg/b50d53424e7ca0cd?output=gplain
(require 'highlight-tail)
(highlight-tail-reload)
;;;;Wikipedia mode- syntax highlighting for Wikipedia, plus some 
;;;;binding of moving around commands.
;;;;http://www.emacswiki.org/cgi-bin/wiki/WikipediaMode
(autoload 'wikipedia-mode "~/emacs/wikipedia-mode.el"
  "Major mode for editing documents in Wikipedia markup." t)
(add-to-list 'auto-mode-alist 
             '("\\.wiki\\'" . wikipedia-mode)) ;;;;Duh.
(add-to-list 'auto-mode-alist 
             '("index.\\.*" . wikipedia-mode))
;;;;add auto-capitalize in addition to wikipedia-mode.
(add-to-list 'auto-mode-alist 
             '("index.\\.*" . auto-capitalize)) 
;;;;Add check for duplicate words to wikipedia-mode.
(add-to-list 'auto-mode-alist 
             '("index.\\.*" . dw-check-to-end)) 
;;;;Pabbrev mode too. Very useful.
(add-to-list 'auto-mode-alist 
             '("index.\\.*" . 'pabbrev-scavenge-buffer)) 
(add-to-list 'auto-mode-alist 
             '("index.\\.*" .  'pabbrev-mode)) 
;;;;Flyspell mode is good as well.
(add-to-list 'auto-mode-alist 
             '("index.\\.*" . 'flyspell-mode)) 
(add-to-list 'auto-mode-alist 
             '("index.\\.*" . 'flyspell-buffer)) 


;;;; la date à la française


;; (defun guillaume-insert-date ()
;; "Insert date at point."
;; (interactive)
;; (insert (format-time-string " %a %e %b %Y à %k:%M")))


(defvar current-time-format " %a %e %b %Y à %k:%M"
  "Format of date to insert with `insert-current-time' func.
Note the weekly scope of the command's precision.")




;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; trucs divers
;; Sauvegarde des fichiers récemment ouverts + création d'un raccourci
(add-to-list 'load-path "~/.emacs.d/lisp/recent")
(require 'recentf)
(recentf-mode 1)
(defun recentf-open-files-compl ()
  (interactive)
  (let* ((all-files recentf-list)
         (tocpl (mapcar (function 
                         (lambda (x) (cons (file-name-nondirectory x) x))) all-files))
         (prompt (append '("File name: ") tocpl))
         (fname (completing-read (car prompt) (cdr prompt) nil nil)))
    (find-file (cdr (assoc-string fname tocpl)))))
 
(global-set-key "\C-x\C-l" 'recentf-open-files-compl)
 
(require 'ido)
(ido-mode t)

;; -----------------------------------------------------
;; CORRECTEUR ISPELL 
;; -----------------------------------------------------
 
;: Dictionnaire francais
(setq-default ispell-program-name "aspell")
(setq ispell-dictionary-alist
      (cons
       '("fr_FR-lrg" "[A-Za-zÀÂÆÇÈÉÊËÎÏÔÙÛÜàâçèéêëîïôùûü]"
         "[^A-Za-zÀÂÆÇÈÉÊËÎÏÔÙÛÜàâçèéêëîïôùûü]" "[-']" t nil "~list"
         iso-8859-1)
       ispell-dictionary-alist)) 
 
;; Empèche Ispell de vérifier le contenu de certaines commandes 
(setq ispell-tex-skip-alists
      (list
       (append (car ispell-tex-skip-alists)
               '(("\\\\cite"            ispell-tex-arg-end)
                 ("\\\\nocite"          ispell-tex-arg-end)
                 ("\\\\includegraphics" ispell-tex-arg-end)
                 ("\\\\figScale"         ispell-tex-arg-end)
                 ("\\\\author"          ispell-tex-arg-end)
                 ("\\\\ref"             ispell-tex-arg-end)
                 ("\\\\eqref"             ispell-tex-arg-end)
                 ("\\\\label"           ispell-tex-arg-end)
                 ))
       (cadr ispell-tex-skip-alists)))
 
;; Empèche Ispell de vérifier le contenu des citation natbib
(eval-after-load "ispell"
  '(let ((list (car ispell-tex-skip-alists)))
     (add-to-list 'list '("\\\\cite[tp]" ispell-tex-arg-end))
     (setcar ispell-tex-skip-alists list)))
 
 
;; -----------------------------------------------------
;; COMMANDES AucTeX / LaTeX
;; -----------------------------------------------------
 
;; Choix des programmes de visualition selon le fichier de sortie
(setq TeX-output-view-style (quote (("^dvi$" "^pstricks$\\|^pst-\\|^psfrag$" "dvips %d -o && start %f") ("^dvi$" "." "xdvi %dS %d") ("^pdf$" "." "okular %o") ("^html?$" "." "start %o"))))
(setq TeX-view-style (quote (("^epsf$" "start %f") ("." "xdvi %dS %d"))))
 
;; Pour voir les les équations compilées directes dans  emacs
(load "preview-latex.el" nil t t)
 
;; Quelques commandes additionnelles du mode LaTeX
(add-hook 'LaTeX-mode-hook
  (function
    (lambda ()
      (add-to-list 'TeX-command-list
             (list "PDFLaTeX" "pdflatex %s.tex"
                   'TeX-run-command nil t))
      (add-to-list 'TeX-command-list
             (list "Shell-Escape" "latex -halt-on-error -shell-escape %s.tex"
                   'TeX-run-command nil t))
      (add-to-list 'TeX-command-list
             (list "Acroread" "acroread %s.pdf"
                  'TeX-run-command nil t))
      (add-to-list 'TeX-command-list
             (list "OKULAR" "okular %s.pdf"
                   'TeX-run-command nil t))
      (add-to-list 'TeX-command-list
             (list "DVIPS" "dvips -o %s.ps %s.dvi"
                   'TeX-run-command nil t))
       (add-to-list 'TeX-command-list
             (list "PS2PDF" "ps2pdf %s.ps %s.pdf"
                   'TeX-run-command nil t))
      (add-to-list 'TeX-command-list
             (list "Clean" "rm %s.log %s.aux %s.out %s.idx"
                   'TeX-run-command nil t))
      (add-to-list 'TeX-command-list
             (list "Quick" "latex -interaction=nonstopmode %s.tex &&  dvips -o %s.ps  %s.dvi && ps2pdf %s.ps %s.pdf && rm %s.ps"
                   'TeX-run-command nil t))
      (add-to-list 'TeX-command-list
             (list "Xelatex" "xelatex -interaction=nonstopmode %s.tex "
                   'TeX-run-command nil t))
;;      (TeX-PDF-mode)
      ;gestion de la table matière et autre...
      (reftex-mode)
      ;; Corrrection à la volée syntaxique
      (flyspell-mode)
      ;; dictionnaire évitant les erreurs d'accents
      (ispell-change-dictionary "francais")
)))
 
;; Aller à la prochaine erreur LaTeX 
(global-set-key [f7]      'TeX-next-error) ; goto next found
                        ; LaTeX error
(global-set-key [f8]      'next-error)     ; goto next found lacheck
                        ; error (run Check first)
;; Hook emacs pour Scilab
(load "scilab.el")
(setq auto-mode-alist (cons '("\\(\\.sci$\\|\\.sce$\\)" . scilab-mode) auto-mode-alist))
(setq scilab-mode-hook '(lambda () (setq fill-column 74)))
 
;; Gestion du retour à la ligne / justification
(add-hook 'text-mode-hook
      (lambda ()
      (auto-fill-mode 1)
      (setq default-justification 'full))
      )
(defun my-fill-nobreak-predicate ()
      (save-match-data
      (or (looking-at "[ \t]*[])}»!?;:]")
      (looking-at "[ \t]*\\.\\.\\.")
      (save-excursion
      (skip-chars-backward " \t")
      (backward-char 1)
      (looking-at "[([{«]")))))
 
(setq fill-nobreak-predicate 'my-fill-nobreak-predicate)
 
;; Parenthésage automatique
(defun brace-insert (sta stb stc)
 (if (= (preceding-char) sta )
     (insert stb)
   (insert stc)
   (backward-char 1)
   )
 )
 
(defun curly-braces     () (interactive "*") (brace-insert ?\\ "{" "{}"))
(defun round-braces     () (interactive "*") (brace-insert ?\\ "(" "()"))
(defun square-braces    () (interactive "*") (brace-insert ?\\ "[" "[]"))
(defun dollar-braces    () (interactive "*") (brace-insert ?\\ "$" "$$"))
(defun guillemet-braces () (interactive "*") (brace-insert ?\\ "«" "«»"))
 
 
(defun One-line-up   () (interactive) (scroll-down 1))
(defun One-line-down () (interactive) (scroll-up 1))
 
(defun left-right () (interactive "*")
 (insert "\\right")
 (backward-char 7)
 (insert "\\left")
 (forward-char 1)
 )
 
(global-set-key "{" 'curly-braces)
(global-set-key "(" 'round-braces)
(global-set-key "[" 'square-braces)
(global-set-key [(?«)] 'guillemet-braces)
(global-set-key "\C-\\" 'left-right)



;; auctex
(setq TeX-parse-self t) ; Enable parse on load.
;(setq TeX-auto-save t) ; Enable parse on save.
;(setq-default TeX-master nil)
; lancer la commande M-x TeX-auto-generate
(setq TeX-auto-private    "~/auctex/auto/")